GenerateKnowledgeExplanationPdfJob.php 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. 'knowledge_id' => $this->knowledgeId,
  52. 'pdfs' => [
  53. 'all_pdf' => $pdfUrl,
  54. ],
  55. 'exam_content' => [],
  56. ]);
  57. $taskManager->sendCallback($this->taskId);
  58. } catch (\Throwable $e) {
  59. Log::error('GenerateKnowledgeExplanationPdfJob 失败', [
  60. 'task_id' => $this->taskId,
  61. 'knowledge_id' => $this->knowledgeId,
  62. 'error' => $e->getMessage(),
  63. ]);
  64. KnowledgeExplanation::query()
  65. ->where('knowledge_id', $this->knowledgeId)
  66. ->update(['status' => 'failed']);
  67. $taskManager->markTaskFailed($this->taskId, $e->getMessage());
  68. }
  69. }
  70. public function failed(Throwable $exception): void
  71. {
  72. KnowledgeExplanation::query()
  73. ->where('knowledge_id', $this->knowledgeId)
  74. ->update(['status' => 'failed']);
  75. app(TaskManager::class)->markTaskFailed($this->taskId, $exception->getMessage());
  76. }
  77. }