Initial commit
This commit is contained in:
+237
@@ -0,0 +1,237 @@
|
||||
#!/usr/bin/env php
|
||||
<?php
|
||||
/**
|
||||
* notify.php — Notifications quotidiennes par mail (Sendmail/Postfix)
|
||||
*
|
||||
* Cron : 0 8 * * * /usr/bin/php /var/www/menage/notify.php >> /var/log/menage_notify.log 2>&1
|
||||
* Test : php notify.php --test
|
||||
* Force: php notify.php --force
|
||||
*/
|
||||
require_once __DIR__ . '/api/config.php';
|
||||
|
||||
define('MAIL_FROM', 'smetais@free.fr');
|
||||
define('MAIL_FROM_NAME', 'Ménage Maison');
|
||||
define('APP_URL', 'https://menage.bobichon.ovh/'); // ← adapter
|
||||
|
||||
$is_test = in_array('--test', $argv ?? []);
|
||||
$is_force = in_array('--force', $argv ?? []);
|
||||
|
||||
log_msg("=== notify.php " . date('Y-m-d H:i:s') . ($is_test?' [TEST]':'') . " ===");
|
||||
|
||||
try {
|
||||
$db = getDB();
|
||||
$today = new DateTime();
|
||||
$today_dow = (int)date('N');
|
||||
|
||||
// ── Toutes les tâches ─────────────────────────────────────
|
||||
$all_tasks = $db->query("
|
||||
SELECT t.id, t.label, t.frequency,
|
||||
c.name as category_name, c.icon as category_icon
|
||||
FROM tasks t
|
||||
JOIN categories c ON c.id = t.category_id
|
||||
ORDER BY c.sort_order, t.sort_order
|
||||
")->fetchAll();
|
||||
|
||||
$period_keys = all_current_period_keys();
|
||||
$week = current_week(); // pour l'affichage dans le mail
|
||||
|
||||
// État actuel — dernière action par tâche sur sa période courante
|
||||
$comp_raw = $db->query("
|
||||
SELECT c.task_id, c.checked, t.frequency
|
||||
FROM completions c
|
||||
JOIN tasks t ON t.id = c.task_id
|
||||
WHERE (t.frequency = 'quotidien' AND c.period_key = '{$period_keys['quotidien']}')
|
||||
OR (t.frequency = 'hebdomadaire' AND c.period_key = '{$period_keys['hebdomadaire']}')
|
||||
OR (t.frequency = 'mensuel' AND c.period_key = '{$period_keys['mensuel']}')
|
||||
OR (t.frequency = 'trimestriel' AND c.period_key = '{$period_keys['trimestriel']}')
|
||||
ORDER BY c.completed_at ASC
|
||||
")->fetchAll();
|
||||
$latest = [];
|
||||
foreach ($comp_raw as $c) $latest[$c['task_id']] = (int)$c['checked'];
|
||||
|
||||
// ── Classifier chaque tâche ───────────────────────────────
|
||||
$tasks_todo = [];
|
||||
$tasks_late = [];
|
||||
$tasks_done = [];
|
||||
|
||||
foreach ($all_tasks as $t) {
|
||||
$done = isset($latest[$t['id']]) && $latest[$t['id']] === 1;
|
||||
if ($done) { $tasks_done[] = $t; continue; }
|
||||
|
||||
switch ($t['frequency']) {
|
||||
case 'quotidien':
|
||||
$tasks_todo[] = $t + ['urgency' => 'quotidien'];
|
||||
break;
|
||||
case 'hebdomadaire':
|
||||
if ($today_dow >= 5) $tasks_late[] = $t + ['urgency' => 'hebdo_retard'];
|
||||
else $tasks_todo[] = $t + ['urgency' => 'hebdo'];
|
||||
break;
|
||||
case 'mensuel':
|
||||
$stmt = $db->prepare("SELECT MAX(completed_at) FROM completions WHERE task_id=:tid AND checked=1");
|
||||
$stmt->execute([':tid' => $t['id']]);
|
||||
$last = $stmt->fetchColumn();
|
||||
if (!$last) $tasks_late[] = $t + ['urgency' => 'mensuel_jamais'];
|
||||
elseif ($today->diff(new DateTime($last))->days > 30) $tasks_late[] = $t + ['urgency' => 'mensuel_retard', 'days' => $today->diff(new DateTime($last))->days];
|
||||
elseif ((int)$today->format('j') === 1) $tasks_todo[] = $t + ['urgency' => 'mensuel'];
|
||||
break;
|
||||
case 'trimestriel':
|
||||
$stmt = $db->prepare("SELECT MAX(completed_at) FROM completions WHERE task_id=:tid AND checked=1");
|
||||
$stmt->execute([':tid' => $t['id']]);
|
||||
$last = $stmt->fetchColumn();
|
||||
if (!$last) $tasks_late[] = $t + ['urgency' => 'trim_jamais'];
|
||||
elseif ($today->diff(new DateTime($last))->days > 90) $tasks_late[] = $t + ['urgency' => 'trim_retard', 'days' => $today->diff(new DateTime($last))->days];
|
||||
break;
|
||||
case 'saisonnier':
|
||||
// Déjà filtré par saison dans la requête — si présent, c'est à faire cette saison
|
||||
$tasks_todo[] = $t + ['urgency' => 'saisonnier'];
|
||||
break;
|
||||
case 'biannuel':
|
||||
$stmt = $db->prepare("SELECT MAX(completed_at) FROM completions WHERE task_id=:tid AND checked=1");
|
||||
$stmt->execute([':tid' => $t['id']]);
|
||||
$last = $stmt->fetchColumn();
|
||||
if (!$last) $tasks_late[] = $t + ['urgency' => 'biannuel_jamais'];
|
||||
elseif ($today->diff(new DateTime($last))->days > 180) $tasks_late[] = $t + ['urgency' => 'biannuel_retard', 'days' => $today->diff(new DateTime($last))->days];
|
||||
else $tasks_todo[] = $t + ['urgency' => 'biannuel'];
|
||||
break;
|
||||
case 'annuel':
|
||||
$stmt = $db->prepare("SELECT MAX(completed_at) FROM completions WHERE task_id=:tid AND checked=1");
|
||||
$stmt->execute([':tid' => $t['id']]);
|
||||
$last = $stmt->fetchColumn();
|
||||
if (!$last) $tasks_late[] = $t + ['urgency' => 'annuel_jamais'];
|
||||
elseif ($today->diff(new DateTime($last))->days > 365) $tasks_late[] = $t + ['urgency' => 'annuel_retard', 'days' => $today->diff(new DateTime($last))->days];
|
||||
else $tasks_todo[] = $t + ['urgency' => 'annuel'];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
log_msg("À faire: ".count($tasks_todo).", retard: ".count($tasks_late).", faites: ".count($tasks_done));
|
||||
|
||||
if (!$is_force && empty($tasks_todo) && empty($tasks_late)) {
|
||||
log_msg("Rien à signaler, pas d'envoi."); exit(0);
|
||||
}
|
||||
|
||||
// ── Destinataires : comptes avec email non vide ───────────
|
||||
$accounts = $db->query("SELECT id, display_name, email, color, avatar FROM accounts WHERE email != '' ORDER BY id")->fetchAll();
|
||||
if (empty($accounts)) { log_msg("Aucun compte avec email. Arrêt."); exit(0); }
|
||||
|
||||
foreach ($accounts as $acc) {
|
||||
$subject = build_subject($tasks_todo, $tasks_late);
|
||||
$html = build_html($acc, $tasks_todo, $tasks_late, $tasks_done, $week);
|
||||
$text = build_text($acc, $tasks_todo, $tasks_late, $tasks_done);
|
||||
|
||||
if ($is_test) {
|
||||
log_msg("[TEST] → {$acc['display_name']} <{$acc['email']}>");
|
||||
log_msg("[TEST] Sujet : $subject");
|
||||
log_msg("[TEST] Texte :\n$text");
|
||||
} else {
|
||||
$sent = send_mail($acc['email'], $acc['display_name'], $subject, $html, $text);
|
||||
log_msg($sent ? "✓ Envoyé à {$acc['display_name']} <{$acc['email']}>" : "✗ Échec → {$acc['email']}");
|
||||
}
|
||||
}
|
||||
|
||||
log_msg("=== Terminé ===\n");
|
||||
exit(0);
|
||||
|
||||
} catch (Exception $e) {
|
||||
log_msg("ERREUR: " . $e->getMessage()); exit(1);
|
||||
}
|
||||
|
||||
// ════════════════════════════════════════════════════════════
|
||||
function build_subject(array $todo, array $late): string {
|
||||
$nl = count($late); $nt = count($todo);
|
||||
if ($nl && $nt) return "🏡 Ménage — {$nl} en retard, {$nt} à faire";
|
||||
if ($nl) return "⚠️ Ménage — {$nl} tâche(s) en retard !";
|
||||
return "🏡 Ménage du " . date('d/m') . " — {$nt} tâche(s) à faire";
|
||||
}
|
||||
|
||||
function build_html(array $acc, array $todo, array $late, array $done, string $week): string {
|
||||
$name = htmlspecialchars($acc['display_name']);
|
||||
$color = htmlspecialchars($acc['color']);
|
||||
$avatar = htmlspecialchars($acc['avatar']);
|
||||
$date_fr = date_fr();
|
||||
$app_url = APP_URL;
|
||||
|
||||
$html = "<!DOCTYPE html><html lang='fr'><head><meta charset='UTF-8'>
|
||||
<style>body{font-family:Arial,sans-serif;background:#f5f3ee;margin:0;padding:20px;}
|
||||
.w{max-width:560px;margin:0 auto;background:#fff;border-radius:12px;overflow:hidden;box-shadow:0 2px 12px rgba(0,0,0,.08);}
|
||||
.h{background:#2d6a4f;color:#fff;padding:20px 24px;display:flex;align-items:center;gap:12px;}
|
||||
.av{width:38px;height:38px;border-radius:50%;background:{$color};color:#fff;display:inline-flex;align-items:center;justify-content:center;font-weight:700;}
|
||||
.b{padding:20px 24px;}
|
||||
.sec{margin-bottom:16px;}
|
||||
.st{font-size:.72rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;margin-bottom:8px;}
|
||||
.st-l{color:#c1440e;} .st-t{color:#2d6a4f;} .st-d{color:#6b6560;}
|
||||
.row{display:flex;align-items:flex-start;gap:8px;padding:6px 0;border-bottom:1px solid #f0ede6;}
|
||||
.row:last-child{border-bottom:none;}
|
||||
.cat{font-size:.72rem;color:#6b6560;margin-top:2px;}
|
||||
.bdg{display:inline-block;padding:1px 6px;border-radius:99px;font-size:.65rem;font-weight:600;background:#fde8d8;color:#7c3d12;margin-left:4px;}
|
||||
.cta{text-align:center;margin:20px 0 8px;}
|
||||
.cta a{background:#2d6a4f;color:#fff;padding:10px 24px;border-radius:8px;text-decoration:none;font-weight:700;font-size:.9rem;}
|
||||
.ft{text-align:center;font-size:.72rem;color:#a09a93;padding:12px;border-top:1px solid #f0ede6;}
|
||||
</style></head><body><div class='w'>
|
||||
<div class='h'><div class='av'>{$avatar}</div><div><strong>Bonjour {$name} !</strong><br><span style='font-size:.82rem;opacity:.8'>{$date_fr}</span></div></div>
|
||||
<div class='b'>";
|
||||
|
||||
if ($late) {
|
||||
$html .= "<div class='sec'><div class='st st-l'>⚠️ En retard (".count($late).")</div>";
|
||||
foreach ($late as $t) {
|
||||
$bdg = isset($t['days']) ? "<span class='bdg'>+{$t['days']}j</span>" : (str_contains($t['urgency'],'jamais')?"<span class='bdg'>jamais fait</span>":'');
|
||||
$html .= "<div class='row'><span style='font-size:.95rem'>{$t['category_icon']}</span><div><div style='font-size:.875rem'>{$t['label']}{$bdg}</div><div class='cat'>{$t['category_name']}</div></div></div>";
|
||||
}
|
||||
$html .= "</div>";
|
||||
}
|
||||
if ($todo) {
|
||||
$html .= "<div class='sec'><div class='st st-t'>✅ À faire aujourd'hui (".count($todo).")</div>";
|
||||
foreach ($todo as $t) $html .= "<div class='row'><span style='font-size:.95rem'>{$t['category_icon']}</span><div><div style='font-size:.875rem'>{$t['label']}</div><div class='cat'>{$t['category_name']}</div></div></div>";
|
||||
$html .= "</div>";
|
||||
}
|
||||
if ($done) {
|
||||
$html .= "<div class='sec'><div class='st st-d'>✓ Faites cette semaine (".count($done).")</div>";
|
||||
foreach (array_slice($done,0,5) as $t) $html .= "<div class='row' style='opacity:.55'><span>✓</span><span style='font-size:.875rem;text-decoration:line-through'>{$t['label']}</span></div>";
|
||||
if (count($done)>5) $html .= "<div style='font-size:.75rem;color:#a09a93;padding:4px'>… et ".(count($done)-5)." autres</div>";
|
||||
$html .= "</div>";
|
||||
}
|
||||
|
||||
$html .= "<div class='cta'><a href='{$app_url}'>Ouvrir l'application →</a></div></div>
|
||||
<div class='ft'>Ménage Maison · Semaine {$week} · <a href='{$app_url}' style='color:#a09a93'>Accéder</a></div>
|
||||
</div></body></html>";
|
||||
return $html;
|
||||
}
|
||||
|
||||
function build_text(array $acc, array $todo, array $late, array $done): string {
|
||||
$lines = ["Bonjour {$acc['display_name']} ! — ".date_fr(), str_repeat('-',40)];
|
||||
if ($late) { $lines[]="⚠️ EN RETARD :"; foreach($late as $t) $lines[]=" • [{$t['category_name']}] {$t['label']}".(isset($t['days'])?" (+{$t['days']}j)":''); }
|
||||
if ($todo) { $lines[]="✅ À FAIRE :"; foreach($todo as $t) $lines[]=" • [{$t['category_name']}] {$t['label']}"; }
|
||||
if ($done) { $lines[]="✓ FAITES :"; foreach(array_slice($done,0,5) as $t) $lines[]=" ✓ {$t['label']}"; }
|
||||
$lines[] = "\n".APP_URL;
|
||||
return implode("\n", $lines);
|
||||
}
|
||||
|
||||
function send_mail(string $to, string $name, string $subject, string $html, string $text): bool {
|
||||
$b = '==b_'.md5(uniqid());
|
||||
$fn = mb_encode_mimeheader(MAIL_FROM_NAME, 'UTF-8', 'B');
|
||||
$tn = mb_encode_mimeheader($name, 'UTF-8', 'B');
|
||||
$sb = mb_encode_mimeheader($subject, 'UTF-8', 'B');
|
||||
$hd = "From: {$fn} <".MAIL_FROM.">\r\n"
|
||||
. "To: {$tn} <{$to}>\r\n"
|
||||
. "MIME-Version: 1.0\r\n"
|
||||
. "Content-Type: multipart/alternative; boundary=\"{$b}\"\r\n"
|
||||
. "X-Mailer: MenagePHP/3\r\n";
|
||||
$bd = "--{$b}\r\n"
|
||||
. "Content-Type: text/plain; charset=UTF-8\r\n"
|
||||
. "Content-Transfer-Encoding: base64\r\n\r\n"
|
||||
. chunk_split(base64_encode($text)) . "\r\n"
|
||||
. "--{$b}\r\n"
|
||||
. "Content-Type: text/html; charset=UTF-8\r\n"
|
||||
. "Content-Transfer-Encoding: base64\r\n\r\n"
|
||||
. chunk_split(base64_encode($html)) . "\r\n"
|
||||
. "--{$b}--";
|
||||
return mail($to, $sb, $bd, $hd, '-f'.MAIL_FROM);
|
||||
}
|
||||
|
||||
function date_fr(): string {
|
||||
$j=['Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi','Dimanche'];
|
||||
$m=['janvier','février','mars','avril','mai','juin','juillet','août','septembre','octobre','novembre','décembre'];
|
||||
return $j[(int)date('N')-1].' '.date('j').' '.$m[(int)date('n')-1].' '.date('Y');
|
||||
}
|
||||
|
||||
function log_msg(string $msg): void { echo '['.date('H:i:s').'] '.$msg.PHP_EOL; }
|
||||
Reference in New Issue
Block a user