GenerateKnowledgeExplanationPdfJob.php 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. <?php
  2. namespace App\Jobs;
  3. use App\Models\KnowledgeExplanation;
  4. use App\Models\Paper;
  5. use App\Services\ExamPdfExportService;
  6. use App\Services\TaskManager;
  7. use Illuminate\Bus\Queueable;
  8. use Illuminate\Contracts\Queue\ShouldQueue;
  9. use Illuminate\Foundation\Bus\Dispatchable;
  10. use Illuminate\Queue\InteractsWithQueue;
  11. use Illuminate\Queue\SerializesModels;
  12. use Illuminate\Support\Facades\Log;
  13. use Throwable;
  14. class GenerateKnowledgeExplanationPdfJob implements ShouldQueue
  15. {
  16. use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  17. public function __construct(
  18. public string $taskId,
  19. public string $knowledgeId,
  20. public array $knowledgePoints
  21. ) {
  22. $this->onQueue('pdf');
  23. $this->afterCommit();
  24. }
  25. public int $tries = 3;
  26. public int $timeout = 300;
  27. public function handle(
  28. ExamPdfExportService $examPdfExportService,
  29. TaskManager $taskManager
  30. ): void {
  31. try {
  32. $record = KnowledgeExplanation::query()
  33. ->where('knowledge_id', $this->knowledgeId)
  34. ->first();
  35. if (! $record) {
  36. $taskManager->markTaskFailed($this->taskId, '知识点讲解记录不存在');
  37. return;
  38. }
  39. $taskManager->updateTaskProgress($this->taskId, 70, '开始渲染知识点讲解PDF...');
  40. $pdfUrl = $examPdfExportService->generateKnowledgeExplanationStandalonePdf($record, $this->knowledgePoints);
  41. if (! $pdfUrl) {
  42. $record->update(['status' => 'failed']);
  43. $taskManager->markTaskFailed($this->taskId, '知识点讲解PDF生成失败');
  44. return;
  45. }
  46. $record->update([
  47. 'status' => 'completed',
  48. 'pdf_url' => $pdfUrl,
  49. 'generated_at' => now(),
  50. ]);
  51. $this->syncPaperRecord($record, $pdfUrl);
  52. $taskManager->markTaskCompleted($this->taskId, [
  53. 'paper_id' => $this->knowledgeId,
  54. 'knowledge_id' => $this->knowledgeId,
  55. 'pdfs' => [
  56. 'all_pdf' => $pdfUrl,
  57. ],
  58. 'exam_content' => $this->buildKnowledgeExamContent($record, $pdfUrl),
  59. ]);
  60. $taskManager->sendCallback($this->taskId);
  61. } catch (\Throwable $e) {
  62. Log::error('GenerateKnowledgeExplanationPdfJob 失败', [
  63. 'task_id' => $this->taskId,
  64. 'knowledge_id' => $this->knowledgeId,
  65. 'error' => $e->getMessage(),
  66. ]);
  67. KnowledgeExplanation::query()
  68. ->where('knowledge_id', $this->knowledgeId)
  69. ->update(['status' => 'failed']);
  70. $taskManager->markTaskFailed($this->taskId, $e->getMessage());
  71. }
  72. }
  73. public function failed(Throwable $exception): void
  74. {
  75. KnowledgeExplanation::query()
  76. ->where('knowledge_id', $this->knowledgeId)
  77. ->update(['status' => 'failed']);
  78. app(TaskManager::class)->markTaskFailed($this->taskId, $exception->getMessage());
  79. }
  80. private function syncPaperRecord(KnowledgeExplanation $record, string $pdfUrl): void
  81. {
  82. $paperId = (string) ($record->knowledge_id ?? '');
  83. if ($paperId === '') {
  84. return;
  85. }
  86. $displayCode = (string) preg_replace('/^(paper_|knowledge_)/', '', $paperId);
  87. if ($displayCode === '') {
  88. $displayCode = $paperId;
  89. }
  90. Paper::query()->updateOrCreate(
  91. ['paper_id' => $paperId],
  92. [
  93. 'student_id' => (string) ($record->student_id ?? ''),
  94. 'teacher_id' => (string) ($record->teacher_id ?? ''),
  95. 'params' => [
  96. 'source' => 'knowledge_explanation',
  97. 'knowledge_id' => $paperId,
  98. 'kp_codes' => is_array($record->kp_codes) ? $record->kp_codes : [],
  99. ],
  100. 'paper_name' => '知识点讲解_' . $displayCode,
  101. 'paper_type' => 22,
  102. 'total_questions' => 0,
  103. 'total_score' => 100,
  104. 'status' => 'completed',
  105. 'difficulty_category' => null,
  106. 'exam_pdf_url' => $pdfUrl,
  107. 'grading_pdf_url' => null,
  108. 'all_pdf_url' => $pdfUrl,
  109. 'completed_at' => now(),
  110. ]
  111. );
  112. }
  113. private function buildKnowledgeExamContent(KnowledgeExplanation $record, string $pdfUrl): array
  114. {
  115. $paperId = (string) ($record->knowledge_id ?? '');
  116. $displayCode = (string) preg_replace('/^(paper_|knowledge_)/', '', $paperId);
  117. if ($displayCode === '') {
  118. $displayCode = $paperId;
  119. }
  120. $kpCodes = is_array($record->kp_codes) ? array_values($record->kp_codes) : [];
  121. $questions = $this->buildKnowledgeQuestions(100);
  122. $knowledgeDistribution = [];
  123. foreach ($kpCodes as $kpCode) {
  124. $knowledgeDistribution[(string) $kpCode] = 0;
  125. }
  126. foreach ($questions as $q) {
  127. $kp = (string) ($q['knowledge_point'] ?? '');
  128. if ($kp === '') {
  129. continue;
  130. }
  131. $knowledgeDistribution[$kp] = (int) ($knowledgeDistribution[$kp] ?? 0) + 1;
  132. }
  133. return [
  134. 'paper_info' => [
  135. 'paper_id' => $paperId,
  136. 'paper_name' => '知识点讲解_' . $displayCode,
  137. 'student_id' => (string) ($record->student_id ?? ''),
  138. 'teacher_id' => (string) ($record->teacher_id ?? ''),
  139. 'total_questions' => count($questions),
  140. 'total_score' => 100,
  141. 'difficulty_category' => null,
  142. 'created_at' => optional($record->created_at)->toISOString(),
  143. 'updated_at' => optional($record->updated_at)->toISOString(),
  144. 'exam_code' => $displayCode,
  145. 'grading_code' => null,
  146. 'paper_id_num' => $displayCode,
  147. ],
  148. 'questions' => $questions,
  149. 'knowledge_points' => $kpCodes,
  150. 'statistics' => [
  151. 'type_distribution' => [
  152. 'choice' => 0,
  153. 'fill' => 0,
  154. 'answer' => count($questions),
  155. ],
  156. 'difficulty_distribution' => [],
  157. 'knowledge_point_distribution' => $knowledgeDistribution,
  158. 'average_difficulty' => null,
  159. 'total_estimated_time' => 0,
  160. ],
  161. 'pdfs' => [
  162. 'all_pdf' => $pdfUrl,
  163. ],
  164. 'source' => 'knowledge_explanation',
  165. ];
  166. }
  167. private function buildKnowledgeQuestions(int $totalScore = 100): array
  168. {
  169. $questions = [];
  170. $seq = 1;
  171. foreach ($this->knowledgePoints as $point) {
  172. $kpCode = (string) ($point['kp_code'] ?? '');
  173. $kpName = (string) ($point['kp_name'] ?? $kpCode);
  174. $cases = is_array($point['cases'] ?? null) ? $point['cases'] : [];
  175. foreach ($cases as $case) {
  176. $questionId = (int) ($case['question_id'] ?? 0);
  177. $questions[] = [
  178. 'question_number' => $seq++,
  179. 'question_id' => $questionId > 0 ? (string) $questionId : '',
  180. 'question_bank_id' => $questionId > 0 ? $questionId : null,
  181. 'question_type' => (string) ($case['question_type'] ?? 'answer'),
  182. 'knowledge_point' => $kpCode,
  183. 'knowledge_point_name' => $kpName,
  184. 'difficulty' => isset($case['difficulty']) && is_numeric($case['difficulty']) ? (float) $case['difficulty'] : null,
  185. 'score' => 0,
  186. 'estimated_time' => null,
  187. 'stem' => (string) ($case['stem'] ?? ''),
  188. 'options' => is_array($case['options'] ?? null) ? $case['options'] : [],
  189. 'correct_answer' => (string) ($case['answer'] ?? ''),
  190. 'solution' => (string) ($case['solution'] ?? ''),
  191. 'metadata' => [
  192. 'source_type' => (string) ($case['source_type'] ?? ''),
  193. 'source_label' => (string) ($case['source_label'] ?? ''),
  194. 'is_wrong_case' => (bool) ($case['is_wrong_case'] ?? false),
  195. 'child_kp_code' => $case['child_kp_code'] ?? null,
  196. 'child_kp_name' => $case['child_kp_name'] ?? null,
  197. ],
  198. ];
  199. }
  200. }
  201. $count = count($questions);
  202. if ($count > 0) {
  203. $baseScore = intdiv($totalScore, $count);
  204. $remainder = $totalScore - ($baseScore * $count);
  205. foreach ($questions as &$q) {
  206. $q['score'] = $baseScore;
  207. }
  208. unset($q);
  209. if ($remainder > 0) {
  210. // 余数分散到末尾若干题,保证总分精确为 totalScore
  211. for ($i = $count - $remainder; $i < $count; $i++) {
  212. if ($i >= 0 && isset($questions[$i])) {
  213. $questions[$i]['score'] += 1;
  214. }
  215. }
  216. }
  217. }
  218. return $questions;
  219. }
  220. }