CleanupPlanLogic.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. <?php
  2. namespace App\Module\Cleanup\Logics;
  3. use App\Module\Cleanup\Models\CleanupPlan;
  4. use App\Module\Cleanup\Models\CleanupPlanContent;
  5. use App\Module\Cleanup\Models\CleanupConfig;
  6. use App\Module\Cleanup\Enums\DATA_CATEGORY;
  7. use App\Module\Cleanup\Enums\CLEANUP_TYPE;
  8. use Illuminate\Support\Facades\Log;
  9. /**
  10. * 清理计划管理逻辑类
  11. *
  12. * 负责清理计划的创建、管理和内容生成
  13. */
  14. class CleanupPlanLogic
  15. {
  16. /**
  17. * 创建清理计划
  18. *
  19. * @param array $planData 计划数据
  20. * @return array 创建结果
  21. */
  22. public static function createPlan(array $planData): array
  23. {
  24. // 检查事务是否已开启
  25. \UCore\Db\Helper::check_tr();
  26. try {
  27. // 验证计划数据
  28. $validatedData = static::validatePlanData($planData);
  29. // 创建计划
  30. $plan = CleanupPlan::create($validatedData);
  31. // 如果需要自动生成内容,则生成计划内容
  32. if ($planData['auto_generate_contents'] ?? true) {
  33. $contentResult = static::generateContents($plan->id, true);
  34. if (!$contentResult['success']) {
  35. throw new \Exception('生成计划内容失败: ' . $contentResult['message']);
  36. }
  37. }
  38. return [
  39. 'success' => true,
  40. 'message' => '清理计划创建成功',
  41. 'data' => [
  42. 'plan_id' => $plan->id,
  43. 'plan_name' => $plan->plan_name,
  44. 'plan_type' => $plan->plan_type,
  45. 'contents_count' => $plan->contents()->count(),
  46. ]
  47. ];
  48. } catch (\Exception $e) {
  49. Log::error('创建清理计划失败', [
  50. 'plan_data' => $planData,
  51. 'error' => $e->getMessage(),
  52. 'trace' => $e->getTraceAsString()
  53. ]);
  54. return [
  55. 'success' => false,
  56. 'message' => '创建清理计划失败: ' . $e->getMessage(),
  57. 'data' => null
  58. ];
  59. }
  60. }
  61. /**
  62. * 为计划生成内容配置
  63. *
  64. * @param int $planId 计划ID
  65. * @param bool $autoGenerate 是否自动生成
  66. * @return array 生成结果
  67. */
  68. public static function generateContents(int $planId, bool $autoGenerate = true): array
  69. {
  70. try {
  71. $plan = CleanupPlan::findOrFail($planId);
  72. // 根据计划类型获取目标表
  73. $targetTables = static::getTargetTables($plan);
  74. if (empty($targetTables)) {
  75. return [
  76. 'success' => false,
  77. 'message' => '未找到符合条件的目标表',
  78. 'data' => null
  79. ];
  80. }
  81. $generatedCount = 0;
  82. $skippedCount = 0;
  83. $errors = [];
  84. foreach ($targetTables as $tableName) {
  85. try {
  86. // 检查是否已存在内容配置
  87. $existingContent = CleanupPlanContent::where('plan_id', $planId)
  88. ->where('table_name', $tableName)
  89. ->first();
  90. if ($existingContent && !$autoGenerate) {
  91. $skippedCount++;
  92. continue;
  93. }
  94. // 获取表的配置信息
  95. $tableConfig = CleanupConfig::where('table_name', $tableName)->first();
  96. // 生成内容配置
  97. $contentData = static::generateTableContent($plan, $tableName, $tableConfig);
  98. if ($existingContent) {
  99. $existingContent->update($contentData);
  100. } else {
  101. $contentData['plan_id'] = $planId;
  102. $contentData['table_name'] = $tableName;
  103. CleanupPlanContent::create($contentData);
  104. }
  105. $generatedCount++;
  106. } catch (\Exception $e) {
  107. $errors[] = "表 {$tableName}: " . $e->getMessage();
  108. Log::error("生成表内容配置失败", [
  109. 'plan_id' => $planId,
  110. 'table_name' => $tableName,
  111. 'error' => $e->getMessage()
  112. ]);
  113. }
  114. }
  115. return [
  116. 'success' => true,
  117. 'message' => "内容生成完成,生成 {$generatedCount} 个,跳过 {$skippedCount} 个",
  118. 'data' => [
  119. 'generated_count' => $generatedCount,
  120. 'skipped_count' => $skippedCount,
  121. 'total_tables' => count($targetTables),
  122. 'errors' => $errors
  123. ]
  124. ];
  125. } catch (\Exception $e) {
  126. Log::error('生成计划内容失败', [
  127. 'plan_id' => $planId,
  128. 'error' => $e->getMessage(),
  129. 'trace' => $e->getTraceAsString()
  130. ]);
  131. return [
  132. 'success' => false,
  133. 'message' => '生成计划内容失败: ' . $e->getMessage(),
  134. 'data' => null
  135. ];
  136. }
  137. }
  138. /**
  139. * 验证计划数据
  140. *
  141. * @param array $planData 计划数据
  142. * @return array 验证后的数据
  143. * @throws \Exception
  144. */
  145. private static function validatePlanData(array $planData): array
  146. {
  147. // 必填字段验证
  148. $required = ['plan_name', 'plan_type'];
  149. foreach ($required as $field) {
  150. if (empty($planData[$field])) {
  151. throw new \Exception("字段 {$field} 不能为空");
  152. }
  153. }
  154. // 验证计划类型
  155. $planType = PLAN_TYPE::tryFrom($planData['plan_type']);
  156. if (!$planType) {
  157. throw new \Exception('无效的计划类型');
  158. }
  159. // 根据计划类型验证目标选择
  160. if ($planType !== PLAN_TYPE::CUSTOM && empty($planData['target_selection'])) {
  161. throw new \Exception('目标选择不能为空');
  162. }
  163. return [
  164. 'plan_name' => $planData['plan_name'],
  165. 'plan_type' => $planData['plan_type'],
  166. 'target_selection' => $planData['target_selection'] ?? [],
  167. 'global_conditions' => $planData['global_conditions'] ?? [],
  168. 'backup_config' => $planData['backup_config'] ?? [],
  169. 'is_template' => $planData['is_template'] ?? false,
  170. 'is_enabled' => $planData['is_enabled'] ?? true,
  171. 'description' => $planData['description'] ?? '',
  172. 'created_by' => $planData['created_by'] ?? 0,
  173. ];
  174. }
  175. /**
  176. * 根据计划获取目标表列表
  177. *
  178. * @param CleanupPlan $plan 清理计划
  179. * @return array 目标表列表
  180. */
  181. private static function getTargetTables(CleanupPlan $plan): array
  182. {
  183. $tables = [];
  184. $selectedModels = $plan->selected_tables ?? [];
  185. foreach ($selectedModels as $modelClass) {
  186. if (class_exists($modelClass) && is_subclass_of($modelClass, \Illuminate\Database\Eloquent\Model::class)) {
  187. try {
  188. // 通过模型实例获取表名
  189. $model = new $modelClass();
  190. $tableName = $model->getTable();
  191. $tables[] = $tableName;
  192. } catch (\Exception $e) {
  193. // 如果模型实例化失败,记录错误但继续处理其他模型
  194. \Log::warning("Failed to get table name for model: {$modelClass}", ['error' => $e->getMessage()]);
  195. }
  196. }
  197. }
  198. return array_unique($tables);
  199. }
  200. /**
  201. * 为表生成内容配置
  202. *
  203. * @param CleanupPlan $plan 清理计划
  204. * @param string $tableName 表名
  205. * @param CleanupConfig|null $tableConfig 表配置
  206. * @return array 内容配置数据
  207. */
  208. private static function generateTableContent(CleanupPlan $plan, string $tableName, ?CleanupConfig $tableConfig): array
  209. {
  210. // 基础配置
  211. $contentData = [
  212. 'cleanup_type' => $tableConfig?->default_cleanup_type ?? CLEANUP_TYPE::DELETE_ALL->value,
  213. 'conditions' => $tableConfig?->default_conditions ?? [],
  214. 'priority' => $tableConfig?->priority ?? 100,
  215. 'batch_size' => $tableConfig?->batch_size ?? 1000,
  216. 'backup_enabled' => true,
  217. 'is_enabled' => true,
  218. 'notes' => $tableConfig?->description ?? "自动生成的 {$tableName} 表清理配置",
  219. ];
  220. // 合并计划的全局条件
  221. if (!empty($plan->global_conditions)) {
  222. $contentData['conditions'] = array_merge(
  223. $contentData['conditions'],
  224. $plan->global_conditions
  225. );
  226. }
  227. // 合并计划的备份配置
  228. if (!empty($plan->backup_config)) {
  229. $contentData['backup_config'] = $plan->backup_config;
  230. }
  231. return $contentData;
  232. }
  233. /**
  234. * 获取计划详情
  235. *
  236. * @param int $planId 计划ID
  237. * @return array 计划详情
  238. */
  239. public static function getPlanDetails(int $planId): array
  240. {
  241. try {
  242. $plan = CleanupPlan::with(['contents.config'])->findOrFail($planId);
  243. $contents = $plan->contents->map(function ($content) {
  244. return [
  245. 'id' => $content->id,
  246. 'table_name' => $content->table_name,
  247. 'cleanup_type' => $content->cleanup_type,
  248. 'cleanup_type_name' => CLEANUP_TYPE::from($content->cleanup_type)->getDescription(),
  249. 'conditions' => $content->conditions,
  250. 'priority' => $content->priority,
  251. 'batch_size' => $content->batch_size,
  252. 'backup_enabled' => $content->backup_enabled,
  253. 'is_enabled' => $content->is_enabled,
  254. 'notes' => $content->notes,
  255. 'module_name' => $content->config?->module_name,
  256. 'data_category' => $content->config?->data_category,
  257. ];
  258. });
  259. return [
  260. 'success' => true,
  261. 'data' => [
  262. 'plan' => [
  263. 'id' => $plan->id,
  264. 'plan_name' => $plan->plan_name,
  265. 'selected_tables' => $plan->selected_tables,
  266. 'global_conditions' => $plan->global_conditions,
  267. 'backup_config' => $plan->backup_config,
  268. 'is_template' => $plan->is_template,
  269. 'is_enabled' => $plan->is_enabled,
  270. 'description' => $plan->description,
  271. 'created_at' => $plan->created_at,
  272. 'updated_at' => $plan->updated_at,
  273. ],
  274. 'contents' => $contents,
  275. 'statistics' => [
  276. 'total_tables' => $contents->count(),
  277. 'enabled_tables' => $contents->where('is_enabled', true)->count(),
  278. 'backup_enabled_tables' => $contents->where('backup_enabled', true)->count(),
  279. ]
  280. ]
  281. ];
  282. } catch (\Exception $e) {
  283. Log::error('获取计划详情失败', [
  284. 'plan_id' => $planId,
  285. 'error' => $e->getMessage()
  286. ]);
  287. return [
  288. 'success' => false,
  289. 'message' => '获取计划详情失败: ' . $e->getMessage(),
  290. 'data' => null
  291. ];
  292. }
  293. }
  294. /**
  295. * 更新计划
  296. *
  297. * @param int $planId 计划ID
  298. * @param array $planData 计划数据
  299. * @return array 更新结果
  300. */
  301. public static function updatePlan(int $planId, array $planData): array
  302. {
  303. try {
  304. $plan = CleanupPlan::findOrFail($planId);
  305. // 验证数据
  306. $validatedData = static::validatePlanData($planData);
  307. // 更新计划
  308. $plan->update($validatedData);
  309. return [
  310. 'success' => true,
  311. 'message' => '计划更新成功',
  312. 'data' => [
  313. 'plan_id' => $plan->id,
  314. 'plan_name' => $plan->plan_name,
  315. ]
  316. ];
  317. } catch (\Exception $e) {
  318. Log::error('更新计划失败', [
  319. 'plan_id' => $planId,
  320. 'plan_data' => $planData,
  321. 'error' => $e->getMessage()
  322. ]);
  323. // 重新抛出异常,不隐藏错误
  324. throw $e;
  325. }
  326. }
  327. /**
  328. * 删除计划
  329. *
  330. * @param int $planId 计划ID
  331. * @return array 删除结果
  332. */
  333. public static function deletePlan(int $planId): array
  334. {
  335. // 检查事务是否已开启
  336. \UCore\Db\Helper::check_tr();
  337. try {
  338. $plan = CleanupPlan::findOrFail($planId);
  339. // 检查是否有关联的任务
  340. if ($plan->tasks()->exists()) {
  341. throw new \Exception('该计划存在关联的任务,无法删除');
  342. }
  343. // 删除计划内容
  344. $plan->contents()->delete();
  345. // 删除计划
  346. $plan->delete();
  347. return [
  348. 'success' => true,
  349. 'message' => '计划删除成功',
  350. 'data' => null
  351. ];
  352. } catch (\Exception $e) {
  353. Log::error('删除计划失败', [
  354. 'plan_id' => $planId,
  355. 'error' => $e->getMessage()
  356. ]);
  357. // 重新抛出异常,不隐藏错误
  358. throw $e;
  359. }
  360. }
  361. }