MarkdownImportResource.php 30 KB

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