Lae/app/Models/Workorder/Reply.php

78 lines
1.9 KiB
PHP
Raw Normal View History

2022-08-13 06:04:47 +00:00
<?php
2022-08-13 06:12:37 +00:00
namespace App\Models\WorkOrder;
2022-08-13 06:04:47 +00:00
2022-08-19 15:27:57 +00:00
use App\Exceptions\CommonException;
use App\Models\User;
2022-08-13 06:04:47 +00:00
use Illuminate\Database\Eloquent\Model;
2022-08-19 15:27:57 +00:00
use Illuminate\Database\Eloquent\Factories\HasFactory;
2022-08-13 06:04:47 +00:00
class Reply extends Model
{
use HasFactory;
2022-08-15 14:29:57 +00:00
protected $table = 'work_order_replies';
2022-08-13 06:12:37 +00:00
protected $fillable = [
'content',
'work_order_id',
2022-08-19 15:27:57 +00:00
'user_id',
2022-08-13 06:12:37 +00:00
'is_pending',
];
2022-08-15 14:29:57 +00:00
public function workOrder()
{
return $this->belongsTo(WorkOrder::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
2022-08-15 14:29:57 +00:00
public function scopeWorkOrderId($query, $work_order_id)
{
return $query->where('work_order_id', $work_order_id);
}
// before create
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
2022-08-19 15:27:57 +00:00
$model->is_pending = 1;
2022-08-15 14:29:57 +00:00
// load work order
$model->load(['workOrder']);
2022-08-19 15:27:57 +00:00
throw_if($model->workOrder->status == 'pending' || $model->workOrder->status == 'error', CommonException::class, '工单状态不正确');
2022-08-15 14:29:57 +00:00
// change work order status
if (auth('sanctum')->check()) {
$model->user_id = auth()->id();
$model->workOrder->status = 'user_replied';
}
if (auth('remote')->check()) {
$model->user_id = null;
$model->workOrder->status = 'replied';
}
$model->workOrder->save();
2022-08-19 15:27:57 +00:00
});
2022-08-15 14:29:57 +00:00
2022-08-19 15:27:57 +00:00
static::created(function ($model) {
if (auth('remote')->check()) {
$model->workOrder->status = 'replied';
$model->workOrder->save();
}
// dispatch
dispatch(new \App\Jobs\Remote\WorkOrder\Reply($model));
dispatch(new \App\Jobs\Remote\WorkOrder\WorkOrder($model->workOrder, 'put'));
2022-08-15 14:29:57 +00:00
});
}
2022-08-13 06:04:47 +00:00
}