QuestionTemQualityReview.php 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337
  1. <?php
  2. namespace App\Filament\Pages;
  3. use App\Jobs\ImportTemToQuestionsJob;
  4. use App\Services\ExamPdfExportService;
  5. use App\Services\MathFormulaProcessor;
  6. use App\Services\QuestionQualityCheckService;
  7. use App\Services\QuestionsTemAssemblyService;
  8. use App\Services\QuestionTemReviewService;
  9. use BackedEnum;
  10. use Filament\Notifications\Notification;
  11. use Filament\Pages\Page;
  12. use Filament\Support\Enums\Width;
  13. use Illuminate\Support\Facades\Auth;
  14. use Illuminate\Support\Facades\Cache;
  15. use Illuminate\Support\Facades\DB;
  16. use Illuminate\Support\Facades\Schema;
  17. use Livewire\Attributes\Computed;
  18. use Livewire\Attributes\Renderless;
  19. use Livewire\Attributes\Url;
  20. use UnitEnum;
  21. class QuestionTemQualityReview extends Page
  22. {
  23. protected static ?string $title = '待入库题目质检';
  24. protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-clipboard-document-check';
  25. protected static ?string $navigationLabel = '待入库质检';
  26. protected static string|UnitEnum|null $navigationGroup = '题库管理';
  27. protected static ?int $navigationSort = 4;
  28. /**
  29. * 三栏布局需要占满主内容区,避免被默认 max-width 压成窄条导致样式像「纯文本」。
  30. */
  31. protected Width|string|null $maxContentWidth = Width::Full;
  32. protected string $view = 'filament.pages.question-tem-quality-review';
  33. #[Url(as: 'kp', except: '')]
  34. public ?string $selectedKpCode = null;
  35. /** 左侧知识点列表搜索(匹配 kp_code、kp_name,不区分大小写) */
  36. #[Url(as: 'kps', except: '')]
  37. public string $kpSearch = '';
  38. /** 左侧按年级筛选;空字符串=全部 */
  39. #[Url(as: 'grade', except: '')]
  40. public string $gradeFilter = '';
  41. /** 左侧按学期筛选;空字符串=全部 */
  42. #[Url(as: 'semester', except: '')]
  43. public string $semesterFilter = '';
  44. /** 中间卡片首屏渲染数量(性能优先,按需加载更多) */
  45. public int $cardRenderLimit = 20;
  46. public ?int $selectedTemId = null;
  47. /** 中间区多选:questions_tem.id,点击题目切换勾选 */
  48. public array $selectedTemIds = [];
  49. /** 逐题审核后加入「待入库」清单的 tem id 列表 */
  50. public array $pendingImportTemIds = [];
  51. /** 为 true 时才计算/展示高级区质检与重复提示(避免每次点击跑质检) */
  52. public bool $qcPanelExpanded = false;
  53. /** 单题入库难度(0.00–0.90,两位小数;切换题目时从 questions_tem 同步) */
  54. public string $importDifficultyInput = '0.50';
  55. /** 生成临时试卷后,判卷页预览 URL(与正式组卷同源路由) */
  56. public ?string $trialGradingUrl = null;
  57. /** 与 generateGradingPdf 同源导出的判卷 PDF 地址(可下载) */
  58. public ?string $trialGradingPdfUrl = null;
  59. public function mount(): void
  60. {
  61. if (! Schema::hasTable('questions_tem')) {
  62. Notification::make()
  63. ->title('缺少 questions_tem 表')
  64. ->danger()
  65. ->send();
  66. }
  67. }
  68. public function updatedSelectedKpCode(): void
  69. {
  70. $this->selectedTemId = null;
  71. $this->selectedTemIds = [];
  72. $this->pendingImportTemIds = [];
  73. $this->cardRenderLimit = 20;
  74. $this->importDifficultyInput = '0.50';
  75. $this->qcPanelExpanded = false;
  76. }
  77. public function updatedGradeFilter(): void
  78. {
  79. $this->semesterFilter = '';
  80. $this->selectedKpCode = null;
  81. $this->selectedTemId = null;
  82. $this->selectedTemIds = [];
  83. $this->pendingImportTemIds = [];
  84. $this->cardRenderLimit = 20;
  85. $this->importDifficultyInput = '0.50';
  86. $this->qcPanelExpanded = false;
  87. }
  88. public function updatedSemesterFilter(): void
  89. {
  90. $this->selectedKpCode = null;
  91. $this->selectedTemId = null;
  92. $this->selectedTemIds = [];
  93. $this->pendingImportTemIds = [];
  94. $this->cardRenderLimit = 20;
  95. $this->importDifficultyInput = '0.50';
  96. $this->qcPanelExpanded = false;
  97. }
  98. #[Computed]
  99. public function kpRows(): array
  100. {
  101. return app(QuestionTemReviewService::class)->listKnowledgePointsByQuestionsAsc(
  102. null,
  103. $this->parseGradeFilter(),
  104. $this->parseSemesterFilter()
  105. );
  106. }
  107. /** @return list<array{value:string,label:string}> */
  108. #[Computed]
  109. public function gradeOptions(): array
  110. {
  111. $vals = app(QuestionTemReviewService::class)->catalogGradeOptions($this->parseSemesterFilter());
  112. $out = [];
  113. foreach ($vals as $g) {
  114. $v = (string) ((int) $g);
  115. $out[] = ['value' => $v, 'label' => $this->formatGradeLabel((int) $g)];
  116. }
  117. return $out;
  118. }
  119. /** @return list<array{value:string,label:string}> */
  120. #[Computed]
  121. public function semesterOptions(): array
  122. {
  123. $vals = app(QuestionTemReviewService::class)->catalogSemesterOptions($this->parseGradeFilter());
  124. $out = [];
  125. foreach ($vals as $s) {
  126. $v = (string) ((int) $s);
  127. $out[] = ['value' => $v, 'label' => $this->formatSemesterLabel((int) $s)];
  128. }
  129. return $out;
  130. }
  131. /**
  132. * 左侧列表:按搜索词筛选知识点(代码、名称子串匹配,UTF-8)
  133. *
  134. * @return list<array{kp_code: string, kp_name: string, questions_count: int, tem_count: int, tem_importable_count: int}>
  135. */
  136. #[Computed]
  137. public function filteredKpRows(): array
  138. {
  139. $rows = array_values(array_filter(
  140. $this->kpRows,
  141. static fn (array $row): bool => (int) ($row['tem_importable_count'] ?? 0) > 0
  142. ));
  143. $raw = trim($this->kpSearch);
  144. if ($raw === '') {
  145. return $rows;
  146. }
  147. $needle = mb_strtolower($raw, 'UTF-8');
  148. return array_values(array_filter($rows, function (array $row) use ($needle): bool {
  149. $code = mb_strtolower((string) ($row['kp_code'] ?? ''), 'UTF-8');
  150. $name = mb_strtolower((string) ($row['kp_name'] ?? ''), 'UTF-8');
  151. return mb_strpos($code, $needle, 0, 'UTF-8') !== false
  152. || mb_strpos($name, $needle, 0, 'UTF-8') !== false;
  153. }));
  154. }
  155. #[Computed]
  156. public function temQuestions(): array
  157. {
  158. if (! $this->selectedKpCode) {
  159. return [];
  160. }
  161. $key = $this->buildPageCacheKey('tem_questions');
  162. return Cache::remember($key, now()->addMinutes(3), function (): array {
  163. $rows = app(QuestionTemReviewService::class)->listTemQuestionsForKp(
  164. $this->selectedKpCode,
  165. 300,
  166. true,
  167. $this->parseGradeFilter()
  168. );
  169. return $this->sortRowsByQuestionType($rows);
  170. });
  171. }
  172. /**
  173. * 独立审核卡片模型:清洗题干、给出三项快检,并附上该题完整渲染所需分组数据。
  174. *
  175. * @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>}}>
  176. */
  177. #[Computed]
  178. public function temQuestionCards(): array
  179. {
  180. $key = $this->buildPageCacheKey('tem_cards');
  181. return Cache::remember($key, now()->addMinutes(3), function (): array {
  182. $cards = [];
  183. foreach ($this->temQuestions as $row) {
  184. $arr = is_array($row) ? $row : (array) $row;
  185. $id = (int) ($arr['id'] ?? 0);
  186. if ($id <= 0) {
  187. continue;
  188. }
  189. $stem = $this->normalizeStemPreview((string) ($arr['stem'] ?? ''));
  190. $answer = trim((string) ($arr['answer'] ?? $arr['correct_answer'] ?? ''));
  191. $solution = trim((string) ($arr['solution'] ?? ''));
  192. $cards[] = [
  193. 'id' => $id,
  194. 'stem_preview' => $stem,
  195. 'checks' => [
  196. 'stem' => $stem !== '',
  197. 'answer' => $answer !== '',
  198. 'solution' => $solution !== '',
  199. ],
  200. 'meta' => [
  201. 'created_at' => $this->formatMetaDatetime($arr['created_at'] ?? null),
  202. 'updated_at' => $this->formatMetaDatetime($arr['updated_at'] ?? null),
  203. 'difficulty' => $this->formatMetaDifficulty($arr['difficulty'] ?? null),
  204. 'audit_reason' => $this->formatMetaAuditReason($arr['audit_reason'] ?? null),
  205. ],
  206. 'grouped_questions' => $this->buildPreviewGroupedQuestionsFromTemRows([$arr]),
  207. ];
  208. }
  209. return $cards;
  210. });
  211. }
  212. /**
  213. * 与判卷 PDF / pdf.exam-grading 使用同一套 components.exam.paper-body 数据管线
  214. *
  215. * @return array{choice: array, fill: array, answer: array}
  216. */
  217. #[Computed]
  218. public function groupedPaperBodyQuestions(): array
  219. {
  220. if (! $this->selectedKpCode) {
  221. return ['choice' => [], 'fill' => [], 'answer' => []];
  222. }
  223. return $this->buildPreviewGroupedQuestionsFromTemRows($this->temQuestions);
  224. }
  225. /** @return list<object> */
  226. #[Computed]
  227. public function assemblyQueueRows(): array
  228. {
  229. $uid = Auth::id();
  230. if (! $uid) {
  231. return [];
  232. }
  233. return app(QuestionsTemAssemblyService::class)->queueForUser((int) $uid);
  234. }
  235. #[Computed]
  236. public function selectedRow(): ?object
  237. {
  238. if (! $this->selectedTemId) {
  239. return null;
  240. }
  241. return DB::table('questions_tem')->where('id', $this->selectedTemId)->first();
  242. }
  243. /**
  244. * @return array{passed: bool, errors: array, results: array}|null
  245. */
  246. #[Computed]
  247. public function qcResult(): ?array
  248. {
  249. if (! $this->qcPanelExpanded) {
  250. return null;
  251. }
  252. $row = $this->selectedRow;
  253. if (! $row) {
  254. return null;
  255. }
  256. $mapped = $this->mapQuestionRowForQc((array) $row);
  257. $qc = app(QuestionQualityCheckService::class)->runAutoCheck($mapped, (int) $row->id, null);
  258. return [
  259. 'passed' => $qc['passed'],
  260. 'errors' => $qc['errors'],
  261. 'results' => $qc['results'],
  262. ];
  263. }
  264. #[Computed]
  265. public function duplicateHint(): ?string
  266. {
  267. if (! $this->qcPanelExpanded) {
  268. return null;
  269. }
  270. $row = $this->selectedRow;
  271. if (! $row) {
  272. return null;
  273. }
  274. $svc = app(QuestionTemReviewService::class);
  275. $stem = $svc->normalizedStemFromTemRow($row);
  276. $kp = (string) ($row->kp_code ?? '');
  277. if ($stem === '' || $kp === '') {
  278. return null;
  279. }
  280. if ($svc->existsDuplicateInQuestions($kp, $stem)) {
  281. return '正式库已存在同知识点、同题干题目';
  282. }
  283. return null;
  284. }
  285. public function selectKp(string $kpCode): void
  286. {
  287. $this->selectedKpCode = $kpCode;
  288. $this->selectedTemId = null;
  289. $this->selectedTemIds = [];
  290. $this->pendingImportTemIds = [];
  291. $this->cardRenderLimit = 20;
  292. $this->importDifficultyInput = '0.50';
  293. $this->qcPanelExpanded = false;
  294. $this->dispatch('qtr-scroll-top');
  295. }
  296. public function loadMoreCards(): void
  297. {
  298. $this->cardRenderLimit += 20;
  299. $this->dispatch('qtr-scroll-top');
  300. }
  301. #[Computed]
  302. public function visibleTemQuestionCards(): array
  303. {
  304. return array_slice($this->temQuestionCards, 0, max(1, $this->cardRenderLimit));
  305. }
  306. /** @return list<object> */
  307. #[Computed]
  308. public function pendingImportRows(): array
  309. {
  310. if ($this->pendingImportTemIds === []) {
  311. return [];
  312. }
  313. $rows = DB::table('questions_tem')
  314. ->whereIn('id', $this->pendingImportTemIds)
  315. ->get()
  316. ->keyBy('id');
  317. $ordered = [];
  318. foreach ($this->pendingImportTemIds as $id) {
  319. $row = $rows->get((int) $id);
  320. if ($row) {
  321. $ordered[] = $row;
  322. }
  323. }
  324. return $this->sortRowsByQuestionType($ordered);
  325. }
  326. /**
  327. * 右侧人工判重参考:当前选中知识点在正式库 questions 的题目(编号+题干)。
  328. *
  329. * @return list<object>
  330. */
  331. #[Computed]
  332. public function currentKpQuestionStemRows(): array
  333. {
  334. if (! $this->selectedKpCode || ! Schema::hasTable('questions')) {
  335. return [];
  336. }
  337. $key = $this->buildPageCacheKey('kp_question_stems_v2');
  338. return Cache::remember($key, now()->addMinutes(2), function (): array {
  339. $q = DB::table('questions')
  340. ->where('kp_code', $this->selectedKpCode)
  341. ->select(['id', 'stem', 'question_type', 'options', 'answer', 'solution'])
  342. ->orderByRaw("
  343. CASE
  344. WHEN LOWER(COALESCE(question_type, '')) LIKE '%choice%' OR question_type LIKE '%选择%' THEN 1
  345. WHEN LOWER(COALESCE(question_type, '')) LIKE '%fill%' OR LOWER(COALESCE(question_type, '')) LIKE '%blank%' OR question_type LIKE '%填空%' THEN 2
  346. ELSE 3
  347. END ASC
  348. ")
  349. ->orderBy('id');
  350. // 右侧人工判重列表仅按当前选中知识点展示:
  351. // 年级/学期筛选已在左侧知识点范围内收敛,避免对 questions.grade 再次过滤导致误空。
  352. return $q->limit(300)->get()->all();
  353. });
  354. }
  355. /**
  356. * 中间卡片:给每道 tem 题计算「当前知识点下最相似的正式库题目」综合相似度。
  357. *
  358. * @return array<int, array{question_id:int, score:float, score_text:string}>
  359. */
  360. #[Computed]
  361. public function temSimilarityHints(): array
  362. {
  363. if (! $this->selectedKpCode) {
  364. return [];
  365. }
  366. $temRows = $this->visibleTemQuestionCards;
  367. $questionRows = $this->currentKpQuestionStemRows;
  368. if ($temRows === [] || $questionRows === []) {
  369. return [];
  370. }
  371. $normalizedQuestions = [];
  372. foreach ($questionRows as $qr) {
  373. $qid = (int) ($qr->id ?? 0);
  374. if ($qid <= 0) {
  375. continue;
  376. }
  377. $normalizedQuestions[$qid] = [
  378. 'type' => $this->normalizeSimilarityQuestionType((string) ($qr->question_type ?? '')),
  379. 'stem' => $this->normalizeSimilarityText((string) ($qr->stem ?? '')),
  380. 'options' => $this->normalizeSimilarityOptions($qr->options ?? null),
  381. 'answer' => $this->normalizeSimilarityText((string) ($qr->answer ?? '')),
  382. 'solution' => $this->normalizeSimilarityText((string) ($qr->solution ?? '')),
  383. ];
  384. }
  385. $out = [];
  386. foreach ($temRows as $card) {
  387. $tid = (int) ($card['id'] ?? 0);
  388. if ($tid <= 0) {
  389. continue;
  390. }
  391. $grouped = $card['grouped_questions'] ?? ['choice' => [], 'fill' => [], 'answer' => []];
  392. $q = $grouped['choice'][0] ?? $grouped['fill'][0] ?? $grouped['answer'][0] ?? null;
  393. $temPayload = [
  394. 'type' => $this->normalizeSimilarityQuestionType((string) ($q->question_type ?? '')),
  395. 'stem' => $this->normalizeSimilarityText((string) ($q->stem ?? $q->content ?? $card['stem_preview'] ?? '')),
  396. 'options' => $this->normalizeSimilarityOptions($q->options ?? null),
  397. 'answer' => $this->normalizeSimilarityText((string) ($q->answer ?? '')),
  398. 'solution' => $this->normalizeSimilarityText((string) ($q->solution ?? '')),
  399. ];
  400. if ($temPayload['stem'] === '') {
  401. continue;
  402. }
  403. $bestQid = 0;
  404. $bestScore = 0.0;
  405. foreach ($normalizedQuestions as $qid => $questionPayload) {
  406. if (($questionPayload['stem'] ?? '') === '') {
  407. continue;
  408. }
  409. if ($temPayload['type'] !== '' && $questionPayload['type'] !== '' && $temPayload['type'] !== $questionPayload['type']) {
  410. continue;
  411. }
  412. $score = $this->calculateCompositeSimilarityScore($temPayload, $questionPayload);
  413. if ($score > $bestScore) {
  414. $bestScore = $score;
  415. $bestQid = (int) $qid;
  416. }
  417. }
  418. if ($bestQid > 0) {
  419. $out[$tid] = [
  420. 'question_id' => $bestQid,
  421. 'score' => round($bestScore, 1),
  422. 'score_text' => number_format($bestScore, 1).'%',
  423. ];
  424. }
  425. }
  426. return $out;
  427. }
  428. public function updatedSelectedTemId(mixed $value): void
  429. {
  430. if ($this->selectedTemId) {
  431. $this->syncImportDifficultyFromSelectedRow();
  432. if (! in_array((int) $this->selectedTemId, $this->selectedTemIds, true)) {
  433. $this->selectedTemIds[] = (int) $this->selectedTemId;
  434. }
  435. } else {
  436. $this->importDifficultyInput = '0.50';
  437. }
  438. $this->selectedTemIds = array_values(array_unique(array_map('intval', $this->selectedTemIds)));
  439. }
  440. public function updatedSelectedTemIds(): void
  441. {
  442. $this->selectedTemIds = array_values(array_unique(array_filter(
  443. array_map('intval', $this->selectedTemIds),
  444. static fn (int $id) => $id > 0
  445. )));
  446. if ($this->selectedTemId && ! in_array((int) $this->selectedTemId, $this->selectedTemIds, true)) {
  447. $this->selectedTemId = $this->selectedTemIds[0] ?? null;
  448. }
  449. if (! $this->selectedTemId && $this->selectedTemIds !== []) {
  450. $this->selectedTemId = $this->selectedTemIds[0];
  451. }
  452. if ($this->selectedTemId) {
  453. $this->syncImportDifficultyFromSelectedRow();
  454. } else {
  455. $this->importDifficultyInput = '0.50';
  456. }
  457. }
  458. public function focusTemQuestion(int $id): void
  459. {
  460. if ($id <= 0) {
  461. return;
  462. }
  463. $this->selectedTemId = $id;
  464. if (! in_array($id, $this->selectedTemIds, true)) {
  465. $this->selectedTemIds[] = $id;
  466. $this->selectedTemIds = array_values(array_unique(array_map('intval', $this->selectedTemIds)));
  467. }
  468. $this->qcPanelExpanded = false;
  469. }
  470. public function addToPendingImport(int $id): void
  471. {
  472. if ($id <= 0) {
  473. return;
  474. }
  475. if (! in_array($id, $this->pendingImportTemIds, true)) {
  476. $this->pendingImportTemIds[] = $id;
  477. $this->pendingImportTemIds = array_values(array_unique(array_map('intval', $this->pendingImportTemIds)));
  478. }
  479. if ((int) ($this->selectedTemId ?? 0) === $id) {
  480. $this->selectedTemId = null;
  481. $this->importDifficultyInput = '0.50';
  482. }
  483. }
  484. #[Renderless]
  485. public function queueImportTem(int $id): void
  486. {
  487. if ($id <= 0) {
  488. return;
  489. }
  490. $status = Cache::get(ImportTemToQuestionsJob::statusKey($id));
  491. $state = (string) ($status['state'] ?? '');
  492. if (in_array($state, ['queued', 'running'], true)) {
  493. return;
  494. }
  495. Cache::put(ImportTemToQuestionsJob::statusKey($id), [
  496. 'state' => 'queued',
  497. 'message' => '已加入队列,等待处理',
  498. 'at' => now()->toDateTimeString(),
  499. ], now()->addMinutes(30));
  500. ImportTemToQuestionsJob::dispatch($id, Auth::id() ? (int) Auth::id() : null, $this->selectedKpCode);
  501. }
  502. public function markAsSimilarQuestion(int $temId, int $questionId): void
  503. {
  504. if ($temId <= 0 || $questionId <= 0) {
  505. Notification::make()->title('参数无效')->warning()->send();
  506. return;
  507. }
  508. if (! Schema::hasTable('questions_tem')) {
  509. Notification::make()->title('questions_tem 表不存在')->danger()->send();
  510. return;
  511. }
  512. $updates = [
  513. 'audit_reason' => "相似题{$questionId}",
  514. 'updated_at' => now(),
  515. ];
  516. if (Schema::hasColumn('questions_tem', 'audit_status')) {
  517. $updates['audit_status'] = -1;
  518. }
  519. DB::table('questions_tem')
  520. ->where('id', $temId)
  521. ->update($updates);
  522. $this->pendingImportTemIds = array_values(array_filter(
  523. $this->pendingImportTemIds,
  524. static fn ($x) => (int) $x !== $temId
  525. ));
  526. $this->forgetCurrentKpCaches();
  527. Notification::make()
  528. ->title("已标记为相似题 #{$questionId}")
  529. ->success()
  530. ->send();
  531. }
  532. public function removeFromPendingImport(int $id): void
  533. {
  534. $this->pendingImportTemIds = array_values(array_filter(
  535. $this->pendingImportTemIds,
  536. static fn ($x) => (int) $x !== $id
  537. ));
  538. }
  539. public function clearPendingImport(): void
  540. {
  541. $this->pendingImportTemIds = [];
  542. }
  543. public function importPendingTem(int $id): void
  544. {
  545. $this->queueImportTem($id);
  546. }
  547. public function importPendingAll(): void
  548. {
  549. if ($this->pendingImportTemIds === []) {
  550. Notification::make()->title('待入库为空')->warning()->send();
  551. return;
  552. }
  553. foreach ($this->pendingImportTemIds as $id) {
  554. $this->queueImportTem((int) $id);
  555. }
  556. }
  557. public function syncAsyncImportStatuses(): void
  558. {
  559. if ($this->pendingImportTemIds === []) {
  560. return;
  561. }
  562. $remaining = [];
  563. $doneFound = false;
  564. foreach ($this->pendingImportTemIds as $id) {
  565. $status = Cache::get(ImportTemToQuestionsJob::statusKey((int) $id));
  566. if (($status['state'] ?? null) === 'done') {
  567. $doneFound = true;
  568. continue;
  569. }
  570. $remaining[] = (int) $id;
  571. }
  572. if ($doneFound) {
  573. $this->pendingImportTemIds = array_values(array_unique($remaining));
  574. $this->forgetCurrentKpCaches();
  575. }
  576. }
  577. /** @return array<int, array{state?:string,message?:string,question_id?:int,at?:string}> */
  578. #[Computed]
  579. public function importStatusMap(): array
  580. {
  581. $ids = [];
  582. foreach ($this->temQuestionCards as $card) {
  583. $id = (int) ($card['id'] ?? 0);
  584. if ($id > 0) {
  585. $ids[] = $id;
  586. }
  587. }
  588. foreach ($this->pendingImportTemIds as $id) {
  589. $id = (int) $id;
  590. if ($id > 0) {
  591. $ids[] = $id;
  592. }
  593. }
  594. $ids = array_values(array_unique($ids));
  595. if ($ids === []) {
  596. return [];
  597. }
  598. $keys = [];
  599. foreach ($ids as $id) {
  600. $keys[$id] = ImportTemToQuestionsJob::statusKey($id);
  601. }
  602. $many = Cache::many(array_values($keys));
  603. $map = [];
  604. foreach ($keys as $id => $key) {
  605. $v = $many[$key] ?? null;
  606. if (is_array($v) && isset($v['state'])) {
  607. $map[(int) $id] = $v;
  608. }
  609. }
  610. return $map;
  611. }
  612. public function clearTemSelection(): void
  613. {
  614. $this->selectedTemIds = [];
  615. $this->selectedTemId = null;
  616. $this->importDifficultyInput = '0.50';
  617. $this->qcPanelExpanded = false;
  618. }
  619. public function importSelectedTemIdsFast(): void
  620. {
  621. if ($this->selectedTemIds === []) {
  622. Notification::make()->title('请先勾选题目')->warning()->send();
  623. return;
  624. }
  625. $svc = app(QuestionTemReviewService::class);
  626. $result = $svc->importTemIdsToQuestions($this->selectedTemIds);
  627. QuestionTemReviewService::mergeQuestionIdsIntoTuningSession($result['imported_question_ids'] ?? []);
  628. $this->notifyBulkImportResult($result);
  629. $this->selectedTemIds = [];
  630. $this->selectedTemId = null;
  631. $this->qcPanelExpanded = false;
  632. $this->dispatch('$refresh');
  633. }
  634. public function addSelectionToAssemblyQueue(): void
  635. {
  636. if ($this->selectedTemIds === []) {
  637. Notification::make()->title('请先勾选题目')->warning()->send();
  638. return;
  639. }
  640. $uid = Auth::id();
  641. if (! $uid) {
  642. return;
  643. }
  644. $svc = app(QuestionsTemAssemblyService::class);
  645. foreach ($this->selectedTemIds as $tid) {
  646. $svc->add((int) $uid, (int) $tid);
  647. }
  648. Notification::make()
  649. ->title('已加入待组卷队列(未写入 questions)')
  650. ->body('共 '.count($this->selectedTemIds).' 道')
  651. ->success()
  652. ->send();
  653. }
  654. public function removeFromAssemblyQueue(int $temId): void
  655. {
  656. $uid = Auth::id();
  657. if (! $uid) {
  658. return;
  659. }
  660. app(QuestionsTemAssemblyService::class)->remove((int) $uid, $temId);
  661. }
  662. public function clearAssemblyQueue(): void
  663. {
  664. $uid = Auth::id();
  665. if (! $uid) {
  666. return;
  667. }
  668. app(QuestionsTemAssemblyService::class)->clear((int) $uid);
  669. $this->trialGradingUrl = null;
  670. $this->trialGradingPdfUrl = null;
  671. Notification::make()->title('已清空待组卷队列')->success()->send();
  672. }
  673. public function generateTrialGradingPdf(): void
  674. {
  675. $uid = Auth::id();
  676. if (! $uid) {
  677. Notification::make()->title('未登录')->danger()->send();
  678. return;
  679. }
  680. $svc = app(QuestionsTemAssemblyService::class);
  681. if (! $svc->tableExists()) {
  682. Notification::make()->title('请先执行迁移:questions_tem_assembly_queue')->danger()->send();
  683. return;
  684. }
  685. $paperId = $svc->createTrialPaperForQueue((int) $uid);
  686. if (! $paperId) {
  687. Notification::make()->title('待组卷队列为空,请先「加入待组卷」')->warning()->send();
  688. return;
  689. }
  690. $this->trialGradingUrl = route('filament.admin.auth.intelligent-exam.grading', ['paper_id' => $paperId]);
  691. $this->trialGradingPdfUrl = null;
  692. $pdfBody = '';
  693. try {
  694. // 与正式组卷一致:学生卷 + 答案详解/判卷段 + 判题卡(强制追加扫描卡,不依赖 .env)
  695. $pdfUrl = app(ExamPdfExportService::class)->generateUnifiedPdf($paperId, false, true);
  696. $this->trialGradingPdfUrl = $pdfUrl ?: null;
  697. $pdfBody = $this->trialGradingPdfUrl
  698. ? '完整卷 PDF(学生卷 + 答案详解 + 判题卡)已生成,可下载核对。'
  699. : '完整卷 PDF 未返回地址,请仅用判卷页预览。';
  700. } catch (\Throwable $e) {
  701. $pdfBody = '完整卷 PDF 导出异常:'.$e->getMessage();
  702. }
  703. if (str_contains($pdfBody, '异常')) {
  704. Notification::make()
  705. ->title('已生成临时试卷(判卷页可预览)')
  706. ->body($pdfBody)
  707. ->warning()
  708. ->send();
  709. } else {
  710. Notification::make()
  711. ->title('已生成临时试卷')
  712. ->body('可打开判卷页预览。'.$pdfBody)
  713. ->success()
  714. ->send();
  715. }
  716. }
  717. /**
  718. * 将当前左侧选中知识点下,中间列表中的全部 questions_tem 写入 questions(与单题入库规则一致)
  719. */
  720. public function importAllCurrentKpToQuestions(): void
  721. {
  722. if (! $this->selectedKpCode) {
  723. Notification::make()->title('请先选择左侧知识点')->warning()->send();
  724. return;
  725. }
  726. $ids = [];
  727. foreach ($this->temQuestions as $row) {
  728. $ids[] = (int) ($row->id ?? 0);
  729. }
  730. if ($ids === []) {
  731. Notification::make()->title('当前知识点下没有待审题目')->warning()->send();
  732. return;
  733. }
  734. $svc = app(QuestionTemReviewService::class);
  735. $result = $svc->importTemIdsToQuestions($ids);
  736. QuestionTemReviewService::mergeQuestionIdsIntoTuningSession($result['imported_question_ids'] ?? []);
  737. $this->notifyBulkImportResult($result);
  738. $this->dispatch('$refresh');
  739. }
  740. /**
  741. * 将右侧「待组卷」队列中的全部 questions_tem 写入 questions
  742. */
  743. public function importAssemblyQueueToQuestions(): void
  744. {
  745. $uid = Auth::id();
  746. if (! $uid) {
  747. return;
  748. }
  749. $ids = [];
  750. foreach ($this->assemblyQueueRows as $row) {
  751. $ids[] = (int) ($row->id ?? 0);
  752. }
  753. if ($ids === []) {
  754. Notification::make()->title('待组卷队列为空')->warning()->send();
  755. return;
  756. }
  757. $svc = app(QuestionTemReviewService::class);
  758. $result = $svc->importTemIdsToQuestions($ids);
  759. QuestionTemReviewService::mergeQuestionIdsIntoTuningSession($result['imported_question_ids'] ?? []);
  760. $this->notifyBulkImportResult($result);
  761. $this->dispatch('$refresh');
  762. }
  763. /**
  764. * @param array{imported: int, skipped: int, failed: int, lines: list<string>, imported_question_ids?: list<int>} $result
  765. */
  766. private function notifyBulkImportResult(array $result): void
  767. {
  768. $body = sprintf(
  769. '成功 %d 道,跳过 %d 道(重复或缺字段),失败 %d 道。',
  770. $result['imported'],
  771. $result['skipped'],
  772. $result['failed']
  773. );
  774. if ($result['lines'] !== []) {
  775. $body .= "\n\n".implode("\n", $result['lines']);
  776. }
  777. $title = $result['imported'] > 0 ? '批量入库完成' : '批量入库结束';
  778. Notification::make()
  779. ->title($title)
  780. ->body($body)
  781. ->success()
  782. ->send();
  783. }
  784. public function importSelected(): void
  785. {
  786. if (! $this->selectedTemId) {
  787. Notification::make()->title('请先选择一道题目')->warning()->send();
  788. return;
  789. }
  790. $difficulty = $this->parseImportDifficultyValidated();
  791. if ($difficulty === null) {
  792. return;
  793. }
  794. $svc = app(QuestionTemReviewService::class);
  795. $result = $svc->importTemRowToQuestions($this->selectedTemId, $difficulty);
  796. if ($result['ok']) {
  797. if (! empty($result['question_id'])) {
  798. QuestionTemReviewService::mergeQuestionIdsIntoTuningSession([(int) $result['question_id']]);
  799. }
  800. $importedTemId = (int) $this->selectedTemId;
  801. Notification::make()
  802. ->title($result['message'])
  803. ->body(sprintf('question_id: %s · difficulty: %s', (string) $result['question_id'], number_format($difficulty, 2, '.', '')))
  804. ->success()
  805. ->send();
  806. $this->selectedTemIds = array_values(array_filter($this->selectedTemIds, fn ($x) => (int) $x !== $importedTemId));
  807. $this->selectedTemId = $this->selectedTemIds[count($this->selectedTemIds) - 1] ?? null;
  808. if ($this->selectedTemId) {
  809. $this->syncImportDifficultyFromSelectedRow();
  810. } else {
  811. $this->importDifficultyInput = '0.50';
  812. }
  813. $this->dispatch('$refresh');
  814. } else {
  815. Notification::make()->title($result['message'])->danger()->send();
  816. }
  817. }
  818. private function syncImportDifficultyFromSelectedRow(): void
  819. {
  820. $row = $this->selectedRow;
  821. if (! $row) {
  822. $this->importDifficultyInput = '0.50';
  823. return;
  824. }
  825. $d = app(QuestionTemReviewService::class)->defaultDifficultyForTemRow($row);
  826. $this->importDifficultyInput = number_format($d, 2, '.', '');
  827. }
  828. /**
  829. * @return ?float 合法难度,或 null(已弹通知)
  830. */
  831. private function parseImportDifficultyValidated(): ?float
  832. {
  833. $raw = trim($this->importDifficultyInput);
  834. if ($raw === '') {
  835. Notification::make()
  836. ->title('请填写难度系数')
  837. ->body('范围为 0.00~0.90,最多两位小数。')
  838. ->warning()
  839. ->send();
  840. return null;
  841. }
  842. if (! is_numeric($raw)) {
  843. Notification::make()
  844. ->title('难度系数格式不正确')
  845. ->body('请输入数字,例如 0.35。')
  846. ->danger()
  847. ->send();
  848. return null;
  849. }
  850. $value = round((float) $raw, 2);
  851. if ($value < 0.0 || $value > 0.9) {
  852. Notification::make()
  853. ->title('难度系数超出范围')
  854. ->body('仅允许 0.00~0.90(保留两位小数)。')
  855. ->danger()
  856. ->send();
  857. return null;
  858. }
  859. $this->importDifficultyInput = number_format($value, 2, '.', '');
  860. return $value;
  861. }
  862. /**
  863. * 仅用于质检页面预览:不改组卷主链路的控制器/视图逻辑。
  864. *
  865. * @param array<int, object|array> $rows
  866. * @return array{choice: array<int, object>, fill: array<int, object>, answer: array<int, object>}
  867. */
  868. private function buildPreviewGroupedQuestionsFromTemRows(array $rows): array
  869. {
  870. $grouped = ['choice' => [], 'fill' => [], 'answer' => []];
  871. foreach (array_values($rows) as $index => $row) {
  872. $arr = is_array($row) ? $row : (array) $row;
  873. $type = $this->normalizePreviewQuestionType((string) ($arr['question_type'] ?? $arr['tags'] ?? 'answer'));
  874. $options = $this->normalizePreviewOptions($arr['options'] ?? null);
  875. $questionData = [
  876. 'id' => isset($arr['id']) ? -abs((int) $arr['id']) : null,
  877. 'question_number' => $index + 1,
  878. 'content' => (string) ($arr['stem'] ?? ''),
  879. 'stem' => (string) ($arr['stem'] ?? ''),
  880. 'answer' => (string) ($arr['answer'] ?? $arr['correct_answer'] ?? ''),
  881. 'solution' => (string) ($arr['solution'] ?? ''),
  882. 'difficulty' => isset($arr['difficulty']) ? (float) $arr['difficulty'] : 0.5,
  883. 'kp_code' => (string) ($arr['kp_code'] ?? ''),
  884. 'tags' => is_string($arr['tags'] ?? null) ? $arr['tags'] : '',
  885. 'options' => $options,
  886. 'score' => $type === 'answer' ? 10 : 5,
  887. 'question_type' => $type,
  888. ];
  889. $grouped[$type][] = (object) $questionData;
  890. }
  891. return $grouped;
  892. }
  893. private function normalizePreviewQuestionType(string $raw): string
  894. {
  895. $t = mb_strtolower(trim($raw));
  896. return match (true) {
  897. str_contains($t, 'choice'), str_contains($t, '选择') => 'choice',
  898. str_contains($t, 'fill'), str_contains($t, 'blank'), str_contains($t, '填空') => 'fill',
  899. default => 'answer',
  900. };
  901. }
  902. /**
  903. * @return array<int, string>|null
  904. */
  905. private function normalizePreviewOptions(mixed $raw): ?array
  906. {
  907. if (is_string($raw)) {
  908. $decoded = json_decode($raw, true);
  909. $raw = is_array($decoded) ? $decoded : null;
  910. }
  911. if (! is_array($raw) || $raw === []) {
  912. return null;
  913. }
  914. if (! isset($raw[0])) {
  915. return array_values(array_map(static fn ($v) => (string) $v, $raw));
  916. }
  917. if (isset($raw[0]) && is_array($raw[0])) {
  918. $out = [];
  919. foreach ($raw as $opt) {
  920. $out[] = (string) (($opt['content'] ?? $opt['text'] ?? $opt['value'] ?? ''));
  921. }
  922. return $out;
  923. }
  924. return array_values(array_map(static fn ($v) => (string) $v, $raw));
  925. }
  926. private function mapQuestionRowForQc(array $row): array
  927. {
  928. $stem = trim((string) ($row['stem'] ?? ''));
  929. if ($stem === '') {
  930. $stem = trim((string) ($row['content'] ?? ''));
  931. }
  932. $options = $row['options'] ?? null;
  933. if (is_string($options) && trim($options) !== '') {
  934. $decoded = json_decode($options, true);
  935. $options = is_array($decoded) ? $decoded : null;
  936. }
  937. $qtRaw = (string) ($row['question_type'] ?? $row['tags'] ?? '');
  938. $qtLower = strtolower(trim($qtRaw));
  939. $explicitNonChoice = in_array($qtLower, ['fill', '填空', '填空题', 'answer', '解答', '解答题'], true);
  940. if (! $explicitNonChoice && is_array($options) && count($options) >= 2) {
  941. $qtForCheck = 'choice';
  942. } else {
  943. $qtForCheck = $qtRaw;
  944. }
  945. return [
  946. 'stem' => $stem,
  947. 'answer' => $row['answer'] ?? $row['correct_answer'] ?? '',
  948. 'solution' => $row['solution'] ?? '',
  949. 'question_type' => $qtForCheck,
  950. 'options' => $options,
  951. ];
  952. }
  953. private function normalizeStemPreview(string $stem): string
  954. {
  955. // 先去掉图片标签,避免界面出现一大串 <img ...>
  956. $text = preg_replace('/<img\b[^>]*>/iu', ' [图] ', $stem) ?? $stem;
  957. $text = strip_tags($text);
  958. $text = html_entity_decode($text, ENT_QUOTES | ENT_HTML5, 'UTF-8');
  959. $text = preg_replace('/\s+/u', ' ', $text) ?? $text;
  960. return trim($text);
  961. }
  962. private function normalizeSimilarityText(string $text): string
  963. {
  964. if ($text === '') {
  965. return '';
  966. }
  967. $text = MathFormulaProcessor::processFormulas($text);
  968. $text = preg_replace('/<img\b[^>]*>/iu', ' ', $text) ?? $text;
  969. $text = strip_tags($text);
  970. $text = html_entity_decode($text, ENT_QUOTES | ENT_HTML5, 'UTF-8');
  971. $text = mb_strtolower($text, 'UTF-8');
  972. $text = preg_replace('/[[:punct:]\p{P}\p{S}]+/u', ' ', $text) ?? $text;
  973. $text = preg_replace('/\s+/u', ' ', $text) ?? $text;
  974. return trim($text);
  975. }
  976. private function normalizeSimilarityOptions(mixed $raw): string
  977. {
  978. if (is_string($raw)) {
  979. $trimmed = trim($raw);
  980. if ($trimmed === '') {
  981. return '';
  982. }
  983. $decoded = json_decode($trimmed, true);
  984. if (is_array($decoded)) {
  985. $raw = $decoded;
  986. } else {
  987. return $this->normalizeSimilarityText($trimmed);
  988. }
  989. }
  990. if (! is_array($raw) || $raw === []) {
  991. return '';
  992. }
  993. $parts = [];
  994. foreach ($raw as $item) {
  995. if (is_array($item)) {
  996. $parts[] = (string) ($item['content'] ?? $item['text'] ?? $item['value'] ?? reset($item) ?? '');
  997. } else {
  998. $parts[] = (string) $item;
  999. }
  1000. }
  1001. return $this->normalizeSimilarityText(implode(' | ', $parts));
  1002. }
  1003. private function normalizeSimilarityQuestionType(string $raw): string
  1004. {
  1005. $type = mb_strtolower(trim($raw), 'UTF-8');
  1006. return match (true) {
  1007. str_contains($type, 'choice'), str_contains($type, '选择') => 'choice',
  1008. str_contains($type, 'fill'), str_contains($type, 'blank'), str_contains($type, '填空') => 'fill',
  1009. str_contains($type, 'answer'), str_contains($type, '解答') => 'answer',
  1010. default => '',
  1011. };
  1012. }
  1013. /**
  1014. * @param array{type:string,stem:string,options:string,answer:string,solution:string} $tem
  1015. * @param array{type:string,stem:string,options:string,answer:string,solution:string} $question
  1016. */
  1017. private function calculateCompositeSimilarityScore(array $tem, array $question): float
  1018. {
  1019. $weights = [
  1020. 'stem' => 0.45,
  1021. 'options' => 0.20,
  1022. 'answer' => 0.20,
  1023. 'solution' => 0.15,
  1024. ];
  1025. $weightedSum = 0.0;
  1026. $effectiveWeight = 0.0;
  1027. foreach ($weights as $field => $weight) {
  1028. $a = (string) ($tem[$field] ?? '');
  1029. $b = (string) ($question[$field] ?? '');
  1030. if ($a === '' || $b === '') {
  1031. continue;
  1032. }
  1033. similar_text($a, $b, $pct);
  1034. $score = max(0.0, min(100.0, (float) $pct));
  1035. $weightedSum += $score * $weight;
  1036. $effectiveWeight += $weight;
  1037. }
  1038. if ($effectiveWeight <= 0.0) {
  1039. return 0.0;
  1040. }
  1041. return round($weightedSum / $effectiveWeight, 1);
  1042. }
  1043. private function formatMetaDatetime(mixed $value): ?string
  1044. {
  1045. if ($value === null) {
  1046. return null;
  1047. }
  1048. $raw = trim((string) $value);
  1049. if ($raw === '' || $raw === '0000-00-00 00:00:00') {
  1050. return null;
  1051. }
  1052. try {
  1053. return \Carbon\Carbon::parse($raw)->format('Y-m-d H:i:s');
  1054. } catch (\Throwable) {
  1055. return $raw;
  1056. }
  1057. }
  1058. private function formatMetaDifficulty(mixed $value): string
  1059. {
  1060. if ($value === null || $value === '') {
  1061. return '-';
  1062. }
  1063. if (! is_numeric($value)) {
  1064. return (string) $value;
  1065. }
  1066. return number_format((float) $value, 2, '.', '');
  1067. }
  1068. private function formatMetaAuditReason(mixed $value): string
  1069. {
  1070. $text = trim((string) ($value ?? ''));
  1071. return $text !== '' ? $text : '-';
  1072. }
  1073. private function buildPageCacheKey(string $suffix): string
  1074. {
  1075. $uid = Auth::id() ?: 'guest';
  1076. $kp = $this->selectedKpCode ?: 'none';
  1077. $grade = $this->parseGradeFilter() ?: 'all';
  1078. $semester = $this->parseSemesterFilter() ?: 'all';
  1079. $version = (int) Cache::get("qtr:version:u{$uid}:kp{$kp}", 1);
  1080. return "qtr:page:{$suffix}:u{$uid}:kp{$kp}:g{$grade}:s{$semester}:v{$version}";
  1081. }
  1082. private function forgetCurrentKpCaches(): void
  1083. {
  1084. foreach (['tem_questions', 'tem_cards', 'kp_question_stems'] as $suffix) {
  1085. Cache::forget($this->buildPageCacheKey($suffix));
  1086. }
  1087. }
  1088. /**
  1089. * @param array<int, object|array<string,mixed>> $rows
  1090. * @return array<int, object|array<string,mixed>>
  1091. */
  1092. private function sortRowsByQuestionType(array $rows): array
  1093. {
  1094. usort($rows, function ($a, $b): int {
  1095. $ar = is_array($a) ? $a : (array) $a;
  1096. $br = is_array($b) ? $b : (array) $b;
  1097. $aRank = $this->questionTypeRank((string) ($ar['question_type'] ?? $ar['tags'] ?? ''));
  1098. $bRank = $this->questionTypeRank((string) ($br['question_type'] ?? $br['tags'] ?? ''));
  1099. if ($aRank !== $bRank) {
  1100. return $aRank <=> $bRank;
  1101. }
  1102. return ((int) ($ar['id'] ?? 0)) <=> ((int) ($br['id'] ?? 0));
  1103. });
  1104. return $rows;
  1105. }
  1106. private function questionTypeRank(string $raw): int
  1107. {
  1108. $t = mb_strtolower(trim($raw));
  1109. return match (true) {
  1110. str_contains($t, 'choice'), str_contains($t, '选择') => 1,
  1111. str_contains($t, 'fill'), str_contains($t, 'blank'), str_contains($t, '填空') => 2,
  1112. default => 3,
  1113. };
  1114. }
  1115. private function parseGradeFilter(): ?int
  1116. {
  1117. $v = trim($this->gradeFilter);
  1118. if ($v === '' || ! is_numeric($v)) {
  1119. return null;
  1120. }
  1121. $i = (int) $v;
  1122. return $i > 0 ? $i : null;
  1123. }
  1124. private function parseSemesterFilter(): ?int
  1125. {
  1126. $v = trim($this->semesterFilter);
  1127. if ($v === '' || ! is_numeric($v)) {
  1128. return null;
  1129. }
  1130. $i = (int) $v;
  1131. return $i > 0 ? $i : null;
  1132. }
  1133. private function formatGradeLabel(int $grade): string
  1134. {
  1135. return match (true) {
  1136. $grade >= 1 && $grade <= 6 => "小学{$grade}年级",
  1137. $grade === 7 => '初一',
  1138. $grade === 8 => '初二',
  1139. $grade === 9 => '初三',
  1140. $grade === 10 => '高一',
  1141. $grade === 11 => '高二',
  1142. $grade === 12 => '高三',
  1143. $grade === 2 => '初中(学段)',
  1144. $grade === 3 => '高中(学段)',
  1145. default => "年级{$grade}",
  1146. };
  1147. }
  1148. private function formatSemesterLabel(int $semester): string
  1149. {
  1150. return match ($semester) {
  1151. 1 => '上学期',
  1152. 2 => '下学期',
  1153. default => "学期{$semester}",
  1154. };
  1155. }
  1156. }