| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406 |
- <?php
- namespace App\Module\Cleanup\Models;
- use App\Module\Cleanup\Enums\TASK_STATUS;
- use UCore\ModelCore;
- use Illuminate\Database\Eloquent\Relations\BelongsTo;
- use Illuminate\Database\Eloquent\Relations\HasMany;
- /**
- * 清理任务模型
- *
- * 存储清理任务的执行信息和状态,即执行某个计划的具体实例
- */
- class CleanupTask extends ModelCore
- {
- /**
- * 数据表名
- */
- protected $table = 'cleanup_tasks';
- // field start
- /**
- * 可批量赋值的字段
- */
- protected $fillable = [
- 'task_name',
- 'plan_id',
- 'backup_id',
- 'status',
- 'progress',
- 'current_step',
- 'total_tables',
- 'processed_tables',
- 'total_records',
- 'deleted_records',
- 'backup_size',
- 'execution_time',
- 'backup_time',
- 'started_at',
- 'backup_completed_at',
- 'completed_at',
- 'error_message',
- 'created_by',
- ];
- // field end
- /**
- * 字段类型转换
- */
- protected $casts = [
- 'plan_id' => 'integer',
- 'backup_id' => 'integer',
- 'status' => 'integer',
- 'progress' => 'decimal:2',
- 'total_tables' => 'integer',
- 'processed_tables' => 'integer',
- 'total_records' => 'integer',
- 'deleted_records' => 'integer',
- 'backup_size' => 'integer',
- 'execution_time' => 'decimal:3',
- 'backup_time' => 'decimal:3',
- 'created_by' => 'integer',
- 'started_at' => 'datetime',
- 'backup_completed_at' => 'datetime',
- 'completed_at' => 'datetime',
- 'created_at' => 'datetime',
- 'updated_at' => 'datetime',
- ];
- /**
- * 获取任务状态枚举
- */
- public function getStatusEnumAttribute(): TASK_STATUS
- {
- return TASK_STATUS::from($this->status);
- }
- /**
- * 获取任务状态描述
- */
- public function getStatusNameAttribute(): string
- {
- return $this->getStatusEnumAttribute()->getDescription();
- }
- /**
- * 获取任务状态颜色
- */
- public function getStatusColorAttribute(): string
- {
- return $this->getStatusEnumAttribute()->getColor();
- }
- /**
- * 获取任务状态图标
- */
- public function getStatusIconAttribute(): string
- {
- return $this->getStatusEnumAttribute()->getIcon();
- }
- /**
- * 判断任务是否正在运行
- */
- public function getIsRunningAttribute(): bool
- {
- return $this->getStatusEnumAttribute()->isRunning();
- }
- /**
- * 判断任务是否已完成
- */
- public function getIsFinishedAttribute(): bool
- {
- return $this->getStatusEnumAttribute()->isFinished();
- }
- /**
- * 判断任务是否可以执行
- */
- public function getCanExecuteAttribute(): bool
- {
- return $this->getStatusEnumAttribute()->canExecute();
- }
- /**
- * 判断任务是否可以取消
- */
- public function getCanCancelAttribute(): bool
- {
- return $this->getStatusEnumAttribute()->canCancel();
- }
- /**
- * 判断任务是否可以暂停
- */
- public function getCanPauseAttribute(): bool
- {
- return $this->getStatusEnumAttribute()->canPause();
- }
- /**
- * 判断任务是否可以恢复
- */
- public function getCanResumeAttribute(): bool
- {
- return $this->getStatusEnumAttribute()->canResume();
- }
- /**
- * 获取进度百分比文本
- */
- public function getProgressTextAttribute(): string
- {
- return number_format($this->progress, 2) . '%';
- }
- /**
- * 获取进度条颜色
- */
- public function getProgressColorAttribute(): string
- {
- if ($this->progress >= 100) {
- return 'success';
- } elseif ($this->progress >= 50) {
- return 'primary';
- } elseif ($this->progress >= 25) {
- return 'warning';
- } else {
- return 'info';
- }
- }
- /**
- * 获取格式化的备份大小
- */
- public function getBackupSizeFormattedAttribute(): string
- {
- return $this->formatBytes($this->backup_size);
- }
- /**
- * 获取格式化的执行时间
- */
- public function getExecutionTimeFormattedAttribute(): string
- {
- return $this->formatDuration($this->execution_time);
- }
- /**
- * 获取格式化的备份时间
- */
- public function getBackupTimeFormattedAttribute(): string
- {
- return $this->formatDuration($this->backup_time);
- }
- /**
- * 获取总执行时间
- */
- public function getTotalTimeAttribute(): float
- {
- return $this->execution_time + $this->backup_time;
- }
- /**
- * 获取格式化的总执行时间
- */
- public function getTotalTimeFormattedAttribute(): string
- {
- return $this->formatDuration($this->total_time);
- }
- /**
- * 获取删除记录的百分比
- */
- public function getDeletedPercentageAttribute(): float
- {
- if ($this->total_records == 0) {
- return 0;
- }
- return ($this->deleted_records / $this->total_records) * 100;
- }
- /**
- * 获取处理表的百分比
- */
- public function getProcessedPercentageAttribute(): float
- {
- if ($this->total_tables == 0) {
- return 0;
- }
- return ($this->processed_tables / $this->total_tables) * 100;
- }
- /**
- * 获取任务持续时间
- */
- public function getDurationAttribute(): ?float
- {
- if (!$this->started_at) {
- return null;
- }
- $endTime = $this->completed_at ?? now();
- return $this->started_at->diffInSeconds($endTime);
- }
- /**
- * 获取格式化的任务持续时间
- */
- public function getDurationFormattedAttribute(): ?string
- {
- $duration = $this->duration;
- return $duration ? $this->formatDuration($duration) : null;
- }
- /**
- * 关联清理计划
- */
- public function plan(): BelongsTo
- {
- return $this->belongsTo(CleanupPlan::class, 'plan_id');
- }
- /**
- * 关联备份记录
- */
- public function backup(): BelongsTo
- {
- return $this->belongsTo(CleanupBackup::class, 'backup_id');
- }
- /**
- * 关联清理日志
- */
- public function logs(): HasMany
- {
- return $this->hasMany(CleanupLog::class, 'task_id');
- }
- /**
- * 作用域:按计划筛选
- */
- public function scopeByPlan($query, int $planId)
- {
- return $query->where('plan_id', $planId);
- }
- /**
- * 作用域:按状态筛选
- */
- public function scopeByStatus($query, int $status)
- {
- return $query->where('status', $status);
- }
- /**
- * 作用域:正在运行的任务
- */
- public function scopeRunning($query)
- {
- return $query->whereIn('status', TASK_STATUS::getRunningStatuses());
- }
- /**
- * 作用域:已完成的任务
- */
- public function scopeFinished($query)
- {
- return $query->whereIn('status', TASK_STATUS::getFinishedStatuses());
- }
- /**
- * 作用域:按创建者筛选
- */
- public function scopeByCreator($query, int $createdBy)
- {
- return $query->where('created_by', $createdBy);
- }
- /**
- * 作用域:按任务名称搜索
- */
- public function scopeSearchName($query, string $search)
- {
- return $query->where('task_name', 'like', "%{$search}%");
- }
- /**
- * 作用域:最近的任务
- */
- public function scopeRecent($query, int $days = 7)
- {
- return $query->where('created_at', '>=', now()->subDays($days));
- }
- /**
- * 格式化字节大小
- */
- private function formatBytes(int $bytes): string
- {
- if ($bytes == 0) {
- return '0 B';
- }
- $units = ['B', 'KB', 'MB', 'GB', 'TB'];
- $i = floor(log($bytes, 1024));
- return round($bytes / pow(1024, $i), 2) . ' ' . $units[$i];
- }
- /**
- * 格式化持续时间
- */
- private function formatDuration(float $seconds): string
- {
- if ($seconds < 60) {
- return number_format($seconds, 2) . ' 秒';
- } elseif ($seconds < 3600) {
- return number_format($seconds / 60, 2) . ' 分钟';
- } else {
- return number_format($seconds / 3600, 2) . ' 小时';
- }
- }
- /**
- * 获取任务状态统计
- */
- public static function getStatusStats(): array
- {
- $stats = static::selectRaw('status, COUNT(*) as count')
- ->groupBy('status')
- ->get()
- ->keyBy('status')
- ->toArray();
- $result = [];
- foreach (TASK_STATUS::cases() as $status) {
- $result[$status->value] = [
- 'name' => $status->getDescription(),
- 'count' => $stats[$status->value]['count'] ?? 0,
- 'color' => $status->getColor(),
- 'icon' => $status->getIcon(),
- ];
- }
- return $result;
- }
- /**
- * 获取最近任务统计
- */
- public static function getRecentStats(int $days = 7): array
- {
- $query = static::where('created_at', '>=', now()->subDays($days));
- return [
- 'total' => $query->count(),
- 'completed' => $query->clone()->where('status', TASK_STATUS::COMPLETED->value)->count(),
- 'failed' => $query->clone()->where('status', TASK_STATUS::FAILED->value)->count(),
- 'running' => $query->clone()->whereIn('status', TASK_STATUS::getRunningStatuses())->count(),
- ];
- }
- }
|