AiTask.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. namespace addons\aicontent\model;
  3. use think\Model;
  4. /**
  5. * Model for the mac_ai_task table.
  6. * Tracks every AI generation request (single or batch).
  7. */
  8. class AiTask extends Model
  9. {
  10. protected $table = 'mac_ai_task';
  11. protected $pk = 'id';
  12. protected $autoWriteTimestamp = false; // We manage timestamps manually
  13. // Task status constants
  14. const STATUS_PENDING = 0;
  15. const STATUS_DONE = 1;
  16. const STATUS_ERROR = 2;
  17. /**
  18. * Create a new pending task record.
  19. */
  20. public static function createTask(
  21. string $contentType,
  22. int $contentId,
  23. string $contentName,
  24. string $provider,
  25. string $model,
  26. string $fields = 'description,tags,seo_title'
  27. ): self {
  28. $task = new self();
  29. $task->content_type = $contentType;
  30. $task->content_id = $contentId;
  31. $task->content_name = $contentName;
  32. $task->provider = $provider;
  33. $task->model = $model;
  34. $task->fields = $fields;
  35. $task->status = self::STATUS_PENDING;
  36. $task->created_at = date('Y-m-d H:i:s');
  37. $task->save();
  38. return $task;
  39. }
  40. /**
  41. * Mark task as successfully completed with the AI result JSON.
  42. */
  43. public function markDone(string $resultJson): void
  44. {
  45. $this->status = self::STATUS_DONE;
  46. $this->result = $resultJson;
  47. $this->error_msg = null;
  48. $this->updated_at = date('Y-m-d H:i:s');
  49. $this->save();
  50. }
  51. /**
  52. * Mark task as failed with an error message.
  53. */
  54. public function markError(string $errorMsg): void
  55. {
  56. $this->status = self::STATUS_ERROR;
  57. $this->error_msg = mb_substr($errorMsg, 0, 499);
  58. $this->updated_at = date('Y-m-d H:i:s');
  59. $this->save();
  60. }
  61. /**
  62. * Get paginated task history.
  63. */
  64. public static function getHistory(int $page = 1, int $pageSize = 20): array
  65. {
  66. $total = self::count();
  67. $list = self::order('id', 'desc')
  68. ->limit(($page - 1) * $pageSize, $pageSize)
  69. ->select()
  70. ->toArray();
  71. return ['total' => $total, 'list' => $list];
  72. }
  73. /**
  74. * Human-readable status label.
  75. */
  76. public function getStatusLabelAttr(): string
  77. {
  78. switch ((int) $this->status) {
  79. case self::STATUS_PENDING: return lang('Pending');
  80. case self::STATUS_DONE: return lang('Done');
  81. case self::STATUS_ERROR: return lang('Error');
  82. default: return lang('Unknown');
  83. }
  84. }
  85. }