PreQuestionCandidateResource.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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('50px')
  61. ->alignCenter()
  62. ->toggleable(),
  63. TextColumn::make('index')
  64. ->label('题号')
  65. ->sortable()
  66. ->width('60px')
  67. ->alignCenter(),
  68. TextColumn::make('part.title')
  69. ->label('区块')
  70. ->limit(10)
  71. ->toggleable(isToggledHiddenByDefault: true),
  72. TextColumn::make('sourcePaper.title')
  73. ->label('卷子')
  74. ->limit(10)
  75. ->toggleable(isToggledHiddenByDefault: true),
  76. TextColumn::make('raw_markdown')
  77. ->label('题目内容')
  78. ->html()
  79. ->formatStateUsing(function (?string $state, Model $record): string {
  80. $stem = $record->stem ? e(\Illuminate\Support\Str::limit($record->stem, 150)) : e(\Illuminate\Support\Str::limit((string) $state, 150));
  81. $hasIssue = $record->is_valid_question === false || $record->status === 'pending';
  82. $issueTag = $hasIssue ? '<span class="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-semibold bg-rose-100 text-rose-700 border border-rose-200">⚠️ 需修正</span>' : '';
  83. $statusBadge = match ($record->status) {
  84. 'pending' => '<span class="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-semibold bg-gray-100 text-gray-700">待审核</span>',
  85. 'reviewed' => '<span class="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-semibold bg-blue-100 text-blue-700">已审核</span>',
  86. 'accepted' => '<span class="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-semibold bg-green-100 text-green-700">已接受</span>',
  87. 'rejected' => '<span class="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-semibold bg-red-100 text-red-700">已拒绝</span>',
  88. default => '<span class="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-semibold bg-slate-100 text-slate-700">' . ($record->status ?? '未知') . '</span>',
  89. };
  90. return <<<HTML
  91. <div class="py-4 pr-4">
  92. <div class="text-base font-medium text-slate-900 leading-relaxed mb-3 border-l-4 border-blue-500 pl-4">
  93. {$stem}
  94. </div>
  95. <div class="flex items-center gap-2 text-xs text-slate-500 flex-wrap">
  96. <span class="inline-flex items-center px-3 py-1 rounded-full bg-slate-100 text-slate-600 font-medium">📁 {$record->part?->title}</span>
  97. <span class="inline-flex items-center px-3 py-1 rounded-full bg-slate-100 text-slate-600 font-medium">📄 {$record->sourcePaper?->title}</span>
  98. {$statusBadge}
  99. {$issueTag}
  100. </div>
  101. </div>
  102. HTML;
  103. })
  104. ->wrap()
  105. ->width('65%')
  106. ->toggleable(isToggledHiddenByDefault: false),
  107. TextColumn::make('ai_confidence')
  108. ->label('AI 置信度')
  109. ->badge()
  110. ->color(fn (Model $record): string => $record->confidence_badge)
  111. ->formatStateUsing(function (?float $state, Model $record): string {
  112. $val = $state ?? $record->confidence;
  113. return $val !== null ? number_format((float)$val * 100, 0) . '%' : 'N/A';
  114. })
  115. ->alignCenter()
  116. ->width('80px')
  117. ->toggleable(isToggledHiddenByDefault: true),
  118. Tables\Columns\ToggleColumn::make('is_question_candidate')
  119. ->label('题目')
  120. ->alignCenter()
  121. ->width('60px')
  122. ->toggleable(isToggledHiddenByDefault: true),
  123. TextColumn::make('status')
  124. ->label('状态')
  125. ->badge()
  126. ->color(fn (Model $record): string => $record->status_badge)
  127. ->alignCenter()
  128. ->width('80px')
  129. ->toggleable(isToggledHiddenByDefault: true),
  130. ])
  131. ->filters([
  132. Tables\Filters\SelectFilter::make('import_id')
  133. ->label('导入记录')
  134. ->options(function () {
  135. return \App\Models\MarkdownImport::query()
  136. ->orderByDesc('id')
  137. ->get(['id', 'file_name'])
  138. ->mapWithKeys(function ($import) {
  139. $label = $import->file_name ?: '未命名导入';
  140. return [$import->id => $label];
  141. })
  142. ->toArray();
  143. })
  144. ->query(function ($query, $data) {
  145. if (!empty($data['value'])) {
  146. $query->where('import_id', $data['value']);
  147. }
  148. }),
  149. TernaryFilter::make('is_question_candidate')
  150. ->label('是否为题目'),
  151. Tables\Filters\SelectFilter::make('status')
  152. ->label('审核状态')
  153. ->options([
  154. 'ai_pending' => 'AI 解析中',
  155. 'pending' => '待审核',
  156. 'reviewed' => '已审核',
  157. 'accepted' => '已接受',
  158. 'rejected' => '已拒绝',
  159. 'superseded' => '已被新解析覆盖',
  160. ]),
  161. ], layout: FiltersLayout::AboveContentCollapsible)
  162. ->actions([
  163. Action::make('review_edit')
  164. ->label('校对/编辑')
  165. ->icon('heroicon-o-pencil-square')
  166. ->color('primary')
  167. ->modalHeading(fn (Model $record): string => "校对候选题 #{$record->index}")
  168. ->form([
  169. Section::make('审核标记')
  170. ->schema([
  171. Toggle::make('is_question_candidate')
  172. ->label('是题目')
  173. ->default(fn (Model $record) => (bool) $record->is_question_candidate),
  174. TextInput::make('ai_confidence')
  175. ->label('AI 置信度')
  176. ->disabled(),
  177. ])->columns(2),
  178. Section::make('原始 Markdown(可编辑)')
  179. ->schema([
  180. Textarea::make('raw_markdown')
  181. ->label('raw_markdown')
  182. ->rows(10)
  183. ->required(),
  184. ])->columnSpanFull(),
  185. Section::make('结构化字段(可编辑)')
  186. ->schema([
  187. Textarea::make('stem')
  188. ->label('题干(stem)')
  189. ->rows(6),
  190. Textarea::make('options')
  191. ->label('选项(JSON)')
  192. ->rows(6)
  193. ->helperText('示例:{"A":"...","B":"..."};没有选项填空留空'),
  194. TagsInput::make('images')
  195. ->label('图片 URLs')
  196. ->placeholder('https://...'),
  197. Textarea::make('tables')
  198. ->label('表格(JSON 数组或 HTML)')
  199. ->rows(6)
  200. ->helperText('支持填写 JSON 数组(推荐)或直接粘贴 <table>...</table>'),
  201. ])->columns(2),
  202. ])
  203. ->fillForm(function (Model $record): array {
  204. return [
  205. 'is_question_candidate' => (bool) $record->is_question_candidate,
  206. 'ai_confidence' => $record->ai_confidence ? number_format($record->ai_confidence * 100, 1) : null,
  207. 'raw_markdown' => (string) $record->raw_markdown,
  208. 'stem' => $record->stem,
  209. 'options' => $record->options ? json_encode($record->options, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) : null,
  210. 'images' => $record->images ?? [],
  211. 'tables' => $record->tables ? json_encode($record->tables, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) : null,
  212. ];
  213. })
  214. ->action(function (array $data, Model $record): void {
  215. $options = null;
  216. if (!empty($data['options'])) {
  217. $decoded = json_decode((string) $data['options'], true);
  218. if (json_last_error() === JSON_ERROR_NONE) {
  219. $options = $decoded;
  220. }
  221. }
  222. $tables = [];
  223. if (!empty($data['tables'])) {
  224. $decoded = json_decode((string) $data['tables'], true);
  225. if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
  226. $tables = $decoded;
  227. } else {
  228. $tables = [(string) $data['tables']];
  229. }
  230. }
  231. $record->update([
  232. 'raw_markdown' => (string) $data['raw_markdown'],
  233. 'stem' => $data['stem'] ?? null,
  234. 'options' => $options,
  235. 'images' => $data['images'] ?? [],
  236. 'tables' => $tables,
  237. 'is_question_candidate' => (bool) ($data['is_question_candidate'] ?? false),
  238. 'status' => 'reviewed',
  239. ]);
  240. }),
  241. ])
  242. ->bulkActions([
  243. BulkActionGroup::make([
  244. \App\Filament\Resources\PreQuestionCandidateResource\Actions\MarkAsQuestionsBulkAction::make()
  245. ->label('标记为题目'),
  246. \App\Filament\Resources\PreQuestionCandidateResource\Actions\MarkAsNonQuestionsBulkAction::make()
  247. ->label('标记为非题目'),
  248. \App\Filament\Resources\PreQuestionCandidateResource\Actions\ConvertToPreQuestionsBulkAction::make()
  249. ->label('入库到筛选库'),
  250. ]),
  251. ])
  252. ->recordClasses(fn (Model $record) => $record->is_valid_question === false ? 'bg-rose-50/60' : null)
  253. ->defaultSort('sequence', 'asc')
  254. ->paginated([20, 50, 100]);
  255. }
  256. public static function getPages(): array
  257. {
  258. return [
  259. 'index' => Pages\ListPreQuestionCandidates::route('/'),
  260. ];
  261. }
  262. }