orderBy('created_at', 'desc')->get(); } public function findById(int $id): ?Notification { return Notification::with(['createdBy', 'sends'])->find($id); } public function create(array $data): Notification { return DB::transaction(function () use ($data) { $data['created_by'] = Auth::id(); $notification = Notification::create($data); $this->dispatchSends($notification); return $notification; }); } public function getUnreadByUser(int $userId): Collection { return NotificationSend::with('notification') ->where('user_id', $userId) ->where('read', false) ->orderBy('created_at', 'desc') ->get(); } public function markAsRead(int $sendId, int $userId): bool { $send = NotificationSend::where('id', $sendId) ->where('user_id', $userId) ->first(); if (!$send) { return false; } $send->update(['read' => true, 'read_at' => now()]); return true; } public function delete(int $id): bool { $model = Notification::find($id); if (!$model) { return false; } return $model->delete(); } private function dispatchSends(Notification $notification): void { $query = User::query(); match ($notification->recipient) { NotificationRecipientEnum::ASSOCIADO => $query->where('type', UserTypeEnum::ASSOCIADO->value), NotificationRecipientEnum::PARCEIRO => $query->where('type', UserTypeEnum::PARCEIRO->value), default => null, }; if ($notification->recipient_position) { $query->whereHas('position', fn($q) => $q->where('name', $notification->recipient_position)); } if ($notification->recipient_sector) { $query->whereHas('sector', fn($q) => $q->where('name', $notification->recipient_sector)); } $users = $query->pluck('id'); $sends = $users->map(fn($userId) => [ 'notification_id' => $notification->id, 'user_id' => $userId, 'read' => false, 'created_at' => now(), 'updated_at' => now(), ])->toArray(); NotificationSend::insert($sends); } }