added functions email and flag

This commit is contained in:
2026-06-11 10:20:46 +02:00
parent 33b627f328
commit fdde16b113
5 changed files with 213 additions and 25 deletions
@@ -1,4 +1,5 @@
<?php
/**
* Scadenzario Email notification cron script
* Run daily: 0 7 * * * php /var/www/html/public/userarea/scadenzario/cron/send_notifications.php
@@ -42,9 +43,19 @@ $errors = 0;
// Get active deadlines that are approaching or overdue
$stmt = $pdo->query("
SELECT d.id, d.topic, s.name AS subject_name, d.due_date, d.notification_days
SELECT
d.id,
d.topic,
s.name AS subject_name,
d.due_date,
d.notification_days,
d.notify_function,
f.email AS function_email,
f.person_full_name AS function_person,
f.name AS function_name
FROM scad_deadlines d
LEFT JOIN scad_subjects s ON s.id = d.subject_id
LEFT JOIN scad_functions f ON f.id = d.function_id
WHERE d.status = 'active'
AND d.due_date <= DATE_ADD(CURDATE(), INTERVAL d.notification_days DAY)
");
@@ -101,20 +112,28 @@ foreach ($deadlines as $dl) {
$type = $isOverdue ? 'overdue' : 'approaching';
$daysLeft = (int)((strtotime($dl['due_date']) - strtotime($today)) / 86400);
// Collect all recipients (direct + department)
// Collect all recipients (direct + department + optional function email)
$recipients = [];
$functionRecipient = null;
$getRecipients->execute([$dl['id']]);
foreach ($getRecipients->fetchAll(PDO::FETCH_ASSOC) as $r) {
$recipients[$r['employee_id']] = $r;
}
$getDeptRecipients->execute([$dl['id']]);
foreach ($getDeptRecipients->fetchAll(PDO::FETCH_ASSOC) as $r) {
$recipients[$r['employee_id']] = $r;
// Optional: also notify the linked function email if enabled on the deadline.
if (
!empty($dl['notify_function'])
&& !empty($dl['function_email'])
&& filter_var($dl['function_email'], FILTER_VALIDATE_EMAIL)
) {
$functionRecipient = [
'email' => $dl['function_email'],
'name' => trim(($dl['function_person'] ?? '') !== '' ? $dl['function_person'] : ($dl['function_name'] ?? 'Funzione')),
];
}
if (empty($recipients)) {
if (empty($recipients) && empty($functionRecipient)) {
continue;
}
@@ -193,15 +212,99 @@ foreach ($deadlines as $dl) {
$sent++;
echo date('H:i:s') . "{$type}{$emp['email']}{$dl['topic']}\n";
} catch (Exception $e) {
$errors++;
echo date('H:i:s') . " ✗ Errore {$emp['email']}: {$e->getMessage()}\n";
}
}
// Send notification to function email if enabled.
// It is tracked with employee_id = 0 to avoid duplicate daily sends.
if ($functionRecipient) {
$functionEmployeeId = 0;
$checkSent->execute([$dl['id'], $functionEmployeeId, $type]);
if ($checkSent->fetchColumn() > 0) {
$skipped++;
} else {
try {
$mail = new PHPMailer(true);
$mailer = $_ENV['MAIL_MAILER'] ?? 'mail';
if ($mailer === 'smtp') {
$mail->isSMTP();
$mail->Host = $_ENV['MAIL_HOST'] ?? 'localhost';
$mail->Port = (int)($_ENV['MAIL_PORT'] ?? 587);
if (!empty($_ENV['MAIL_USERNAME']) && $_ENV['MAIL_USERNAME'] !== 'null') {
$mail->SMTPAuth = true;
$mail->Username = $_ENV['MAIL_USERNAME'];
$mail->Password = $_ENV['MAIL_PASSWORD'] ?? '';
}
$enc = $_ENV['MAIL_ENCRYPTION'] ?? '';
if ($enc && $enc !== 'null') {
$mail->SMTPSecure = $enc;
}
}
$mail->CharSet = 'UTF-8';
$mail->setFrom(
$_ENV['MAIL_FROM_ADDRESS'] ?? 'noreply@zibogomma.it',
$_ENV['MAIL_FROM_NAME'] ?? 'Scadenzario ZIBOGOMMA'
);
$mail->addAddress($functionRecipient['email'], $functionRecipient['name']);
if ($managerCcEmail && strcasecmp($managerCcEmail, $functionRecipient['email']) !== 0) {
$mail->addCC($managerCcEmail);
}
$detailUrl = $appUrl . '/userarea/scadenzario/detail.php?id=' . $dl['id'];
$topicText = (!empty($dl['subject_name']) ? $dl['subject_name'] . ' — ' : '') . $dl['topic'];
if ($isOverdue) {
$mail->Subject = '⚠️ Scadenza superata: ' . $dl['topic'];
$mail->Body = buildHtml(
'Scadenza superata',
$topicText,
'La scadenza era prevista per il <strong>' . date('d/m/Y', strtotime($dl['due_date'])) . '</strong> ed è stata superata da <strong>' . abs($daysLeft) . ' giorni</strong>.',
'#dc3545',
$detailUrl
);
} else {
$mail->Subject = '📅 Scadenza in arrivo: ' . $dl['topic'];
$daysText = $daysLeft === 0 ? 'oggi' : 'tra <strong>' . $daysLeft . ' giorni</strong>';
$mail->Body = buildHtml(
'Scadenza in arrivo',
$topicText,
'La scadenza è prevista per il <strong>' . date('d/m/Y', strtotime($dl['due_date'])) . '</strong> (' . $daysText . ').',
'#e8930c',
$detailUrl
);
}
$mail->isHTML(true);
$mail->AltBody = strip_tags(str_replace('<br>', "\n", $mail->Body));
$mail->send();
$insertNotif->execute([$dl['id'], $functionEmployeeId, $type]);
$sent++;
echo date('H:i:s') . "{$type} → funzione {$functionRecipient['email']}{$dl['topic']}\n";
} catch (Exception $e) {
$errors++;
echo date('H:i:s') . " ✗ Errore funzione {$functionRecipient['email']}: {$e->getMessage()}\n";
}
}
}
// History (one per deadline, not per recipient)
$recipientNames = implode(', ', array_map(fn($r) => trim($r['first_name'] . ' ' . $r['last_name']), $recipients));
if ($functionRecipient) {
$recipientNames .= ($recipientNames !== '' ? ', ' : '') . 'Funzione: ' . $functionRecipient['name'] . ' <' . $functionRecipient['email'] . '>';
}
$insertHistory->execute([$dl['id'], "Notifica {$type} inviata a: {$recipientNames}"]);
}