QuestionTemQualityReview.php 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118
  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}, 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>}}>
  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. 'meta' => [
  195. 'created_at' => $this->formatMetaDatetime($arr['created_at'] ?? null),
  196. 'updated_at' => $this->formatMetaDatetime($arr['updated_at'] ?? null),
  197. 'difficulty' => $this->formatMetaDifficulty($arr['difficulty'] ?? null),
  198. 'audit_reason' => $this->formatMetaAuditReason($arr['audit_reason'] ?? null),
  199. ],
  200. 'grouped_questions' => $this->buildPreviewGroupedQuestionsFromTemRows([$arr]),
  201. ];
  202. }
  203. return $cards;
  204. });
  205. }
  206. /**
  207. * 与判卷 PDF / pdf.exam-grading 使用同一套 components.exam.paper-body 数据管线
  208. *
  209. * @return array{choice: array, fill: array, answer: array}
  210. */
  211. #[Computed]
  212. public function groupedPaperBodyQuestions(): array
  213. {
  214. if (! $this->selectedKpCode) {
  215. return ['choice' => [], 'fill' => [], 'answer' => []];
  216. }
  217. return $this->buildPreviewGroupedQuestionsFromTemRows($this->temQuestions);
  218. }
  219. /** @return list<object> */
  220. #[Computed]
  221. public function assemblyQueueRows(): array
  222. {
  223. $uid = Auth::id();
  224. if (! $uid) {
  225. return [];
  226. }
  227. return app(QuestionsTemAssemblyService::class)->queueForUser((int) $uid);
  228. }
  229. #[Computed]
  230. public function selectedRow(): ?object
  231. {
  232. if (! $this->selectedTemId) {
  233. return null;
  234. }
  235. return DB::table('questions_tem')->where('id', $this->selectedTemId)->first();
  236. }
  237. /**
  238. * @return array{passed: bool, errors: array, results: array}|null
  239. */
  240. #[Computed]
  241. public function qcResult(): ?array
  242. {
  243. if (! $this->qcPanelExpanded) {
  244. return null;
  245. }
  246. $row = $this->selectedRow;
  247. if (! $row) {
  248. return null;
  249. }
  250. $mapped = $this->mapQuestionRowForQc((array) $row);
  251. $qc = app(QuestionQualityCheckService::class)->runAutoCheck($mapped, (int) $row->id, null);
  252. return [
  253. 'passed' => $qc['passed'],
  254. 'errors' => $qc['errors'],
  255. 'results' => $qc['results'],
  256. ];
  257. }
  258. #[Computed]
  259. public function duplicateHint(): ?string
  260. {
  261. if (! $this->qcPanelExpanded) {
  262. return null;
  263. }
  264. $row = $this->selectedRow;
  265. if (! $row) {
  266. return null;
  267. }
  268. $svc = app(QuestionTemReviewService::class);
  269. $stem = $svc->normalizedStemFromTemRow($row);
  270. $kp = (string) ($row->kp_code ?? '');
  271. if ($stem === '' || $kp === '') {
  272. return null;
  273. }
  274. if ($svc->existsDuplicateInQuestions($kp, $stem)) {
  275. return '正式库已存在同知识点、同题干题目';
  276. }
  277. return null;
  278. }
  279. public function selectKp(string $kpCode): void
  280. {
  281. $this->selectedKpCode = $kpCode;
  282. $this->selectedTemId = null;
  283. $this->selectedTemIds = [];
  284. $this->pendingImportTemIds = [];
  285. $this->cardRenderLimit = 20;
  286. $this->importDifficultyInput = '0.50';
  287. $this->qcPanelExpanded = false;
  288. $this->dispatch('qtr-scroll-top');
  289. }
  290. public function loadMoreCards(): void
  291. {
  292. $this->cardRenderLimit += 20;
  293. $this->dispatch('qtr-scroll-top');
  294. }
  295. #[Computed]
  296. public function visibleTemQuestionCards(): array
  297. {
  298. return array_slice($this->temQuestionCards, 0, max(1, $this->cardRenderLimit));
  299. }
  300. /** @return list<object> */
  301. #[Computed]
  302. public function pendingImportRows(): array
  303. {
  304. if ($this->pendingImportTemIds === []) {
  305. return [];
  306. }
  307. $rows = DB::table('questions_tem')
  308. ->whereIn('id', $this->pendingImportTemIds)
  309. ->get()
  310. ->keyBy('id');
  311. $ordered = [];
  312. foreach ($this->pendingImportTemIds as $id) {
  313. $row = $rows->get((int) $id);
  314. if ($row) {
  315. $ordered[] = $row;
  316. }
  317. }
  318. return $this->sortRowsByQuestionType($ordered);
  319. }
  320. /**
  321. * 右侧人工判重参考:当前选中知识点在正式库 questions 的题目(编号+题干)。
  322. *
  323. * @return list<object>
  324. */
  325. #[Computed]
  326. public function currentKpQuestionStemRows(): array
  327. {
  328. if (! $this->selectedKpCode || ! Schema::hasTable('questions')) {
  329. return [];
  330. }
  331. $key = $this->buildPageCacheKey('kp_question_stems_v2');
  332. return Cache::remember($key, now()->addMinutes(2), function (): array {
  333. $q = DB::table('questions')
  334. ->where('kp_code', $this->selectedKpCode)
  335. ->select(['id', 'stem', 'question_type'])
  336. ->orderByRaw("
  337. CASE
  338. WHEN LOWER(COALESCE(question_type, '')) LIKE '%choice%' OR question_type LIKE '%选择%' THEN 1
  339. WHEN LOWER(COALESCE(question_type, '')) LIKE '%fill%' OR LOWER(COALESCE(question_type, '')) LIKE '%blank%' OR question_type LIKE '%填空%' THEN 2
  340. ELSE 3
  341. END ASC
  342. ")
  343. ->orderBy('id');
  344. // 右侧人工判重列表仅按当前选中知识点展示:
  345. // 年级/学期筛选已在左侧知识点范围内收敛,避免对 questions.grade 再次过滤导致误空。
  346. return $q->limit(300)->get()->all();
  347. });
  348. }
  349. public function updatedSelectedTemId(mixed $value): void
  350. {
  351. if ($this->selectedTemId) {
  352. $this->syncImportDifficultyFromSelectedRow();
  353. if (! in_array((int) $this->selectedTemId, $this->selectedTemIds, true)) {
  354. $this->selectedTemIds[] = (int) $this->selectedTemId;
  355. }
  356. } else {
  357. $this->importDifficultyInput = '0.50';
  358. }
  359. $this->selectedTemIds = array_values(array_unique(array_map('intval', $this->selectedTemIds)));
  360. }
  361. public function updatedSelectedTemIds(): void
  362. {
  363. $this->selectedTemIds = array_values(array_unique(array_filter(
  364. array_map('intval', $this->selectedTemIds),
  365. static fn (int $id) => $id > 0
  366. )));
  367. if ($this->selectedTemId && ! in_array((int) $this->selectedTemId, $this->selectedTemIds, true)) {
  368. $this->selectedTemId = $this->selectedTemIds[0] ?? null;
  369. }
  370. if (! $this->selectedTemId && $this->selectedTemIds !== []) {
  371. $this->selectedTemId = $this->selectedTemIds[0];
  372. }
  373. if ($this->selectedTemId) {
  374. $this->syncImportDifficultyFromSelectedRow();
  375. } else {
  376. $this->importDifficultyInput = '0.50';
  377. }
  378. }
  379. public function focusTemQuestion(int $id): void
  380. {
  381. if ($id <= 0) {
  382. return;
  383. }
  384. $this->selectedTemId = $id;
  385. if (! in_array($id, $this->selectedTemIds, true)) {
  386. $this->selectedTemIds[] = $id;
  387. $this->selectedTemIds = array_values(array_unique(array_map('intval', $this->selectedTemIds)));
  388. }
  389. $this->qcPanelExpanded = false;
  390. }
  391. public function addToPendingImport(int $id): void
  392. {
  393. if ($id <= 0) {
  394. return;
  395. }
  396. if (! in_array($id, $this->pendingImportTemIds, true)) {
  397. $this->pendingImportTemIds[] = $id;
  398. $this->pendingImportTemIds = array_values(array_unique(array_map('intval', $this->pendingImportTemIds)));
  399. }
  400. if ((int) ($this->selectedTemId ?? 0) === $id) {
  401. $this->selectedTemId = null;
  402. $this->importDifficultyInput = '0.50';
  403. }
  404. }
  405. #[Renderless]
  406. public function queueImportTem(int $id): void
  407. {
  408. if ($id <= 0) {
  409. return;
  410. }
  411. $status = Cache::get(ImportTemToQuestionsJob::statusKey($id));
  412. $state = (string) ($status['state'] ?? '');
  413. if (in_array($state, ['queued', 'running'], true)) {
  414. return;
  415. }
  416. Cache::put(ImportTemToQuestionsJob::statusKey($id), [
  417. 'state' => 'queued',
  418. 'message' => '已加入队列,等待处理',
  419. 'at' => now()->toDateTimeString(),
  420. ], now()->addMinutes(30));
  421. ImportTemToQuestionsJob::dispatch($id, Auth::id() ? (int) Auth::id() : null, $this->selectedKpCode);
  422. }
  423. public function removeFromPendingImport(int $id): void
  424. {
  425. $this->pendingImportTemIds = array_values(array_filter(
  426. $this->pendingImportTemIds,
  427. static fn ($x) => (int) $x !== $id
  428. ));
  429. }
  430. public function clearPendingImport(): void
  431. {
  432. $this->pendingImportTemIds = [];
  433. }
  434. public function importPendingTem(int $id): void
  435. {
  436. $this->queueImportTem($id);
  437. }
  438. public function importPendingAll(): void
  439. {
  440. if ($this->pendingImportTemIds === []) {
  441. Notification::make()->title('待入库为空')->warning()->send();
  442. return;
  443. }
  444. foreach ($this->pendingImportTemIds as $id) {
  445. $this->queueImportTem((int) $id);
  446. }
  447. }
  448. public function syncAsyncImportStatuses(): void
  449. {
  450. if ($this->pendingImportTemIds === []) {
  451. return;
  452. }
  453. $remaining = [];
  454. $doneFound = false;
  455. foreach ($this->pendingImportTemIds as $id) {
  456. $status = Cache::get(ImportTemToQuestionsJob::statusKey((int) $id));
  457. if (($status['state'] ?? null) === 'done') {
  458. $doneFound = true;
  459. continue;
  460. }
  461. $remaining[] = (int) $id;
  462. }
  463. if ($doneFound) {
  464. $this->pendingImportTemIds = array_values(array_unique($remaining));
  465. $this->forgetCurrentKpCaches();
  466. }
  467. }
  468. /** @return array<int, array{state?:string,message?:string,question_id?:int,at?:string}> */
  469. #[Computed]
  470. public function importStatusMap(): array
  471. {
  472. $ids = [];
  473. foreach ($this->temQuestionCards as $card) {
  474. $id = (int) ($card['id'] ?? 0);
  475. if ($id > 0) {
  476. $ids[] = $id;
  477. }
  478. }
  479. foreach ($this->pendingImportTemIds as $id) {
  480. $id = (int) $id;
  481. if ($id > 0) {
  482. $ids[] = $id;
  483. }
  484. }
  485. $ids = array_values(array_unique($ids));
  486. if ($ids === []) {
  487. return [];
  488. }
  489. $keys = [];
  490. foreach ($ids as $id) {
  491. $keys[$id] = ImportTemToQuestionsJob::statusKey($id);
  492. }
  493. $many = Cache::many(array_values($keys));
  494. $map = [];
  495. foreach ($keys as $id => $key) {
  496. $v = $many[$key] ?? null;
  497. if (is_array($v) && isset($v['state'])) {
  498. $map[(int) $id] = $v;
  499. }
  500. }
  501. return $map;
  502. }
  503. public function clearTemSelection(): void
  504. {
  505. $this->selectedTemIds = [];
  506. $this->selectedTemId = null;
  507. $this->importDifficultyInput = '0.50';
  508. $this->qcPanelExpanded = false;
  509. }
  510. public function importSelectedTemIdsFast(): void
  511. {
  512. if ($this->selectedTemIds === []) {
  513. Notification::make()->title('请先勾选题目')->warning()->send();
  514. return;
  515. }
  516. $svc = app(QuestionTemReviewService::class);
  517. $result = $svc->importTemIdsToQuestions($this->selectedTemIds);
  518. QuestionTemReviewService::mergeQuestionIdsIntoTuningSession($result['imported_question_ids'] ?? []);
  519. $this->notifyBulkImportResult($result);
  520. $this->selectedTemIds = [];
  521. $this->selectedTemId = null;
  522. $this->qcPanelExpanded = false;
  523. $this->dispatch('$refresh');
  524. }
  525. public function addSelectionToAssemblyQueue(): void
  526. {
  527. if ($this->selectedTemIds === []) {
  528. Notification::make()->title('请先勾选题目')->warning()->send();
  529. return;
  530. }
  531. $uid = Auth::id();
  532. if (! $uid) {
  533. return;
  534. }
  535. $svc = app(QuestionsTemAssemblyService::class);
  536. foreach ($this->selectedTemIds as $tid) {
  537. $svc->add((int) $uid, (int) $tid);
  538. }
  539. Notification::make()
  540. ->title('已加入待组卷队列(未写入 questions)')
  541. ->body('共 '.count($this->selectedTemIds).' 道')
  542. ->success()
  543. ->send();
  544. }
  545. public function removeFromAssemblyQueue(int $temId): void
  546. {
  547. $uid = Auth::id();
  548. if (! $uid) {
  549. return;
  550. }
  551. app(QuestionsTemAssemblyService::class)->remove((int) $uid, $temId);
  552. }
  553. public function clearAssemblyQueue(): void
  554. {
  555. $uid = Auth::id();
  556. if (! $uid) {
  557. return;
  558. }
  559. app(QuestionsTemAssemblyService::class)->clear((int) $uid);
  560. $this->trialGradingUrl = null;
  561. $this->trialGradingPdfUrl = null;
  562. Notification::make()->title('已清空待组卷队列')->success()->send();
  563. }
  564. public function generateTrialGradingPdf(): void
  565. {
  566. $uid = Auth::id();
  567. if (! $uid) {
  568. Notification::make()->title('未登录')->danger()->send();
  569. return;
  570. }
  571. $svc = app(QuestionsTemAssemblyService::class);
  572. if (! $svc->tableExists()) {
  573. Notification::make()->title('请先执行迁移:questions_tem_assembly_queue')->danger()->send();
  574. return;
  575. }
  576. $paperId = $svc->createTrialPaperForQueue((int) $uid);
  577. if (! $paperId) {
  578. Notification::make()->title('待组卷队列为空,请先「加入待组卷」')->warning()->send();
  579. return;
  580. }
  581. $this->trialGradingUrl = route('filament.admin.auth.intelligent-exam.grading', ['paper_id' => $paperId]);
  582. $this->trialGradingPdfUrl = null;
  583. $pdfBody = '';
  584. try {
  585. // 与正式组卷一致:学生卷 + 答案详解/判卷段 + 判题卡(强制追加扫描卡,不依赖 .env)
  586. $pdfUrl = app(ExamPdfExportService::class)->generateUnifiedPdf($paperId, false, true);
  587. $this->trialGradingPdfUrl = $pdfUrl ?: null;
  588. $pdfBody = $this->trialGradingPdfUrl
  589. ? '完整卷 PDF(学生卷 + 答案详解 + 判题卡)已生成,可下载核对。'
  590. : '完整卷 PDF 未返回地址,请仅用判卷页预览。';
  591. } catch (\Throwable $e) {
  592. $pdfBody = '完整卷 PDF 导出异常:'.$e->getMessage();
  593. }
  594. if (str_contains($pdfBody, '异常')) {
  595. Notification::make()
  596. ->title('已生成临时试卷(判卷页可预览)')
  597. ->body($pdfBody)
  598. ->warning()
  599. ->send();
  600. } else {
  601. Notification::make()
  602. ->title('已生成临时试卷')
  603. ->body('可打开判卷页预览。'.$pdfBody)
  604. ->success()
  605. ->send();
  606. }
  607. }
  608. /**
  609. * 将当前左侧选中知识点下,中间列表中的全部 questions_tem 写入 questions(与单题入库规则一致)
  610. */
  611. public function importAllCurrentKpToQuestions(): void
  612. {
  613. if (! $this->selectedKpCode) {
  614. Notification::make()->title('请先选择左侧知识点')->warning()->send();
  615. return;
  616. }
  617. $ids = [];
  618. foreach ($this->temQuestions as $row) {
  619. $ids[] = (int) ($row->id ?? 0);
  620. }
  621. if ($ids === []) {
  622. Notification::make()->title('当前知识点下没有待审题目')->warning()->send();
  623. return;
  624. }
  625. $svc = app(QuestionTemReviewService::class);
  626. $result = $svc->importTemIdsToQuestions($ids);
  627. QuestionTemReviewService::mergeQuestionIdsIntoTuningSession($result['imported_question_ids'] ?? []);
  628. $this->notifyBulkImportResult($result);
  629. $this->dispatch('$refresh');
  630. }
  631. /**
  632. * 将右侧「待组卷」队列中的全部 questions_tem 写入 questions
  633. */
  634. public function importAssemblyQueueToQuestions(): void
  635. {
  636. $uid = Auth::id();
  637. if (! $uid) {
  638. return;
  639. }
  640. $ids = [];
  641. foreach ($this->assemblyQueueRows as $row) {
  642. $ids[] = (int) ($row->id ?? 0);
  643. }
  644. if ($ids === []) {
  645. Notification::make()->title('待组卷队列为空')->warning()->send();
  646. return;
  647. }
  648. $svc = app(QuestionTemReviewService::class);
  649. $result = $svc->importTemIdsToQuestions($ids);
  650. QuestionTemReviewService::mergeQuestionIdsIntoTuningSession($result['imported_question_ids'] ?? []);
  651. $this->notifyBulkImportResult($result);
  652. $this->dispatch('$refresh');
  653. }
  654. /**
  655. * @param array{imported: int, skipped: int, failed: int, lines: list<string>, imported_question_ids?: list<int>} $result
  656. */
  657. private function notifyBulkImportResult(array $result): void
  658. {
  659. $body = sprintf(
  660. '成功 %d 道,跳过 %d 道(重复或缺字段),失败 %d 道。',
  661. $result['imported'],
  662. $result['skipped'],
  663. $result['failed']
  664. );
  665. if ($result['lines'] !== []) {
  666. $body .= "\n\n".implode("\n", $result['lines']);
  667. }
  668. $title = $result['imported'] > 0 ? '批量入库完成' : '批量入库结束';
  669. Notification::make()
  670. ->title($title)
  671. ->body($body)
  672. ->success()
  673. ->send();
  674. }
  675. public function importSelected(): void
  676. {
  677. if (! $this->selectedTemId) {
  678. Notification::make()->title('请先选择一道题目')->warning()->send();
  679. return;
  680. }
  681. $difficulty = $this->parseImportDifficultyValidated();
  682. if ($difficulty === null) {
  683. return;
  684. }
  685. $svc = app(QuestionTemReviewService::class);
  686. $result = $svc->importTemRowToQuestions($this->selectedTemId, $difficulty);
  687. if ($result['ok']) {
  688. if (! empty($result['question_id'])) {
  689. QuestionTemReviewService::mergeQuestionIdsIntoTuningSession([(int) $result['question_id']]);
  690. }
  691. $importedTemId = (int) $this->selectedTemId;
  692. Notification::make()
  693. ->title($result['message'])
  694. ->body(sprintf('question_id: %s · difficulty: %s', (string) $result['question_id'], number_format($difficulty, 2, '.', '')))
  695. ->success()
  696. ->send();
  697. $this->selectedTemIds = array_values(array_filter($this->selectedTemIds, fn ($x) => (int) $x !== $importedTemId));
  698. $this->selectedTemId = $this->selectedTemIds[count($this->selectedTemIds) - 1] ?? null;
  699. if ($this->selectedTemId) {
  700. $this->syncImportDifficultyFromSelectedRow();
  701. } else {
  702. $this->importDifficultyInput = '0.50';
  703. }
  704. $this->dispatch('$refresh');
  705. } else {
  706. Notification::make()->title($result['message'])->danger()->send();
  707. }
  708. }
  709. private function syncImportDifficultyFromSelectedRow(): void
  710. {
  711. $row = $this->selectedRow;
  712. if (! $row) {
  713. $this->importDifficultyInput = '0.50';
  714. return;
  715. }
  716. $d = app(QuestionTemReviewService::class)->defaultDifficultyForTemRow($row);
  717. $this->importDifficultyInput = number_format($d, 2, '.', '');
  718. }
  719. /**
  720. * @return ?float 合法难度,或 null(已弹通知)
  721. */
  722. private function parseImportDifficultyValidated(): ?float
  723. {
  724. $raw = trim($this->importDifficultyInput);
  725. if ($raw === '') {
  726. Notification::make()
  727. ->title('请填写难度系数')
  728. ->body('范围为 0.00~0.90,最多两位小数。')
  729. ->warning()
  730. ->send();
  731. return null;
  732. }
  733. if (! is_numeric($raw)) {
  734. Notification::make()
  735. ->title('难度系数格式不正确')
  736. ->body('请输入数字,例如 0.35。')
  737. ->danger()
  738. ->send();
  739. return null;
  740. }
  741. $value = round((float) $raw, 2);
  742. if ($value < 0.0 || $value > 0.9) {
  743. Notification::make()
  744. ->title('难度系数超出范围')
  745. ->body('仅允许 0.00~0.90(保留两位小数)。')
  746. ->danger()
  747. ->send();
  748. return null;
  749. }
  750. $this->importDifficultyInput = number_format($value, 2, '.', '');
  751. return $value;
  752. }
  753. /**
  754. * 仅用于质检页面预览:不改组卷主链路的控制器/视图逻辑。
  755. *
  756. * @param array<int, object|array> $rows
  757. * @return array{choice: array<int, object>, fill: array<int, object>, answer: array<int, object>}
  758. */
  759. private function buildPreviewGroupedQuestionsFromTemRows(array $rows): array
  760. {
  761. $grouped = ['choice' => [], 'fill' => [], 'answer' => []];
  762. foreach (array_values($rows) as $index => $row) {
  763. $arr = is_array($row) ? $row : (array) $row;
  764. $type = $this->normalizePreviewQuestionType((string) ($arr['question_type'] ?? $arr['tags'] ?? 'answer'));
  765. $options = $this->normalizePreviewOptions($arr['options'] ?? null);
  766. $questionData = [
  767. 'id' => isset($arr['id']) ? -abs((int) $arr['id']) : null,
  768. 'question_number' => $index + 1,
  769. 'content' => (string) ($arr['stem'] ?? ''),
  770. 'stem' => (string) ($arr['stem'] ?? ''),
  771. 'answer' => (string) ($arr['answer'] ?? $arr['correct_answer'] ?? ''),
  772. 'solution' => (string) ($arr['solution'] ?? ''),
  773. 'difficulty' => isset($arr['difficulty']) ? (float) $arr['difficulty'] : 0.5,
  774. 'kp_code' => (string) ($arr['kp_code'] ?? ''),
  775. 'tags' => is_string($arr['tags'] ?? null) ? $arr['tags'] : '',
  776. 'options' => $options,
  777. 'score' => $type === 'answer' ? 10 : 5,
  778. 'question_type' => $type,
  779. ];
  780. $grouped[$type][] = (object) $questionData;
  781. }
  782. return $grouped;
  783. }
  784. private function normalizePreviewQuestionType(string $raw): string
  785. {
  786. $t = mb_strtolower(trim($raw));
  787. return match (true) {
  788. str_contains($t, 'choice'), str_contains($t, '选择') => 'choice',
  789. str_contains($t, 'fill'), str_contains($t, 'blank'), str_contains($t, '填空') => 'fill',
  790. default => 'answer',
  791. };
  792. }
  793. /**
  794. * @return array<int, string>|null
  795. */
  796. private function normalizePreviewOptions(mixed $raw): ?array
  797. {
  798. if (is_string($raw)) {
  799. $decoded = json_decode($raw, true);
  800. $raw = is_array($decoded) ? $decoded : null;
  801. }
  802. if (! is_array($raw) || $raw === []) {
  803. return null;
  804. }
  805. if (! isset($raw[0])) {
  806. return array_values(array_map(static fn ($v) => (string) $v, $raw));
  807. }
  808. if (isset($raw[0]) && is_array($raw[0])) {
  809. $out = [];
  810. foreach ($raw as $opt) {
  811. $out[] = (string) (($opt['content'] ?? $opt['text'] ?? $opt['value'] ?? ''));
  812. }
  813. return $out;
  814. }
  815. return array_values(array_map(static fn ($v) => (string) $v, $raw));
  816. }
  817. private function mapQuestionRowForQc(array $row): array
  818. {
  819. $stem = trim((string) ($row['stem'] ?? ''));
  820. if ($stem === '') {
  821. $stem = trim((string) ($row['content'] ?? ''));
  822. }
  823. $options = $row['options'] ?? null;
  824. if (is_string($options) && trim($options) !== '') {
  825. $decoded = json_decode($options, true);
  826. $options = is_array($decoded) ? $decoded : null;
  827. }
  828. $qtRaw = (string) ($row['question_type'] ?? $row['tags'] ?? '');
  829. $qtLower = strtolower(trim($qtRaw));
  830. $explicitNonChoice = in_array($qtLower, ['fill', '填空', '填空题', 'answer', '解答', '解答题'], true);
  831. if (! $explicitNonChoice && is_array($options) && count($options) >= 2) {
  832. $qtForCheck = 'choice';
  833. } else {
  834. $qtForCheck = $qtRaw;
  835. }
  836. return [
  837. 'stem' => $stem,
  838. 'answer' => $row['answer'] ?? $row['correct_answer'] ?? '',
  839. 'solution' => $row['solution'] ?? '',
  840. 'question_type' => $qtForCheck,
  841. 'options' => $options,
  842. ];
  843. }
  844. private function normalizeStemPreview(string $stem): string
  845. {
  846. // 先去掉图片标签,避免界面出现一大串 <img ...>
  847. $text = preg_replace('/<img\b[^>]*>/iu', ' [图] ', $stem) ?? $stem;
  848. $text = strip_tags($text);
  849. $text = html_entity_decode($text, ENT_QUOTES | ENT_HTML5, 'UTF-8');
  850. $text = preg_replace('/\s+/u', ' ', $text) ?? $text;
  851. return trim($text);
  852. }
  853. private function formatMetaDatetime(mixed $value): ?string
  854. {
  855. if ($value === null) {
  856. return null;
  857. }
  858. $raw = trim((string) $value);
  859. if ($raw === '' || $raw === '0000-00-00 00:00:00') {
  860. return null;
  861. }
  862. try {
  863. return \Carbon\Carbon::parse($raw)->format('Y-m-d H:i:s');
  864. } catch (\Throwable) {
  865. return $raw;
  866. }
  867. }
  868. private function formatMetaDifficulty(mixed $value): string
  869. {
  870. if ($value === null || $value === '') {
  871. return '-';
  872. }
  873. if (! is_numeric($value)) {
  874. return (string) $value;
  875. }
  876. return number_format((float) $value, 2, '.', '');
  877. }
  878. private function formatMetaAuditReason(mixed $value): string
  879. {
  880. $text = trim((string) ($value ?? ''));
  881. return $text !== '' ? $text : '-';
  882. }
  883. private function buildPageCacheKey(string $suffix): string
  884. {
  885. $uid = Auth::id() ?: 'guest';
  886. $kp = $this->selectedKpCode ?: 'none';
  887. $grade = $this->parseGradeFilter() ?: 'all';
  888. $semester = $this->parseSemesterFilter() ?: 'all';
  889. $version = (int) Cache::get("qtr:version:u{$uid}:kp{$kp}", 1);
  890. return "qtr:page:{$suffix}:u{$uid}:kp{$kp}:g{$grade}:s{$semester}:v{$version}";
  891. }
  892. private function forgetCurrentKpCaches(): void
  893. {
  894. foreach (['tem_questions', 'tem_cards', 'kp_question_stems'] as $suffix) {
  895. Cache::forget($this->buildPageCacheKey($suffix));
  896. }
  897. }
  898. /**
  899. * @param array<int, object|array<string,mixed>> $rows
  900. * @return array<int, object|array<string,mixed>>
  901. */
  902. private function sortRowsByQuestionType(array $rows): array
  903. {
  904. usort($rows, function ($a, $b): int {
  905. $ar = is_array($a) ? $a : (array) $a;
  906. $br = is_array($b) ? $b : (array) $b;
  907. $aRank = $this->questionTypeRank((string) ($ar['question_type'] ?? $ar['tags'] ?? ''));
  908. $bRank = $this->questionTypeRank((string) ($br['question_type'] ?? $br['tags'] ?? ''));
  909. if ($aRank !== $bRank) {
  910. return $aRank <=> $bRank;
  911. }
  912. return ((int) ($ar['id'] ?? 0)) <=> ((int) ($br['id'] ?? 0));
  913. });
  914. return $rows;
  915. }
  916. private function questionTypeRank(string $raw): int
  917. {
  918. $t = mb_strtolower(trim($raw));
  919. return match (true) {
  920. str_contains($t, 'choice'), str_contains($t, '选择') => 1,
  921. str_contains($t, 'fill'), str_contains($t, 'blank'), str_contains($t, '填空') => 2,
  922. default => 3,
  923. };
  924. }
  925. private function parseGradeFilter(): ?int
  926. {
  927. $v = trim($this->gradeFilter);
  928. if ($v === '' || ! is_numeric($v)) {
  929. return null;
  930. }
  931. $i = (int) $v;
  932. return $i > 0 ? $i : null;
  933. }
  934. private function parseSemesterFilter(): ?int
  935. {
  936. $v = trim($this->semesterFilter);
  937. if ($v === '' || ! is_numeric($v)) {
  938. return null;
  939. }
  940. $i = (int) $v;
  941. return $i > 0 ? $i : null;
  942. }
  943. private function formatGradeLabel(int $grade): string
  944. {
  945. return match (true) {
  946. $grade >= 1 && $grade <= 6 => "小学{$grade}年级",
  947. $grade === 7 => '初一',
  948. $grade === 8 => '初二',
  949. $grade === 9 => '初三',
  950. $grade === 10 => '高一',
  951. $grade === 11 => '高二',
  952. $grade === 12 => '高三',
  953. $grade === 2 => '初中(学段)',
  954. $grade === 3 => '高中(学段)',
  955. default => "年级{$grade}",
  956. };
  957. }
  958. private function formatSemesterLabel(int $semester): string
  959. {
  960. return match ($semester) {
  961. 1 => '上学期',
  962. 2 => '下学期',
  963. default => "学期{$semester}",
  964. };
  965. }
  966. }