Files
Siro/backend/marketing_engine/cron_weekly_report.php
T

78 lines
3.1 KiB
PHP

<?php
// ============================================================
// marketing_engine/cron_weekly_report.php
// Script to be run via cron (e.g. weekly) to summarize all reports
// ============================================================
require_once __DIR__ . '/../core/bootstrap.php';
require_once __DIR__ . '/../functions.php';
require_once __DIR__ . '/../core/Services/SiroGeminiService.php';
require_once __DIR__ . '/../core/Services/FcmService.php';
try {
$con = Database::get('main');
// Fetch all reports from the last 7 days (that are not weekly themselves)
$stmt = $con->prepare("
SELECT platform, report_html, created_at
FROM marketing_reports
WHERE is_weekly = 0
AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
ORDER BY created_at ASC
");
$stmt->execute();
$reports = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (empty($reports)) {
echo "No reports generated in the last 7 days to summarize.\n";
exit;
}
// Combine all report data for Gemini
$combinedData = [];
foreach ($reports as $report) {
$combinedData[] = [
'platform' => $report['platform'],
'date' => $report['created_at'],
'content' => strip_tags($report['report_html']) // Send stripped HTML to save tokens
];
}
$gemini = new SiroGeminiService();
// Create a new method in GeminiService or use evaluatePostsForReporting with a specific prompt wrapper
$prompt = "You are a Chief Marketing Officer AI. Below are all the daily/individual social media intelligence reports collected over the last 7 days from our scraper bots. Please read through all of them and generate one comprehensive, executive 'Weekly Market Intelligence Summary'. Format it beautifully in HTML. Highlight key market trends, recurrent complaints, competitor activities, and actionable advice for the week.\n\nData:\n" . json_encode($combinedData);
$response = $gemini->callGemini($prompt, 'gemini-1.5-flash');
if (isset($response['candidates'][0]['content']['parts'][0]['text'])) {
$weeklyHtml = $response['candidates'][0]['content']['parts'][0]['text'];
// Save the weekly report
$insert = $con->prepare("INSERT INTO marketing_reports (platform, report_html, is_weekly) VALUES ('all', ?, 1)");
$insert->execute([$weeklyHtml]);
$reportId = $con->lastInsertId();
// Notify Admins
$fcm = new FcmService();
$fcm->send(
token: '/topics/admin_alerts',
title: 'Weekly Market Intelligence Summary 📈',
body: 'The comprehensive weekly social media report has been generated.',
data: [
'type' => 'marketing_report',
'report_id' => $reportId,
'is_weekly' => 1
],
category: 'marketing_report'
);
echo "Weekly report generated and saved successfully. ID: $reportId\n";
} else {
echo "Failed to generate report from Gemini.\n";
}
} catch (Exception $e) {
echo "Error generating weekly report: " . $e->getMessage() . "\n";
}