EmailSendJob.php 2.3 KB
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 邮件发送任务
 * @author:dc
 * @time 2022/11/9 11:17
 * Class EmailSendJob
 * @package App\Http\Mail\Models
 */
class EmailSendJob extends Model{

    const STATUS_RUNING =   1;
    const STATUS_WAIT   =   0;
    const STATUS_SUCCESS   =   2;

    const STATUS_DISCARD   =   3;



    /**
     * 新增一个job
     * @param $data
     * @return false|mixed
     * @throws \Throwable
     * @author:dc
     * @time 2022/11/9 11:34
     */
    public static function _insert($data){
        $model = new static();

        $model->email_id = $data['email_id'];// 发送邮件的id,好像要随机发送
        $model->the_manage_id = $data['the_manage_id'];
        $model->user_id = $data['user_id'];
        if(isset($data['data']['to'])){unset($data['data']['to']);}
        $model->maildata = json_encode($data['data']);
        $model->title = $data['title'];
        $model->total = sizeof($data['to']);
        $model->send_time = $data['send_time']; // 发送时间
        $model->tags = implode(',',$data['tags']??[]); // tag标签
        DB::beginTransaction();
        if($model->save()){
            foreach ($data['to'] as $email){
                $id = EmailSendJobStatu::insertGetId([
                    'job_id'    =>  $model->id,
                    'to_email'  =>  $email['email'],
                    'status'    =>  0,
                    'created_at'    =>  date('Y-m-d H:i:s')
                ]);
                if(!$id){
                    DB::rollBack();
                    return false;
                }
            }
            DB::commit();
            return $model->id;
        }
        DB::rollBack();
        return false;
    }


    public function getStatusTextAttribute($key)
    {
        switch ($this->status){
            case self::STATUS_WAIT:{
                return '等待中';
            }
            case self::STATUS_RUNING:{
                return '发送中';
            }
            case self::STATUS_SUCCESS:{
                return '已完成';
            }
            case self::STATUS_DISCARD:{
                return '废弃';
            }
        }
        return '';
    }
}