SendActionBrowserNotification.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. namespace App\Listeners;
  3. use App\Events\ObjectActionCreate;
  4. use App\Models\Enums\ActionObjectType;
  5. use App\Models\Enums\NotificationObjectType;
  6. use App\Models\Enums\ObjectAction;
  7. use App\Models\Notification;
  8. use App\Models\NotificationRecord;
  9. use Illuminate\Contracts\Queue\ShouldQueue;
  10. use Illuminate\Queue\InteractsWithQueue;
  11. class SendActionBrowserNotification implements ShouldQueue
  12. {
  13. /**
  14. * Create the event listener.
  15. */
  16. public function __construct()
  17. {
  18. //
  19. }
  20. /**
  21. * Handle the event.
  22. */
  23. public function handle(ObjectActionCreate $event): void
  24. {
  25. $actionObjectType = ActionObjectType::tryFrom($event->action->object_type);
  26. $object = $actionObjectType->modelBuilder()->find($event->action->object_id);
  27. if (! $object) {
  28. return;
  29. }
  30. $userIds = match ($actionObjectType) {
  31. ActionObjectType::TASK => $object->assign > 0 ? [$object->assign] : [],
  32. default => [],
  33. };
  34. if (! $userIds) {
  35. return;
  36. }
  37. $notification = Notification::query()->create([
  38. 'object_type' => NotificationObjectType::ACTION->value,
  39. 'object_id' => $event->action->id,
  40. ]);
  41. foreach ($userIds as $userId) {
  42. NotificationRecord::query()->create([
  43. 'notification_id' => $notification->id,
  44. 'user_id' => $userId,
  45. ]);
  46. }
  47. }
  48. public function shouldQueue(ObjectActionCreate $event): bool
  49. {
  50. $actionObjectType = ActionObjectType::tryFrom($event->action->object_type);
  51. $objectAction = ObjectAction::tryFrom($event->action->action);
  52. if (! $actionObjectType || !$objectAction) {
  53. return false;
  54. }
  55. return in_array($objectAction->value, $event->notificationSetting[$actionObjectType->value]['email'] ?? []);
  56. }
  57. }