CleanupPapers.php 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. use App\Services\QuestionBankService;
  5. class CleanupPapers extends Command
  6. {
  7. /**
  8. * The name and signature of the console command.
  9. *
  10. * @var string
  11. */
  12. protected $signature = 'exams:cleanup {--check : 检查数据完整性} {--cleanup : 清理不一致的试卷} {--fix : 修复题目数量统计}';
  13. /**
  14. * The console command description.
  15. *
  16. * @var string
  17. */
  18. protected $description = '检查和清理试卷数据完整性问题';
  19. /**
  20. * Execute the console command.
  21. */
  22. public function handle()
  23. {
  24. $questionBankService = app(QuestionBankService::class);
  25. if ($this->option('check')) {
  26. return $this->checkDataIntegrity($questionBankService);
  27. }
  28. if ($this->option('cleanup')) {
  29. return $this->cleanupInconsistentPapers($questionBankService);
  30. }
  31. if ($this->option('fix')) {
  32. return $this->fixPaperQuestionCounts($questionBankService);
  33. }
  34. // 默认执行所有操作
  35. $this->info('开始执行试卷数据完整性检查和清理...');
  36. $this->checkDataIntegrity($questionBankService);
  37. $this->cleanupInconsistentPapers($questionBankService);
  38. $this->fixPaperQuestionCounts($questionBankService);
  39. $this->info('所有操作完成!');
  40. return Command::SUCCESS;
  41. }
  42. private function checkDataIntegrity(QuestionBankService $service): int
  43. {
  44. $this->info('检查数据完整性...');
  45. $result = $service->checkDataIntegrity();
  46. $count = $result['inconsistent_count'];
  47. if ($count === 0) {
  48. $this->info('✅ 未发现数据不一致问题');
  49. } else {
  50. $this->warn("⚠️ 发现 {$count} 个数据不一致的试卷:");
  51. $this->table(
  52. ['试卷ID', '试卷名称', '预期题目数', '学生ID'],
  53. array_map(function($paper) {
  54. return [
  55. $paper->paper_id,
  56. $paper->paper_name ?? '未命名',
  57. $paper->question_count ?? 0,
  58. $paper->student_id ?? 'unknown'
  59. ];
  60. }, $result['papers'])
  61. );
  62. }
  63. return $count;
  64. }
  65. private function cleanupInconsistentPapers(QuestionBankService $service): int
  66. {
  67. $this->info('清理不一致的试卷记录...');
  68. $deletedCount = $service->cleanupInconsistentPapers();
  69. if ($deletedCount === 0) {
  70. $this->info('✅ 没有需要清理的试卷');
  71. } else {
  72. $this->info("🗑️ 已清理 {$deletedCount} 个不一致的试卷记录");
  73. }
  74. return $deletedCount;
  75. }
  76. private function fixPaperQuestionCounts(QuestionBankService $service): int
  77. {
  78. $this->info('修复试卷题目数量统计...');
  79. $fixedCount = $service->fixPaperQuestionCounts();
  80. if ($fixedCount === 0) {
  81. $this->info('✅ 所有试卷的题目数量统计都正确');
  82. } else {
  83. $this->info("🔧 已修复 {$fixedCount} 个试卷的题目数量统计");
  84. }
  85. return $fixedCount;
  86. }
  87. }