NotificationService.php 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. <?php
  2. namespace App\Services;
  3. use App\Broadcasting\Entity\WebsocketEventData;
  4. use App\Broadcasting\Events\WebsocketEvent;
  5. use App\Enums\UserTypeEnum;
  6. use App\Models\Notification;
  7. use App\Models\NotificationRecipient;
  8. use App\Models\User;
  9. use Illuminate\Database\Eloquent\Collection;
  10. use Illuminate\Support\Facades\DB;
  11. class NotificationService
  12. {
  13. // ------------------------------------------------------------------
  14. // CRUD genérico (mantido para o controller base / rotas existentes)
  15. // ------------------------------------------------------------------
  16. public function getAll(): Collection
  17. {
  18. return Notification::orderBy('created_at', 'desc')->get();
  19. }
  20. public function findById(int $id): ?Notification
  21. {
  22. return Notification::find($id);
  23. }
  24. public function create(array $data): Notification
  25. {
  26. return Notification::create($data);
  27. }
  28. public function update(int $id, array $data): ?Notification
  29. {
  30. $model = $this->findById($id);
  31. if (!$model) {
  32. return null;
  33. }
  34. $model->update($data);
  35. return $model->fresh();
  36. }
  37. public function delete(int $id): bool
  38. {
  39. $model = $this->findById($id);
  40. if (!$model) {
  41. return false;
  42. }
  43. return $model->delete();
  44. }
  45. // ------------------------------------------------------------------
  46. // Dispatch: cria a notificação + um recipient por usuário + realtime
  47. // ------------------------------------------------------------------
  48. /**
  49. * @param array{
  50. * origin_table:string, origin_id:int, type:string, title:string, message:string,
  51. * recipient_user_ids:int[], unit_id?:int|null, franchisee_id?:int|null,
  52. * url?:string|null, action_text?:string|null, priority?:string,
  53. * expires_at?:string|null, created_by_user_id?:int|null
  54. * } $params
  55. */
  56. public function dispatch(array $params): ?Notification
  57. {
  58. $recipientUserIds = array_values(array_unique($params['recipient_user_ids'] ?? []));
  59. if (empty($recipientUserIds)) {
  60. return null; // ninguém para notificar
  61. }
  62. return DB::transaction(function () use ($params, $recipientUserIds) {
  63. $notification = Notification::create([
  64. 'origin_table' => $params['origin_table'],
  65. 'origin_id' => $params['origin_id'],
  66. 'unit_id' => $params['unit_id'] ?? null,
  67. 'franchisee_id' => $params['franchisee_id'] ?? null,
  68. 'notification_type' => $params['type'],
  69. 'title' => $params['title'],
  70. 'message' => $params['message'],
  71. 'url' => $params['url'] ?? null,
  72. 'action_text' => $params['action_text'] ?? null,
  73. 'priority' => $params['priority'] ?? 'normal',
  74. 'expires_at' => $params['expires_at'] ?? null,
  75. 'created_by_user_id' => $params['created_by_user_id'] ?? null,
  76. ]);
  77. $now = now();
  78. $rows = array_map(fn ($userId) => [
  79. 'notification_id' => $notification->id,
  80. 'user_id' => $userId,
  81. 'unit_id' => $params['unit_id'] ?? null,
  82. 'franchisee_id' => $params['franchisee_id'] ?? null,
  83. 'is_read' => false,
  84. 'channel' => 'in_app',
  85. 'is_delivered' => true,
  86. 'delivered_at' => $now,
  87. 'created_at' => $now,
  88. 'updated_at' => $now,
  89. ], $recipientUserIds);
  90. NotificationRecipient::insert($rows);
  91. $this->broadcast($notification, $recipientUserIds);
  92. return $notification;
  93. });
  94. }
  95. /**
  96. * Emite um evento realtime por usuário destino (best-effort).
  97. */
  98. private function broadcast(Notification $notification, array $userIds): void
  99. {
  100. $payload = [
  101. 'id' => $notification->id,
  102. 'type' => $notification->notification_type,
  103. 'title' => $notification->title,
  104. ];
  105. foreach ($userIds as $userId) {
  106. try {
  107. event(new WebsocketEvent(WebsocketEventData::from(
  108. room: "user.{$userId}",
  109. data: $payload,
  110. event: 'notification',
  111. )));
  112. } catch (\Throwable $e) {
  113. // Realtime é complementar: nunca deve quebrar o fluxo de negócio.
  114. report($e);
  115. }
  116. }
  117. }
  118. // ------------------------------------------------------------------
  119. // Resolvers de destinatários (fan-out para todos os usuários)
  120. // ------------------------------------------------------------------
  121. /** Todos os usuários vinculados a uma unidade. */
  122. public function unitUserIds(?int $unitId): array
  123. {
  124. if (!$unitId) {
  125. return [];
  126. }
  127. return User::whereHas('units', fn ($q) => $q->where('units.id', $unitId))
  128. ->pluck('id')->all();
  129. }
  130. /** Todos os usuários da matriz (franqueadora). */
  131. public function matrizUserIds(): array
  132. {
  133. return User::where('user_type', UserTypeEnum::ADMIN->value)
  134. ->pluck('id')->all();
  135. }
  136. // ------------------------------------------------------------------
  137. // Consulta do sino (usuário logado)
  138. // ------------------------------------------------------------------
  139. public function forUser(int $userId, int $limit = 30): Collection
  140. {
  141. return Notification::query()
  142. ->select('notifications.*')
  143. ->join('notification_recipients as nr', 'nr.notification_id', '=', 'notifications.id')
  144. ->where('nr.user_id', $userId)
  145. ->where(fn ($q) => $q
  146. ->whereNull('notifications.expires_at')
  147. ->orWhere('notifications.expires_at', '>', now()))
  148. ->with(['recipients' => fn ($q) => $q->where('user_id', $userId)])
  149. ->orderByDesc('notifications.created_at')
  150. ->limit($limit)
  151. ->get();
  152. }
  153. public function unreadCount(int $userId): int
  154. {
  155. return NotificationRecipient::where('user_id', $userId)
  156. ->where('is_read', false)
  157. ->count();
  158. }
  159. public function markRead(int $notificationId, int $userId): void
  160. {
  161. NotificationRecipient::where('notification_id', $notificationId)
  162. ->where('user_id', $userId)
  163. ->where('is_read', false)
  164. ->update(['is_read' => true, 'read_at' => now()]);
  165. }
  166. public function markAllRead(int $userId): void
  167. {
  168. NotificationRecipient::where('user_id', $userId)
  169. ->where('is_read', false)
  170. ->update(['is_read' => true, 'read_at' => now()]);
  171. }
  172. }