78 lines
2.0 KiB
PHP
78 lines
2.0 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\Notification;
|
|
use App\Models\User;
|
|
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
|
use Illuminate\Support\Collection;
|
|
|
|
class NotificationService
|
|
{
|
|
/**
|
|
* @param Collection<int, int>|array<int, int> $userIds
|
|
*/
|
|
public function sendToUsers(Collection|array $userIds, string $title, ?string $content = null, ?int $createdBy = null): void
|
|
{
|
|
$userIds = collect($userIds)->filter()->unique()->values();
|
|
|
|
if ($userIds->isEmpty()) {
|
|
return;
|
|
}
|
|
|
|
$createdBy ??= auth()->id();
|
|
$now = now();
|
|
|
|
Notification::insert($userIds->map(fn (int $userId) => [
|
|
'user_id' => $userId,
|
|
'created_by' => $createdBy,
|
|
'title' => $title,
|
|
'content' => $content,
|
|
'is_read' => false,
|
|
'created_at' => $now,
|
|
'updated_at' => $now,
|
|
])->all());
|
|
}
|
|
|
|
public function paginated(User $user, int $perPage = 15): LengthAwarePaginator
|
|
{
|
|
return Notification::query()
|
|
->where('user_id', $user->id)
|
|
->with('creator.profile')
|
|
->orderByDesc('created_at')
|
|
->orderByDesc('id')
|
|
->paginate($perPage);
|
|
}
|
|
|
|
public function unreadCount(User $user): int
|
|
{
|
|
return Notification::query()
|
|
->where('user_id', $user->id)
|
|
->where('is_read', false)
|
|
->count();
|
|
}
|
|
|
|
public function markAsRead(Notification $notification): void
|
|
{
|
|
$notification->update(['is_read' => true]);
|
|
}
|
|
|
|
public function markAllAsRead(User $user): void
|
|
{
|
|
Notification::query()
|
|
->where('user_id', $user->id)
|
|
->where('is_read', false)
|
|
->update(['is_read' => true]);
|
|
}
|
|
|
|
public function delete(Notification $notification): bool
|
|
{
|
|
return $notification->delete();
|
|
}
|
|
|
|
public function deleteAll(User $user): void
|
|
{
|
|
Notification::query()->where('user_id', $user->id)->delete();
|
|
}
|
|
}
|