NotificationService.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. namespace App\Services;
  3. use App\Enums\NotificationRecipientEnum;
  4. use App\Enums\UserTypeEnum;
  5. use App\Models\Notification;
  6. use App\Models\NotificationSend;
  7. use App\Models\User;
  8. use Illuminate\Database\Eloquent\Collection;
  9. use Illuminate\Support\Facades\Auth;
  10. use Illuminate\Support\Facades\DB;
  11. class NotificationService
  12. {
  13. public function getAll(): Collection
  14. {
  15. return Notification::with('createdBy')->orderBy('created_at', 'desc')->get();
  16. }
  17. public function findById(int $id): ?Notification
  18. {
  19. return Notification::with(['createdBy', 'sends'])->find($id);
  20. }
  21. public function create(array $data): Notification
  22. {
  23. return DB::transaction(function () use ($data) {
  24. $data['created_by'] = Auth::id();
  25. $notification = Notification::create($data);
  26. $this->dispatchSends($notification);
  27. return $notification;
  28. });
  29. }
  30. public function getUnreadByUser(int $userId): Collection
  31. {
  32. return NotificationSend::with('notification')
  33. ->where('user_id', $userId)
  34. ->where('read', false)
  35. ->orderBy('created_at', 'desc')
  36. ->get();
  37. }
  38. public function markAsRead(int $sendId, int $userId): bool
  39. {
  40. $send = NotificationSend::where('id', $sendId)
  41. ->where('user_id', $userId)
  42. ->first();
  43. if (!$send) {
  44. return false;
  45. }
  46. $send->update(['read' => true, 'read_at' => now()]);
  47. return true;
  48. }
  49. public function delete(int $id): bool
  50. {
  51. $model = Notification::find($id);
  52. if (!$model) {
  53. return false;
  54. }
  55. return $model->delete();
  56. }
  57. private function dispatchSends(Notification $notification): void
  58. {
  59. $query = User::query();
  60. match ($notification->recipient) {
  61. NotificationRecipientEnum::ASSOCIADO => $query->where('type', UserTypeEnum::ASSOCIADO->value),
  62. NotificationRecipientEnum::PARCEIRO => $query->where('type', UserTypeEnum::PARCEIRO->value),
  63. default => null,
  64. };
  65. if ($notification->recipient_position) {
  66. $query->whereHas('position', fn($q) => $q->where('name', $notification->recipient_position));
  67. }
  68. if ($notification->recipient_sector) {
  69. $query->whereHas('sector', fn($q) => $q->where('name', $notification->recipient_sector));
  70. }
  71. $users = $query->pluck('id');
  72. $sends = $users->map(fn($userId) => [
  73. 'notification_id' => $notification->id,
  74. 'user_id' => $userId,
  75. 'read' => false,
  76. 'created_at' => now(),
  77. 'updated_at' => now(),
  78. ])->toArray();
  79. NotificationSend::insert($sends);
  80. }
  81. }