CRM/backend/app/Services/NotificationService.php

80 خطوط
2.9 KiB
PHP

<?php
namespace App\Services;
use App\Models\Notification as NotificationModel;
use App\Models\Setting;
use App\Models\User;
class NotificationService
{
public static function send(int $userId, string $title, string $message, string $type = 'info', ?array $data = null): NotificationModel
{
if (!self::enabled($type)) {
return new NotificationModel();
}
return NotificationModel::create([
'user_id' => $userId,
'title' => $title,
'message' => $message,
'type' => $type,
'data' => $data,
'is_read' => false,
]);
}
public static function sendOnce(int $userId, string $title, string $message, string $type = 'info', ?array $data = null): ?NotificationModel
{
$exists = NotificationModel::where('user_id', $userId)
->where('type', $type)
->where('data->follow_up_id', $data['follow_up_id'] ?? null)
->whereDate('created_at', now()->toDateString())
->exists();
return $exists ? null : self::send($userId, $title, $message, $type, $data);
}
public static function notifyAssignment(int $userId, string $leadName): void
{
self::send($userId, 'لید جدید', "لید {$leadName} به شما اختصاص داده شد", 'assignment');
}
public static function notifyFollowUpReminder(int $userId, string $leadName): void
{
self::send($userId, 'یادآوری پیگیری', "موعد پیگیری لید {$leadName} رسیده است", 'follow_up');
}
public static function notifyFeedback(int $userId, string $agentName): void
{
self::send($userId, 'بازخورد جدید', "بازخورد جدیدی برای شما ثبت شده است", 'feedback');
}
public static function notifyReassignment(int $userId, string $leadName): void
{
self::send($userId, 'تغییر وضعیت لید', "لید {$leadName} دوباره به شما اختصاص داده شد", 'reassignment');
}
public static function notifyToAllAgents(string $title, string $message, string $type = 'system'): void
{
$agents = User::role('agent')->get();
foreach ($agents as $agent) {
self::send($agent->id, $title, $message, $type);
}
}
private static function enabled(string $type): bool
{
if (Setting::where('key', 'in_app_notifications_enabled')->value('value') === 'false') {
return false;
}
return match ($type) {
'assignment', 'reassignment' => Setting::where('key', 'assigned_lead_notification_enabled')->value('value') !== 'false',
'follow_up' => Setting::where('key', 'follow_up_notification_enabled')->value('value') !== 'false',
'overdue_follow_up' => Setting::where('key', 'overdue_notification_enabled')->value('value') !== 'false',
default => true,
};
}
}