SendMessageJob.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. /*
  3. * This file is part of the Jiannei/lumen-api-starter.
  4. *
  5. * (c) Jiannei <longjian.huang@foxmail.com>
  6. *
  7. * This source file is subject to the MIT license that is bundled
  8. * with this source code in the file LICENSE.
  9. */
  10. namespace App\Jobs\News;
  11. use App\Jobs\Job;
  12. use App\Mail\NoticeMail;
  13. use App\Repositories\Enums\News\SendStatusEnum;
  14. use App\Repositories\Enums\News\SendTypeEnum;
  15. use App\Repositories\Models\Base\Admin;
  16. use App\Repositories\Models\News\Message;
  17. use App\Repositories\Models\News\UserMessage;
  18. use Carbon\Carbon;
  19. use Illuminate\Support\Facades\Mail;
  20. class SendMessageJob extends Job
  21. {
  22. private $model;
  23. /**
  24. * Create a new job instance.
  25. */
  26. public function __construct($message_id)
  27. {
  28. $this->model = Message::query()->find($message_id);
  29. $this->delay(Carbon::parse($this->model->send_time));
  30. }
  31. /**
  32. * 确定任务应该超时的时间
  33. *
  34. * @return \DateTime
  35. */
  36. public function retryUntil()
  37. {
  38. return Carbon::now()->addHours(8);
  39. }
  40. /**
  41. * Execute the job.
  42. */
  43. public function handle()
  44. {
  45. $model = Message::query()->find($this->model->id);
  46. if (!$model) return false;
  47. if ($model->status != SendStatusEnum::wait) return false;
  48. $model->status = SendStatusEnum::sending;
  49. $model->save();
  50. $sendTypes = $model->send_type;
  51. $message = false;
  52. switch ($model->type) {
  53. case 1:
  54. $message = $model->message;
  55. break;
  56. case 2:
  57. $message = $model->resource->name;
  58. break;
  59. }
  60. $users = Admin::query()->whereIn('id', $model->user_ids)->select(['id', 'mobile', 'email'])->get();
  61. //发送消息
  62. foreach ($users as $user) {
  63. if (in_array(SendTypeEnum::system, $sendTypes)) {
  64. //系统消息通知
  65. UserMessage::query()->create([
  66. 'admin_id' => $user->id,
  67. 'message' => $message,
  68. 'type' => $model->type,
  69. 'message_id' => $model->id,
  70. 'resource_type' => $model->resource_type,
  71. 'resource_id' => $model->resource_id,
  72. ]);
  73. }
  74. if (in_array(SendTypeEnum::mail, $sendTypes)) {
  75. //邮箱通知
  76. Mail::to($user['email'])->send(new NoticeMail('消息通知', $message));
  77. }
  78. if (in_array(SendTypeEnum::sms, $sendTypes)) {
  79. //短信
  80. }
  81. }
  82. $model->status = SendStatusEnum::ok;
  83. $model->save();
  84. return true;
  85. }
  86. }