PreQuestionCandidateResource.php 12 KB

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