QuestionTemQualityReview.php 35 KB

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