123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120 |
- <?php
- /*
- * This file is part of the Jiannei/lumen-api-starter.
- *
- * (c) Jiannei <longjian.huang@foxmail.com>
- *
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
- */
- namespace App\Jobs\Base;
- use App\Jobs\Job;
- use App\Mail\NoticeMail;
- use App\Repositories\Enums\ModelStatusEnum;
- use App\Repositories\Models\Base\Admin;
- use App\Repositories\Models\Base\Message;
- use App\Repositories\Models\Base\UserMessage;
- use Carbon\Carbon;
- use Illuminate\Support\Facades\Mail;
- class SendMessageJob extends Job
- {
- private $send_tag;
- /**
- * Create a new job instance.
- */
- public function __construct($send_tag)
- {
- $this->send_tag = $send_tag;
- }
- /**
- * 确定任务应该超时的时间
- *
- * @return \DateTime
- */
- public function retryUntil()
- {
- return Carbon::now()->addHours(8);
- }
- /**
- * Execute the job.
- */
- public function handle()
- {
- $model = Message::query()->where('send_tag', $this->send_tag)->first();
- if (!$model) return true;
- if ($model->status == ModelStatusEnum::PAUSE) {
- $model->send_status = Message::SEND_STATUS_ERROR;
- $model->send_time = Carbon::now()->toDateTimeString();
- $model->result = [
- 'msg' => '任务已经暂停'
- ];
- $model->save();
- return true;
- }
- $model->send_status = Message::SEND_STATUS_EXECUTE;
- $model->send_time = Carbon::now()->toDateTimeString();
- $model->save();
- $users = Admin::query()->whereIn('id', array_column($model->users, 'id'))->where('status', ModelStatusEnum::OK)->select(['id', 'name', 'mobile', 'email'])->get();
- $sendTypes = $model->send_type;
- try {
- if (in_array(Message::SEND_TYPE_SITE, $sendTypes)) {
- //站内信
- $this->sendSiteMsg($model, $users);
- }
- if (in_array(Message::SEND_TYPE_MAIL, $sendTypes)) {
- //邮件
- $this->sendMailMsg($model, $users);
- }
- } catch (\Exception $exception) {
- $model->send_status = Message::SEND_STATUS_ERROR;
- $model->send_time = Carbon::now()->toDateTimeString();
- $model->result = [
- 'msg' => $exception->getMessage(),
- 'data' => $exception
- ];
- $model->save();
- return true;
- }
- $model->send_status = Message::SEND_STATUS_COMPLETE;
- $model->save();
- return true;
- }
- private function sendSiteMsg($model, $users = [])
- {
- foreach ($users as $user) {
- UserMessage::query()->create([
- 'user_id' => $user->id,
- 'user_type' => get_class($user),
- 'name' => $model['name'],
- 'body' => $model['body'],
- 'type' => $model['type'],
- 'source_type' => get_class($model),
- 'source_id' => $model['id'],
- ]);
- }
- }
- private function sendMailMsg($model, $users = [])
- {
- foreach ($users as $user) {
- if (!empty($user->email)) {
- Mail::to($user['email'])->send(new NoticeMail($model->title, $model->body));
- }
- }
- }
- }
|