CleanupTask.php 10 KB

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