You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

93 lines
2.7 KiB

  1. <?php
  2. namespace App\Listeners;
  3. use App\Events\ProjectUserCreate;
  4. use App\Models\Project;
  5. use App\Models\User;
  6. use App\Notifications\DBNotification;
  7. use App\Notifications\FcmNotification;
  8. use App\Notifications\MailNotification;
  9. use Illuminate\Contracts\Queue\ShouldQueue;
  10. use Illuminate\Queue\InteractsWithQueue;
  11. use Illuminate\Support\Facades\Notification;
  12. class ProjectUserCreateNotif
  13. {
  14. /**
  15. * Create the event listener.
  16. *
  17. * @return void
  18. */
  19. public function __construct()
  20. {
  21. //
  22. }
  23. /**
  24. * Handle the event.
  25. *
  26. * @param ProjectUserCreate $event
  27. * @return void
  28. */
  29. public function handle(ProjectUserCreate $event)
  30. {
  31. $payload = $event->message;
  32. $new_user = User::findOrFail($payload->data->original->user_id);
  33. $project = Project::findOrFail($payload->data->original->project_id);
  34. $owners_id = request('_business_info')['info']['projects'][$project->id]['members']->reject(function ($item, $key) use ($new_user) {
  35. return $item['level'] < enum('levels.owner.id') || $key === $new_user->id;
  36. })->toArray();
  37. $owners = User::whereIn('id', array_keys($owners_id))->get();
  38. $notif = $this->makeNotif($payload,['project' => $project->name, 'user' => $new_user->name]);
  39. $users = $owners->prepend($new_user);
  40. $this->sendNotifications($users, $notif);
  41. }
  42. /**
  43. * Make notification object
  44. *
  45. * @param $payload
  46. * @param array $options
  47. * @return array
  48. */
  49. public function makeNotif($payload, $options = []) {
  50. return [
  51. 'greeting' => $this->getMessageLine($payload, 'greeting'),
  52. 'subject' => $this->getMessageLine($payload, 'subject'),
  53. 'title' => $this->getMessageLine($payload, 'title'),
  54. 'body' => $this->getMessageLine($payload, 'body', $options)
  55. ];
  56. }
  57. /**
  58. * Fetch message from notifications lang file
  59. *
  60. * @param $payload
  61. * @param $key
  62. * @param null $options
  63. * @return array|\Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Translation\Translator|string|null
  64. *
  65. */
  66. public function getMessageLine($payload, $key, $options = [])
  67. {
  68. return __('notification.'.$payload->data->table_name.'.'.enum('cruds.inverse.'.$payload->data->crud_id.'.singular_name').'.'.$key, $options);
  69. }
  70. /**
  71. * Call notifications
  72. *
  73. * @param $users
  74. * @param $notif
  75. */
  76. public function sendNotifications($users, $notif) {
  77. Notification::send($users, new MailNotification($notif));
  78. Notification::send($users, new DBNotification($notif));
  79. Notification::send($users, new FcmNotification($notif));
  80. }
  81. }