PushNotificationService.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace App\Services;
  3. use App\Models\DeviceToken;
  4. use App\Models\PushNotificationLog;
  5. use App\Models\User;
  6. use App\Notifications\Push\BasePushNotification;
  7. use Illuminate\Support\Collection;
  8. use Kreait\Firebase\Contract\Messaging;
  9. use Kreait\Firebase\Messaging\AndroidConfig;
  10. use Kreait\Firebase\Messaging\CloudMessage;
  11. use Kreait\Firebase\Messaging\Notification;
  12. class PushNotificationService
  13. {
  14. public function __construct(private Messaging $messaging) {}
  15. /**
  16. * Envia uma push notification para todos os tokens ativos de um usuário.
  17. * Registra o envio no log e desativa tokens inválidos automaticamente.
  18. */
  19. public function sendToUser(User $user, BasePushNotification $notification): void
  20. {
  21. if (! $user->push_notifications_enabled) {
  22. return;
  23. }
  24. $tokens = DeviceToken::where('user_id', $user->id)
  25. ->where('app_type', $notification->target()->value)
  26. ->where('active', true)
  27. ->pluck('token')
  28. ->toArray();
  29. if (empty($tokens)) {
  30. return;
  31. }
  32. $message = CloudMessage::new()
  33. ->withNotification(
  34. Notification::create(
  35. $notification->title(),
  36. $notification->body()
  37. )
  38. )
  39. ->withAndroidConfig(AndroidConfig::fromArray([
  40. 'notification' => ['channel_id' => 'diaria'],
  41. 'priority' => 'high',
  42. ]));
  43. $report = $this->messaging->sendMulticast($message, $tokens);
  44. $this->deactivateInvalidTokens($report->invalidTokens());
  45. if ($report->successes()->count() > 0) {
  46. $this->log($user, $notification);
  47. }
  48. }
  49. /**
  50. * Envia para uma coleção de usuários, respeitando cooldowns.
  51. * Usuários sem tokens ativos são ignorados silenciosamente.
  52. */
  53. public function sendToUsers(Collection $users, BasePushNotification $notification): void
  54. {
  55. foreach ($users as $user) {
  56. $this->sendToUser($user, $notification);
  57. }
  58. }
  59. //
  60. private function deactivateInvalidTokens(array $tokens): void
  61. {
  62. if (empty($tokens)) {
  63. return;
  64. }
  65. DeviceToken::whereIn('token', $tokens)->update(['active' => false]);
  66. }
  67. private function log(User $user, BasePushNotification $notification): void
  68. {
  69. PushNotificationLog::create([
  70. 'label' => $notification->label(),
  71. 'user_id' => $user->id,
  72. 'target' => $notification->target()->value,
  73. 'category' => $notification->category()->value,
  74. 'sent_at' => now(),
  75. ]);
  76. }
  77. }