ExamAnalysisPdfController.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Jobs\GenerateAnalysisPdfJob;
  4. use Illuminate\Http\Request;
  5. use Illuminate\Support\Facades\Cache;
  6. use Illuminate\Support\Facades\DB;
  7. use Illuminate\Support\Facades\Log;
  8. class ExamAnalysisPdfController extends Controller
  9. {
  10. private const ENQUEUE_LOCK_TTL_SECONDS = 120;
  11. public function show(Request $request)
  12. {
  13. $paperId = $request->query('paperId');
  14. $studentId = $request->query('studentId');
  15. $recordId = $request->query('recordId'); // 可选的OCR记录ID
  16. if (!$paperId || !$studentId) {
  17. return response()->json([
  18. 'success' => false,
  19. 'message' => 'paperId 和 studentId 不能为空',
  20. ], 400);
  21. }
  22. // 已生成则直接返回链接
  23. $existingPdfUrl = DB::connection('mysql')
  24. ->table('exam_analysis_results')
  25. ->where('paper_id', $paperId)
  26. ->where('student_id', $studentId)
  27. ->whereNotNull('analysis_pdf_url')
  28. ->where('analysis_pdf_url', '!=', '')
  29. ->orderByDesc('updated_at')
  30. ->value('analysis_pdf_url');
  31. if ($existingPdfUrl) {
  32. return response()->json([
  33. 'success' => true,
  34. 'message' => '学情报告已生成',
  35. 'data' => [
  36. 'paper_id' => $paperId,
  37. 'student_id' => $studentId,
  38. 'record_id' => $recordId,
  39. 'status' => 'completed',
  40. 'pdf_url' => $existingPdfUrl,
  41. 'queued' => false,
  42. ],
  43. ]);
  44. }
  45. $lockKey = sprintf('analysis_pdf:enqueue:%s:%s', $paperId, $studentId);
  46. $acquired = Cache::add($lockKey, now()->timestamp, now()->addSeconds(self::ENQUEUE_LOCK_TTL_SECONDS));
  47. if (! $acquired) {
  48. return response()->json([
  49. 'success' => true,
  50. 'message' => '学情报告正在生成中,请稍后重试',
  51. 'data' => [
  52. 'paper_id' => $paperId,
  53. 'student_id' => $studentId,
  54. 'record_id' => $recordId,
  55. 'status' => 'processing',
  56. 'pdf_url' => null,
  57. 'queued' => false,
  58. ],
  59. ], 202);
  60. }
  61. dispatch(new GenerateAnalysisPdfJob($paperId, $studentId, $recordId));
  62. Log::info('ExamAnalysisPdfController: 学情报告生成任务已入队', [
  63. 'paper_id' => $paperId,
  64. 'student_id' => $studentId,
  65. 'record_id' => $recordId,
  66. ]);
  67. return response()->json([
  68. 'success' => true,
  69. 'message' => '学情报告任务已入队,正在后台生成',
  70. 'data' => [
  71. 'paper_id' => $paperId,
  72. 'student_id' => $studentId,
  73. 'record_id' => $recordId,
  74. 'status' => 'processing',
  75. 'pdf_url' => null,
  76. 'queued' => true,
  77. ],
  78. ], 202);
  79. }
  80. }