MarkdownImportResource.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  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. // 文件名列 - 固定宽度,可折行显示
  189. TextColumn::make('file_name')
  190. ->label('文件')
  191. ->searchable()
  192. ->sortable()
  193. ->weight('bold')
  194. ->color('gray-900')
  195. ->wrap()
  196. ->width('200px'),
  197. // 状态列 - 固定宽度
  198. TextColumn::make('current_status')
  199. ->label('状态')
  200. ->getStateUsing(function (?Model $record): string {
  201. if (!$record) return '—';
  202. return match ($record->status) {
  203. 'pending' => '⏳ 待处理',
  204. 'processing' => '🟡 处理中',
  205. 'parsed' => '✅ 已解析',
  206. 'reviewed' => '📝 已校对',
  207. 'completed' => '🎉 已完成',
  208. 'failed' => '❌ 处理失败',
  209. default => '—',
  210. };
  211. })
  212. ->badge()
  213. ->color(fn (?Model $record): string => match ($record?->status ?? '') {
  214. 'pending' => 'gray',
  215. 'processing' => 'warning',
  216. 'parsed' => 'success',
  217. 'reviewed' => 'primary',
  218. 'completed' => 'success',
  219. 'failed' => 'danger',
  220. default => 'gray',
  221. })
  222. ->width('120px'),
  223. // 详细信息列 - 自适应剩余空间,完整显示所有内容
  224. TextColumn::make('detailed_progress')
  225. ->label('详情')
  226. ->getStateUsing(function (?Model $record): string {
  227. if (!$record) return '—';
  228. return match ($record->status) {
  229. 'processing' => $record->progress_message ?: 'AI 正在解析题目...',
  230. 'parsed' => sprintf(
  231. '已解析 %d 个候选题,请进入校对环节',
  232. $record->parsed_count ?? 0
  233. ),
  234. 'reviewed' => sprintf(
  235. '已校对 %d 个候选题,请确认入库',
  236. $record->accepted_count ?? 0
  237. ),
  238. 'completed' => sprintf(
  239. '成功入库 %d 个题目',
  240. $record->accepted_count ?? 0
  241. ),
  242. 'failed' => $record->error_message ?: '未知错误',
  243. 'pending' => '准备就绪,等待开始解析',
  244. default => '—',
  245. };
  246. })
  247. ->wrap()
  248. ->color('gray-600')
  249. ->width('1fr'), // 占据剩余所有空间
  250. // 快速操作列 - 固定宽度
  251. TextColumn::make('quick_actions')
  252. ->label('操作')
  253. ->getStateUsing(function (?Model $record): string {
  254. if (!$record) return '—';
  255. return match ($record->status) {
  256. 'processing' => '🔄 处理中',
  257. 'parsed', 'reviewed' => '👁️ 查看校对',
  258. 'completed' => '📊 查看结果',
  259. 'failed' => '🔁 重试',
  260. 'pending' => '▶️ 开始',
  261. default => '—',
  262. };
  263. })
  264. ->url(function (?Model $record): ?string {
  265. if (!$record) return null;
  266. return match ($record->status) {
  267. 'parsed', 'reviewed' => route('filament.admin.resources.pre-question-candidates.index', [
  268. 'import_id' => $record->id,
  269. 'tab' => $record->status === 'reviewed' ? 'reviewed' : null
  270. ]),
  271. 'completed' => route('filament.admin.pages.markdown-import-workbench', [
  272. 'import_id' => $record->id,
  273. ]),
  274. default => null,
  275. };
  276. })
  277. ->color('primary')
  278. ->weight('medium')
  279. ->wrap()
  280. ->width('100px'),
  281. ])
  282. ->filters([
  283. Tables\Filters\SelectFilter::make('status')
  284. ->label('状态')
  285. ->options([
  286. 'pending' => '待处理',
  287. 'processing' => '处理中',
  288. 'parsed' => '已解析',
  289. 'reviewed' => '已校对',
  290. 'completed' => '已完成',
  291. 'failed' => '处理失败',
  292. ]),
  293. Tables\Filters\SelectFilter::make('source_type')
  294. ->label('来源类型')
  295. ->options([
  296. 'textbook' => '教材',
  297. 'exam' => '考试',
  298. 'other' => '其他',
  299. ]),
  300. Tables\Filters\SelectFilter::make('filename_parse')
  301. ->label('命名规范')
  302. ->options([
  303. 'valid' => '正常',
  304. 'invalid' => '不规范',
  305. ])
  306. ->query(function (Builder $query, array $data) {
  307. $value = $data['value'] ?? null;
  308. $driver = DB::getDriverName();
  309. $regex = '^.+_[0-9]+_[0-2]_.+_.+$';
  310. if ($value === 'valid') {
  311. if ($driver === 'mysql') {
  312. $query->whereRaw('file_name REGEXP ?', [$regex]);
  313. } else {
  314. $query->where('file_name', 'like', '%_%_%_%_%');
  315. }
  316. }
  317. if ($value === 'invalid') {
  318. if ($driver === 'mysql') {
  319. $query->where(function ($q) use ($regex) {
  320. $q->whereNull('file_name')->orWhereRaw('file_name NOT REGEXP ?', [$regex]);
  321. });
  322. } else {
  323. $query->where(function ($q) {
  324. $q->whereNull('file_name')->orWhere('file_name', 'not like', '%_%_%_%_%');
  325. });
  326. }
  327. }
  328. }),
  329. ], layout: FiltersLayout::AboveContentCollapsible)
  330. ->actions([
  331. // 第一行按钮 - 主要操作
  332. EditAction::make()
  333. ->label('编辑')
  334. ->size('sm'),
  335. Action::make('workbench')
  336. ->label('工作台')
  337. ->icon('heroicon-o-rectangle-stack')
  338. ->color('primary')
  339. ->size('sm')
  340. ->visible(fn (?Model $record): bool => !empty($record?->parseFilename()))
  341. ->url(fn (?Model $record): string => route('filament.admin.pages.markdown-import-workbench', [
  342. 'import_id' => $record?->id,
  343. ])),
  344. Action::make('review')
  345. ->label('校对')
  346. ->icon('heroicon-o-clipboard-document-list')
  347. ->color('success')
  348. ->size('sm')
  349. ->visible(fn (?Model $record): bool => in_array($record?->status, ['parsed', 'reviewed', 'completed']) && !empty($record?->parseFilename()))
  350. ->url(function (?Model $record): string {
  351. $importId = $record?->id;
  352. $status = $record?->status;
  353. if ($status === 'parsed') {
  354. return route('filament.admin.resources.pre-question-candidates.index', [
  355. 'import_id' => $importId
  356. ]);
  357. } elseif (in_array($status, ['reviewed', 'completed'])) {
  358. return route('filament.admin.resources.pre-question-candidates.index', [
  359. 'import_id' => $importId,
  360. 'tab' => 'reviewed'
  361. ]);
  362. }
  363. return route('filament.admin.resources.pre-question-candidates.index', [
  364. 'import_id' => $importId
  365. ]);
  366. }),
  367. Action::make('delete')
  368. ->label('删除')
  369. ->icon('heroicon-o-trash')
  370. ->color('danger')
  371. ->size('sm')
  372. ->requiresConfirmation()
  373. ->modalHeading('删除导入记录')
  374. ->modalDescription('确定要删除这条导入记录吗?此操作不可撤销。')
  375. ->action(function (?Model $record) {
  376. if ($record) {
  377. $record->delete();
  378. Notification::make()
  379. ->title('删除成功')
  380. ->success()
  381. ->send();
  382. }
  383. }),
  384. // 第二行按钮 - 处理操作
  385. Action::make('run_pipeline')
  386. ->label('全流程')
  387. ->icon('heroicon-o-play-circle')
  388. ->color('success')
  389. ->size('sm')
  390. ->requiresConfirmation()
  391. ->modalHeading('触发 Markdown 拆分 + AI 结构化')
  392. ->modalDescription('立即提交队列,按 source_file → source_paper → paper_part → candidate → AI 结构化 执行。')
  393. ->action(function (?Model $record) {
  394. if (!$record) {
  395. return;
  396. }
  397. dispatch(new \App\Jobs\ProcessMarkdownSplit($record->id));
  398. $record->update([
  399. 'status' => MarkdownImport::STATUS_PROCESSING,
  400. 'progress_stage' => MarkdownImport::STAGE_QUEUED,
  401. 'progress_message' => '已进入队列…',
  402. 'processing_started_at' => now(),
  403. 'processing_finished_at' => null,
  404. 'error_message' => null,
  405. ]);
  406. Notification::make()
  407. ->title('已提交解析队列')
  408. ->success()
  409. ->send();
  410. }),
  411. Action::make('parse')
  412. ->label('解析')
  413. ->icon('heroicon-o-cog-6-tooth')
  414. ->color('info')
  415. ->size('sm')
  416. ->visible(fn (?Model $record): bool => in_array($record?->status, ['pending', 'failed']))
  417. ->requiresConfirmation()
  418. ->modalHeading('解析 Markdown')
  419. ->modalDescription('将解析 Markdown 中的题目候选,并使用 AI 进行初步筛选。')
  420. ->action(function (?Model $record) {
  421. if ($record) {
  422. static::parseMarkdown($record);
  423. }
  424. }),
  425. Action::make('ai_parse')
  426. ->label('AI解析')
  427. ->icon('heroicon-o-sparkles')
  428. ->color('warning')
  429. ->size('sm')
  430. ->visible(fn (?Model $record): bool => in_array($record?->status, ['pending', 'processing', 'parsed', 'failed']))
  431. ->requiresConfirmation()
  432. ->modalHeading('重新执行 AI 解析')
  433. ->modalDescription('将对所有候选题重新进行 AI 结构化解析,清除之前的解析标记。此操作不会重新拆分题目。')
  434. ->action(function (?Model $record) {
  435. if (!$record) {
  436. return;
  437. }
  438. static::triggerAiParsing($record);
  439. }),
  440. ])
  441. ->bulkActions([
  442. BulkActionGroup::make([
  443. DeleteBulkAction::make(),
  444. BulkAction::make('bulk_ai_parse')
  445. ->label('批量 AI 解析')
  446. ->icon('heroicon-o-sparkles')
  447. ->color('warning')
  448. ->requiresConfirmation()
  449. ->modalHeading('批量执行 AI 解析')
  450. ->modalDescription('将对选中的所有记录重新执行 AI 结构化解析,清除之前的解析标记。')
  451. ->action(function (Collection $records) {
  452. foreach ($records as $record) {
  453. static::triggerAiParsing($record);
  454. }
  455. }),
  456. ]),
  457. ])
  458. ->recordClasses(fn (Model $record) => $record->status === 'failed' ? 'bg-rose-50/60' : null)
  459. ->defaultSort('created_at', 'desc')
  460. ->paginated([10, 25, 50, 100]);
  461. }
  462. public static function getEloquentQuery(): Builder
  463. {
  464. // 让 parsed_count / accepted_count 成为可排序的 SQL 字段(避免 order by accessor 报错)
  465. return parent::getEloquentQuery()
  466. ->withCount([
  467. 'candidates as parsed_count' => fn (Builder $query) => $query->where('status', '!=', 'superseded'),
  468. 'candidates as accepted_count' => fn (Builder $query) => $query
  469. ->where('status', '!=', 'superseded')
  470. ->where('is_question_candidate', true),
  471. ]);
  472. }
  473. public static function getPages(): array
  474. {
  475. return [
  476. 'index' => Pages\ListMarkdownImports::route('/'),
  477. 'create' => Pages\CreateMarkdownImport::route('/create'),
  478. 'edit' => Pages\EditMarkdownImport::route('/{record}/edit'),
  479. ];
  480. }
  481. /**
  482. * 解析 Markdown
  483. */
  484. public static function parseMarkdown(Model $record): void
  485. {
  486. try {
  487. // 验证状态
  488. if (!in_array($record->status, ['pending', 'failed'], true)) {
  489. Notification::make()
  490. ->title('只能解析待处理或失败状态的记录')
  491. ->warning()
  492. ->send();
  493. return;
  494. }
  495. // 验证 markdown 内容
  496. if (empty($record->original_markdown)) {
  497. Notification::make()
  498. ->title('Markdown 内容不能为空')
  499. ->warning()
  500. ->send();
  501. return;
  502. }
  503. // 失败状态重试:清空错误信息并重新进入待处理
  504. if ($record->status === 'failed') {
  505. $record->update([
  506. 'status' => 'pending',
  507. 'error_message' => null,
  508. ]);
  509. }
  510. // 先更新状态,确保列表页可见变化(避免“点了没反应”的体验)
  511. $record->update([
  512. 'status' => 'processing',
  513. 'progress_stage' => \App\Models\MarkdownImport::STAGE_QUEUED,
  514. 'progress_message' => '已提交解析任务,等待处理…',
  515. 'progress_current' => 0,
  516. 'progress_total' => 0,
  517. 'progress_updated_at' => now(),
  518. 'processing_started_at' => now(),
  519. 'processing_finished_at' => null,
  520. 'error_message' => null,
  521. ]);
  522. \Log::info('Markdown import parse queued', [
  523. 'import_id' => $record->id,
  524. 'status' => $record->status,
  525. 'stage' => $record->progress_stage,
  526. ]);
  527. // 派发异步任务
  528. \App\Jobs\ProcessMarkdownSplit::dispatch($record->id);
  529. Notification::make()
  530. ->title('已提交解析任务,正在后台处理...')
  531. ->body('列表页将自动刷新显示进度;若长期无进度,请确认 queue worker 正在运行。')
  532. ->success()
  533. ->send();
  534. } catch (\Exception $e) {
  535. Notification::make()
  536. ->title('解析失败:' . $e->getMessage())
  537. ->danger()
  538. ->send();
  539. }
  540. }
  541. /**
  542. * 重新执行 AI 解析
  543. */
  544. public static function triggerAiParsing(Model $record): void
  545. {
  546. try {
  547. // 检查是否有候选题
  548. $candidateCount = \App\Models\PreQuestionCandidate::where('import_id', $record->id)
  549. ->where('status', '!=', 'superseded')
  550. ->count();
  551. if ($candidateCount === 0) {
  552. Notification::make()
  553. ->title('没有找到候选题,无法执行 AI 解析')
  554. ->warning()
  555. ->send();
  556. return;
  557. }
  558. // 清理旧的队列任务
  559. \Illuminate\Support\Facades\DB::table('jobs')
  560. ->where('payload', 'like', '%"markdownImportId":' . $record->id . '%')
  561. ->orWhere('payload', 'like', '%"markdownImportId";i:' . $record->id . ';%')
  562. ->delete();
  563. // 清除所有候选题的 AI 解析标记
  564. $candidates = \App\Models\PreQuestionCandidate::where('import_id', $record->id)
  565. ->where('status', '!=', 'superseded')
  566. ->get();
  567. foreach ($candidates as $candidate) {
  568. $meta = $candidate->meta ?? [];
  569. unset($meta['ai_parsed'], $meta['ai_parsed_at']);
  570. $candidate->update([
  571. 'stem' => null,
  572. 'options' => null,
  573. 'images' => null,
  574. 'tables' => null,
  575. 'ai_confidence' => null,
  576. 'confidence' => null,
  577. 'status' => 'pending',
  578. 'meta' => $meta,
  579. ]);
  580. }
  581. // 更新导入记录状态
  582. $record->update([
  583. 'status' => 'processing',
  584. 'progress_stage' => \App\Models\MarkdownImport::STAGE_AI_PARSING,
  585. 'progress_message' => 'AI 解析中…',
  586. 'progress_current' => 0,
  587. 'progress_total' => $candidateCount,
  588. 'progress_updated_at' => now(),
  589. 'processing_started_at' => now(),
  590. 'processing_finished_at' => null,
  591. 'error_message' => null,
  592. ]);
  593. // 创建批次并派发 jobs
  594. $batchSize = 10;
  595. $batches = (int) ceil($candidateCount / $batchSize);
  596. for ($b = 0; $b < $batches; $b++) {
  597. $startSeq = ($b * $batchSize) + 1;
  598. $endSeq = min(($b + 1) * $batchSize, $candidateCount);
  599. \App\Jobs\ProcessMarkdownCandidateBatch::dispatch($record->id, $startSeq, $endSeq);
  600. }
  601. \Illuminate\Support\Facades\Log::info('AI parsing batches dispatched', [
  602. 'import_id' => $record->id,
  603. 'total_candidates' => $candidateCount,
  604. 'batch_size' => $batchSize,
  605. 'batches' => $batches,
  606. ]);
  607. Notification::make()
  608. ->title('已提交 AI 解析任务')
  609. ->body("共 {$candidateCount} 个候选题,已分为 {$batches} 个批次并发处理")
  610. ->success()
  611. ->send();
  612. } catch (\Exception $e) {
  613. Notification::make()
  614. ->title('AI 解析失败:' . $e->getMessage())
  615. ->danger()
  616. ->send();
  617. }
  618. }
  619. }