128 lines
2.8 KiB
PHP
128 lines
2.8 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
|
|
class PrintJob extends Model
|
|
{
|
|
use HasFactory;
|
|
|
|
protected $fillable = [
|
|
'user_id',
|
|
'job_no',
|
|
'order_id',
|
|
'platform',
|
|
'plugin_code',
|
|
'template_id',
|
|
'print_data',
|
|
'status',
|
|
'priority',
|
|
'retry_count',
|
|
'error_message',
|
|
'printed_by',
|
|
'print_start_time',
|
|
'print_end_time',
|
|
];
|
|
|
|
protected $casts = [
|
|
'print_data' => 'array',
|
|
'priority' => 'integer',
|
|
'retry_count' => 'integer',
|
|
'print_start_time' => 'datetime',
|
|
'print_end_time' => 'datetime',
|
|
];
|
|
|
|
public const STATUS_PENDING = 'pending';
|
|
public const STATUS_QUEUED = 'queued';
|
|
public const STATUS_PRINTING = 'printing';
|
|
public const STATUS_COMPLETED = 'completed';
|
|
public const STATUS_FAILED = 'failed';
|
|
public const STATUS_CANCELLED = 'cancelled';
|
|
|
|
public const MAX_RETRY = 3;
|
|
|
|
public function user(): BelongsTo
|
|
{
|
|
return $this->belongsTo(User::class);
|
|
}
|
|
|
|
public function order(): BelongsTo
|
|
{
|
|
return $this->belongsTo(Order::class, 'order_id');
|
|
}
|
|
|
|
public function template(): BelongsTo
|
|
{
|
|
return $this->belongsTo(Template::class, 'template_id');
|
|
}
|
|
|
|
/**
|
|
* 生成任务编号
|
|
*/
|
|
public static function generateJobNo(): string
|
|
{
|
|
return 'PJ' . date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
|
|
}
|
|
|
|
/**
|
|
* 检查是否可以重试
|
|
*/
|
|
public function canRetry(): bool
|
|
{
|
|
return $this->status === self::STATUS_FAILED && $this->retry_count < self::MAX_RETRY;
|
|
}
|
|
|
|
/**
|
|
* 标记为打印中
|
|
*/
|
|
public function markAsPrinting(): void
|
|
{
|
|
$this->update([
|
|
'status' => self::STATUS_PRINTING,
|
|
'print_start_time' => now(),
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* 标记为完成
|
|
*/
|
|
public function markAsCompleted(): void
|
|
{
|
|
$this->update([
|
|
'status' => self::STATUS_COMPLETED,
|
|
'print_end_time' => now(),
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* 标记为失败
|
|
*/
|
|
public function markAsFailed(string $error): void
|
|
{
|
|
$this->update([
|
|
'status' => self::STATUS_FAILED,
|
|
'error_message' => $error,
|
|
'retry_count' => $this->retry_count + 1,
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* 加入打印队列
|
|
*/
|
|
public function queue(): void
|
|
{
|
|
$this->update(['status' => self::STATUS_QUEUED]);
|
|
}
|
|
|
|
/**
|
|
* 取消任务
|
|
*/
|
|
public function cancel(): void
|
|
{
|
|
$this->update(['status' => self::STATUS_CANCELLED]);
|
|
}
|
|
}
|