orderBy('created_at', 'desc')->get(); } public function getAllPaginated(int $perPage = 12): LengthAwarePaginator { return Notification::with(['createdBy', 'media']) ->withCount([ 'sends', 'sends as seen_count' => fn($q) => $q->where('read', true), ]) ->orderBy('created_at', 'desc') ->paginate($perPage); } public function findById(int $id): ?Notification { return Notification::with(['createdBy', 'sends', 'media'])->find($id); } public function create(array $data): Notification { return DB::transaction(function () use ($data) { $image = null; if (isset($data['image']) && $data['image'] instanceof UploadedFile) { $image = $data['image']; } unset($data['image']); $data['created_by'] = Auth::id(); $data['type'] = $data['type'] ?? 'manual'; $notification = Notification::create($data); if ($image) { $this->mediaService->upload($image, 'notification', $notification->id, 'imagem'); } $this->dispatchSends($notification); return $notification->load('media'); }); } 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_id) { $query->where('position_id', $notification->recipient_position_id); } if ($notification->recipient_sector_id) { $query->where('sector_id', $notification->recipient_sector_id); } $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); } }