CleanupTask.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. <?php
  2. namespace App\Module\Cleanup\Models;
  3. use App\Module\Cleanup\Enums\TASK_STATUS;
  4. use UCore\ModelCore;
  5. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  6. use Illuminate\Database\Eloquent\Relations\HasMany;
  7. /**
  8. * 清理任务模型
  9. *
  10. * 存储清理任务的执行信息和状态,即执行某个计划的具体实例
  11. */
  12. class CleanupTask extends ModelCore
  13. {
  14. /**
  15. * 数据表名
  16. */
  17. protected $table = 'cleanup_tasks';
  18. // field start
  19. * @property int $id 主键ID
  20. * @property string $task_name 任务名称
  21. * @property int $plan_id 关联的清理计划ID
  22. * @property int $backup_id 关联的备份ID
  23. * @property int $status 任务状态:1待执行,2备份中,3执行中,4已完成,5已失败,6已取消,7已暂停
  24. * @property float $progress 执行进度百分比
  25. * @property string $current_step 当前执行步骤
  26. * @property int $total_tables 总表数
  27. * @property int $processed_tables 已处理表数
  28. * @property int $total_records 总记录数
  29. * @property int $deleted_records 已删除记录数
  30. * @property int $backup_size 备份文件大小(字节)
  31. * @property float $execution_time 执行时间(秒)
  32. * @property float $backup_time 备份时间(秒)
  33. * @property \Carbon\Carbon $started_at 开始时间
  34. * @property \Carbon\Carbon $backup_completed_at 备份完成时间
  35. * @property \Carbon\Carbon $completed_at 完成时间
  36. * @property string $error_message 错误信息
  37. * @property int $created_by 创建者用户ID
  38. * @property \Carbon\Carbon $created_at 创建时间
  39. * @property \Carbon\Carbon $updated_at 更新时间
  40. * field end
  41. /**
  42. * 字段类型转换
  43. */
  44. protected $casts = [
  45. 'plan_id' => 'integer',
  46. 'backup_id' => 'integer',
  47. 'status' => 'integer',
  48. 'progress' => 'decimal:2',
  49. 'total_tables' => 'integer',
  50. 'processed_tables' => 'integer',
  51. 'total_records' => 'integer',
  52. 'deleted_records' => 'integer',
  53. 'backup_size' => 'integer',
  54. 'execution_time' => 'decimal:3',
  55. 'backup_time' => 'decimal:3',
  56. 'created_by' => 'integer',
  57. 'started_at' => 'datetime',
  58. 'backup_completed_at' => 'datetime',
  59. 'completed_at' => 'datetime',
  60. 'created_at' => 'datetime',
  61. 'updated_at' => 'datetime',
  62. ];
  63. /**
  64. * 获取任务状态枚举
  65. */
  66. public function getStatusEnumAttribute(): TASK_STATUS
  67. {
  68. return TASK_STATUS::from($this->status);
  69. }
  70. /**
  71. * 获取任务状态描述
  72. */
  73. public function getStatusNameAttribute(): string
  74. {
  75. return $this->getStatusEnumAttribute()->getDescription();
  76. }
  77. /**
  78. * 获取任务状态颜色
  79. */
  80. public function getStatusColorAttribute(): string
  81. {
  82. return $this->getStatusEnumAttribute()->getColor();
  83. }
  84. /**
  85. * 获取任务状态图标
  86. */
  87. public function getStatusIconAttribute(): string
  88. {
  89. return $this->getStatusEnumAttribute()->getIcon();
  90. }
  91. /**
  92. * 判断任务是否正在运行
  93. */
  94. public function getIsRunningAttribute(): bool
  95. {
  96. return $this->getStatusEnumAttribute()->isRunning();
  97. }
  98. /**
  99. * 判断任务是否已完成
  100. */
  101. public function getIsFinishedAttribute(): bool
  102. {
  103. return $this->getStatusEnumAttribute()->isFinished();
  104. }
  105. /**
  106. * 判断任务是否可以执行
  107. */
  108. public function getCanExecuteAttribute(): bool
  109. {
  110. return $this->getStatusEnumAttribute()->canExecute();
  111. }
  112. /**
  113. * 判断任务是否可以取消
  114. */
  115. public function getCanCancelAttribute(): bool
  116. {
  117. return $this->getStatusEnumAttribute()->canCancel();
  118. }
  119. /**
  120. * 判断任务是否可以暂停
  121. */
  122. public function getCanPauseAttribute(): bool
  123. {
  124. return $this->getStatusEnumAttribute()->canPause();
  125. }
  126. /**
  127. * 判断任务是否可以恢复
  128. */
  129. public function getCanResumeAttribute(): bool
  130. {
  131. return $this->getStatusEnumAttribute()->canResume();
  132. }
  133. /**
  134. * 获取进度百分比文本
  135. */
  136. public function getProgressTextAttribute(): string
  137. {
  138. return number_format($this->progress, 2) . '%';
  139. }
  140. /**
  141. * 获取进度条颜色
  142. */
  143. public function getProgressColorAttribute(): string
  144. {
  145. if ($this->progress >= 100) {
  146. return 'success';
  147. } elseif ($this->progress >= 50) {
  148. return 'primary';
  149. } elseif ($this->progress >= 25) {
  150. return 'warning';
  151. } else {
  152. return 'info';
  153. }
  154. }
  155. /**
  156. * 获取格式化的备份大小
  157. */
  158. public function getBackupSizeFormattedAttribute(): string
  159. {
  160. return $this->formatBytes($this->backup_size);
  161. }
  162. /**
  163. * 获取格式化的执行时间
  164. */
  165. public function getExecutionTimeFormattedAttribute(): string
  166. {
  167. return $this->formatDuration($this->execution_time);
  168. }
  169. /**
  170. * 获取格式化的备份时间
  171. */
  172. public function getBackupTimeFormattedAttribute(): string
  173. {
  174. return $this->formatDuration($this->backup_time);
  175. }
  176. /**
  177. * 获取总执行时间
  178. */
  179. public function getTotalTimeAttribute(): float
  180. {
  181. return $this->execution_time + $this->backup_time;
  182. }
  183. /**
  184. * 获取格式化的总执行时间
  185. */
  186. public function getTotalTimeFormattedAttribute(): string
  187. {
  188. return $this->formatDuration($this->total_time);
  189. }
  190. /**
  191. * 获取删除记录的百分比
  192. */
  193. public function getDeletedPercentageAttribute(): float
  194. {
  195. if ($this->total_records == 0) {
  196. return 0;
  197. }
  198. return ($this->deleted_records / $this->total_records) * 100;
  199. }
  200. /**
  201. * 获取处理表的百分比
  202. */
  203. public function getProcessedPercentageAttribute(): float
  204. {
  205. if ($this->total_tables == 0) {
  206. return 0;
  207. }
  208. return ($this->processed_tables / $this->total_tables) * 100;
  209. }
  210. /**
  211. * 获取任务持续时间
  212. */
  213. public function getDurationAttribute(): ?float
  214. {
  215. if (!$this->started_at) {
  216. return null;
  217. }
  218. $endTime = $this->completed_at ?? now();
  219. return $this->started_at->diffInSeconds($endTime);
  220. }
  221. /**
  222. * 获取格式化的任务持续时间
  223. */
  224. public function getDurationFormattedAttribute(): ?string
  225. {
  226. $duration = $this->duration;
  227. return $duration ? $this->formatDuration($duration) : null;
  228. }
  229. /**
  230. * 关联清理计划
  231. */
  232. public function plan(): BelongsTo
  233. {
  234. return $this->belongsTo(CleanupPlan::class, 'plan_id');
  235. }
  236. /**
  237. * 关联备份记录
  238. */
  239. public function backup(): BelongsTo
  240. {
  241. return $this->belongsTo(CleanupBackup::class, 'backup_id');
  242. }
  243. /**
  244. * 关联清理日志
  245. */
  246. public function logs(): HasMany
  247. {
  248. return $this->hasMany(CleanupLog::class, 'task_id');
  249. }
  250. /**
  251. * 作用域:按计划筛选
  252. */
  253. public function scopeByPlan($query, int $planId)
  254. {
  255. return $query->where('plan_id', $planId);
  256. }
  257. /**
  258. * 作用域:按状态筛选
  259. */
  260. public function scopeByStatus($query, int $status)
  261. {
  262. return $query->where('status', $status);
  263. }
  264. /**
  265. * 作用域:正在运行的任务
  266. */
  267. public function scopeRunning($query)
  268. {
  269. return $query->whereIn('status', TASK_STATUS::getRunningStatuses());
  270. }
  271. /**
  272. * 作用域:已完成的任务
  273. */
  274. public function scopeFinished($query)
  275. {
  276. return $query->whereIn('status', TASK_STATUS::getFinishedStatuses());
  277. }
  278. /**
  279. * 作用域:按创建者筛选
  280. */
  281. public function scopeByCreator($query, int $createdBy)
  282. {
  283. return $query->where('created_by', $createdBy);
  284. }
  285. /**
  286. * 作用域:按任务名称搜索
  287. */
  288. public function scopeSearchName($query, string $search)
  289. {
  290. return $query->where('task_name', 'like', "%{$search}%");
  291. }
  292. /**
  293. * 作用域:最近的任务
  294. */
  295. public function scopeRecent($query, int $days = 7)
  296. {
  297. return $query->where('created_at', '>=', now()->subDays($days));
  298. }
  299. /**
  300. * 格式化字节大小
  301. */
  302. private function formatBytes(int $bytes): string
  303. {
  304. if ($bytes == 0) {
  305. return '0 B';
  306. }
  307. $units = ['B', 'KB', 'MB', 'GB', 'TB'];
  308. $i = floor(log($bytes, 1024));
  309. return round($bytes / pow(1024, $i), 2) . ' ' . $units[$i];
  310. }
  311. /**
  312. * 格式化持续时间
  313. */
  314. private function formatDuration(float $seconds): string
  315. {
  316. if ($seconds < 60) {
  317. return number_format($seconds, 2) . ' 秒';
  318. } elseif ($seconds < 3600) {
  319. return number_format($seconds / 60, 2) . ' 分钟';
  320. } else {
  321. return number_format($seconds / 3600, 2) . ' 小时';
  322. }
  323. }
  324. /**
  325. * 获取任务状态统计
  326. */
  327. public static function getStatusStats(): array
  328. {
  329. $stats = static::selectRaw('status, COUNT(*) as count')
  330. ->groupBy('status')
  331. ->get()
  332. ->keyBy('status')
  333. ->toArray();
  334. $result = [];
  335. foreach (TASK_STATUS::cases() as $status) {
  336. $result[$status->value] = [
  337. 'name' => $status->getDescription(),
  338. 'count' => $stats[$status->value]['count'] ?? 0,
  339. 'color' => $status->getColor(),
  340. 'icon' => $status->getIcon(),
  341. ];
  342. }
  343. return $result;
  344. }
  345. /**
  346. * 获取最近任务统计
  347. */
  348. public static function getRecentStats(int $days = 7): array
  349. {
  350. $query = static::where('created_at', '>=', now()->subDays($days));
  351. return [
  352. 'total' => $query->count(),
  353. 'completed' => $query->clone()->where('status', TASK_STATUS::COMPLETED->value)->count(),
  354. 'failed' => $query->clone()->where('status', TASK_STATUS::FAILED->value)->count(),
  355. 'running' => $query->clone()->whereIn('status', TASK_STATUS::getRunningStatuses())->count(),
  356. ];
  357. }
  358. }