GenerateKnowledgeExplanationPdfJob.php 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. namespace App\Jobs;
  3. use App\Models\KnowledgeExplanation;
  4. use App\Services\ExamPdfExportService;
  5. use App\Services\TaskManager;
  6. use Illuminate\Bus\Queueable;
  7. use Illuminate\Contracts\Queue\ShouldQueue;
  8. use Illuminate\Foundation\Bus\Dispatchable;
  9. use Illuminate\Queue\InteractsWithQueue;
  10. use Illuminate\Queue\SerializesModels;
  11. use Illuminate\Support\Facades\Log;
  12. use Throwable;
  13. class GenerateKnowledgeExplanationPdfJob implements ShouldQueue
  14. {
  15. use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  16. public function __construct(
  17. public string $taskId,
  18. public string $knowledgeId,
  19. public array $knowledgePoints
  20. ) {
  21. $this->onQueue('pdf');
  22. $this->afterCommit();
  23. }
  24. public int $tries = 3;
  25. public int $timeout = 300;
  26. public function handle(
  27. ExamPdfExportService $examPdfExportService,
  28. TaskManager $taskManager
  29. ): void {
  30. try {
  31. $record = KnowledgeExplanation::query()
  32. ->where('knowledge_id', $this->knowledgeId)
  33. ->first();
  34. if (! $record) {
  35. $taskManager->markTaskFailed($this->taskId, '知识点讲解记录不存在');
  36. return;
  37. }
  38. $taskManager->updateTaskProgress($this->taskId, 70, '开始渲染知识点讲解PDF...');
  39. $pdfUrl = $examPdfExportService->generateKnowledgeExplanationStandalonePdf($record, $this->knowledgePoints);
  40. if (! $pdfUrl) {
  41. $record->update(['status' => 'failed']);
  42. $taskManager->markTaskFailed($this->taskId, '知识点讲解PDF生成失败');
  43. return;
  44. }
  45. $record->update([
  46. 'status' => 'completed',
  47. 'pdf_url' => $pdfUrl,
  48. 'generated_at' => now(),
  49. ]);
  50. $taskManager->markTaskCompleted($this->taskId, [
  51. 'paper_id' => $this->knowledgeId,
  52. 'knowledge_id' => $this->knowledgeId,
  53. 'pdfs' => [
  54. 'all_pdf' => $pdfUrl,
  55. ],
  56. 'exam_content' => [],
  57. ]);
  58. $taskManager->sendCallback($this->taskId);
  59. } catch (\Throwable $e) {
  60. Log::error('GenerateKnowledgeExplanationPdfJob 失败', [
  61. 'task_id' => $this->taskId,
  62. 'knowledge_id' => $this->knowledgeId,
  63. 'error' => $e->getMessage(),
  64. ]);
  65. KnowledgeExplanation::query()
  66. ->where('knowledge_id', $this->knowledgeId)
  67. ->update(['status' => 'failed']);
  68. $taskManager->markTaskFailed($this->taskId, $e->getMessage());
  69. }
  70. }
  71. public function failed(Throwable $exception): void
  72. {
  73. KnowledgeExplanation::query()
  74. ->where('knowledge_id', $this->knowledgeId)
  75. ->update(['status' => 'failed']);
  76. app(TaskManager::class)->markTaskFailed($this->taskId, $exception->getMessage());
  77. }
  78. }