RegeneratePdfJob.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace App\Jobs;
  3. use App\Models\Paper;
  4. use App\Services\ExamPdfExportService;
  5. use Illuminate\Bus\Queueable;
  6. use Illuminate\Contracts\Queue\ShouldQueue;
  7. use Illuminate\Foundation\Bus\Dispatchable;
  8. use Illuminate\Queue\InteractsWithQueue;
  9. use Illuminate\Queue\SerializesModels;
  10. use Illuminate\Support\Facades\Log;
  11. /**
  12. * 单个试卷 PDF 重新生成任务(用于批量重生成 API 的队列)
  13. */
  14. class RegeneratePdfJob implements ShouldQueue
  15. {
  16. use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  17. public string $paperId;
  18. public ?bool $includeKpExplain;
  19. public int $tries = 2;
  20. public int $timeout = 300;
  21. public function __construct(string $paperId, ?bool $includeKpExplain = null)
  22. {
  23. $this->paperId = $paperId;
  24. $this->includeKpExplain = $includeKpExplain;
  25. $this->onQueue('pdf');
  26. }
  27. public function handle(ExamPdfExportService $pdfExportService): void
  28. {
  29. $paper = Paper::with('questions')->find($this->paperId);
  30. if (! $paper || $paper->questions->isEmpty()) {
  31. Log::warning('RegeneratePdfJob: 跳过无题目试卷', ['paper_id' => $this->paperId]);
  32. return;
  33. }
  34. $useKpExplain = $this->includeKpExplain ?? ($paper->paper_type !== 0);
  35. try {
  36. Log::info('RegeneratePdfJob: 开始', ['paper_id' => $this->paperId]);
  37. $pdfUrl = $pdfExportService->generateUnifiedPdf($this->paperId, $useKpExplain);
  38. if ($pdfUrl) {
  39. Log::info('RegeneratePdfJob: 成功', ['paper_id' => $this->paperId, 'pdf_url' => $pdfUrl]);
  40. } else {
  41. Log::warning('RegeneratePdfJob: 返回空', ['paper_id' => $this->paperId]);
  42. }
  43. } catch (\Exception $e) {
  44. Log::error('RegeneratePdfJob: 异常', [
  45. 'paper_id' => $this->paperId,
  46. 'error' => $e->getMessage(),
  47. ]);
  48. throw $e;
  49. }
  50. }
  51. }