QuestionTemQualityReview.php 35 KB

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