CleanupPlanLogic.php 14 KB

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