CRM/backend/app/Services/TaskReminderService.php

38 خطوط
1.1 KiB
PHP

<?php
namespace App\Services;
use App\Models\Task;
use App\Notifications\TaskDueNotification;
class TaskReminderService
{
public function sendDueNotifications(): int
{
$sent = 0;
$now = now();
Task::active()
->whereNotNull('assigned_to')
->where(function ($query) use ($now): void {
$query->where(fn ($reminders) => $reminders->whereNotNull('reminder_at')->where('reminder_at', '<=', $now))
->orWhere(fn ($overdue) => $overdue->whereNotNull('due_at')->where('due_at', '<', $now));
})
->orderBy('id')
->chunkById(100, function ($tasks) use (&$sent, $now): void {
foreach ($tasks as $task) {
if ($task->reminder_at?->lte($now)) {
TaskDueNotification::send($task, 'reminder');
$sent++;
}
if ($task->due_at?->lt($now)) {
TaskDueNotification::send($task, 'overdue');
$sent++;
}
}
});
return $sent;
}
}