MarkdownImportResource.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  1. <?php
  2. namespace App\Filament\Resources;
  3. use App\Filament\Resources\MarkdownImportResource\Pages;
  4. use App\Models\MarkdownImport;
  5. use BackedEnum;
  6. use Filament\Actions\BulkActionGroup;
  7. use Filament\Actions\DeleteBulkAction;
  8. use Filament\Actions\EditAction;
  9. use Filament\Actions\Action;
  10. use Filament\Facades\Filament;
  11. use Filament\Notifications\Notification;
  12. use Filament\Forms\Components\FileUpload;
  13. use Filament\Forms\Components\Hidden;
  14. use Filament\Forms\Components\MarkdownEditor;
  15. use Filament\Schemas\Components\Section;
  16. use Filament\Forms\Components\Select;
  17. use Filament\Forms\Components\Toggle;
  18. use Filament\Forms\Components\TextInput;
  19. use Filament\Schemas\Components\Utilities\Get;
  20. use Filament\Schemas\Components\Utilities\Set;
  21. use Filament\Resources\Resource;
  22. use Filament\Schemas\Schema;
  23. use Filament\Tables;
  24. use Filament\Tables\Table;
  25. use Illuminate\Database\Eloquent\Builder;
  26. use Illuminate\Database\Eloquent\Model;
  27. use Illuminate\Support\Facades\Storage;
  28. use Illuminate\Support\Facades\DB;
  29. use Illuminate\Support\Collection;
  30. use UnitEnum;
  31. use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
  32. use App\Support\TextEncoding;
  33. use App\Rules\MarkdownFileExtension;
  34. use Filament\Tables\Columns\TextColumn;
  35. use Filament\Tables\Enums\FiltersLayout;
  36. class MarkdownImportResource extends Resource
  37. {
  38. protected static ?string $model = MarkdownImport::class;
  39. protected static BackedEnum|string|null $navigationIcon = 'heroicon-o-arrow-up-tray';
  40. protected static ?string $navigationLabel = 'Markdown 导入';
  41. protected static ?string $modelLabel = 'Markdown 导入';
  42. protected static ?string $pluralModelLabel = 'Markdown 导入';
  43. protected static UnitEnum|string|null $navigationGroup = '卷子导入流程';
  44. protected static ?int $navigationSort = 1;
  45. protected static ?string $title = 'Markdown 试卷导入管理';
  46. protected static ?string $description = '导入 Markdown 格式的数学试卷,AI 智能识别题目,人工校对后入库';
  47. public static function mutateFormDataBeforeCreate(array $data): array
  48. {
  49. // 支持上传 markdown 文件:读取内容写入 original_markdown
  50. if (!empty($data['markdown_file']) && empty($data['original_markdown'])) {
  51. $path = $data['markdown_file'];
  52. if (is_string($path) && Storage::disk('local')->exists($path)) {
  53. $data['original_markdown'] = TextEncoding::toUtf8(Storage::disk('local')->get($path));
  54. }
  55. }
  56. // 文件名默认取上传文件名(优先原始文件名,其次取存储路径 basename)
  57. if (empty($data['file_name']) && !empty($data['markdown_file'])) {
  58. $storedNames = $data['uploaded_file_names'] ?? null;
  59. if (is_array($storedNames) && !empty($storedNames)) {
  60. $data['file_name'] = (string) array_values($storedNames)[0];
  61. } else {
  62. $path = is_array($data['markdown_file']) ? ($data['markdown_file'][0] ?? '') : (string) $data['markdown_file'];
  63. $data['file_name'] = $path !== '' ? basename($path) : null;
  64. }
  65. }
  66. // 文件名作为来源名称
  67. if (!empty($data['file_name'])) {
  68. $data['source_name'] = $data['file_name'];
  69. $data['source_type'] = 'other';
  70. }
  71. unset($data['markdown_file']);
  72. unset($data['uploaded_file_names']);
  73. return $data;
  74. }
  75. /**
  76. * 允许创建新的 Markdown 导入记录
  77. */
  78. public static function canCreate(): bool
  79. {
  80. return true;
  81. }
  82. public static function form(Schema $schema): Schema
  83. {
  84. return $schema
  85. ->schema([
  86. Section::make('上传与来源信息')
  87. ->schema([
  88. \Filament\Forms\Components\TextInput::make('file_name')
  89. ->label('文件名(来源名称)')
  90. ->required(fn (Get $get): bool => empty($get('markdown_file')))
  91. ->maxLength(255),
  92. FileUpload::make('markdown_file')
  93. ->label('Markdown 文件(可选)')
  94. ->disk('local')
  95. ->directory('imports/markdown')
  96. ->helperText('仅支持 .md / .markdown / .txt;上传后会自动读取内容并填充编辑器')
  97. ->maxSize(10 * 1024)
  98. ->storeFileNamesIn('uploaded_file_names')
  99. ->dehydrated(true)
  100. ->preserveFilenames()
  101. ->rules([new MarkdownFileExtension()])
  102. ->afterStateUpdated(function ($state, Set $set, Get $get): void {
  103. // 在提交表单前,FileUpload 的 state 可能还是 TemporaryUploadedFile(尚未保存到 disk)
  104. $first = is_array($state) ? ($state[0] ?? null) : $state;
  105. if ($first instanceof TemporaryUploadedFile) {
  106. $set('original_markdown', TextEncoding::toUtf8((string) @file_get_contents($first->getRealPath())));
  107. if (empty($get('file_name'))) {
  108. $set('file_name', $first->getClientOriginalName());
  109. }
  110. return;
  111. }
  112. $paths = is_array($state) ? $state : (empty($state) ? [] : [$state]);
  113. $path = (string) ($paths[0] ?? '');
  114. if ($path === '') {
  115. return;
  116. }
  117. // 已保存到 disk 后:读取文件内容填充编辑器
  118. if (Storage::disk('local')->exists($path)) {
  119. $set('original_markdown', TextEncoding::toUtf8(Storage::disk('local')->get($path)));
  120. }
  121. // 上传后的真实文件名:BaseFileUpload 会在保存时 storeFileName($storedFile, originalName)
  122. $storedNames = $get('uploaded_file_names');
  123. if (is_string($storedNames) && $storedNames !== '') {
  124. $set('file_name', $storedNames);
  125. } elseif (empty($get('file_name'))) {
  126. $set('file_name', basename($path));
  127. }
  128. }),
  129. Hidden::make('uploaded_file_names')
  130. ->dehydrated(true),
  131. ])
  132. ->columns(2),
  133. Section::make('解析规则(可选)')
  134. ->schema([
  135. Select::make('parse_mode')
  136. ->label('解析模式')
  137. ->options([
  138. 'strict' => '严格模式',
  139. 'relaxed' => '宽松模式',
  140. ])
  141. ->default('strict')
  142. ->dehydrated(false),
  143. TextInput::make('split_marker')
  144. ->label('分题符号')
  145. ->placeholder('如:---')
  146. ->dehydrated(false),
  147. TextInput::make('type_marker')
  148. ->label('题型标记')
  149. ->placeholder('如:#选择题')
  150. ->dehydrated(false),
  151. Toggle::make('auto_detect_images')
  152. ->label('自动识别图片')
  153. ->default(true)
  154. ->dehydrated(false),
  155. ])
  156. ->columns(2)
  157. ->collapsed(),
  158. Section::make('Markdown 内容')
  159. ->schema([
  160. MarkdownEditor::make('original_markdown')
  161. ->label('Markdown 内容(编辑器)')
  162. ->required(fn (Get $get): bool => empty($get('markdown_file')))
  163. ->columnSpanFull()
  164. // 固定编辑器高度,避免内容过长把页面撑开
  165. ->minHeight('45vh')
  166. ->maxHeight('45vh')
  167. ->toolbarButtons([
  168. 'bold',
  169. 'italic',
  170. 'strike',
  171. 'blockquote',
  172. 'bulletList',
  173. 'orderedList',
  174. 'link',
  175. 'codeBlock',
  176. 'table',
  177. 'undo',
  178. 'redo',
  179. ]),
  180. ]),
  181. ]);
  182. }
  183. public static function table(Table $table): Table
  184. {
  185. return $table
  186. ->columns([
  187. TextColumn::make('file_name')
  188. ->label('文件名')
  189. ->searchable()
  190. ->sortable(),
  191. TextColumn::make('remote_url')
  192. ->label('源文件')
  193. ->getStateUsing(fn (?Model $record) => $record?->remote_url ? '查看' : '—')
  194. ->icon('heroicon-o-document-arrow-down')
  195. ->color('primary')
  196. ->url(fn (?Model $record) => $record?->remote_url)
  197. ->openUrlInNewTab()
  198. ->toggleable(),
  199. TextColumn::make('filename_parse_status')
  200. ->label('命名解析')
  201. ->badge()
  202. ->getStateUsing(function (?Model $record): string {
  203. if (!$record) {
  204. return '未知';
  205. }
  206. $parsed = $record->parseFilename();
  207. return empty($parsed) ? '不规范' : '正常';
  208. })
  209. ->color(function (?Model $record): string {
  210. if (!$record) {
  211. return 'gray';
  212. }
  213. return empty($record->parseFilename()) ? 'warning' : 'success';
  214. })
  215. ->tooltip(function (?Model $record): ?string {
  216. if (!$record) {
  217. return null;
  218. }
  219. $parsed = $record->parseFilename();
  220. if (empty($parsed)) {
  221. return '系列_年级_学期_学科_名称';
  222. }
  223. return sprintf(
  224. '系列:%s 年级:%s 学期:%s 学科:%s 名称:%s',
  225. $parsed['series'] ?? '-',
  226. $parsed['grade'] ?? '-',
  227. $parsed['term'] ?? '-',
  228. $parsed['subject'] ?? '-',
  229. $parsed['name'] ?? '-'
  230. );
  231. })
  232. ->url(fn (?Model $record): ?string => $record ? route('filament.admin.pages.markdown-import-workbench', [
  233. 'import_id' => $record->id,
  234. ]) : null)
  235. ->openUrlInNewTab(),
  236. TextColumn::make('source_name')
  237. ->label('来源')
  238. ->toggleable(isToggledHiddenByDefault: true),
  239. TextColumn::make('status')
  240. ->label('状态')
  241. ->badge()
  242. ->color(fn (string $state): string => match ($state) {
  243. 'pending' => 'gray',
  244. 'processing' => 'warning',
  245. 'parsed' => 'info',
  246. 'reviewed' => 'primary',
  247. 'completed' => 'success',
  248. 'failed' => 'danger',
  249. default => 'gray',
  250. })
  251. ->getStateUsing(function (?Model $record): string {
  252. if (!$record) {
  253. return '—';
  254. }
  255. return match ($record->status) {
  256. 'pending' => '待处理',
  257. 'processing' => $record->progress_label ?: '处理中',
  258. 'parsed' => '已解析(待校对)',
  259. 'reviewed' => '已校对(待入库)',
  260. 'completed' => '已完成(已入库)',
  261. 'failed' => '失败' . ($record->progress_message ? "({$record->progress_message})" : ''),
  262. default => (string) $record->status,
  263. };
  264. }),
  265. TextColumn::make('progress_message')
  266. ->label('当前步骤')
  267. ->getStateUsing(fn (?Model $record) => $record?->progress_message ?: '—')
  268. ->wrap()
  269. ->limit(60),
  270. TextColumn::make('progress_label')
  271. ->label('进度')
  272. ->getStateUsing(fn (?Model $record) => $record?->progress_label ?: '—')
  273. ->color('gray'),
  274. TextColumn::make('parsed_count')
  275. ->label('候选题数')
  276. ->getStateUsing(fn (?Model $record) => $record?->parsed_count ?? 0)
  277. ->sortable(),
  278. TextColumn::make('accepted_count')
  279. ->label('已接受')
  280. ->getStateUsing(fn (?Model $record) => $record?->accepted_count ?? 0)
  281. ->sortable(),
  282. TextColumn::make('created_at')
  283. ->label('导入时间')
  284. ->dateTime()
  285. ->sortable(),
  286. TextColumn::make('processing_started_at')
  287. ->label('开始')
  288. ->dateTime('m-d H:i')
  289. ->toggleable(isToggledHiddenByDefault: true),
  290. TextColumn::make('processing_finished_at')
  291. ->label('结束')
  292. ->dateTime('m-d H:i')
  293. ->toggleable(isToggledHiddenByDefault: true),
  294. TextColumn::make('error_message')
  295. ->label('错误')
  296. ->visible(fn (?Model $record): bool => $record?->status === 'failed')
  297. ->wrap()
  298. ->limit(80),
  299. ])
  300. ->filters([
  301. Tables\Filters\SelectFilter::make('status')
  302. ->label('状态')
  303. ->options([
  304. 'pending' => '待处理',
  305. 'processing' => '处理中',
  306. 'parsed' => '已解析',
  307. 'reviewed' => '已校对',
  308. 'completed' => '已完成',
  309. 'failed' => '处理失败',
  310. ]),
  311. Tables\Filters\SelectFilter::make('source_type')
  312. ->label('来源类型')
  313. ->options([
  314. 'textbook' => '教材',
  315. 'exam' => '考试',
  316. 'other' => '其他',
  317. ]),
  318. Tables\Filters\SelectFilter::make('filename_parse')
  319. ->label('命名规范')
  320. ->options([
  321. 'valid' => '正常',
  322. 'invalid' => '不规范',
  323. ])
  324. ->query(function (Builder $query, array $data) {
  325. $value = $data['value'] ?? null;
  326. $driver = DB::getDriverName();
  327. $regex = '^.+_[0-9]+_[0-2]_.+_.+$';
  328. if ($value === 'valid') {
  329. if ($driver === 'mysql') {
  330. $query->whereRaw('file_name REGEXP ?', [$regex]);
  331. } else {
  332. $query->where('file_name', 'like', '%_%_%_%_%');
  333. }
  334. }
  335. if ($value === 'invalid') {
  336. if ($driver === 'mysql') {
  337. $query->where(function ($q) use ($regex) {
  338. $q->whereNull('file_name')->orWhereRaw('file_name NOT REGEXP ?', [$regex]);
  339. });
  340. } else {
  341. $query->where(function ($q) {
  342. $q->whereNull('file_name')->orWhere('file_name', 'not like', '%_%_%_%_%');
  343. });
  344. }
  345. }
  346. }),
  347. ], layout: FiltersLayout::AboveContentCollapsible)
  348. ->actions([
  349. EditAction::make()
  350. ->label('编辑'),
  351. Action::make('workbench')
  352. ->label('导入工作台')
  353. ->icon('heroicon-o-rectangle-stack')
  354. ->color('primary')
  355. ->visible(fn (?Model $record): bool => !empty($record?->parseFilename()))
  356. ->url(fn (?Model $record): string => route('filament.admin.pages.markdown-import-workbench', [
  357. 'import_id' => $record?->id,
  358. ])),
  359. Action::make('run_pipeline')
  360. ->label('触发全流程')
  361. ->icon('heroicon-o-play-circle')
  362. ->color('success')
  363. ->requiresConfirmation()
  364. ->modalHeading('触发 Markdown 拆分 + AI 结构化')
  365. ->modalDescription('立即提交队列,按 source_file → source_paper → paper_part → candidate → AI 结构化 执行。')
  366. ->action(function (?Model $record) {
  367. if (!$record) {
  368. return;
  369. }
  370. dispatch(new \App\Jobs\ProcessMarkdownSplit($record->id));
  371. $record->update([
  372. 'status' => MarkdownImport::STATUS_PROCESSING,
  373. 'progress_stage' => MarkdownImport::STAGE_QUEUED,
  374. 'progress_message' => '已进入队列…',
  375. 'processing_started_at' => now(),
  376. 'processing_finished_at' => null,
  377. 'error_message' => null,
  378. ]);
  379. Notification::make()
  380. ->title('已提交解析队列')
  381. ->success()
  382. ->send();
  383. }),
  384. Action::make('parse')
  385. ->label('解析 Markdown')
  386. ->icon('heroicon-o-cog-6-tooth')
  387. ->color('info')
  388. ->visible(fn (?Model $record): bool => in_array($record?->status, ['pending', 'failed']))
  389. ->requiresConfirmation()
  390. ->modalHeading('解析 Markdown')
  391. ->modalDescription('将解析 Markdown 中的题目候选,并使用 AI 进行初步筛选。')
  392. ->action(function (?Model $record) {
  393. if ($record) {
  394. static::parseMarkdown($record);
  395. }
  396. }),
  397. Action::make('ai_parse')
  398. ->label('AI 解析')
  399. ->icon('heroicon-o-sparkles')
  400. ->color('warning')
  401. ->visible(fn (?Model $record): bool => in_array($record?->status, ['pending', 'processing', 'parsed', 'failed']))
  402. ->requiresConfirmation()
  403. ->modalHeading('重新执行 AI 解析')
  404. ->modalDescription('将对所有候选题重新进行 AI 结构化解析,清除之前的解析标记。此操作不会重新拆分题目。')
  405. ->action(function (?Model $record) {
  406. if (!$record) {
  407. return;
  408. }
  409. static::triggerAiParsing($record);
  410. }),
  411. Action::make('review')
  412. ->label('进入校对')
  413. ->icon('heroicon-o-clipboard-document-list')
  414. ->color('success')
  415. ->visible(fn (?Model $record): bool => in_array($record?->status, ['parsed', 'reviewed', 'completed']) && !empty($record?->parseFilename()))
  416. ->url(function (?Model $record): string {
  417. // 根据状态跳转到不同页面
  418. $importId = $record?->id;
  419. $status = $record?->status;
  420. // 兼容 PHP 7.4 的写法
  421. if ($status === 'parsed') {
  422. return route('filament.admin.resources.pre-question-candidates.index', [
  423. 'import_id' => $importId
  424. ]);
  425. } elseif (in_array($status, ['reviewed', 'completed'])) {
  426. return route('filament.admin.resources.pre-question-candidates.index', [
  427. 'import_id' => $importId,
  428. 'tab' => 'reviewed' // 显示已校对标签页
  429. ]);
  430. }
  431. return route('filament.admin.resources.pre-question-candidates.index', [
  432. 'import_id' => $importId
  433. ]);
  434. }),
  435. Action::make('delete')
  436. ->label('删除')
  437. ->icon('heroicon-o-trash')
  438. ->color('danger')
  439. ->requiresConfirmation()
  440. ->modalHeading('删除导入记录')
  441. ->modalDescription('确定要删除这条导入记录吗?此操作不可撤销。')
  442. ->action(function (?Model $record) {
  443. if ($record) {
  444. $record->delete();
  445. Notification::make()
  446. ->title('删除成功')
  447. ->success()
  448. ->send();
  449. }
  450. }),
  451. ])
  452. ->bulkActions([
  453. BulkActionGroup::make([
  454. DeleteBulkAction::make(),
  455. Tables\Actions\BulkAction::make('bulk_ai_parse')
  456. ->label('批量 AI 解析')
  457. ->icon('heroicon-o-sparkles')
  458. ->color('warning')
  459. ->requiresConfirmation()
  460. ->modalHeading('批量执行 AI 解析')
  461. ->modalDescription('将对选中的所有记录重新执行 AI 结构化解析,清除之前的解析标记。')
  462. ->action(function (Collection $records) {
  463. foreach ($records as $record) {
  464. static::triggerAiParsing($record);
  465. }
  466. }),
  467. ]),
  468. ])
  469. ->recordClasses(fn (Model $record) => $record->status === 'failed' ? 'bg-rose-50/60' : null)
  470. ->defaultSort('created_at', 'desc')
  471. ->paginated([10, 25, 50, 100]);
  472. }
  473. public static function getEloquentQuery(): Builder
  474. {
  475. // 让 parsed_count / accepted_count 成为可排序的 SQL 字段(避免 order by accessor 报错)
  476. return parent::getEloquentQuery()
  477. ->withCount([
  478. 'candidates as parsed_count' => fn (Builder $query) => $query->where('status', '!=', 'superseded'),
  479. 'candidates as accepted_count' => fn (Builder $query) => $query
  480. ->where('status', '!=', 'superseded')
  481. ->where('is_question_candidate', true),
  482. ]);
  483. }
  484. public static function getPages(): array
  485. {
  486. return [
  487. 'index' => Pages\ListMarkdownImports::route('/'),
  488. 'create' => Pages\CreateMarkdownImport::route('/create'),
  489. 'edit' => Pages\EditMarkdownImport::route('/{record}/edit'),
  490. ];
  491. }
  492. /**
  493. * 解析 Markdown
  494. */
  495. public static function parseMarkdown(Model $record): void
  496. {
  497. try {
  498. // 验证状态
  499. if (!in_array($record->status, ['pending', 'failed'], true)) {
  500. Notification::make()
  501. ->title('只能解析待处理或失败状态的记录')
  502. ->warning()
  503. ->send();
  504. return;
  505. }
  506. // 验证 markdown 内容
  507. if (empty($record->original_markdown)) {
  508. Notification::make()
  509. ->title('Markdown 内容不能为空')
  510. ->warning()
  511. ->send();
  512. return;
  513. }
  514. // 失败状态重试:清空错误信息并重新进入待处理
  515. if ($record->status === 'failed') {
  516. $record->update([
  517. 'status' => 'pending',
  518. 'error_message' => null,
  519. ]);
  520. }
  521. // 先更新状态,确保列表页可见变化(避免“点了没反应”的体验)
  522. $record->update([
  523. 'status' => 'processing',
  524. 'progress_stage' => \App\Models\MarkdownImport::STAGE_QUEUED,
  525. 'progress_message' => '已提交解析任务,等待处理…',
  526. 'progress_current' => 0,
  527. 'progress_total' => 0,
  528. 'progress_updated_at' => now(),
  529. 'processing_started_at' => now(),
  530. 'processing_finished_at' => null,
  531. 'error_message' => null,
  532. ]);
  533. \Log::info('Markdown import parse queued', [
  534. 'import_id' => $record->id,
  535. 'status' => $record->status,
  536. 'stage' => $record->progress_stage,
  537. ]);
  538. // 派发异步任务
  539. \App\Jobs\ProcessMarkdownSplit::dispatch($record->id);
  540. Notification::make()
  541. ->title('已提交解析任务,正在后台处理...')
  542. ->body('列表页将自动刷新显示进度;若长期无进度,请确认 queue worker 正在运行。')
  543. ->success()
  544. ->send();
  545. } catch (\Exception $e) {
  546. Notification::make()
  547. ->title('解析失败:' . $e->getMessage())
  548. ->danger()
  549. ->send();
  550. }
  551. }
  552. /**
  553. * 重新执行 AI 解析
  554. */
  555. public static function triggerAiParsing(Model $record): void
  556. {
  557. try {
  558. // 检查是否有候选题
  559. $candidateCount = \App\Models\PreQuestionCandidate::where('import_id', $record->id)
  560. ->where('status', '!=', 'superseded')
  561. ->count();
  562. if ($candidateCount === 0) {
  563. Notification::make()
  564. ->title('没有找到候选题,无法执行 AI 解析')
  565. ->warning()
  566. ->send();
  567. return;
  568. }
  569. // 清理旧的队列任务
  570. \Illuminate\Support\Facades\DB::table('jobs')
  571. ->where('payload', 'like', '%"markdownImportId":' . $record->id . '%')
  572. ->orWhere('payload', 'like', '%"markdownImportId";i:' . $record->id . ';%')
  573. ->delete();
  574. // 清除所有候选题的 AI 解析标记
  575. $candidates = \App\Models\PreQuestionCandidate::where('import_id', $record->id)
  576. ->where('status', '!=', 'superseded')
  577. ->get();
  578. foreach ($candidates as $candidate) {
  579. $meta = $candidate->meta ?? [];
  580. unset($meta['ai_parsed'], $meta['ai_parsed_at']);
  581. $candidate->update([
  582. 'stem' => null,
  583. 'options' => null,
  584. 'images' => null,
  585. 'tables' => null,
  586. 'ai_confidence' => null,
  587. 'confidence' => null,
  588. 'status' => 'pending',
  589. 'meta' => $meta,
  590. ]);
  591. }
  592. // 更新导入记录状态
  593. $record->update([
  594. 'status' => 'processing',
  595. 'progress_stage' => \App\Models\MarkdownImport::STAGE_AI_PARSING,
  596. 'progress_message' => 'AI 解析中…',
  597. 'progress_current' => 0,
  598. 'progress_total' => $candidateCount,
  599. 'progress_updated_at' => now(),
  600. 'processing_started_at' => now(),
  601. 'processing_finished_at' => null,
  602. 'error_message' => null,
  603. ]);
  604. // 创建批次并派发 jobs
  605. $batchSize = 10;
  606. $batches = (int) ceil($candidateCount / $batchSize);
  607. for ($b = 0; $b < $batches; $b++) {
  608. $startSeq = ($b * $batchSize) + 1;
  609. $endSeq = min(($b + 1) * $batchSize, $candidateCount);
  610. \App\Jobs\ProcessMarkdownCandidateBatch::dispatch($record->id, $startSeq, $endSeq);
  611. }
  612. \Illuminate\Support\Facades\Log::info('AI parsing batches dispatched', [
  613. 'import_id' => $record->id,
  614. 'total_candidates' => $candidateCount,
  615. 'batch_size' => $batchSize,
  616. 'batches' => $batches,
  617. ]);
  618. Notification::make()
  619. ->title('已提交 AI 解析任务')
  620. ->body("共 {$candidateCount} 个候选题,已分为 {$batches} 个批次并发处理")
  621. ->success()
  622. ->send();
  623. } catch (\Exception $e) {
  624. Notification::make()
  625. ->title('AI 解析失败:' . $e->getMessage())
  626. ->danger()
  627. ->send();
  628. }
  629. }
  630. }