| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337 |
- <?php
- namespace App\Filament\Pages;
- use App\Jobs\ImportTemToQuestionsJob;
- use App\Services\ExamPdfExportService;
- use App\Services\MathFormulaProcessor;
- use App\Services\QuestionQualityCheckService;
- use App\Services\QuestionsTemAssemblyService;
- use App\Services\QuestionTemReviewService;
- use BackedEnum;
- use Filament\Notifications\Notification;
- use Filament\Pages\Page;
- use Filament\Support\Enums\Width;
- use Illuminate\Support\Facades\Auth;
- use Illuminate\Support\Facades\Cache;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Schema;
- use Livewire\Attributes\Computed;
- use Livewire\Attributes\Renderless;
- use Livewire\Attributes\Url;
- use UnitEnum;
- class QuestionTemQualityReview extends Page
- {
- protected static ?string $title = '待入库题目质检';
- protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-clipboard-document-check';
- protected static ?string $navigationLabel = '待入库质检';
- protected static string|UnitEnum|null $navigationGroup = '题库管理';
- protected static ?int $navigationSort = 4;
- /**
- * 三栏布局需要占满主内容区,避免被默认 max-width 压成窄条导致样式像「纯文本」。
- */
- protected Width|string|null $maxContentWidth = Width::Full;
- protected string $view = 'filament.pages.question-tem-quality-review';
- #[Url(as: 'kp', except: '')]
- public ?string $selectedKpCode = null;
- /** 左侧知识点列表搜索(匹配 kp_code、kp_name,不区分大小写) */
- #[Url(as: 'kps', except: '')]
- public string $kpSearch = '';
- /** 左侧按年级筛选;空字符串=全部 */
- #[Url(as: 'grade', except: '')]
- public string $gradeFilter = '';
- /** 左侧按学期筛选;空字符串=全部 */
- #[Url(as: 'semester', except: '')]
- public string $semesterFilter = '';
- /** 中间卡片首屏渲染数量(性能优先,按需加载更多) */
- public int $cardRenderLimit = 20;
- public ?int $selectedTemId = null;
- /** 中间区多选:questions_tem.id,点击题目切换勾选 */
- public array $selectedTemIds = [];
- /** 逐题审核后加入「待入库」清单的 tem id 列表 */
- public array $pendingImportTemIds = [];
- /** 为 true 时才计算/展示高级区质检与重复提示(避免每次点击跑质检) */
- public bool $qcPanelExpanded = false;
- /** 单题入库难度(0.00–0.90,两位小数;切换题目时从 questions_tem 同步) */
- public string $importDifficultyInput = '0.50';
- /** 生成临时试卷后,判卷页预览 URL(与正式组卷同源路由) */
- public ?string $trialGradingUrl = null;
- /** 与 generateGradingPdf 同源导出的判卷 PDF 地址(可下载) */
- public ?string $trialGradingPdfUrl = null;
- public function mount(): void
- {
- if (! Schema::hasTable('questions_tem')) {
- Notification::make()
- ->title('缺少 questions_tem 表')
- ->danger()
- ->send();
- }
- }
- public function updatedSelectedKpCode(): void
- {
- $this->selectedTemId = null;
- $this->selectedTemIds = [];
- $this->pendingImportTemIds = [];
- $this->cardRenderLimit = 20;
- $this->importDifficultyInput = '0.50';
- $this->qcPanelExpanded = false;
- }
- public function updatedGradeFilter(): void
- {
- $this->semesterFilter = '';
- $this->selectedKpCode = null;
- $this->selectedTemId = null;
- $this->selectedTemIds = [];
- $this->pendingImportTemIds = [];
- $this->cardRenderLimit = 20;
- $this->importDifficultyInput = '0.50';
- $this->qcPanelExpanded = false;
- }
- public function updatedSemesterFilter(): void
- {
- $this->selectedKpCode = null;
- $this->selectedTemId = null;
- $this->selectedTemIds = [];
- $this->pendingImportTemIds = [];
- $this->cardRenderLimit = 20;
- $this->importDifficultyInput = '0.50';
- $this->qcPanelExpanded = false;
- }
- #[Computed]
- public function kpRows(): array
- {
- return app(QuestionTemReviewService::class)->listKnowledgePointsByQuestionsAsc(
- null,
- $this->parseGradeFilter(),
- $this->parseSemesterFilter()
- );
- }
- /** @return list<array{value:string,label:string}> */
- #[Computed]
- public function gradeOptions(): array
- {
- $vals = app(QuestionTemReviewService::class)->catalogGradeOptions($this->parseSemesterFilter());
- $out = [];
- foreach ($vals as $g) {
- $v = (string) ((int) $g);
- $out[] = ['value' => $v, 'label' => $this->formatGradeLabel((int) $g)];
- }
- return $out;
- }
- /** @return list<array{value:string,label:string}> */
- #[Computed]
- public function semesterOptions(): array
- {
- $vals = app(QuestionTemReviewService::class)->catalogSemesterOptions($this->parseGradeFilter());
- $out = [];
- foreach ($vals as $s) {
- $v = (string) ((int) $s);
- $out[] = ['value' => $v, 'label' => $this->formatSemesterLabel((int) $s)];
- }
- return $out;
- }
- /**
- * 左侧列表:按搜索词筛选知识点(代码、名称子串匹配,UTF-8)
- *
- * @return list<array{kp_code: string, kp_name: string, questions_count: int, tem_count: int, tem_importable_count: int}>
- */
- #[Computed]
- public function filteredKpRows(): array
- {
- $rows = array_values(array_filter(
- $this->kpRows,
- static fn (array $row): bool => (int) ($row['tem_importable_count'] ?? 0) > 0
- ));
- $raw = trim($this->kpSearch);
- if ($raw === '') {
- return $rows;
- }
- $needle = mb_strtolower($raw, 'UTF-8');
- return array_values(array_filter($rows, function (array $row) use ($needle): bool {
- $code = mb_strtolower((string) ($row['kp_code'] ?? ''), 'UTF-8');
- $name = mb_strtolower((string) ($row['kp_name'] ?? ''), 'UTF-8');
- return mb_strpos($code, $needle, 0, 'UTF-8') !== false
- || mb_strpos($name, $needle, 0, 'UTF-8') !== false;
- }));
- }
- #[Computed]
- public function temQuestions(): array
- {
- if (! $this->selectedKpCode) {
- return [];
- }
- $key = $this->buildPageCacheKey('tem_questions');
- return Cache::remember($key, now()->addMinutes(3), function (): array {
- $rows = app(QuestionTemReviewService::class)->listTemQuestionsForKp(
- $this->selectedKpCode,
- 300,
- true,
- $this->parseGradeFilter()
- );
- return $this->sortRowsByQuestionType($rows);
- });
- }
- /**
- * 独立审核卡片模型:清洗题干、给出三项快检,并附上该题完整渲染所需分组数据。
- *
- * @return list<array{id:int, stem_preview:string, checks:array{stem:bool,answer:bool,solution:bool}, meta:array{created_at:?string,updated_at:?string,difficulty:string,audit_reason:string}, grouped_questions:array{choice:array<int,object>,fill:array<int,object>,answer:array<int,object>}}>
- */
- #[Computed]
- public function temQuestionCards(): array
- {
- $key = $this->buildPageCacheKey('tem_cards');
- return Cache::remember($key, now()->addMinutes(3), function (): array {
- $cards = [];
- foreach ($this->temQuestions as $row) {
- $arr = is_array($row) ? $row : (array) $row;
- $id = (int) ($arr['id'] ?? 0);
- if ($id <= 0) {
- continue;
- }
- $stem = $this->normalizeStemPreview((string) ($arr['stem'] ?? ''));
- $answer = trim((string) ($arr['answer'] ?? $arr['correct_answer'] ?? ''));
- $solution = trim((string) ($arr['solution'] ?? ''));
- $cards[] = [
- 'id' => $id,
- 'stem_preview' => $stem,
- 'checks' => [
- 'stem' => $stem !== '',
- 'answer' => $answer !== '',
- 'solution' => $solution !== '',
- ],
- 'meta' => [
- 'created_at' => $this->formatMetaDatetime($arr['created_at'] ?? null),
- 'updated_at' => $this->formatMetaDatetime($arr['updated_at'] ?? null),
- 'difficulty' => $this->formatMetaDifficulty($arr['difficulty'] ?? null),
- 'audit_reason' => $this->formatMetaAuditReason($arr['audit_reason'] ?? null),
- ],
- 'grouped_questions' => $this->buildPreviewGroupedQuestionsFromTemRows([$arr]),
- ];
- }
- return $cards;
- });
- }
- /**
- * 与判卷 PDF / pdf.exam-grading 使用同一套 components.exam.paper-body 数据管线
- *
- * @return array{choice: array, fill: array, answer: array}
- */
- #[Computed]
- public function groupedPaperBodyQuestions(): array
- {
- if (! $this->selectedKpCode) {
- return ['choice' => [], 'fill' => [], 'answer' => []];
- }
- return $this->buildPreviewGroupedQuestionsFromTemRows($this->temQuestions);
- }
- /** @return list<object> */
- #[Computed]
- public function assemblyQueueRows(): array
- {
- $uid = Auth::id();
- if (! $uid) {
- return [];
- }
- return app(QuestionsTemAssemblyService::class)->queueForUser((int) $uid);
- }
- #[Computed]
- public function selectedRow(): ?object
- {
- if (! $this->selectedTemId) {
- return null;
- }
- return DB::table('questions_tem')->where('id', $this->selectedTemId)->first();
- }
- /**
- * @return array{passed: bool, errors: array, results: array}|null
- */
- #[Computed]
- public function qcResult(): ?array
- {
- if (! $this->qcPanelExpanded) {
- return null;
- }
- $row = $this->selectedRow;
- if (! $row) {
- return null;
- }
- $mapped = $this->mapQuestionRowForQc((array) $row);
- $qc = app(QuestionQualityCheckService::class)->runAutoCheck($mapped, (int) $row->id, null);
- return [
- 'passed' => $qc['passed'],
- 'errors' => $qc['errors'],
- 'results' => $qc['results'],
- ];
- }
- #[Computed]
- public function duplicateHint(): ?string
- {
- if (! $this->qcPanelExpanded) {
- return null;
- }
- $row = $this->selectedRow;
- if (! $row) {
- return null;
- }
- $svc = app(QuestionTemReviewService::class);
- $stem = $svc->normalizedStemFromTemRow($row);
- $kp = (string) ($row->kp_code ?? '');
- if ($stem === '' || $kp === '') {
- return null;
- }
- if ($svc->existsDuplicateInQuestions($kp, $stem)) {
- return '正式库已存在同知识点、同题干题目';
- }
- return null;
- }
- public function selectKp(string $kpCode): void
- {
- $this->selectedKpCode = $kpCode;
- $this->selectedTemId = null;
- $this->selectedTemIds = [];
- $this->pendingImportTemIds = [];
- $this->cardRenderLimit = 20;
- $this->importDifficultyInput = '0.50';
- $this->qcPanelExpanded = false;
- $this->dispatch('qtr-scroll-top');
- }
- public function loadMoreCards(): void
- {
- $this->cardRenderLimit += 20;
- $this->dispatch('qtr-scroll-top');
- }
- #[Computed]
- public function visibleTemQuestionCards(): array
- {
- return array_slice($this->temQuestionCards, 0, max(1, $this->cardRenderLimit));
- }
- /** @return list<object> */
- #[Computed]
- public function pendingImportRows(): array
- {
- if ($this->pendingImportTemIds === []) {
- return [];
- }
- $rows = DB::table('questions_tem')
- ->whereIn('id', $this->pendingImportTemIds)
- ->get()
- ->keyBy('id');
- $ordered = [];
- foreach ($this->pendingImportTemIds as $id) {
- $row = $rows->get((int) $id);
- if ($row) {
- $ordered[] = $row;
- }
- }
- return $this->sortRowsByQuestionType($ordered);
- }
- /**
- * 右侧人工判重参考:当前选中知识点在正式库 questions 的题目(编号+题干)。
- *
- * @return list<object>
- */
- #[Computed]
- public function currentKpQuestionStemRows(): array
- {
- if (! $this->selectedKpCode || ! Schema::hasTable('questions')) {
- return [];
- }
- $key = $this->buildPageCacheKey('kp_question_stems_v2');
- return Cache::remember($key, now()->addMinutes(2), function (): array {
- $q = DB::table('questions')
- ->where('kp_code', $this->selectedKpCode)
- ->select(['id', 'stem', 'question_type', 'options', 'answer', 'solution'])
- ->orderByRaw("
- CASE
- WHEN LOWER(COALESCE(question_type, '')) LIKE '%choice%' OR question_type LIKE '%选择%' THEN 1
- WHEN LOWER(COALESCE(question_type, '')) LIKE '%fill%' OR LOWER(COALESCE(question_type, '')) LIKE '%blank%' OR question_type LIKE '%填空%' THEN 2
- ELSE 3
- END ASC
- ")
- ->orderBy('id');
- // 右侧人工判重列表仅按当前选中知识点展示:
- // 年级/学期筛选已在左侧知识点范围内收敛,避免对 questions.grade 再次过滤导致误空。
- return $q->limit(300)->get()->all();
- });
- }
- /**
- * 中间卡片:给每道 tem 题计算「当前知识点下最相似的正式库题目」综合相似度。
- *
- * @return array<int, array{question_id:int, score:float, score_text:string}>
- */
- #[Computed]
- public function temSimilarityHints(): array
- {
- if (! $this->selectedKpCode) {
- return [];
- }
- $temRows = $this->visibleTemQuestionCards;
- $questionRows = $this->currentKpQuestionStemRows;
- if ($temRows === [] || $questionRows === []) {
- return [];
- }
- $normalizedQuestions = [];
- foreach ($questionRows as $qr) {
- $qid = (int) ($qr->id ?? 0);
- if ($qid <= 0) {
- continue;
- }
- $normalizedQuestions[$qid] = [
- 'type' => $this->normalizeSimilarityQuestionType((string) ($qr->question_type ?? '')),
- 'stem' => $this->normalizeSimilarityText((string) ($qr->stem ?? '')),
- 'options' => $this->normalizeSimilarityOptions($qr->options ?? null),
- 'answer' => $this->normalizeSimilarityText((string) ($qr->answer ?? '')),
- 'solution' => $this->normalizeSimilarityText((string) ($qr->solution ?? '')),
- ];
- }
- $out = [];
- foreach ($temRows as $card) {
- $tid = (int) ($card['id'] ?? 0);
- if ($tid <= 0) {
- continue;
- }
- $grouped = $card['grouped_questions'] ?? ['choice' => [], 'fill' => [], 'answer' => []];
- $q = $grouped['choice'][0] ?? $grouped['fill'][0] ?? $grouped['answer'][0] ?? null;
- $temPayload = [
- 'type' => $this->normalizeSimilarityQuestionType((string) ($q->question_type ?? '')),
- 'stem' => $this->normalizeSimilarityText((string) ($q->stem ?? $q->content ?? $card['stem_preview'] ?? '')),
- 'options' => $this->normalizeSimilarityOptions($q->options ?? null),
- 'answer' => $this->normalizeSimilarityText((string) ($q->answer ?? '')),
- 'solution' => $this->normalizeSimilarityText((string) ($q->solution ?? '')),
- ];
- if ($temPayload['stem'] === '') {
- continue;
- }
- $bestQid = 0;
- $bestScore = 0.0;
- foreach ($normalizedQuestions as $qid => $questionPayload) {
- if (($questionPayload['stem'] ?? '') === '') {
- continue;
- }
- if ($temPayload['type'] !== '' && $questionPayload['type'] !== '' && $temPayload['type'] !== $questionPayload['type']) {
- continue;
- }
- $score = $this->calculateCompositeSimilarityScore($temPayload, $questionPayload);
- if ($score > $bestScore) {
- $bestScore = $score;
- $bestQid = (int) $qid;
- }
- }
- if ($bestQid > 0) {
- $out[$tid] = [
- 'question_id' => $bestQid,
- 'score' => round($bestScore, 1),
- 'score_text' => number_format($bestScore, 1).'%',
- ];
- }
- }
- return $out;
- }
- public function updatedSelectedTemId(mixed $value): void
- {
- if ($this->selectedTemId) {
- $this->syncImportDifficultyFromSelectedRow();
- if (! in_array((int) $this->selectedTemId, $this->selectedTemIds, true)) {
- $this->selectedTemIds[] = (int) $this->selectedTemId;
- }
- } else {
- $this->importDifficultyInput = '0.50';
- }
- $this->selectedTemIds = array_values(array_unique(array_map('intval', $this->selectedTemIds)));
- }
- public function updatedSelectedTemIds(): void
- {
- $this->selectedTemIds = array_values(array_unique(array_filter(
- array_map('intval', $this->selectedTemIds),
- static fn (int $id) => $id > 0
- )));
- if ($this->selectedTemId && ! in_array((int) $this->selectedTemId, $this->selectedTemIds, true)) {
- $this->selectedTemId = $this->selectedTemIds[0] ?? null;
- }
- if (! $this->selectedTemId && $this->selectedTemIds !== []) {
- $this->selectedTemId = $this->selectedTemIds[0];
- }
- if ($this->selectedTemId) {
- $this->syncImportDifficultyFromSelectedRow();
- } else {
- $this->importDifficultyInput = '0.50';
- }
- }
- public function focusTemQuestion(int $id): void
- {
- if ($id <= 0) {
- return;
- }
- $this->selectedTemId = $id;
- if (! in_array($id, $this->selectedTemIds, true)) {
- $this->selectedTemIds[] = $id;
- $this->selectedTemIds = array_values(array_unique(array_map('intval', $this->selectedTemIds)));
- }
- $this->qcPanelExpanded = false;
- }
- public function addToPendingImport(int $id): void
- {
- if ($id <= 0) {
- return;
- }
- if (! in_array($id, $this->pendingImportTemIds, true)) {
- $this->pendingImportTemIds[] = $id;
- $this->pendingImportTemIds = array_values(array_unique(array_map('intval', $this->pendingImportTemIds)));
- }
- if ((int) ($this->selectedTemId ?? 0) === $id) {
- $this->selectedTemId = null;
- $this->importDifficultyInput = '0.50';
- }
- }
- #[Renderless]
- public function queueImportTem(int $id): void
- {
- if ($id <= 0) {
- return;
- }
- $status = Cache::get(ImportTemToQuestionsJob::statusKey($id));
- $state = (string) ($status['state'] ?? '');
- if (in_array($state, ['queued', 'running'], true)) {
- return;
- }
- Cache::put(ImportTemToQuestionsJob::statusKey($id), [
- 'state' => 'queued',
- 'message' => '已加入队列,等待处理',
- 'at' => now()->toDateTimeString(),
- ], now()->addMinutes(30));
- ImportTemToQuestionsJob::dispatch($id, Auth::id() ? (int) Auth::id() : null, $this->selectedKpCode);
- }
- public function markAsSimilarQuestion(int $temId, int $questionId): void
- {
- if ($temId <= 0 || $questionId <= 0) {
- Notification::make()->title('参数无效')->warning()->send();
- return;
- }
- if (! Schema::hasTable('questions_tem')) {
- Notification::make()->title('questions_tem 表不存在')->danger()->send();
- return;
- }
- $updates = [
- 'audit_reason' => "相似题{$questionId}",
- 'updated_at' => now(),
- ];
- if (Schema::hasColumn('questions_tem', 'audit_status')) {
- $updates['audit_status'] = -1;
- }
- DB::table('questions_tem')
- ->where('id', $temId)
- ->update($updates);
- $this->pendingImportTemIds = array_values(array_filter(
- $this->pendingImportTemIds,
- static fn ($x) => (int) $x !== $temId
- ));
- $this->forgetCurrentKpCaches();
- Notification::make()
- ->title("已标记为相似题 #{$questionId}")
- ->success()
- ->send();
- }
- public function removeFromPendingImport(int $id): void
- {
- $this->pendingImportTemIds = array_values(array_filter(
- $this->pendingImportTemIds,
- static fn ($x) => (int) $x !== $id
- ));
- }
- public function clearPendingImport(): void
- {
- $this->pendingImportTemIds = [];
- }
- public function importPendingTem(int $id): void
- {
- $this->queueImportTem($id);
- }
- public function importPendingAll(): void
- {
- if ($this->pendingImportTemIds === []) {
- Notification::make()->title('待入库为空')->warning()->send();
- return;
- }
- foreach ($this->pendingImportTemIds as $id) {
- $this->queueImportTem((int) $id);
- }
- }
- public function syncAsyncImportStatuses(): void
- {
- if ($this->pendingImportTemIds === []) {
- return;
- }
- $remaining = [];
- $doneFound = false;
- foreach ($this->pendingImportTemIds as $id) {
- $status = Cache::get(ImportTemToQuestionsJob::statusKey((int) $id));
- if (($status['state'] ?? null) === 'done') {
- $doneFound = true;
- continue;
- }
- $remaining[] = (int) $id;
- }
- if ($doneFound) {
- $this->pendingImportTemIds = array_values(array_unique($remaining));
- $this->forgetCurrentKpCaches();
- }
- }
- /** @return array<int, array{state?:string,message?:string,question_id?:int,at?:string}> */
- #[Computed]
- public function importStatusMap(): array
- {
- $ids = [];
- foreach ($this->temQuestionCards as $card) {
- $id = (int) ($card['id'] ?? 0);
- if ($id > 0) {
- $ids[] = $id;
- }
- }
- foreach ($this->pendingImportTemIds as $id) {
- $id = (int) $id;
- if ($id > 0) {
- $ids[] = $id;
- }
- }
- $ids = array_values(array_unique($ids));
- if ($ids === []) {
- return [];
- }
- $keys = [];
- foreach ($ids as $id) {
- $keys[$id] = ImportTemToQuestionsJob::statusKey($id);
- }
- $many = Cache::many(array_values($keys));
- $map = [];
- foreach ($keys as $id => $key) {
- $v = $many[$key] ?? null;
- if (is_array($v) && isset($v['state'])) {
- $map[(int) $id] = $v;
- }
- }
- return $map;
- }
- public function clearTemSelection(): void
- {
- $this->selectedTemIds = [];
- $this->selectedTemId = null;
- $this->importDifficultyInput = '0.50';
- $this->qcPanelExpanded = false;
- }
- public function importSelectedTemIdsFast(): void
- {
- if ($this->selectedTemIds === []) {
- Notification::make()->title('请先勾选题目')->warning()->send();
- return;
- }
- $svc = app(QuestionTemReviewService::class);
- $result = $svc->importTemIdsToQuestions($this->selectedTemIds);
- QuestionTemReviewService::mergeQuestionIdsIntoTuningSession($result['imported_question_ids'] ?? []);
- $this->notifyBulkImportResult($result);
- $this->selectedTemIds = [];
- $this->selectedTemId = null;
- $this->qcPanelExpanded = false;
- $this->dispatch('$refresh');
- }
- public function addSelectionToAssemblyQueue(): void
- {
- if ($this->selectedTemIds === []) {
- Notification::make()->title('请先勾选题目')->warning()->send();
- return;
- }
- $uid = Auth::id();
- if (! $uid) {
- return;
- }
- $svc = app(QuestionsTemAssemblyService::class);
- foreach ($this->selectedTemIds as $tid) {
- $svc->add((int) $uid, (int) $tid);
- }
- Notification::make()
- ->title('已加入待组卷队列(未写入 questions)')
- ->body('共 '.count($this->selectedTemIds).' 道')
- ->success()
- ->send();
- }
- public function removeFromAssemblyQueue(int $temId): void
- {
- $uid = Auth::id();
- if (! $uid) {
- return;
- }
- app(QuestionsTemAssemblyService::class)->remove((int) $uid, $temId);
- }
- public function clearAssemblyQueue(): void
- {
- $uid = Auth::id();
- if (! $uid) {
- return;
- }
- app(QuestionsTemAssemblyService::class)->clear((int) $uid);
- $this->trialGradingUrl = null;
- $this->trialGradingPdfUrl = null;
- Notification::make()->title('已清空待组卷队列')->success()->send();
- }
- public function generateTrialGradingPdf(): void
- {
- $uid = Auth::id();
- if (! $uid) {
- Notification::make()->title('未登录')->danger()->send();
- return;
- }
- $svc = app(QuestionsTemAssemblyService::class);
- if (! $svc->tableExists()) {
- Notification::make()->title('请先执行迁移:questions_tem_assembly_queue')->danger()->send();
- return;
- }
- $paperId = $svc->createTrialPaperForQueue((int) $uid);
- if (! $paperId) {
- Notification::make()->title('待组卷队列为空,请先「加入待组卷」')->warning()->send();
- return;
- }
- $this->trialGradingUrl = route('filament.admin.auth.intelligent-exam.grading', ['paper_id' => $paperId]);
- $this->trialGradingPdfUrl = null;
- $pdfBody = '';
- try {
- // 与正式组卷一致:学生卷 + 答案详解/判卷段 + 判题卡(强制追加扫描卡,不依赖 .env)
- $pdfUrl = app(ExamPdfExportService::class)->generateUnifiedPdf($paperId, false, true);
- $this->trialGradingPdfUrl = $pdfUrl ?: null;
- $pdfBody = $this->trialGradingPdfUrl
- ? '完整卷 PDF(学生卷 + 答案详解 + 判题卡)已生成,可下载核对。'
- : '完整卷 PDF 未返回地址,请仅用判卷页预览。';
- } catch (\Throwable $e) {
- $pdfBody = '完整卷 PDF 导出异常:'.$e->getMessage();
- }
- if (str_contains($pdfBody, '异常')) {
- Notification::make()
- ->title('已生成临时试卷(判卷页可预览)')
- ->body($pdfBody)
- ->warning()
- ->send();
- } else {
- Notification::make()
- ->title('已生成临时试卷')
- ->body('可打开判卷页预览。'.$pdfBody)
- ->success()
- ->send();
- }
- }
- /**
- * 将当前左侧选中知识点下,中间列表中的全部 questions_tem 写入 questions(与单题入库规则一致)
- */
- public function importAllCurrentKpToQuestions(): void
- {
- if (! $this->selectedKpCode) {
- Notification::make()->title('请先选择左侧知识点')->warning()->send();
- return;
- }
- $ids = [];
- foreach ($this->temQuestions as $row) {
- $ids[] = (int) ($row->id ?? 0);
- }
- if ($ids === []) {
- Notification::make()->title('当前知识点下没有待审题目')->warning()->send();
- return;
- }
- $svc = app(QuestionTemReviewService::class);
- $result = $svc->importTemIdsToQuestions($ids);
- QuestionTemReviewService::mergeQuestionIdsIntoTuningSession($result['imported_question_ids'] ?? []);
- $this->notifyBulkImportResult($result);
- $this->dispatch('$refresh');
- }
- /**
- * 将右侧「待组卷」队列中的全部 questions_tem 写入 questions
- */
- public function importAssemblyQueueToQuestions(): void
- {
- $uid = Auth::id();
- if (! $uid) {
- return;
- }
- $ids = [];
- foreach ($this->assemblyQueueRows as $row) {
- $ids[] = (int) ($row->id ?? 0);
- }
- if ($ids === []) {
- Notification::make()->title('待组卷队列为空')->warning()->send();
- return;
- }
- $svc = app(QuestionTemReviewService::class);
- $result = $svc->importTemIdsToQuestions($ids);
- QuestionTemReviewService::mergeQuestionIdsIntoTuningSession($result['imported_question_ids'] ?? []);
- $this->notifyBulkImportResult($result);
- $this->dispatch('$refresh');
- }
- /**
- * @param array{imported: int, skipped: int, failed: int, lines: list<string>, imported_question_ids?: list<int>} $result
- */
- private function notifyBulkImportResult(array $result): void
- {
- $body = sprintf(
- '成功 %d 道,跳过 %d 道(重复或缺字段),失败 %d 道。',
- $result['imported'],
- $result['skipped'],
- $result['failed']
- );
- if ($result['lines'] !== []) {
- $body .= "\n\n".implode("\n", $result['lines']);
- }
- $title = $result['imported'] > 0 ? '批量入库完成' : '批量入库结束';
- Notification::make()
- ->title($title)
- ->body($body)
- ->success()
- ->send();
- }
- public function importSelected(): void
- {
- if (! $this->selectedTemId) {
- Notification::make()->title('请先选择一道题目')->warning()->send();
- return;
- }
- $difficulty = $this->parseImportDifficultyValidated();
- if ($difficulty === null) {
- return;
- }
- $svc = app(QuestionTemReviewService::class);
- $result = $svc->importTemRowToQuestions($this->selectedTemId, $difficulty);
- if ($result['ok']) {
- if (! empty($result['question_id'])) {
- QuestionTemReviewService::mergeQuestionIdsIntoTuningSession([(int) $result['question_id']]);
- }
- $importedTemId = (int) $this->selectedTemId;
- Notification::make()
- ->title($result['message'])
- ->body(sprintf('question_id: %s · difficulty: %s', (string) $result['question_id'], number_format($difficulty, 2, '.', '')))
- ->success()
- ->send();
- $this->selectedTemIds = array_values(array_filter($this->selectedTemIds, fn ($x) => (int) $x !== $importedTemId));
- $this->selectedTemId = $this->selectedTemIds[count($this->selectedTemIds) - 1] ?? null;
- if ($this->selectedTemId) {
- $this->syncImportDifficultyFromSelectedRow();
- } else {
- $this->importDifficultyInput = '0.50';
- }
- $this->dispatch('$refresh');
- } else {
- Notification::make()->title($result['message'])->danger()->send();
- }
- }
- private function syncImportDifficultyFromSelectedRow(): void
- {
- $row = $this->selectedRow;
- if (! $row) {
- $this->importDifficultyInput = '0.50';
- return;
- }
- $d = app(QuestionTemReviewService::class)->defaultDifficultyForTemRow($row);
- $this->importDifficultyInput = number_format($d, 2, '.', '');
- }
- /**
- * @return ?float 合法难度,或 null(已弹通知)
- */
- private function parseImportDifficultyValidated(): ?float
- {
- $raw = trim($this->importDifficultyInput);
- if ($raw === '') {
- Notification::make()
- ->title('请填写难度系数')
- ->body('范围为 0.00~0.90,最多两位小数。')
- ->warning()
- ->send();
- return null;
- }
- if (! is_numeric($raw)) {
- Notification::make()
- ->title('难度系数格式不正确')
- ->body('请输入数字,例如 0.35。')
- ->danger()
- ->send();
- return null;
- }
- $value = round((float) $raw, 2);
- if ($value < 0.0 || $value > 0.9) {
- Notification::make()
- ->title('难度系数超出范围')
- ->body('仅允许 0.00~0.90(保留两位小数)。')
- ->danger()
- ->send();
- return null;
- }
- $this->importDifficultyInput = number_format($value, 2, '.', '');
- return $value;
- }
- /**
- * 仅用于质检页面预览:不改组卷主链路的控制器/视图逻辑。
- *
- * @param array<int, object|array> $rows
- * @return array{choice: array<int, object>, fill: array<int, object>, answer: array<int, object>}
- */
- private function buildPreviewGroupedQuestionsFromTemRows(array $rows): array
- {
- $grouped = ['choice' => [], 'fill' => [], 'answer' => []];
- foreach (array_values($rows) as $index => $row) {
- $arr = is_array($row) ? $row : (array) $row;
- $type = $this->normalizePreviewQuestionType((string) ($arr['question_type'] ?? $arr['tags'] ?? 'answer'));
- $options = $this->normalizePreviewOptions($arr['options'] ?? null);
- $questionData = [
- 'id' => isset($arr['id']) ? -abs((int) $arr['id']) : null,
- 'question_number' => $index + 1,
- 'content' => (string) ($arr['stem'] ?? ''),
- 'stem' => (string) ($arr['stem'] ?? ''),
- 'answer' => (string) ($arr['answer'] ?? $arr['correct_answer'] ?? ''),
- 'solution' => (string) ($arr['solution'] ?? ''),
- 'difficulty' => isset($arr['difficulty']) ? (float) $arr['difficulty'] : 0.5,
- 'kp_code' => (string) ($arr['kp_code'] ?? ''),
- 'tags' => is_string($arr['tags'] ?? null) ? $arr['tags'] : '',
- 'options' => $options,
- 'score' => $type === 'answer' ? 10 : 5,
- 'question_type' => $type,
- ];
- $grouped[$type][] = (object) $questionData;
- }
- return $grouped;
- }
- private function normalizePreviewQuestionType(string $raw): string
- {
- $t = mb_strtolower(trim($raw));
- return match (true) {
- str_contains($t, 'choice'), str_contains($t, '选择') => 'choice',
- str_contains($t, 'fill'), str_contains($t, 'blank'), str_contains($t, '填空') => 'fill',
- default => 'answer',
- };
- }
- /**
- * @return array<int, string>|null
- */
- private function normalizePreviewOptions(mixed $raw): ?array
- {
- if (is_string($raw)) {
- $decoded = json_decode($raw, true);
- $raw = is_array($decoded) ? $decoded : null;
- }
- if (! is_array($raw) || $raw === []) {
- return null;
- }
- if (! isset($raw[0])) {
- return array_values(array_map(static fn ($v) => (string) $v, $raw));
- }
- if (isset($raw[0]) && is_array($raw[0])) {
- $out = [];
- foreach ($raw as $opt) {
- $out[] = (string) (($opt['content'] ?? $opt['text'] ?? $opt['value'] ?? ''));
- }
- return $out;
- }
- return array_values(array_map(static fn ($v) => (string) $v, $raw));
- }
- private function mapQuestionRowForQc(array $row): array
- {
- $stem = trim((string) ($row['stem'] ?? ''));
- if ($stem === '') {
- $stem = trim((string) ($row['content'] ?? ''));
- }
- $options = $row['options'] ?? null;
- if (is_string($options) && trim($options) !== '') {
- $decoded = json_decode($options, true);
- $options = is_array($decoded) ? $decoded : null;
- }
- $qtRaw = (string) ($row['question_type'] ?? $row['tags'] ?? '');
- $qtLower = strtolower(trim($qtRaw));
- $explicitNonChoice = in_array($qtLower, ['fill', '填空', '填空题', 'answer', '解答', '解答题'], true);
- if (! $explicitNonChoice && is_array($options) && count($options) >= 2) {
- $qtForCheck = 'choice';
- } else {
- $qtForCheck = $qtRaw;
- }
- return [
- 'stem' => $stem,
- 'answer' => $row['answer'] ?? $row['correct_answer'] ?? '',
- 'solution' => $row['solution'] ?? '',
- 'question_type' => $qtForCheck,
- 'options' => $options,
- ];
- }
- private function normalizeStemPreview(string $stem): string
- {
- // 先去掉图片标签,避免界面出现一大串 <img ...>
- $text = preg_replace('/<img\b[^>]*>/iu', ' [图] ', $stem) ?? $stem;
- $text = strip_tags($text);
- $text = html_entity_decode($text, ENT_QUOTES | ENT_HTML5, 'UTF-8');
- $text = preg_replace('/\s+/u', ' ', $text) ?? $text;
- return trim($text);
- }
- private function normalizeSimilarityText(string $text): string
- {
- if ($text === '') {
- return '';
- }
- $text = MathFormulaProcessor::processFormulas($text);
- $text = preg_replace('/<img\b[^>]*>/iu', ' ', $text) ?? $text;
- $text = strip_tags($text);
- $text = html_entity_decode($text, ENT_QUOTES | ENT_HTML5, 'UTF-8');
- $text = mb_strtolower($text, 'UTF-8');
- $text = preg_replace('/[[:punct:]\p{P}\p{S}]+/u', ' ', $text) ?? $text;
- $text = preg_replace('/\s+/u', ' ', $text) ?? $text;
- return trim($text);
- }
- private function normalizeSimilarityOptions(mixed $raw): string
- {
- if (is_string($raw)) {
- $trimmed = trim($raw);
- if ($trimmed === '') {
- return '';
- }
- $decoded = json_decode($trimmed, true);
- if (is_array($decoded)) {
- $raw = $decoded;
- } else {
- return $this->normalizeSimilarityText($trimmed);
- }
- }
- if (! is_array($raw) || $raw === []) {
- return '';
- }
- $parts = [];
- foreach ($raw as $item) {
- if (is_array($item)) {
- $parts[] = (string) ($item['content'] ?? $item['text'] ?? $item['value'] ?? reset($item) ?? '');
- } else {
- $parts[] = (string) $item;
- }
- }
- return $this->normalizeSimilarityText(implode(' | ', $parts));
- }
- private function normalizeSimilarityQuestionType(string $raw): string
- {
- $type = mb_strtolower(trim($raw), 'UTF-8');
- return match (true) {
- str_contains($type, 'choice'), str_contains($type, '选择') => 'choice',
- str_contains($type, 'fill'), str_contains($type, 'blank'), str_contains($type, '填空') => 'fill',
- str_contains($type, 'answer'), str_contains($type, '解答') => 'answer',
- default => '',
- };
- }
- /**
- * @param array{type:string,stem:string,options:string,answer:string,solution:string} $tem
- * @param array{type:string,stem:string,options:string,answer:string,solution:string} $question
- */
- private function calculateCompositeSimilarityScore(array $tem, array $question): float
- {
- $weights = [
- 'stem' => 0.45,
- 'options' => 0.20,
- 'answer' => 0.20,
- 'solution' => 0.15,
- ];
- $weightedSum = 0.0;
- $effectiveWeight = 0.0;
- foreach ($weights as $field => $weight) {
- $a = (string) ($tem[$field] ?? '');
- $b = (string) ($question[$field] ?? '');
- if ($a === '' || $b === '') {
- continue;
- }
- similar_text($a, $b, $pct);
- $score = max(0.0, min(100.0, (float) $pct));
- $weightedSum += $score * $weight;
- $effectiveWeight += $weight;
- }
- if ($effectiveWeight <= 0.0) {
- return 0.0;
- }
- return round($weightedSum / $effectiveWeight, 1);
- }
- private function formatMetaDatetime(mixed $value): ?string
- {
- if ($value === null) {
- return null;
- }
- $raw = trim((string) $value);
- if ($raw === '' || $raw === '0000-00-00 00:00:00') {
- return null;
- }
- try {
- return \Carbon\Carbon::parse($raw)->format('Y-m-d H:i:s');
- } catch (\Throwable) {
- return $raw;
- }
- }
- private function formatMetaDifficulty(mixed $value): string
- {
- if ($value === null || $value === '') {
- return '-';
- }
- if (! is_numeric($value)) {
- return (string) $value;
- }
- return number_format((float) $value, 2, '.', '');
- }
- private function formatMetaAuditReason(mixed $value): string
- {
- $text = trim((string) ($value ?? ''));
- return $text !== '' ? $text : '-';
- }
- private function buildPageCacheKey(string $suffix): string
- {
- $uid = Auth::id() ?: 'guest';
- $kp = $this->selectedKpCode ?: 'none';
- $grade = $this->parseGradeFilter() ?: 'all';
- $semester = $this->parseSemesterFilter() ?: 'all';
- $version = (int) Cache::get("qtr:version:u{$uid}:kp{$kp}", 1);
- return "qtr:page:{$suffix}:u{$uid}:kp{$kp}:g{$grade}:s{$semester}:v{$version}";
- }
- private function forgetCurrentKpCaches(): void
- {
- foreach (['tem_questions', 'tem_cards', 'kp_question_stems'] as $suffix) {
- Cache::forget($this->buildPageCacheKey($suffix));
- }
- }
- /**
- * @param array<int, object|array<string,mixed>> $rows
- * @return array<int, object|array<string,mixed>>
- */
- private function sortRowsByQuestionType(array $rows): array
- {
- usort($rows, function ($a, $b): int {
- $ar = is_array($a) ? $a : (array) $a;
- $br = is_array($b) ? $b : (array) $b;
- $aRank = $this->questionTypeRank((string) ($ar['question_type'] ?? $ar['tags'] ?? ''));
- $bRank = $this->questionTypeRank((string) ($br['question_type'] ?? $br['tags'] ?? ''));
- if ($aRank !== $bRank) {
- return $aRank <=> $bRank;
- }
- return ((int) ($ar['id'] ?? 0)) <=> ((int) ($br['id'] ?? 0));
- });
- return $rows;
- }
- private function questionTypeRank(string $raw): int
- {
- $t = mb_strtolower(trim($raw));
- return match (true) {
- str_contains($t, 'choice'), str_contains($t, '选择') => 1,
- str_contains($t, 'fill'), str_contains($t, 'blank'), str_contains($t, '填空') => 2,
- default => 3,
- };
- }
- private function parseGradeFilter(): ?int
- {
- $v = trim($this->gradeFilter);
- if ($v === '' || ! is_numeric($v)) {
- return null;
- }
- $i = (int) $v;
- return $i > 0 ? $i : null;
- }
- private function parseSemesterFilter(): ?int
- {
- $v = trim($this->semesterFilter);
- if ($v === '' || ! is_numeric($v)) {
- return null;
- }
- $i = (int) $v;
- return $i > 0 ? $i : null;
- }
- private function formatGradeLabel(int $grade): string
- {
- return match (true) {
- $grade >= 1 && $grade <= 6 => "小学{$grade}年级",
- $grade === 7 => '初一',
- $grade === 8 => '初二',
- $grade === 9 => '初三',
- $grade === 10 => '高一',
- $grade === 11 => '高二',
- $grade === 12 => '高三',
- $grade === 2 => '初中(学段)',
- $grade === 3 => '高中(学段)',
- default => "年级{$grade}",
- };
- }
- private function formatSemesterLabel(int $semester): string
- {
- return match ($semester) {
- 1 => '上学期',
- 2 => '下学期',
- default => "学期{$semester}",
- };
- }
- }
|