dstpabuaran.com/app/Jobs/SendAttendanceReminderJob.php

73 lines
2.1 KiB
PHP

<?php
namespace App\Jobs;
use App\Enums\Permission;
use App\Models\Attendance;
use App\Models\LeaveRequest;
use App\Models\User;
use App\Notifications\WebPushNotification;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
class SendAttendanceReminderJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public int $tries = 3;
public function handle(): void
{
$today = now()->toDateString();
$users = User::query()
->select(['id', 'name'])
->active()
->whereHas('roles', function ($q) {
$q->whereHas('permissions', fn($pq) => $pq->where('name', Permission::ATTENDANCES_CREATE->value));
})
->whereHas('employee')
->get();
foreach ($users as $user) {
$employee = $user->employee;
if (! $employee) {
continue;
}
$hasAttendedToday = Attendance::where('employee_id', $employee->id)
->where('attendance_date', $today)
->exists();
if ($hasAttendedToday) {
continue;
}
$isOnLeave = LeaveRequest::approved()
->where('employee_id', $employee->id)
->where('start_date', '<=', $today)
->where('end_date', '>=', $today)
->exists();
if ($isOnLeave) {
continue;
}
try {
$user->notify(new WebPushNotification(
title: 'Reminder Presensi',
body: 'Selamat pagi! Jangan lupa untuk melakukan presensi masuk hari ini.',
url: route('admin.hr.attendances.index'),
));
} catch (\Exception $e) {
Log::error("Gagal mengirim reminder presensi ke user {$user->id}: {$e->getMessage()}");
}
}
}
}