Files
portal-api/app/Models/Notification.php

81 lines
2.1 KiB
PHP

<?php
namespace App\Models;
use App\Events\AdminNotificationCreated;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;
class Notification extends Model
{
use HasFactory, HasUuids;
protected $hidden = ['id'];
public function uniqueIds(): array
{
return ['uuid'];
}
protected $fillable = [
'recipient_type',
'recipient_id',
'type',
'title',
'body',
'link',
'is_read',
'read_at',
'data',
];
protected $casts = [
'is_read' => 'boolean',
'read_at' => 'datetime',
'data' => 'array',
];
public static function notifyCustomer(Customer $customer, array $attributes): void
{
self::create([
'recipient_type' => 'client',
'recipient_id' => $customer->id,
] + $attributes);
}
public static function notifyAdmins(array $attributes): void
{
$adminIds = User::query()
->whereHas('roles', fn ($query) => $query->where('guard_name', 'admin'))
->pluck('id');
foreach ($adminIds as $adminId) {
self::create([
'recipient_type' => 'admin',
'recipient_id' => $adminId,
...$attributes,
]);
}
if ($adminIds->isEmpty()) {
return;
}
try {
broadcast(new AdminNotificationCreated(
type: (string) ($attributes['type'] ?? 'system'),
title: (string) ($attributes['title'] ?? 'Có thông báo mới'),
body: isset($attributes['body']) ? (string) $attributes['body'] : null,
link: isset($attributes['link']) ? (string) $attributes['link'] : null,
));
} catch (\Throwable $e) {
Log::warning('Không thể phát thông báo realtime cho quản trị viên.', [
'type' => $attributes['type'] ?? null,
'error' => $e->getMessage(),
]);
}
}
}