PreQuestionCandidateResource.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. <?php
  2. namespace App\Filament\Resources;
  3. use App\Filament\Resources\PreQuestionCandidateResource\Pages;
  4. use App\Models\PreQuestionCandidate;
  5. use BackedEnum;
  6. use Filament\Actions\Action;
  7. use Filament\Actions\BulkActionGroup;
  8. use Filament\Forms\Components\TagsInput;
  9. use Filament\Forms\Components\Textarea;
  10. use Filament\Forms\Components\TextInput;
  11. use Filament\Forms\Components\Toggle;
  12. use Filament\Resources\Resource;
  13. use Filament\Schemas\Components\Section;
  14. use Filament\Tables;
  15. use Filament\Tables\Columns\TextColumn;
  16. use Filament\Tables\Filters\TernaryFilter;
  17. use Illuminate\Database\Eloquent\Model;
  18. use UnitEnum;
  19. use Filament\Tables\Enums\FiltersLayout;
  20. class PreQuestionCandidateResource extends Resource
  21. {
  22. protected static ?string $model = PreQuestionCandidate::class;
  23. protected static bool $shouldRegisterNavigation = false;
  24. protected static BackedEnum|string|null $navigationIcon = 'heroicon-o-sparkles';
  25. protected static ?string $navigationLabel = '题目校对';
  26. protected static ?string $modelLabel = '题目候选';
  27. protected static ?string $pluralModelLabel = '题目候选';
  28. protected static UnitEnum|string|null $navigationGroup = '卷子导入流程';
  29. protected static ?int $navigationSort = 2;
  30. protected static ?string $title = '候选题目校对';
  31. protected static ?string $description = '从 Markdown 导入解析出的候选题目,支持 AI 辅助校对和批量操作';
  32. public static function canViewAny(): bool
  33. {
  34. // 允许访问的条件:
  35. // 1. URL 中有 import_id 参数(从 MarkdownImport 跳转进入)
  36. $hasImportId = request()->has('import_id')
  37. && !empty(request()->input('import_id'));
  38. // 2. 或者是管理员角色(直接检查 role 字段)
  39. $user = auth()->user();
  40. $isAdmin = $user && in_array($user->role, ['super_admin', 'admin']);
  41. return $hasImportId || $isAdmin;
  42. }
  43. public static function canCreate(): bool
  44. {
  45. // 不允许手动创建候选题目,只能从 Markdown 解析生成
  46. return false;
  47. }
  48. public static function canEdit(Model $record): bool
  49. {
  50. // 允许在“人工校对”阶段对候选题进行编辑(题干/选项/标记)
  51. return true;
  52. }
  53. public static function table(Tables\Table $table): Tables\Table
  54. {
  55. return $table
  56. ->columns([
  57. TextColumn::make('sequence')
  58. ->label('序')
  59. ->sortable()
  60. ->width('60px'),
  61. TextColumn::make('index')
  62. ->label('题号')
  63. ->sortable()
  64. ->width('70px'),
  65. TextColumn::make('question_number')
  66. ->label('原题号')
  67. ->sortable()
  68. ->toggleable()
  69. ->width('80px'),
  70. TextColumn::make('part.title')
  71. ->label('区块')
  72. ->toggleable()
  73. ->limit(16),
  74. TextColumn::make('sourcePaper.title')
  75. ->label('卷子')
  76. ->toggleable()
  77. ->limit(16),
  78. TextColumn::make('raw_markdown')
  79. ->label('题目预览')
  80. ->html()
  81. ->formatStateUsing(function (?string $state, Model $record): string {
  82. $stem = $record->stem ? e(\Illuminate\Support\Str::limit($record->stem, 120)) : e(\Illuminate\Support\Str::limit((string) $state, 120));
  83. $hasIssue = $record->is_valid_question === false || $record->status === 'pending';
  84. $issueTag = $hasIssue ? '<span class="ui-tag text-rose-600 border-rose-200 bg-rose-50">需修正</span>' : '';
  85. return <<<HTML
  86. <div class="space-y-2">
  87. <div class="text-sm text-slate-800">{$stem}</div>
  88. <div class="flex flex-wrap gap-2 text-xs text-slate-500">
  89. <span class="ui-tag">区块:{$record->part?->title}</span>
  90. <span class="ui-tag">卷子:{$record->sourcePaper?->title}</span>
  91. {$issueTag}
  92. </div>
  93. </div>
  94. HTML;
  95. })
  96. ->wrap()
  97. ->toggleable(),
  98. Tables\Columns\ImageColumn::make('first_image')
  99. ->label('图片')
  100. ->height(60)
  101. ->width(60)
  102. ->circular(),
  103. TextColumn::make('ai_confidence')
  104. ->label('AI 置信度')
  105. ->badge()
  106. ->color(fn (Model $record): string => $record->confidence_badge)
  107. ->formatStateUsing(function (?float $state, Model $record): string {
  108. $val = $state ?? $record->confidence;
  109. return $val !== null ? number_format((float)$val * 100, 1) . '%' : 'N/A';
  110. }),
  111. TextColumn::make('structured_json')
  112. ->label('结构化')
  113. ->getStateUsing(fn (?Model $record) => $record?->structured_json ? '已生成' : '未生成')
  114. ->badge()
  115. ->color(fn (?Model $record) => $record?->structured_json ? 'success' : 'gray')
  116. ->toggleable(isToggledHiddenByDefault: true),
  117. Tables\Columns\ToggleColumn::make('is_question_candidate')
  118. ->label('是题目'),
  119. TextColumn::make('status')
  120. ->label('状态')
  121. ->badge()
  122. ->color(fn (Model $record): string => $record->status_badge),
  123. ])
  124. ->filters([
  125. Tables\Filters\SelectFilter::make('import_id')
  126. ->label('导入记录')
  127. ->options(function () {
  128. return \App\Models\MarkdownImport::query()
  129. ->orderByDesc('id')
  130. ->get(['id', 'file_name'])
  131. ->mapWithKeys(function ($import) {
  132. $label = $import->file_name ?: '未命名导入';
  133. return [$import->id => $label];
  134. })
  135. ->toArray();
  136. })
  137. ->query(function ($query, $data) {
  138. if (!empty($data['value'])) {
  139. $query->where('import_id', $data['value']);
  140. }
  141. }),
  142. TernaryFilter::make('is_question_candidate')
  143. ->label('是否为题目'),
  144. Tables\Filters\SelectFilter::make('status')
  145. ->label('审核状态')
  146. ->options([
  147. 'ai_pending' => 'AI 解析中',
  148. 'pending' => '待审核',
  149. 'reviewed' => '已审核',
  150. 'accepted' => '已接受',
  151. 'rejected' => '已拒绝',
  152. 'superseded' => '已被新解析覆盖',
  153. ]),
  154. ], layout: FiltersLayout::AboveContentCollapsible)
  155. ->actions([
  156. Action::make('review_edit')
  157. ->label('校对/编辑')
  158. ->icon('heroicon-o-pencil-square')
  159. ->color('primary')
  160. ->modalHeading(fn (Model $record): string => "校对候选题 #{$record->index}")
  161. ->form([
  162. Section::make('审核标记')
  163. ->schema([
  164. Toggle::make('is_question_candidate')
  165. ->label('是题目')
  166. ->default(fn (Model $record) => (bool) $record->is_question_candidate),
  167. TextInput::make('ai_confidence')
  168. ->label('AI 置信度')
  169. ->disabled(),
  170. ])->columns(2),
  171. Section::make('原始 Markdown(可编辑)')
  172. ->schema([
  173. Textarea::make('raw_markdown')
  174. ->label('raw_markdown')
  175. ->rows(10)
  176. ->required(),
  177. ])->columnSpanFull(),
  178. Section::make('结构化字段(可编辑)')
  179. ->schema([
  180. Textarea::make('stem')
  181. ->label('题干(stem)')
  182. ->rows(6),
  183. Textarea::make('options')
  184. ->label('选项(JSON)')
  185. ->rows(6)
  186. ->helperText('示例:{"A":"...","B":"..."};没有选项填空留空'),
  187. TagsInput::make('images')
  188. ->label('图片 URLs')
  189. ->placeholder('https://...'),
  190. Textarea::make('tables')
  191. ->label('表格(JSON 数组或 HTML)')
  192. ->rows(6)
  193. ->helperText('支持填写 JSON 数组(推荐)或直接粘贴 <table>...</table>'),
  194. ])->columns(2),
  195. ])
  196. ->fillForm(function (Model $record): array {
  197. return [
  198. 'is_question_candidate' => (bool) $record->is_question_candidate,
  199. 'ai_confidence' => $record->ai_confidence ? number_format($record->ai_confidence * 100, 1) : null,
  200. 'raw_markdown' => (string) $record->raw_markdown,
  201. 'stem' => $record->stem,
  202. 'options' => $record->options ? json_encode($record->options, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) : null,
  203. 'images' => $record->images ?? [],
  204. 'tables' => $record->tables ? json_encode($record->tables, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) : null,
  205. ];
  206. })
  207. ->action(function (array $data, Model $record): void {
  208. $options = null;
  209. if (!empty($data['options'])) {
  210. $decoded = json_decode((string) $data['options'], true);
  211. if (json_last_error() === JSON_ERROR_NONE) {
  212. $options = $decoded;
  213. }
  214. }
  215. $tables = [];
  216. if (!empty($data['tables'])) {
  217. $decoded = json_decode((string) $data['tables'], true);
  218. if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
  219. $tables = $decoded;
  220. } else {
  221. $tables = [(string) $data['tables']];
  222. }
  223. }
  224. $record->update([
  225. 'raw_markdown' => (string) $data['raw_markdown'],
  226. 'stem' => $data['stem'] ?? null,
  227. 'options' => $options,
  228. 'images' => $data['images'] ?? [],
  229. 'tables' => $tables,
  230. 'is_question_candidate' => (bool) ($data['is_question_candidate'] ?? false),
  231. 'status' => 'reviewed',
  232. ]);
  233. }),
  234. ])
  235. ->bulkActions([
  236. BulkActionGroup::make([
  237. \App\Filament\Resources\PreQuestionCandidateResource\Actions\MarkAsQuestionsBulkAction::make()
  238. ->label('标记为题目'),
  239. \App\Filament\Resources\PreQuestionCandidateResource\Actions\MarkAsNonQuestionsBulkAction::make()
  240. ->label('标记为非题目'),
  241. \App\Filament\Resources\PreQuestionCandidateResource\Actions\ConvertToPreQuestionsBulkAction::make()
  242. ->label('入库到筛选库'),
  243. ]),
  244. ])
  245. ->recordClasses(fn (Model $record) => $record->is_valid_question === false ? 'bg-rose-50/60' : null)
  246. ->defaultSort('sequence', 'asc')
  247. ->paginated([20, 50, 100]);
  248. }
  249. public static function getPages(): array
  250. {
  251. return [
  252. 'index' => Pages\ListPreQuestionCandidates::route('/'),
  253. ];
  254. }
  255. }