|
@@ -2,96 +2,59 @@
|
|
|
|
|
|
|
|
namespace App\Services;
|
|
namespace App\Services;
|
|
|
|
|
|
|
|
-use App\Http\Controllers\ExamPdfController;
|
|
|
|
|
|
|
+use App\DTO\ExamAnalysisDataDto;
|
|
|
|
|
+use App\DTO\ReportPayloadDto;
|
|
|
use App\Models\Paper;
|
|
use App\Models\Paper;
|
|
|
use App\Models\PaperQuestion;
|
|
use App\Models\PaperQuestion;
|
|
|
use App\Models\Student;
|
|
use App\Models\Student;
|
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Http\Request;
|
|
|
use Illuminate\Support\Facades\File;
|
|
use Illuminate\Support\Facades\File;
|
|
|
|
|
+use Illuminate\Support\Facades\Http;
|
|
|
use Illuminate\Support\Facades\Log;
|
|
use Illuminate\Support\Facades\Log;
|
|
|
use Illuminate\Support\Facades\Storage;
|
|
use Illuminate\Support\Facades\Storage;
|
|
|
use Illuminate\Support\Facades\URL;
|
|
use Illuminate\Support\Facades\URL;
|
|
|
-use App\Services\LearningAnalyticsService;
|
|
|
|
|
-use App\Services\QuestionBankService;
|
|
|
|
|
-use App\Services\QuestionServiceApi;
|
|
|
|
|
-use App\Services\PdfStorageService;
|
|
|
|
|
use Symfony\Component\Process\Exception\ProcessSignaledException;
|
|
use Symfony\Component\Process\Exception\ProcessSignaledException;
|
|
|
use Symfony\Component\Process\Exception\ProcessTimedOutException;
|
|
use Symfony\Component\Process\Exception\ProcessTimedOutException;
|
|
|
use Symfony\Component\Process\Process;
|
|
use Symfony\Component\Process\Process;
|
|
|
|
|
|
|
|
|
|
+/**
|
|
|
|
|
+ * PDF导出服务(重构版)
|
|
|
|
|
+ * 负责生成试卷PDF、判卷PDF和学情报告PDF
|
|
|
|
|
+ */
|
|
|
class ExamPdfExportService
|
|
class ExamPdfExportService
|
|
|
{
|
|
{
|
|
|
- private ExamPdfController $controller;
|
|
|
|
|
- private LearningAnalyticsService $learningAnalyticsService;
|
|
|
|
|
- private QuestionBankService $questionBankService;
|
|
|
|
|
- private PdfStorageService $pdfStorageService;
|
|
|
|
|
-
|
|
|
|
|
public function __construct(
|
|
public function __construct(
|
|
|
- ExamPdfController $controller,
|
|
|
|
|
- LearningAnalyticsService $learningAnalyticsService,
|
|
|
|
|
- QuestionBankService $questionBankService,
|
|
|
|
|
- PdfStorageService $pdfStorageService
|
|
|
|
|
- )
|
|
|
|
|
- {
|
|
|
|
|
- $this->controller = $controller;
|
|
|
|
|
- $this->learningAnalyticsService = $learningAnalyticsService;
|
|
|
|
|
- $this->questionBankService = $questionBankService;
|
|
|
|
|
- $this->pdfStorageService = $pdfStorageService;
|
|
|
|
|
- }
|
|
|
|
|
|
|
+ private readonly LearningAnalyticsService $learningAnalyticsService,
|
|
|
|
|
+ private readonly QuestionBankService $questionBankService,
|
|
|
|
|
+ private readonly QuestionServiceApi $questionServiceApi,
|
|
|
|
|
+ private readonly PdfStorageService $pdfStorageService
|
|
|
|
|
+ ) {}
|
|
|
|
|
|
|
|
/**
|
|
/**
|
|
|
- 生成试卷 PDF(不含答案)
|
|
|
|
|
|
|
+ * 生成试卷 PDF(不含答案)
|
|
|
*/
|
|
*/
|
|
|
public function generateExamPdf(string $paperId): ?string
|
|
public function generateExamPdf(string $paperId): ?string
|
|
|
{
|
|
{
|
|
|
- $url = $this->renderAndStore($paperId, includeAnswer: false, suffix: 'exam');
|
|
|
|
|
|
|
+ $url = $this->renderAndStoreExamPdf($paperId, includeAnswer: false, suffix: 'exam');
|
|
|
|
|
|
|
|
// 如果生成成功,将 URL 写入数据库
|
|
// 如果生成成功,将 URL 写入数据库
|
|
|
if ($url) {
|
|
if ($url) {
|
|
|
- try {
|
|
|
|
|
- $paper = Paper::where('paper_id', $paperId)->first();
|
|
|
|
|
- if ($paper) {
|
|
|
|
|
- $paper->update(['exam_pdf_url' => $url]);
|
|
|
|
|
- Log::info('ExamPdfExportService: 试卷PDF URL已写入数据库', [
|
|
|
|
|
- 'paper_id' => $paperId,
|
|
|
|
|
- 'url' => $url,
|
|
|
|
|
- ]);
|
|
|
|
|
- }
|
|
|
|
|
- } catch (\Throwable $e) {
|
|
|
|
|
- Log::error('ExamPdfExportService: 写入试卷PDF URL失败', [
|
|
|
|
|
- 'paper_id' => $paperId,
|
|
|
|
|
- 'error' => $e->getMessage(),
|
|
|
|
|
- ]);
|
|
|
|
|
- }
|
|
|
|
|
|
|
+ $this->savePdfUrlToDatabase($paperId, 'exam_pdf_url', $url);
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
return $url;
|
|
return $url;
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
/**
|
|
|
- 生成判卷 PDF(含答案与解析)
|
|
|
|
|
|
|
+ * 生成判卷 PDF(含答案与解析)
|
|
|
*/
|
|
*/
|
|
|
public function generateGradingPdf(string $paperId): ?string
|
|
public function generateGradingPdf(string $paperId): ?string
|
|
|
{
|
|
{
|
|
|
- $url = $this->renderAndStore($paperId, includeAnswer: true, suffix: 'grading', useGradingView: true);
|
|
|
|
|
|
|
+ $url = $this->renderAndStoreExamPdf($paperId, includeAnswer: true, suffix: 'grading', useGradingView: true);
|
|
|
|
|
|
|
|
// 如果生成成功,将 URL 写入数据库
|
|
// 如果生成成功,将 URL 写入数据库
|
|
|
if ($url) {
|
|
if ($url) {
|
|
|
- try {
|
|
|
|
|
- $paper = Paper::where('paper_id', $paperId)->first();
|
|
|
|
|
- if ($paper) {
|
|
|
|
|
- $paper->update(['grading_pdf_url' => $url]);
|
|
|
|
|
- Log::info('ExamPdfExportService: 判卷PDF URL已写入数据库', [
|
|
|
|
|
- 'paper_id' => $paperId,
|
|
|
|
|
- 'url' => $url,
|
|
|
|
|
- ]);
|
|
|
|
|
- }
|
|
|
|
|
- } catch (\Throwable $e) {
|
|
|
|
|
- Log::error('ExamPdfExportService: 写入判卷PDF URL失败', [
|
|
|
|
|
- 'paper_id' => $paperId,
|
|
|
|
|
- 'error' => $e->getMessage(),
|
|
|
|
|
- ]);
|
|
|
|
|
- }
|
|
|
|
|
|
|
+ $this->savePdfUrlToDatabase($paperId, 'grading_pdf_url', $url);
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
return $url;
|
|
return $url;
|
|
@@ -107,65 +70,45 @@ class ExamPdfExportService
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
try {
|
|
|
- $payload = $this->buildAnalysisPayload($paperId, $studentId);
|
|
|
|
|
- if (!$payload) {
|
|
|
|
|
|
|
+ // 构建分析数据
|
|
|
|
|
+ $analysisData = $this->buildAnalysisData($paperId, $studentId);
|
|
|
|
|
+ if (!$analysisData) {
|
|
|
|
|
+ return null;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // 创建DTO
|
|
|
|
|
+ $dto = ExamAnalysisDataDto::fromArray($analysisData);
|
|
|
|
|
+ $payloadDto = ReportPayloadDto::fromExamAnalysisDataDto($dto);
|
|
|
|
|
+
|
|
|
|
|
+ // 渲染HTML
|
|
|
|
|
+ $html = view('exam-analysis.pdf-report', $payloadDto->toArray())->render();
|
|
|
|
|
+ if (!$html) {
|
|
|
|
|
+ Log::error('ExamPdfExportService: 渲染HTML为空', ['paper_id' => $paperId]);
|
|
|
return null;
|
|
return null;
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- $html = view('exam-analysis.pdf-report', $payload)->render();
|
|
|
|
|
|
|
+ // 生成PDF
|
|
|
$pdfBinary = $this->buildPdf($html);
|
|
$pdfBinary = $this->buildPdf($html);
|
|
|
if (!$pdfBinary) {
|
|
if (!$pdfBinary) {
|
|
|
return null;
|
|
return null;
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
+ // 保存PDF
|
|
|
$version = time();
|
|
$version = time();
|
|
|
$path = "analysis_reports/{$paperId}_{$studentId}_{$version}.pdf";
|
|
$path = "analysis_reports/{$paperId}_{$studentId}_{$version}.pdf";
|
|
|
$url = $this->pdfStorageService->put($path, $pdfBinary);
|
|
$url = $this->pdfStorageService->put($path, $pdfBinary);
|
|
|
if (!$url) {
|
|
if (!$url) {
|
|
|
- Log::error('ExamPdfExportService: 保存学情 PDF 失败', [
|
|
|
|
|
- 'path' => $path,
|
|
|
|
|
- ]);
|
|
|
|
|
|
|
+ Log::error('ExamPdfExportService: 保存学情PDF失败', ['path' => $path]);
|
|
|
return null;
|
|
return null;
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- // 根据记录类型将 URL 写入不同表
|
|
|
|
|
- try {
|
|
|
|
|
- if ($recordId) {
|
|
|
|
|
- // OCR 记录:写入 ocr_records 表
|
|
|
|
|
- $ocrRecord = \App\Models\OCRRecord::find($recordId);
|
|
|
|
|
- if ($ocrRecord) {
|
|
|
|
|
- $ocrRecord->update(['analysis_pdf_url' => $url]);
|
|
|
|
|
- Log::info('ExamPdfExportService: OCR记录学情分析PDF URL已写入数据库', [
|
|
|
|
|
- 'record_id' => $recordId,
|
|
|
|
|
- 'paper_id' => $paperId,
|
|
|
|
|
- 'student_id' => $studentId,
|
|
|
|
|
- 'url' => $url,
|
|
|
|
|
- ]);
|
|
|
|
|
- }
|
|
|
|
|
- } else {
|
|
|
|
|
- // 学生记录:写入 students 表
|
|
|
|
|
- $student = \App\Models\Student::where('student_id', $studentId)->first();
|
|
|
|
|
- if ($student) {
|
|
|
|
|
- $student->update(['student_report_pdf_url' => $url]);
|
|
|
|
|
- Log::info('ExamPdfExportService: 学生学情报告PDF URL已写入数据库', [
|
|
|
|
|
- 'student_id' => $studentId,
|
|
|
|
|
- 'paper_id' => $paperId,
|
|
|
|
|
- 'url' => $url,
|
|
|
|
|
- ]);
|
|
|
|
|
- }
|
|
|
|
|
- }
|
|
|
|
|
- } catch (\Throwable $e) {
|
|
|
|
|
- Log::error('ExamPdfExportService: 写入学情分析PDF URL失败', [
|
|
|
|
|
- 'paper_id' => $paperId,
|
|
|
|
|
- 'student_id' => $studentId,
|
|
|
|
|
- 'record_id' => $recordId,
|
|
|
|
|
- 'error' => $e->getMessage(),
|
|
|
|
|
- ]);
|
|
|
|
|
- }
|
|
|
|
|
|
|
+ // 保存URL到数据库
|
|
|
|
|
+ $this->saveAnalysisPdfUrl($paperId, $studentId, $recordId, $url);
|
|
|
|
|
|
|
|
return $url;
|
|
return $url;
|
|
|
|
|
+
|
|
|
} catch (\Throwable $e) {
|
|
} catch (\Throwable $e) {
|
|
|
- Log::error('ExamPdfExportService: 生成学情分析 PDF 失败', [
|
|
|
|
|
|
|
+ Log::error('ExamPdfExportService: 生成学情分析PDF失败', [
|
|
|
'paper_id' => $paperId,
|
|
'paper_id' => $paperId,
|
|
|
'student_id' => $studentId,
|
|
'student_id' => $studentId,
|
|
|
'record_id' => $recordId,
|
|
'record_id' => $recordId,
|
|
@@ -177,21 +120,24 @@ class ExamPdfExportService
|
|
|
}
|
|
}
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- private function renderAndStore(
|
|
|
|
|
|
|
+ /**
|
|
|
|
|
+ * 渲染并存储试卷PDF
|
|
|
|
|
+ */
|
|
|
|
|
+ private function renderAndStoreExamPdf(
|
|
|
string $paperId,
|
|
string $paperId,
|
|
|
bool $includeAnswer,
|
|
bool $includeAnswer,
|
|
|
string $suffix,
|
|
string $suffix,
|
|
|
bool $useGradingView = false
|
|
bool $useGradingView = false
|
|
|
): ?string {
|
|
): ?string {
|
|
|
- // 放宽脚本执行时间,避免长耗时渲染被 PHP 全局超时打断
|
|
|
|
|
|
|
+ // 放宽脚本执行时间
|
|
|
if (function_exists('set_time_limit')) {
|
|
if (function_exists('set_time_limit')) {
|
|
|
@set_time_limit(240);
|
|
@set_time_limit(240);
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
try {
|
|
|
- $html = $this->renderHtml($paperId, $includeAnswer, $useGradingView);
|
|
|
|
|
|
|
+ $html = $this->renderExamHtml($paperId, $includeAnswer, $useGradingView);
|
|
|
if (!$html) {
|
|
if (!$html) {
|
|
|
- Log::error('ExamPdfExportService: 渲染 HTML 为空', [
|
|
|
|
|
|
|
+ Log::error('ExamPdfExportService: 渲染HTML为空', [
|
|
|
'paper_id' => $paperId,
|
|
'paper_id' => $paperId,
|
|
|
'include_answer' => $includeAnswer,
|
|
'include_answer' => $includeAnswer,
|
|
|
'use_grading_view' => $useGradingView,
|
|
'use_grading_view' => $useGradingView,
|
|
@@ -207,15 +153,14 @@ class ExamPdfExportService
|
|
|
$path = "exams/{$paperId}_{$suffix}.pdf";
|
|
$path = "exams/{$paperId}_{$suffix}.pdf";
|
|
|
$url = $this->pdfStorageService->put($path, $pdfBinary);
|
|
$url = $this->pdfStorageService->put($path, $pdfBinary);
|
|
|
if (!$url) {
|
|
if (!$url) {
|
|
|
- Log::error('ExamPdfExportService: 保存 PDF 失败', [
|
|
|
|
|
- 'path' => $path,
|
|
|
|
|
- ]);
|
|
|
|
|
|
|
+ Log::error('ExamPdfExportService: 保存PDF失败', ['path' => $path]);
|
|
|
return null;
|
|
return null;
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
return $url;
|
|
return $url;
|
|
|
|
|
+
|
|
|
} catch (\Throwable $e) {
|
|
} catch (\Throwable $e) {
|
|
|
- Log::error('ExamPdfExportService: 生成 PDF 失败', [
|
|
|
|
|
|
|
+ Log::error('ExamPdfExportService: 生成PDF失败', [
|
|
|
'paper_id' => $paperId,
|
|
'paper_id' => $paperId,
|
|
|
'suffix' => $suffix,
|
|
'suffix' => $suffix,
|
|
|
'error' => $e->getMessage(),
|
|
'error' => $e->getMessage(),
|
|
@@ -226,71 +171,232 @@ class ExamPdfExportService
|
|
|
}
|
|
}
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- private function renderHtml(string $paperId, bool $includeAnswer, bool $useGradingView): ?string
|
|
|
|
|
|
|
+ /**
|
|
|
|
|
+ * 渲染试卷HTML(重构版)
|
|
|
|
|
+ */
|
|
|
|
|
+ private function renderExamHtml(string $paperId, bool $includeAnswer, bool $useGradingView): ?string
|
|
|
{
|
|
{
|
|
|
- // 复用已有控制器的渲染逻辑,保证版式一致
|
|
|
|
|
- $request = Request::create(
|
|
|
|
|
- '/admin/intelligent-exam/' . ($useGradingView ? 'grading' : 'pdf') . '/' . $paperId,
|
|
|
|
|
- 'GET',
|
|
|
|
|
- ['answer' => $includeAnswer ? 'true' : 'false']
|
|
|
|
|
- );
|
|
|
|
|
-
|
|
|
|
|
- $view = $useGradingView
|
|
|
|
|
- ? $this->controller->showGrading($request, $paperId)
|
|
|
|
|
- : $this->controller->show($request, $paperId);
|
|
|
|
|
-
|
|
|
|
|
- if (is_object($view) && method_exists($view, 'render')) {
|
|
|
|
|
- return $this->ensureUtf8Html($view->render());
|
|
|
|
|
|
|
+ // 直接构造请求URL,使用路由生成HTML
|
|
|
|
|
+ $routeName = $useGradingView
|
|
|
|
|
+ ? 'filament.admin.auth.intelligent-exam.grading'
|
|
|
|
|
+ : 'filament.admin.auth.intelligent-exam.pdf';
|
|
|
|
|
+
|
|
|
|
|
+ $url = route($routeName, ['paper_id' => $paperId, 'answer' => $includeAnswer ? 'true' : 'false']);
|
|
|
|
|
+
|
|
|
|
|
+ // 使用HTTP客户端获取渲染后的HTML
|
|
|
|
|
+ try {
|
|
|
|
|
+ $response = Http::get($url);
|
|
|
|
|
+ if ($response->successful()) {
|
|
|
|
|
+ return $this->ensureUtf8Html($response->body());
|
|
|
|
|
+ }
|
|
|
|
|
+ } catch (\Exception $e) {
|
|
|
|
|
+ Log::warning('ExamPdfExportService: 通过HTTP获取HTML失败,使用备用方案', [
|
|
|
|
|
+ 'paper_id' => $paperId,
|
|
|
|
|
+ 'error' => $e->getMessage(),
|
|
|
|
|
+ ]);
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- return null;
|
|
|
|
|
|
|
+ // 备用方案:直接渲染视图(如果路由不可用)
|
|
|
|
|
+ try {
|
|
|
|
|
+ $paper = Paper::with('questions')->find($paperId);
|
|
|
|
|
+ if (!$paper) {
|
|
|
|
|
+ return null;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ $viewName = $useGradingView ? 'exam-pdf.grading' : 'exam-pdf.student';
|
|
|
|
|
+ $html = view($viewName, compact('paper'))->render();
|
|
|
|
|
+ return $this->ensureUtf8Html($html);
|
|
|
|
|
+
|
|
|
|
|
+ } catch (\Exception $e) {
|
|
|
|
|
+ Log::error('ExamPdfExportService: 备用方案渲染失败', [
|
|
|
|
|
+ 'paper_id' => $paperId,
|
|
|
|
|
+ 'error' => $e->getMessage(),
|
|
|
|
|
+ ]);
|
|
|
|
|
+ return null;
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ /**
|
|
|
|
|
+ * 构建分析数据(重构版)
|
|
|
|
|
+ */
|
|
|
|
|
+ private function buildAnalysisData(string $paperId, string $studentId): ?array
|
|
|
|
|
+ {
|
|
|
|
|
+ $paper = Paper::with(['questions' => function ($query) {
|
|
|
|
|
+ $query->orderBy('question_number')->orderBy('id');
|
|
|
|
|
+ }])->find($paperId);
|
|
|
|
|
+
|
|
|
|
|
+ if (!$paper) {
|
|
|
|
|
+ Log::error('ExamPdfExportService: 未找到试卷', [
|
|
|
|
|
+ 'paper_id' => $paperId,
|
|
|
|
|
+ 'student_id' => $studentId,
|
|
|
|
|
+ ]);
|
|
|
|
|
+ return null;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ $student = Student::find($studentId);
|
|
|
|
|
+ $studentInfo = [
|
|
|
|
|
+ 'id' => $student?->student_id ?? $studentId,
|
|
|
|
|
+ 'name' => $student?->name ?? $studentId,
|
|
|
|
|
+ 'grade' => $student?->grade ?? '未知年级',
|
|
|
|
|
+ 'class' => $student?->class_name ?? '未知班级',
|
|
|
|
|
+ ];
|
|
|
|
|
+
|
|
|
|
|
+ // 获取分析数据
|
|
|
|
|
+ $analysisData = [];
|
|
|
|
|
+ if (!empty($paper->analysis_id)) {
|
|
|
|
|
+ $analysis = $this->learningAnalyticsService->getAnalysisResult($paper->analysis_id);
|
|
|
|
|
+ if (!empty($analysis['data'])) {
|
|
|
|
|
+ $analysisData = $analysis['data'];
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // 获取掌握度数据
|
|
|
|
|
+ $masteryData = [];
|
|
|
|
|
+ $masteryResponse = $this->learningAnalyticsService->getStudentMastery($studentId);
|
|
|
|
|
+ if (!empty($masteryResponse['data'])) {
|
|
|
|
|
+ $masteryData = $masteryResponse['data'];
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // 获取学习建议
|
|
|
|
|
+ $recommendations = [];
|
|
|
|
|
+ $recommendationResponse = $this->learningAnalyticsService->getLearningRecommendations($studentId);
|
|
|
|
|
+ if (!empty($recommendationResponse['data'])) {
|
|
|
|
|
+ $recommendations = $recommendationResponse['data'];
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // 获取知识点名称映射
|
|
|
|
|
+ $kpNameMap = $this->buildKnowledgePointNameMap();
|
|
|
|
|
+
|
|
|
|
|
+ // 获取题目详情
|
|
|
|
|
+ $questionDetails = $this->getQuestionDetailsFromPaper($paper);
|
|
|
|
|
+
|
|
|
|
|
+ // 处理题目数据
|
|
|
|
|
+ $questions = $this->processQuestionsForReport($paper, $questionDetails, $kpNameMap);
|
|
|
|
|
+
|
|
|
|
|
+ return [
|
|
|
|
|
+ 'paper' => [
|
|
|
|
|
+ 'id' => $paper->paper_id,
|
|
|
|
|
+ 'name' => $paper->paper_name,
|
|
|
|
|
+ 'total_questions' => $paper->question_count,
|
|
|
|
|
+ 'total_score' => $paper->total_score,
|
|
|
|
|
+ 'created_at' => $paper->created_at,
|
|
|
|
|
+ ],
|
|
|
|
|
+ 'student' => $studentInfo,
|
|
|
|
|
+ 'questions' => $questions,
|
|
|
|
|
+ 'mastery' => $this->buildMasterySummary($masteryData, $kpNameMap),
|
|
|
|
|
+ 'insights' => $analysisData['question_results'] ?? [],
|
|
|
|
|
+ 'recommendations' => $recommendations,
|
|
|
|
|
+ 'analysis_data' => $analysisData,
|
|
|
|
|
+ ];
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ /**
|
|
|
|
|
+ * 获取题目详情
|
|
|
|
|
+ */
|
|
|
|
|
+ private function getQuestionDetailsFromPaper(Paper $paper): array
|
|
|
|
|
+ {
|
|
|
|
|
+ $details = [];
|
|
|
|
|
+ $questionIds = $paper->questions->pluck('question_id')->filter()->unique()->values();
|
|
|
|
|
+
|
|
|
|
|
+ foreach ($questionIds as $qid) {
|
|
|
|
|
+ try {
|
|
|
|
|
+ $detail = $this->questionBankService->getQuestion((string) $qid);
|
|
|
|
|
+ if (!empty($detail)) {
|
|
|
|
|
+ $details[(string) $qid] = $detail;
|
|
|
|
|
+ }
|
|
|
|
|
+ } catch (\Throwable $e) {
|
|
|
|
|
+ Log::warning('ExamPdfExportService: 获取题目详情失败', [
|
|
|
|
|
+ 'question_id' => $qid,
|
|
|
|
|
+ 'error' => $e->getMessage(),
|
|
|
|
|
+ ]);
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ return $details;
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
+ /**
|
|
|
|
|
+ * 处理题目数据(用于报告)
|
|
|
|
|
+ */
|
|
|
|
|
+ private function processQuestionsForReport(Paper $paper, array $questionDetails, array $kpNameMap): array
|
|
|
|
|
+ {
|
|
|
|
|
+ $grouped = [
|
|
|
|
|
+ 'choice' => [],
|
|
|
|
|
+ 'fill' => [],
|
|
|
|
|
+ 'answer' => [],
|
|
|
|
|
+ ];
|
|
|
|
|
+
|
|
|
|
|
+ $sortedQuestions = $paper->questions
|
|
|
|
|
+ ->sortBy(function (PaperQuestion $q, int $idx) {
|
|
|
|
|
+ $number = $q->question_number ?? $idx + 1;
|
|
|
|
|
+ return is_numeric($number) ? (float) $number : ($q->id ?? $idx);
|
|
|
|
|
+ });
|
|
|
|
|
+
|
|
|
|
|
+ foreach ($sortedQuestions as $idx => $question) {
|
|
|
|
|
+ $kpCode = $question->knowledge_point ?? '';
|
|
|
|
|
+ $kpName = $kpNameMap[$kpCode] ?? $kpCode ?: '未标注';
|
|
|
|
|
+ $detail = $questionDetails[(string) ($question->question_id ?? '')] ?? [];
|
|
|
|
|
+ $solution = $detail['solution'] ?? $detail['解析'] ?? $detail['analysis'] ?? null;
|
|
|
|
|
+ $typeRaw = $question->question_type ?? ($detail['question_type'] ?? $detail['type'] ?? '');
|
|
|
|
|
+ $normalizedType = $this->normalizeQuestionType($typeRaw);
|
|
|
|
|
+ $number = $question->question_number ?? ($idx + 1);
|
|
|
|
|
+
|
|
|
|
|
+ $payload = [
|
|
|
|
|
+ 'question_number' => $number,
|
|
|
|
|
+ 'question_text' => is_array($question->question_text)
|
|
|
|
|
+ ? json_encode($question->question_text, JSON_UNESCAPED_UNICODE)
|
|
|
|
|
+ : ($question->question_text ?? ''),
|
|
|
|
|
+ 'question_type' => $normalizedType,
|
|
|
|
|
+ 'knowledge_point' => $kpCode,
|
|
|
|
|
+ 'knowledge_point_name' => $kpName,
|
|
|
|
|
+ 'score' => $question->score,
|
|
|
|
|
+ 'solution' => $solution,
|
|
|
|
|
+ ];
|
|
|
|
|
+
|
|
|
|
|
+ $grouped[$normalizedType][] = $payload;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ $ordered = array_merge($grouped['choice'], $grouped['fill'], $grouped['answer']);
|
|
|
|
|
+
|
|
|
|
|
+ // 按卷面顺序重新编号
|
|
|
|
|
+ foreach ($ordered as $i => &$q) {
|
|
|
|
|
+ $q['display_number'] = $i + 1;
|
|
|
|
|
+ }
|
|
|
|
|
+ unset($q);
|
|
|
|
|
+
|
|
|
|
|
+ return $ordered;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ /**
|
|
|
|
|
+ * 构建PDF
|
|
|
|
|
+ */
|
|
|
private function buildPdf(string $html): ?string
|
|
private function buildPdf(string $html): ?string
|
|
|
{
|
|
{
|
|
|
$tmpHtml = tempnam(sys_get_temp_dir(), 'exam_html_') . '.html';
|
|
$tmpHtml = tempnam(sys_get_temp_dir(), 'exam_html_') . '.html';
|
|
|
$utf8Html = $this->ensureUtf8Html($html);
|
|
$utf8Html = $this->ensureUtf8Html($html);
|
|
|
file_put_contents($tmpHtml, $utf8Html);
|
|
file_put_contents($tmpHtml, $utf8Html);
|
|
|
|
|
|
|
|
- // 仅使用 Chrome 渲染,去掉 wkhtmltopdf 兜底以暴露真实问题
|
|
|
|
|
|
|
+ // 仅使用Chrome渲染
|
|
|
$chromePdf = $this->renderWithChrome($tmpHtml);
|
|
$chromePdf = $this->renderWithChrome($tmpHtml);
|
|
|
@unlink($tmpHtml);
|
|
@unlink($tmpHtml);
|
|
|
return $chromePdf;
|
|
return $chromePdf;
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
+ /**
|
|
|
|
|
+ * 使用Chrome渲染PDF
|
|
|
|
|
+ */
|
|
|
private function renderWithChrome(string $htmlPath): ?string
|
|
private function renderWithChrome(string $htmlPath): ?string
|
|
|
{
|
|
{
|
|
|
$tmpPdf = tempnam(sys_get_temp_dir(), 'exam_pdf_') . '.pdf';
|
|
$tmpPdf = tempnam(sys_get_temp_dir(), 'exam_pdf_') . '.pdf';
|
|
|
- // 每次使用唯一的临时用户目录,彻底避免钥匙串问题
|
|
|
|
|
$userDataDir = sys_get_temp_dir() . '/chrome-profile-' . uniqid();
|
|
$userDataDir = sys_get_temp_dir() . '/chrome-profile-' . uniqid();
|
|
|
|
|
|
|
|
- $chromeBinary = env('PDF_CHROME_BINARY');
|
|
|
|
|
- if (!$chromeBinary) {
|
|
|
|
|
- $candidates = [
|
|
|
|
|
- '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
|
|
|
|
|
- '/usr/bin/google-chrome-stable',
|
|
|
|
|
- '/usr/bin/google-chrome',
|
|
|
|
|
- '/usr/bin/chromium-browser',
|
|
|
|
|
- '/usr/bin/chromium',
|
|
|
|
|
- ];
|
|
|
|
|
- foreach ($candidates as $path) {
|
|
|
|
|
- if (is_file($path) && is_executable($path)) {
|
|
|
|
|
- $chromeBinary = $path;
|
|
|
|
|
- break;
|
|
|
|
|
- }
|
|
|
|
|
- }
|
|
|
|
|
- }
|
|
|
|
|
-
|
|
|
|
|
|
|
+ $chromeBinary = $this->findChromeBinary();
|
|
|
if (!$chromeBinary) {
|
|
if (!$chromeBinary) {
|
|
|
- Log::error('ExamPdfExportService: 未找到可用的 Chrome/Chromium,已停止导出', [
|
|
|
|
|
- 'html_path' => $htmlPath,
|
|
|
|
|
- 'path_env' => env('PATH'),
|
|
|
|
|
- 'candidates_checked' => $candidates ?? [],
|
|
|
|
|
- ]);
|
|
|
|
|
|
|
+ Log::error('ExamPdfExportService: 未找到可用的Chrome/Chromium');
|
|
|
return null;
|
|
return null;
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- // 为无权限环境设置可写的 HOME/XDG 目录,避免创建 /var/www/.local 报错
|
|
|
|
|
|
|
+ // 设置运行时目录
|
|
|
$runtimeHome = sys_get_temp_dir() . '/chrome-home';
|
|
$runtimeHome = sys_get_temp_dir() . '/chrome-home';
|
|
|
$runtimeXdg = sys_get_temp_dir() . '/chrome-xdg';
|
|
$runtimeXdg = sys_get_temp_dir() . '/chrome-xdg';
|
|
|
if (!File::exists($runtimeHome)) {
|
|
if (!File::exists($runtimeHome)) {
|
|
@@ -340,142 +446,66 @@ class ExamPdfExportService
|
|
|
'HOME' => $runtimeHome,
|
|
'HOME' => $runtimeHome,
|
|
|
'XDG_RUNTIME_DIR' => $runtimeXdg,
|
|
'XDG_RUNTIME_DIR' => $runtimeXdg,
|
|
|
]);
|
|
]);
|
|
|
- $process->setTimeout(60);
|
|
|
|
|
|
|
|
|
|
|
|
+ $process->setTimeout(60);
|
|
|
$killSignal = \defined('SIGKILL') ? \SIGKILL : 9;
|
|
$killSignal = \defined('SIGKILL') ? \SIGKILL : 9;
|
|
|
|
|
|
|
|
try {
|
|
try {
|
|
|
$startedAt = microtime(true);
|
|
$startedAt = microtime(true);
|
|
|
- Log::info('ExamPdfExportService: Chrome 渲染启动', [
|
|
|
|
|
- 'cmd' => $process->getCommandLine(),
|
|
|
|
|
- 'html_path' => $htmlPath,
|
|
|
|
|
- 'tmp_pdf' => $tmpPdf,
|
|
|
|
|
- 'user_data_dir' => $userDataDir,
|
|
|
|
|
- 'html_exists' => file_exists($htmlPath),
|
|
|
|
|
- 'html_size' => file_exists($htmlPath) ? filesize($htmlPath) : null,
|
|
|
|
|
- 'cwd' => $process->getWorkingDirectory(),
|
|
|
|
|
- ]);
|
|
|
|
|
$process->start();
|
|
$process->start();
|
|
|
$pdfGenerated = false;
|
|
$pdfGenerated = false;
|
|
|
|
|
|
|
|
- // 轮询检测 PDF 是否生成,尽快返回,避免等待 Chrome 完整退出
|
|
|
|
|
|
|
+ // 轮询检测PDF是否生成
|
|
|
$pollStart = microtime(true);
|
|
$pollStart = microtime(true);
|
|
|
$maxPollSeconds = 30;
|
|
$maxPollSeconds = 30;
|
|
|
while ($process->isRunning() && (microtime(true) - $pollStart) < $maxPollSeconds) {
|
|
while ($process->isRunning() && (microtime(true) - $pollStart) < $maxPollSeconds) {
|
|
|
if (file_exists($tmpPdf) && filesize($tmpPdf) > 0) {
|
|
if (file_exists($tmpPdf) && filesize($tmpPdf) > 0) {
|
|
|
$pdfGenerated = true;
|
|
$pdfGenerated = true;
|
|
|
- Log::info('ExamPdfExportService: 发现 PDF 已生成,提前结束 Chrome', [
|
|
|
|
|
- 'duration_sec' => round(microtime(true) - $startedAt, 3),
|
|
|
|
|
- 'tmp_pdf_size' => filesize($tmpPdf),
|
|
|
|
|
- ]);
|
|
|
|
|
$process->stop(5, $killSignal);
|
|
$process->stop(5, $killSignal);
|
|
|
break;
|
|
break;
|
|
|
}
|
|
}
|
|
|
- usleep(200_000); // 200ms
|
|
|
|
|
|
|
+ usleep(200_000);
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- // 如果仍在运行且超过轮询窗口,则强制结束
|
|
|
|
|
if ($process->isRunning()) {
|
|
if ($process->isRunning()) {
|
|
|
- Log::warning('ExamPdfExportService: Chrome 轮询超时,强制结束', [
|
|
|
|
|
- 'duration_sec' => round(microtime(true) - $startedAt, 3),
|
|
|
|
|
- ]);
|
|
|
|
|
$process->stop(5, $killSignal);
|
|
$process->stop(5, $killSignal);
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
$process->wait();
|
|
$process->wait();
|
|
|
- Log::info('ExamPdfExportService: Chrome 渲染完成', [
|
|
|
|
|
- 'duration_sec' => round(microtime(true) - $startedAt, 3),
|
|
|
|
|
- 'exit_code' => $process->getExitCode(),
|
|
|
|
|
- 'tmp_pdf_exists' => file_exists($tmpPdf),
|
|
|
|
|
- 'tmp_pdf_size' => file_exists($tmpPdf) ? filesize($tmpPdf) : null,
|
|
|
|
|
- 'stderr' => $process->getErrorOutput(),
|
|
|
|
|
- 'stdout' => $process->getOutput(),
|
|
|
|
|
- 'pdf_generated_during_poll' => $pdfGenerated,
|
|
|
|
|
- ]);
|
|
|
|
|
|
|
+
|
|
|
} catch (ProcessTimedOutException|ProcessSignaledException $e) {
|
|
} catch (ProcessTimedOutException|ProcessSignaledException $e) {
|
|
|
- Log::error('ExamPdfExportService: Chrome 进程异常', [
|
|
|
|
|
- 'cmd' => $process->getCommandLine(),
|
|
|
|
|
- 'signal' => method_exists($process, 'getTermSignal') ? $process->getTermSignal() : null,
|
|
|
|
|
- 'error' => $process->getErrorOutput(),
|
|
|
|
|
- 'output' => $process->getOutput(),
|
|
|
|
|
- 'exit_code' => $process->getExitCode(),
|
|
|
|
|
- 'exception' => $e->getMessage(),
|
|
|
|
|
- 'trace' => $e->getTraceAsString(),
|
|
|
|
|
- ]);
|
|
|
|
|
if ($process->isRunning()) {
|
|
if ($process->isRunning()) {
|
|
|
$process->stop(5, $killSignal);
|
|
$process->stop(5, $killSignal);
|
|
|
}
|
|
}
|
|
|
- $pdfExists = file_exists($tmpPdf);
|
|
|
|
|
- $pdfSize = $pdfExists ? filesize($tmpPdf) : null;
|
|
|
|
|
- if ($pdfExists && $pdfSize > 0) {
|
|
|
|
|
- Log::warning('ExamPdfExportService: Chrome 异常但产生了 PDF,尝试继续返回', [
|
|
|
|
|
- 'tmp_pdf_exists' => $pdfExists,
|
|
|
|
|
- 'tmp_pdf_size' => $pdfSize,
|
|
|
|
|
- 'duration_sec' => isset($startedAt) ? round(microtime(true) - $startedAt, 3) : null,
|
|
|
|
|
- ]);
|
|
|
|
|
- $pdfBinary = file_get_contents($tmpPdf);
|
|
|
|
|
- @unlink($tmpPdf);
|
|
|
|
|
- File::deleteDirectory($userDataDir);
|
|
|
|
|
- return $pdfBinary ?: null;
|
|
|
|
|
- }
|
|
|
|
|
- @unlink($tmpPdf);
|
|
|
|
|
- File::deleteDirectory($userDataDir);
|
|
|
|
|
- return null;
|
|
|
|
|
|
|
+ return $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, $startedAt);
|
|
|
} catch (\Throwable $e) {
|
|
} catch (\Throwable $e) {
|
|
|
- Log::error('ExamPdfExportService: Chrome 调用异常', [
|
|
|
|
|
- 'cmd' => $process->getCommandLine(),
|
|
|
|
|
- 'error' => $e->getMessage(),
|
|
|
|
|
- 'exit_code' => $process->getExitCode(),
|
|
|
|
|
- 'stderr' => $process->getErrorOutput(),
|
|
|
|
|
- 'stdout' => $process->getOutput(),
|
|
|
|
|
- 'trace' => $e->getTraceAsString(),
|
|
|
|
|
- ]);
|
|
|
|
|
if ($process->isRunning()) {
|
|
if ($process->isRunning()) {
|
|
|
$process->stop(5, $killSignal);
|
|
$process->stop(5, $killSignal);
|
|
|
}
|
|
}
|
|
|
- $pdfExists = file_exists($tmpPdf);
|
|
|
|
|
- $pdfSize = $pdfExists ? filesize($tmpPdf) : null;
|
|
|
|
|
- if ($pdfExists && $pdfSize > 0) {
|
|
|
|
|
- Log::warning('ExamPdfExportService: Chrome 调用异常但产生了 PDF,尝试继续返回', [
|
|
|
|
|
- 'tmp_pdf_exists' => $pdfExists,
|
|
|
|
|
- 'tmp_pdf_size' => $pdfSize,
|
|
|
|
|
- 'duration_sec' => isset($startedAt) ? round(microtime(true) - $startedAt, 3) : null,
|
|
|
|
|
- ]);
|
|
|
|
|
- $pdfBinary = file_get_contents($tmpPdf);
|
|
|
|
|
- @unlink($tmpPdf);
|
|
|
|
|
- File::deleteDirectory($userDataDir);
|
|
|
|
|
- return $pdfBinary ?: null;
|
|
|
|
|
- }
|
|
|
|
|
- @unlink($tmpPdf);
|
|
|
|
|
- File::deleteDirectory($userDataDir);
|
|
|
|
|
- return null;
|
|
|
|
|
|
|
+ return $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, null);
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
+ return $this->handleChromeProcessResult($tmpPdf, $userDataDir, $process, null);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ /**
|
|
|
|
|
+ * 处理Chrome进程结果
|
|
|
|
|
+ */
|
|
|
|
|
+ private function handleChromeProcessResult(string $tmpPdf, string $userDataDir, Process $process, ?float $startedAt): ?string
|
|
|
|
|
+ {
|
|
|
$pdfExists = file_exists($tmpPdf);
|
|
$pdfExists = file_exists($tmpPdf);
|
|
|
$pdfSize = $pdfExists ? filesize($tmpPdf) : null;
|
|
$pdfSize = $pdfExists ? filesize($tmpPdf) : null;
|
|
|
|
|
|
|
|
if (!$process->isSuccessful()) {
|
|
if (!$process->isSuccessful()) {
|
|
|
if ($pdfExists && $pdfSize > 0) {
|
|
if ($pdfExists && $pdfSize > 0) {
|
|
|
- Log::warning('ExamPdfExportService: Chrome 进程异常但生成了 PDF,继续使用', [
|
|
|
|
|
- 'cmd' => implode(' ', (array) $process->getCommandLine()),
|
|
|
|
|
|
|
+ Log::warning('ExamPdfExportService: Chrome进程异常但生成了PDF', [
|
|
|
'exit_code' => $process->getExitCode(),
|
|
'exit_code' => $process->getExitCode(),
|
|
|
- 'error' => $process->getErrorOutput(),
|
|
|
|
|
- 'output' => $process->getOutput(),
|
|
|
|
|
- 'tmp_pdf_exists' => $pdfExists,
|
|
|
|
|
'tmp_pdf_size' => $pdfSize,
|
|
'tmp_pdf_size' => $pdfSize,
|
|
|
- 'html_path' => $htmlPath,
|
|
|
|
|
- 'user_data_dir' => $userDataDir,
|
|
|
|
|
]);
|
|
]);
|
|
|
} else {
|
|
} else {
|
|
|
- Log::error('ExamPdfExportService: Chrome 渲染失败', [
|
|
|
|
|
- 'cmd' => implode(' ', (array) $process->getCommandLine()),
|
|
|
|
|
|
|
+ Log::error('ExamPdfExportService: Chrome渲染失败', [
|
|
|
'exit_code' => $process->getExitCode(),
|
|
'exit_code' => $process->getExitCode(),
|
|
|
'error' => $process->getErrorOutput(),
|
|
'error' => $process->getErrorOutput(),
|
|
|
- 'output' => $process->getOutput(),
|
|
|
|
|
- 'tmp_pdf_exists' => $pdfExists,
|
|
|
|
|
- 'tmp_pdf_size' => $pdfSize,
|
|
|
|
|
- 'html_path' => $htmlPath,
|
|
|
|
|
- 'user_data_dir' => $userDataDir,
|
|
|
|
|
]);
|
|
]);
|
|
|
@unlink($tmpPdf);
|
|
@unlink($tmpPdf);
|
|
|
File::deleteDirectory($userDataDir);
|
|
File::deleteDirectory($userDataDir);
|
|
@@ -489,172 +519,60 @@ class ExamPdfExportService
|
|
|
return $pdfBinary ?: null;
|
|
return $pdfBinary ?: null;
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- private function buildAnalysisPayload(string $paperId, string $studentId): ?array
|
|
|
|
|
|
|
+ /**
|
|
|
|
|
+ * 查找Chrome二进制文件
|
|
|
|
|
+ */
|
|
|
|
|
+ private function findChromeBinary(): ?string
|
|
|
{
|
|
{
|
|
|
- $paper = Paper::with(['questions' => function ($query) {
|
|
|
|
|
- $query->orderBy('question_number')->orderBy('id');
|
|
|
|
|
- }])->find($paperId);
|
|
|
|
|
- if (!$paper) {
|
|
|
|
|
- Log::error('ExamPdfExportService: 未找到试卷,无法生成学情报告', [
|
|
|
|
|
- 'paper_id' => $paperId,
|
|
|
|
|
- 'student_id' => $studentId,
|
|
|
|
|
- ]);
|
|
|
|
|
- return null;
|
|
|
|
|
- }
|
|
|
|
|
-
|
|
|
|
|
- $student = Student::find($studentId);
|
|
|
|
|
- $studentInfo = [
|
|
|
|
|
- 'id' => $student?->student_id ?? $studentId,
|
|
|
|
|
- 'name' => $student?->name ?? $studentId,
|
|
|
|
|
- 'grade' => $student?->grade ?? '未知年级',
|
|
|
|
|
- 'class' => $student?->class_name ?? '未知班级',
|
|
|
|
|
|
|
+ $candidates = [
|
|
|
|
|
+ env('PDF_CHROME_BINARY'),
|
|
|
|
|
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
|
|
|
|
|
+ '/usr/bin/google-chrome-stable',
|
|
|
|
|
+ '/usr/bin/google-chrome',
|
|
|
|
|
+ '/usr/bin/chromium-browser',
|
|
|
|
|
+ '/usr/bin/chromium',
|
|
|
];
|
|
];
|
|
|
|
|
|
|
|
- // 调用学习分析服务获取本卷分析与掌握度
|
|
|
|
|
- $analysisData = [];
|
|
|
|
|
- if (!empty($paper->analysis_id)) {
|
|
|
|
|
- $analysis = $this->learningAnalyticsService->getAnalysisResult($paper->analysis_id);
|
|
|
|
|
- if (!empty($analysis['data'])) {
|
|
|
|
|
- $analysisData = $analysis['data'];
|
|
|
|
|
|
|
+ foreach ($candidates as $path) {
|
|
|
|
|
+ if ($path && is_file($path) && is_executable($path)) {
|
|
|
|
|
+ return $path;
|
|
|
}
|
|
}
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- $masteryData = [];
|
|
|
|
|
- $masteryResponse = $this->learningAnalyticsService->getStudentMastery($studentId);
|
|
|
|
|
- if (!empty($masteryResponse['data'])) {
|
|
|
|
|
- $masteryData = $masteryResponse['data'];
|
|
|
|
|
- }
|
|
|
|
|
-
|
|
|
|
|
- $recommendations = [];
|
|
|
|
|
- $recommendationResponse = $this->learningAnalyticsService->getLearningRecommendations($studentId);
|
|
|
|
|
- if (!empty($recommendationResponse['data'])) {
|
|
|
|
|
- $recommendations = $recommendationResponse['data'];
|
|
|
|
|
- }
|
|
|
|
|
-
|
|
|
|
|
- $kpNameMap = $this->buildKnowledgePointNameMap();
|
|
|
|
|
-
|
|
|
|
|
- // 预取题库详情用于解析/解题思路
|
|
|
|
|
- $questionDetails = [];
|
|
|
|
|
- $questionIds = $paper->questions->pluck('question_id')->filter()->unique()->values();
|
|
|
|
|
- foreach ($questionIds as $qid) {
|
|
|
|
|
- try {
|
|
|
|
|
- $detail = $this->questionBankService->getQuestion((string) $qid);
|
|
|
|
|
- if (!empty($detail)) {
|
|
|
|
|
- $questionDetails[(string) $qid] = $detail;
|
|
|
|
|
- }
|
|
|
|
|
- } catch (\Throwable $e) {
|
|
|
|
|
- Log::warning('ExamPdfExportService: 获取题库题目详情失败', [
|
|
|
|
|
- 'question_id' => $qid,
|
|
|
|
|
- 'error' => $e->getMessage(),
|
|
|
|
|
- ]);
|
|
|
|
|
- }
|
|
|
|
|
- }
|
|
|
|
|
-
|
|
|
|
|
- // 分组保持卷面顺序:选择题 -> 填空题 -> 解答题
|
|
|
|
|
- $grouped = [
|
|
|
|
|
- 'choice' => [],
|
|
|
|
|
- 'fill' => [],
|
|
|
|
|
- 'answer' => [],
|
|
|
|
|
- ];
|
|
|
|
|
-
|
|
|
|
|
- $sortedQuestions = $paper->questions
|
|
|
|
|
- ->sortBy(function (PaperQuestion $q, int $idx) {
|
|
|
|
|
- $number = $q->question_number ?? $idx + 1;
|
|
|
|
|
- return is_numeric($number) ? (float) $number : ($q->id ?? $idx);
|
|
|
|
|
- });
|
|
|
|
|
-
|
|
|
|
|
- foreach ($sortedQuestions as $idx => $question) {
|
|
|
|
|
- $kpCode = $question->knowledge_point ?? '';
|
|
|
|
|
- $kpName = $kpNameMap[$kpCode] ?? $kpCode ?: '未标注';
|
|
|
|
|
- $detail = $questionDetails[(string) ($question->question_id ?? '')] ?? [];
|
|
|
|
|
- $solution = $detail['solution'] ?? $detail['解析'] ?? $detail['analysis'] ?? null;
|
|
|
|
|
- // 题型优先使用试卷记录,其次题库详情
|
|
|
|
|
- $typeRaw = $question->question_type ?? ($detail['question_type'] ?? $detail['type'] ?? '');
|
|
|
|
|
- $normalizedType = $this->normalizeQuestionType($typeRaw);
|
|
|
|
|
- $number = $question->question_number ?? ($idx + 1);
|
|
|
|
|
-
|
|
|
|
|
- $payload = [
|
|
|
|
|
- 'question_number' => $number,
|
|
|
|
|
- 'question_text' => is_array($question->question_text) ? json_encode($question->question_text, JSON_UNESCAPED_UNICODE) : ($question->question_text ?? ''),
|
|
|
|
|
- 'question_type' => $normalizedType,
|
|
|
|
|
- 'knowledge_point' => $kpCode,
|
|
|
|
|
- 'knowledge_point_name' => $kpName,
|
|
|
|
|
- 'score' => $question->score,
|
|
|
|
|
- 'solution' => $solution,
|
|
|
|
|
- ];
|
|
|
|
|
-
|
|
|
|
|
- $grouped[$normalizedType][] = $payload;
|
|
|
|
|
- }
|
|
|
|
|
-
|
|
|
|
|
- $ordered = array_merge($grouped['choice'], $grouped['fill'], $grouped['answer']);
|
|
|
|
|
|
|
+ return null;
|
|
|
|
|
+ }
|
|
|
|
|
|
|
|
- // 按卷面顺序重新编号以匹配判卷/显示
|
|
|
|
|
- foreach ($ordered as $i => &$q) {
|
|
|
|
|
- $q['display_number'] = $i + 1;
|
|
|
|
|
|
|
+ /**
|
|
|
|
|
+ * 确保HTML为UTF-8编码
|
|
|
|
|
+ */
|
|
|
|
|
+ private function ensureUtf8Html(string $html): string
|
|
|
|
|
+ {
|
|
|
|
|
+ $meta = '<meta charset="UTF-8">';
|
|
|
|
|
+ if (stripos($html, '<head>') !== false) {
|
|
|
|
|
+ return preg_replace('/<head>/i', "<head>{$meta}", $html, 1);
|
|
|
}
|
|
}
|
|
|
- unset($q);
|
|
|
|
|
-
|
|
|
|
|
- $questions = $ordered;
|
|
|
|
|
-
|
|
|
|
|
- $questionInsights = $analysisData['question_results'] ?? [];
|
|
|
|
|
- $masterySummary = $this->buildMasterySummary($masteryData, $kpNameMap);
|
|
|
|
|
-
|
|
|
|
|
- return [
|
|
|
|
|
- 'paper' => [
|
|
|
|
|
- 'id' => $paper->paper_id,
|
|
|
|
|
- 'name' => $paper->paper_name,
|
|
|
|
|
- 'total_questions' => $paper->question_count,
|
|
|
|
|
- 'total_score' => $paper->total_score,
|
|
|
|
|
- 'created_at' => $paper->created_at,
|
|
|
|
|
- ],
|
|
|
|
|
- 'student' => $studentInfo,
|
|
|
|
|
- 'questions' => $questions,
|
|
|
|
|
- 'mastery' => $masterySummary,
|
|
|
|
|
- 'question_insights' => $questionInsights,
|
|
|
|
|
- 'recommendations' => $recommendations,
|
|
|
|
|
- 'analysis_data' => $analysisData,
|
|
|
|
|
- ];
|
|
|
|
|
|
|
+ return $meta . $html;
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
+ /**
|
|
|
|
|
+ * 构建知识点名称映射
|
|
|
|
|
+ */
|
|
|
private function buildKnowledgePointNameMap(): array
|
|
private function buildKnowledgePointNameMap(): array
|
|
|
{
|
|
{
|
|
|
try {
|
|
try {
|
|
|
- // 优先使用 QuestionServiceApi(已有知识点名称缓存)
|
|
|
|
|
- if (class_exists(QuestionServiceApi::class)) {
|
|
|
|
|
- /** @var QuestionServiceApi $service */
|
|
|
|
|
- $service = app(QuestionServiceApi::class);
|
|
|
|
|
- $options = $service->getKnowledgePointOptions();
|
|
|
|
|
- if (!empty($options)) {
|
|
|
|
|
- return $options;
|
|
|
|
|
- }
|
|
|
|
|
- }
|
|
|
|
|
-
|
|
|
|
|
- // 退回 QuestionBankService(可能缺少此方法)
|
|
|
|
|
- if (method_exists($this->questionBankService, 'getKnowledgePointOptions')) {
|
|
|
|
|
- $options = $this->questionBankService->getKnowledgePointOptions();
|
|
|
|
|
- $map = [];
|
|
|
|
|
- foreach ($options as $item) {
|
|
|
|
|
- if (is_array($item)) {
|
|
|
|
|
- $code = $item['kp_code'] ?? null;
|
|
|
|
|
- $name = $item['kp_name'] ?? $item['name'] ?? null;
|
|
|
|
|
- if ($code && $name) {
|
|
|
|
|
- $map[$code] = $name;
|
|
|
|
|
- }
|
|
|
|
|
- }
|
|
|
|
|
- }
|
|
|
|
|
- if (!empty($map)) {
|
|
|
|
|
- return $map;
|
|
|
|
|
- }
|
|
|
|
|
- }
|
|
|
|
|
|
|
+ $options = $this->questionServiceApi->getKnowledgePointOptions();
|
|
|
|
|
+ return $options ?: [];
|
|
|
} catch (\Throwable $e) {
|
|
} catch (\Throwable $e) {
|
|
|
- Log::warning('ExamPdfExportService: 获取知识点名称失败,退回使用编码', [
|
|
|
|
|
|
|
+ Log::warning('ExamPdfExportService: 获取知识点名称失败', [
|
|
|
'error' => $e->getMessage(),
|
|
'error' => $e->getMessage(),
|
|
|
]);
|
|
]);
|
|
|
|
|
+ return [];
|
|
|
}
|
|
}
|
|
|
-
|
|
|
|
|
- return [];
|
|
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
+ /**
|
|
|
|
|
+ * 构建掌握度摘要
|
|
|
|
|
+ */
|
|
|
private function buildMasterySummary(array $masteryData, array $kpNameMap): array
|
|
private function buildMasterySummary(array $masteryData, array $kpNameMap): array
|
|
|
{
|
|
{
|
|
|
$items = [];
|
|
$items = [];
|
|
@@ -665,25 +583,26 @@ class ExamPdfExportService
|
|
|
foreach ($masteryData as $row) {
|
|
foreach ($masteryData as $row) {
|
|
|
$code = $row['kp_code'] ?? null;
|
|
$code = $row['kp_code'] ?? null;
|
|
|
if ($hasMap && $code && !isset($kpNameMap[$code])) {
|
|
if ($hasMap && $code && !isset($kpNameMap[$code])) {
|
|
|
- // 不在知识图谱中的知识点不呈现
|
|
|
|
|
continue;
|
|
continue;
|
|
|
}
|
|
}
|
|
|
$name = $row['kp_name'] ?? ($code ? ($kpNameMap[$code] ?? $code) : '未知知识点');
|
|
$name = $row['kp_name'] ?? ($code ? ($kpNameMap[$code] ?? $code) : '未知知识点');
|
|
|
$level = (float) ($row['mastery_level'] ?? 0);
|
|
$level = (float) ($row['mastery_level'] ?? 0);
|
|
|
$delta = $row['mastery_change'] ?? null;
|
|
$delta = $row['mastery_change'] ?? null;
|
|
|
|
|
+
|
|
|
$items[] = [
|
|
$items[] = [
|
|
|
'kp_code' => $code,
|
|
'kp_code' => $code,
|
|
|
'kp_name' => $name,
|
|
'kp_name' => $name,
|
|
|
'mastery_level' => $level,
|
|
'mastery_level' => $level,
|
|
|
'mastery_change' => $delta,
|
|
'mastery_change' => $delta,
|
|
|
];
|
|
];
|
|
|
|
|
+
|
|
|
$total += $level;
|
|
$total += $level;
|
|
|
$count++;
|
|
$count++;
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
$average = $count > 0 ? round($total / $count, 2) : null;
|
|
$average = $count > 0 ? round($total / $count, 2) : null;
|
|
|
|
|
|
|
|
- // 按掌握度从低到高排序,便于突出薄弱点
|
|
|
|
|
|
|
+ // 按掌握度从低到高排序
|
|
|
usort($items, fn($a, $b) => ($a['mastery_level'] <=> $b['mastery_level']));
|
|
usort($items, fn($a, $b) => ($a['mastery_level'] <=> $b['mastery_level']));
|
|
|
|
|
|
|
|
return [
|
|
return [
|
|
@@ -693,9 +612,12 @@ class ExamPdfExportService
|
|
|
];
|
|
];
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- private function normalizeQuestionType(?string $type): string
|
|
|
|
|
|
|
+ /**
|
|
|
|
|
+ * 标准化题型
|
|
|
|
|
+ */
|
|
|
|
|
+ private function normalizeQuestionType(string $type): string
|
|
|
{
|
|
{
|
|
|
- $t = strtolower(trim((string) $type));
|
|
|
|
|
|
|
+ $t = strtolower(trim($type));
|
|
|
return match (true) {
|
|
return match (true) {
|
|
|
str_contains($t, 'choice') || str_contains($t, '选择') => 'choice',
|
|
str_contains($t, 'choice') || str_contains($t, '选择') => 'choice',
|
|
|
str_contains($t, 'fill') || str_contains($t, 'blank') || str_contains($t, '填空') => 'fill',
|
|
str_contains($t, 'fill') || str_contains($t, 'blank') || str_contains($t, '填空') => 'fill',
|
|
@@ -703,13 +625,77 @@ class ExamPdfExportService
|
|
|
};
|
|
};
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- private function ensureUtf8Html(string $html): string
|
|
|
|
|
|
|
+ /**
|
|
|
|
|
+ * 保存PDF URL到数据库
|
|
|
|
|
+ */
|
|
|
|
|
+ private function savePdfUrlToDatabase(string $paperId, string $field, string $url): void
|
|
|
{
|
|
{
|
|
|
- $meta = '<meta charset="UTF-8">';
|
|
|
|
|
- if (stripos($html, '<head>') !== false) {
|
|
|
|
|
- return preg_replace('/<head>/i', "<head>{$meta}", $html, 1);
|
|
|
|
|
|
|
+ try {
|
|
|
|
|
+ $paper = Paper::where('paper_id', $paperId)->first();
|
|
|
|
|
+ if ($paper) {
|
|
|
|
|
+ $paper->update([$field => $url]);
|
|
|
|
|
+ Log::info('ExamPdfExportService: PDF URL已写入数据库', [
|
|
|
|
|
+ 'paper_id' => $paperId,
|
|
|
|
|
+ 'field' => $field,
|
|
|
|
|
+ 'url' => $url,
|
|
|
|
|
+ ]);
|
|
|
|
|
+ }
|
|
|
|
|
+ } catch (\Throwable $e) {
|
|
|
|
|
+ Log::error('ExamPdfExportService: 写入PDF URL失败', [
|
|
|
|
|
+ 'paper_id' => $paperId,
|
|
|
|
|
+ 'field' => $field,
|
|
|
|
|
+ 'error' => $e->getMessage(),
|
|
|
|
|
+ ]);
|
|
|
}
|
|
}
|
|
|
- return $meta . $html;
|
|
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
+ /**
|
|
|
|
|
+ * 保存学情分析PDF URL
|
|
|
|
|
+ */
|
|
|
|
|
+ private function saveAnalysisPdfUrl(string $paperId, string $studentId, ?string $recordId, string $url): void
|
|
|
|
|
+ {
|
|
|
|
|
+ try {
|
|
|
|
|
+ if ($recordId) {
|
|
|
|
|
+ // OCR记录
|
|
|
|
|
+ $ocrRecord = \App\Models\OCRRecord::find($recordId);
|
|
|
|
|
+ if ($ocrRecord) {
|
|
|
|
|
+ $ocrRecord->update(['analysis_pdf_url' => $url]);
|
|
|
|
|
+ Log::info('ExamPdfExportService: OCR记录学情分析PDF URL已写入数据库', [
|
|
|
|
|
+ 'record_id' => $recordId,
|
|
|
|
|
+ 'paper_id' => $paperId,
|
|
|
|
|
+ 'student_id' => $studentId,
|
|
|
|
|
+ 'url' => $url,
|
|
|
|
|
+ ]);
|
|
|
|
|
+ }
|
|
|
|
|
+ } else {
|
|
|
|
|
+ // 学生记录 - 使用新的 student_reports 表
|
|
|
|
|
+ \App\Models\StudentReport::updateOrCreate(
|
|
|
|
|
+ [
|
|
|
|
|
+ 'student_id' => $studentId,
|
|
|
|
|
+ 'report_type' => 'exam_analysis',
|
|
|
|
|
+ 'exam_id' => $paperId,
|
|
|
|
|
+ ],
|
|
|
|
|
+ [
|
|
|
|
|
+ 'pdf_url' => $url,
|
|
|
|
|
+ 'generation_status' => 'completed',
|
|
|
|
|
+ 'generated_at' => now(),
|
|
|
|
|
+ 'updated_at' => now(),
|
|
|
|
|
+ ]
|
|
|
|
|
+ );
|
|
|
|
|
+
|
|
|
|
|
+ Log::info('ExamPdfExportService: 学生学情报告PDF URL已保存到student_reports表', [
|
|
|
|
|
+ 'student_id' => $studentId,
|
|
|
|
|
+ 'paper_id' => $paperId,
|
|
|
|
|
+ 'url' => $url,
|
|
|
|
|
+ ]);
|
|
|
|
|
+ }
|
|
|
|
|
+ } catch (\Throwable $e) {
|
|
|
|
|
+ Log::error('ExamPdfExportService: 写入学情分析PDF URL失败', [
|
|
|
|
|
+ 'paper_id' => $paperId,
|
|
|
|
|
+ 'student_id' => $studentId,
|
|
|
|
|
+ 'record_id' => $recordId,
|
|
|
|
|
+ 'error' => $e->getMessage(),
|
|
|
|
|
+ ]);
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
}
|
|
}
|