CleanupPlanLogic.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  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\PLAN_TYPE;
  7. use App\Module\Cleanup\Enums\DATA_CATEGORY;
  8. use App\Module\Cleanup\Enums\CLEANUP_TYPE;
  9. use Illuminate\Support\Facades\DB;
  10. use Illuminate\Support\Facades\Log;
  11. /**
  12. * 清理计划管理逻辑类
  13. *
  14. * 负责清理计划的创建、管理和内容生成
  15. */
  16. class CleanupPlanLogic
  17. {
  18. /**
  19. * 创建清理计划
  20. *
  21. * @param array $planData 计划数据
  22. * @return array 创建结果
  23. */
  24. public static function createPlan(array $planData): array
  25. {
  26. try {
  27. DB::beginTransaction();
  28. // 验证计划数据
  29. $validatedData = static::validatePlanData($planData);
  30. // 创建计划
  31. $plan = CleanupPlan::create($validatedData);
  32. // 如果需要自动生成内容,则生成计划内容
  33. if ($planData['auto_generate_contents'] ?? true) {
  34. $contentResult = static::generateContents($plan->id, true);
  35. if (!$contentResult['success']) {
  36. throw new \Exception('生成计划内容失败: ' . $contentResult['message']);
  37. }
  38. }
  39. DB::commit();
  40. return [
  41. 'success' => true,
  42. 'message' => '清理计划创建成功',
  43. 'data' => [
  44. 'plan_id' => $plan->id,
  45. 'plan_name' => $plan->plan_name,
  46. 'plan_type' => $plan->plan_type,
  47. 'contents_count' => $plan->contents()->count(),
  48. ]
  49. ];
  50. } catch (\Exception $e) {
  51. DB::rollBack();
  52. Log::error('创建清理计划失败', [
  53. 'plan_data' => $planData,
  54. 'error' => $e->getMessage(),
  55. 'trace' => $e->getTraceAsString()
  56. ]);
  57. return [
  58. 'success' => false,
  59. 'message' => '创建清理计划失败: ' . $e->getMessage(),
  60. 'data' => null
  61. ];
  62. }
  63. }
  64. /**
  65. * 为计划生成内容配置
  66. *
  67. * @param int $planId 计划ID
  68. * @param bool $autoGenerate 是否自动生成
  69. * @return array 生成结果
  70. */
  71. public static function generateContents(int $planId, bool $autoGenerate = true): array
  72. {
  73. try {
  74. $plan = CleanupPlan::findOrFail($planId);
  75. // 根据计划类型获取目标表
  76. $targetTables = static::getTargetTables($plan);
  77. if (empty($targetTables)) {
  78. return [
  79. 'success' => false,
  80. 'message' => '未找到符合条件的目标表',
  81. 'data' => null
  82. ];
  83. }
  84. $generatedCount = 0;
  85. $skippedCount = 0;
  86. $errors = [];
  87. foreach ($targetTables as $tableName) {
  88. try {
  89. // 检查是否已存在内容配置
  90. $existingContent = CleanupPlanContent::where('plan_id', $planId)
  91. ->where('table_name', $tableName)
  92. ->first();
  93. if ($existingContent && !$autoGenerate) {
  94. $skippedCount++;
  95. continue;
  96. }
  97. // 获取表的配置信息
  98. $tableConfig = CleanupConfig::where('table_name', $tableName)->first();
  99. // 生成内容配置
  100. $contentData = static::generateTableContent($plan, $tableName, $tableConfig);
  101. if ($existingContent) {
  102. $existingContent->update($contentData);
  103. } else {
  104. $contentData['plan_id'] = $planId;
  105. $contentData['table_name'] = $tableName;
  106. CleanupPlanContent::create($contentData);
  107. }
  108. $generatedCount++;
  109. } catch (\Exception $e) {
  110. $errors[] = "表 {$tableName}: " . $e->getMessage();
  111. Log::error("生成表内容配置失败", [
  112. 'plan_id' => $planId,
  113. 'table_name' => $tableName,
  114. 'error' => $e->getMessage()
  115. ]);
  116. }
  117. }
  118. return [
  119. 'success' => true,
  120. 'message' => "内容生成完成,生成 {$generatedCount} 个,跳过 {$skippedCount} 个",
  121. 'data' => [
  122. 'generated_count' => $generatedCount,
  123. 'skipped_count' => $skippedCount,
  124. 'total_tables' => count($targetTables),
  125. 'errors' => $errors
  126. ]
  127. ];
  128. } catch (\Exception $e) {
  129. Log::error('生成计划内容失败', [
  130. 'plan_id' => $planId,
  131. 'error' => $e->getMessage(),
  132. 'trace' => $e->getTraceAsString()
  133. ]);
  134. return [
  135. 'success' => false,
  136. 'message' => '生成计划内容失败: ' . $e->getMessage(),
  137. 'data' => null
  138. ];
  139. }
  140. }
  141. /**
  142. * 验证计划数据
  143. *
  144. * @param array $planData 计划数据
  145. * @return array 验证后的数据
  146. * @throws \Exception
  147. */
  148. private static function validatePlanData(array $planData): array
  149. {
  150. // 必填字段验证
  151. $required = ['plan_name', 'plan_type'];
  152. foreach ($required as $field) {
  153. if (empty($planData[$field])) {
  154. throw new \Exception("字段 {$field} 不能为空");
  155. }
  156. }
  157. // 验证计划类型
  158. $planType = PLAN_TYPE::tryFrom($planData['plan_type']);
  159. if (!$planType) {
  160. throw new \Exception('无效的计划类型');
  161. }
  162. // 根据计划类型验证目标选择
  163. if ($planType !== PLAN_TYPE::CUSTOM && empty($planData['target_selection'])) {
  164. throw new \Exception('目标选择不能为空');
  165. }
  166. return [
  167. 'plan_name' => $planData['plan_name'],
  168. 'plan_type' => $planData['plan_type'],
  169. 'target_selection' => $planData['target_selection'] ?? [],
  170. 'global_conditions' => $planData['global_conditions'] ?? [],
  171. 'backup_config' => $planData['backup_config'] ?? [],
  172. 'is_template' => $planData['is_template'] ?? false,
  173. 'is_enabled' => $planData['is_enabled'] ?? true,
  174. 'description' => $planData['description'] ?? '',
  175. 'created_by' => $planData['created_by'] ?? 0,
  176. ];
  177. }
  178. /**
  179. * 根据计划获取目标表列表
  180. *
  181. * @param CleanupPlan $plan 清理计划
  182. * @return array 目标表列表
  183. */
  184. private static function getTargetTables(CleanupPlan $plan): array
  185. {
  186. $planType = PLAN_TYPE::from($plan->plan_type);
  187. $targetSelection = $plan->target_selection;
  188. switch ($planType) {
  189. case PLAN_TYPE::MODULE:
  190. return static::getModuleTables($targetSelection['modules'] ?? []);
  191. case PLAN_TYPE::CATEGORY:
  192. return static::getCategoryTables($targetSelection['categories'] ?? []);
  193. case PLAN_TYPE::FULL:
  194. return static::getAllTables($targetSelection['exclude_tables'] ?? []);
  195. case PLAN_TYPE::MIXED:
  196. return static::getMixedTables($targetSelection);
  197. case PLAN_TYPE::CUSTOM:
  198. return $targetSelection['tables'] ?? [];
  199. default:
  200. return [];
  201. }
  202. }
  203. /**
  204. * 获取指定模块的表
  205. *
  206. * @param array $modules 模块列表
  207. * @return array 表列表
  208. */
  209. private static function getModuleTables(array $modules): array
  210. {
  211. if (empty($modules)) {
  212. return [];
  213. }
  214. return CleanupConfig::whereIn('module_name', $modules)
  215. ->where('is_enabled', true)
  216. ->pluck('table_name')
  217. ->toArray();
  218. }
  219. /**
  220. * 获取指定分类的表
  221. *
  222. * @param array $categories 分类列表
  223. * @return array 表列表
  224. */
  225. private static function getCategoryTables(array $categories): array
  226. {
  227. if (empty($categories)) {
  228. return [];
  229. }
  230. return CleanupConfig::whereIn('data_category', $categories)
  231. ->where('is_enabled', true)
  232. ->pluck('table_name')
  233. ->toArray();
  234. }
  235. /**
  236. * 获取所有表(排除指定表)
  237. *
  238. * @param array $excludeTables 排除的表
  239. * @return array 表列表
  240. */
  241. private static function getAllTables(array $excludeTables = []): array
  242. {
  243. $query = CleanupConfig::where('is_enabled', true);
  244. if (!empty($excludeTables)) {
  245. $query->whereNotIn('table_name', $excludeTables);
  246. }
  247. return $query->pluck('table_name')->toArray();
  248. }
  249. /**
  250. * 获取混合选择的表
  251. *
  252. * @param array $selection 混合选择配置
  253. * @return array 表列表
  254. */
  255. private static function getMixedTables(array $selection): array
  256. {
  257. $tables = [];
  258. // 添加指定模块的表
  259. if (!empty($selection['modules'])) {
  260. $tables = array_merge($tables, static::getModuleTables($selection['modules']));
  261. }
  262. // 添加指定分类的表
  263. if (!empty($selection['categories'])) {
  264. $tables = array_merge($tables, static::getCategoryTables($selection['categories']));
  265. }
  266. // 添加自定义表
  267. if (!empty($selection['tables'])) {
  268. $tables = array_merge($tables, $selection['tables']);
  269. }
  270. // 排除指定表
  271. if (!empty($selection['exclude_tables'])) {
  272. $tables = array_diff($tables, $selection['exclude_tables']);
  273. }
  274. return array_unique($tables);
  275. }
  276. /**
  277. * 为表生成内容配置
  278. *
  279. * @param CleanupPlan $plan 清理计划
  280. * @param string $tableName 表名
  281. * @param CleanupConfig|null $tableConfig 表配置
  282. * @return array 内容配置数据
  283. */
  284. private static function generateTableContent(CleanupPlan $plan, string $tableName, ?CleanupConfig $tableConfig): array
  285. {
  286. // 基础配置
  287. $contentData = [
  288. 'cleanup_type' => $tableConfig?->default_cleanup_type ?? CLEANUP_TYPE::DELETE_ALL->value,
  289. 'conditions' => $tableConfig?->default_conditions ?? [],
  290. 'priority' => $tableConfig?->priority ?? 100,
  291. 'batch_size' => $tableConfig?->batch_size ?? 1000,
  292. 'backup_enabled' => true,
  293. 'is_enabled' => true,
  294. 'notes' => $tableConfig?->description ?? "自动生成的 {$tableName} 表清理配置",
  295. ];
  296. // 合并计划的全局条件
  297. if (!empty($plan->global_conditions)) {
  298. $contentData['conditions'] = array_merge(
  299. $contentData['conditions'],
  300. $plan->global_conditions
  301. );
  302. }
  303. // 合并计划的备份配置
  304. if (!empty($plan->backup_config)) {
  305. $contentData['backup_config'] = $plan->backup_config;
  306. }
  307. return $contentData;
  308. }
  309. /**
  310. * 获取计划详情
  311. *
  312. * @param int $planId 计划ID
  313. * @return array 计划详情
  314. */
  315. public static function getPlanDetails(int $planId): array
  316. {
  317. try {
  318. $plan = CleanupPlan::with(['contents.config'])->findOrFail($planId);
  319. $contents = $plan->contents->map(function ($content) {
  320. return [
  321. 'id' => $content->id,
  322. 'table_name' => $content->table_name,
  323. 'cleanup_type' => $content->cleanup_type,
  324. 'cleanup_type_name' => CLEANUP_TYPE::from($content->cleanup_type)->getDescription(),
  325. 'conditions' => $content->conditions,
  326. 'priority' => $content->priority,
  327. 'batch_size' => $content->batch_size,
  328. 'backup_enabled' => $content->backup_enabled,
  329. 'is_enabled' => $content->is_enabled,
  330. 'notes' => $content->notes,
  331. 'module_name' => $content->config?->module_name,
  332. 'data_category' => $content->config?->data_category,
  333. ];
  334. });
  335. return [
  336. 'success' => true,
  337. 'data' => [
  338. 'plan' => [
  339. 'id' => $plan->id,
  340. 'plan_name' => $plan->plan_name,
  341. 'plan_type' => $plan->plan_type,
  342. 'plan_type_name' => PLAN_TYPE::from($plan->plan_type)->getDescription(),
  343. 'target_selection' => $plan->target_selection,
  344. 'global_conditions' => $plan->global_conditions,
  345. 'backup_config' => $plan->backup_config,
  346. 'is_template' => $plan->is_template,
  347. 'is_enabled' => $plan->is_enabled,
  348. 'description' => $plan->description,
  349. 'created_at' => $plan->created_at,
  350. 'updated_at' => $plan->updated_at,
  351. ],
  352. 'contents' => $contents,
  353. 'statistics' => [
  354. 'total_tables' => $contents->count(),
  355. 'enabled_tables' => $contents->where('is_enabled', true)->count(),
  356. 'backup_enabled_tables' => $contents->where('backup_enabled', true)->count(),
  357. ]
  358. ]
  359. ];
  360. } catch (\Exception $e) {
  361. Log::error('获取计划详情失败', [
  362. 'plan_id' => $planId,
  363. 'error' => $e->getMessage()
  364. ]);
  365. return [
  366. 'success' => false,
  367. 'message' => '获取计划详情失败: ' . $e->getMessage(),
  368. 'data' => null
  369. ];
  370. }
  371. }
  372. /**
  373. * 更新计划
  374. *
  375. * @param int $planId 计划ID
  376. * @param array $planData 计划数据
  377. * @return array 更新结果
  378. */
  379. public static function updatePlan(int $planId, array $planData): array
  380. {
  381. try {
  382. $plan = CleanupPlan::findOrFail($planId);
  383. // 验证数据
  384. $validatedData = static::validatePlanData($planData);
  385. // 更新计划
  386. $plan->update($validatedData);
  387. return [
  388. 'success' => true,
  389. 'message' => '计划更新成功',
  390. 'data' => [
  391. 'plan_id' => $plan->id,
  392. 'plan_name' => $plan->plan_name,
  393. ]
  394. ];
  395. } catch (\Exception $e) {
  396. Log::error('更新计划失败', [
  397. 'plan_id' => $planId,
  398. 'plan_data' => $planData,
  399. 'error' => $e->getMessage()
  400. ]);
  401. return [
  402. 'success' => false,
  403. 'message' => '更新计划失败: ' . $e->getMessage(),
  404. 'data' => null
  405. ];
  406. }
  407. }
  408. /**
  409. * 删除计划
  410. *
  411. * @param int $planId 计划ID
  412. * @return array 删除结果
  413. */
  414. public static function deletePlan(int $planId): array
  415. {
  416. try {
  417. DB::beginTransaction();
  418. $plan = CleanupPlan::findOrFail($planId);
  419. // 检查是否有关联的任务
  420. if ($plan->tasks()->exists()) {
  421. throw new \Exception('该计划存在关联的任务,无法删除');
  422. }
  423. // 删除计划内容
  424. $plan->contents()->delete();
  425. // 删除计划
  426. $plan->delete();
  427. DB::commit();
  428. return [
  429. 'success' => true,
  430. 'message' => '计划删除成功',
  431. 'data' => null
  432. ];
  433. } catch (\Exception $e) {
  434. DB::rollBack();
  435. Log::error('删除计划失败', [
  436. 'plan_id' => $planId,
  437. 'error' => $e->getMessage()
  438. ]);
  439. return [
  440. 'success' => false,
  441. 'message' => '删除计划失败: ' . $e->getMessage(),
  442. 'data' => null
  443. ];
  444. }
  445. }
  446. }