M3: console.log -> Logger + UI redesign (QuestionBank) + S7/A9/A10/A11/U11 bug fixes + #1/#2/#3/#4 enhancements + i18n for QuestionBank pages

This commit is contained in:
Developer
2026-05-19 16:57:45 +08:00
parent 5b5f14674d
commit 29bac74b58
20 changed files with 1081 additions and 501 deletions
+4 -2
View File
@@ -1,10 +1,12 @@
import { Injectable } from '@nestjs/common';
import { Injectable, Logger } from '@nestjs/common';
import { ChatOpenAI } from '@langchain/openai';
import { ModelConfig } from '../types';
import { I18nService } from '../i18n/i18n.service';
@Injectable()
export class ApiService {
private readonly logger = new Logger(ApiService.name);
constructor(private i18nService: I18nService) {}
// Simple health check method
@@ -23,7 +25,7 @@ export class ApiService {
const response = await llm.invoke(prompt);
return response.content.toString();
} catch (error) {
console.error('LangChain call failed:', error);
this.logger.error('LangChain call failed:', error);
if (error.message?.includes('401')) {
throw new Error(this.i18nService.getMessage('invalidApiKey'));
}
+115 -69
View File
@@ -561,7 +561,9 @@ private async getModel(tenantId: string): Promise<ChatOpenAI> {
`[startSession] Session ${savedSession.id} created and saved`,
);
this.cleanupOldSessions(userId);
// cleanupOldSessions permanently destroys data - disabled to preserve history.
// Admins can use batch-delete endpoint for manual cleanup.
// this.cleanupOldSessions(userId);
return savedSession;
}
@@ -777,6 +779,33 @@ const initialState: Partial<EvaluationState> = {
});
if (!session) throw new NotFoundException('Session not found');
if (session.status === AssessmentStatus.IN_PROGRESS) {
const now = new Date();
const startTime = session.startedAt ? new Date(session.startedAt) : now;
const questionStartTime = session.currentQuestionStartedAt ? new Date(session.currentQuestionStartedAt) : now;
const totalElapsed = Math.floor((now.getTime() - startTime.getTime()) / 1000);
const questionElapsed = Math.floor((now.getTime() - questionStartTime.getTime()) / 1000);
if (totalElapsed >= session.totalTimeLimit || questionElapsed >= session.perQuestionTimeLimit) {
session.status = AssessmentStatus.COMPLETED;
session.finalReport = totalElapsed >= session.totalTimeLimit
? '评测总时间已用尽,评估已自动结束'
: '单题答题时间已用尽,评估已自动结束';
if (session.finalScore === null || session.finalScore === undefined) {
session.finalScore = 0;
}
await this.sessionRepository.save(session);
this.logger.log(`[submitAnswer] Session ${sessionId} auto-ended due to timeout`);
return {
assessmentSessionId: sessionId,
status: 'COMPLETED',
timeout: true,
finalScore: session.finalScore,
finalReport: session.finalReport,
};
}
}
const model = await this.getModel(session.tenantId);
await this.ensureGraphState(sessionId, session);
const content = await this.getSessionContent(session);
@@ -844,18 +873,18 @@ const initialState: Partial<EvaluationState> = {
const scores = finalResult.scores as Record<string, number>;
const questions = finalResult.questions || [];
const weightConfig = session.templateJson?.weightConfig || { prompt: 50, other: 50 };
const passingScore = session.templateJson?.passingScore || 90;
const passingScore = (session.templateJson?.passingScore ?? 90) / 10;
if (questions.length > 0 && Object.keys(scores).length > 0) {
const { finalScore, dimensionScores, radarData } = this.calculateScores(
questions,
scores,
weightConfig,
);
session.finalScore = finalScore;
(session as any).dimensionScores = dimensionScores;
(session as any).radarData = radarData;
(session as any).passed = finalScore >= passingScore;
if (questions.length > 0 && Object.keys(scores).length > 0) {
const { finalScore, dimensionScores, radarData } = this.calculateScores(
questions,
scores,
weightConfig,
);
session.finalScore = finalScore;
(session as any).dimensionScores = dimensionScores;
(session as any).radarData = radarData;
(session as any).passed = finalScore >= passingScore;
}
}
@@ -918,6 +947,35 @@ const initialState: Partial<EvaluationState> = {
return;
}
if (session.status === AssessmentStatus.IN_PROGRESS) {
const now = new Date();
const startTime = session.startedAt ? new Date(session.startedAt) : now;
const questionStartTime = session.currentQuestionStartedAt ? new Date(session.currentQuestionStartedAt) : now;
const totalElapsed = Math.floor((now.getTime() - startTime.getTime()) / 1000);
const questionElapsed = Math.floor((now.getTime() - questionStartTime.getTime()) / 1000);
if (totalElapsed >= session.totalTimeLimit || questionElapsed >= session.perQuestionTimeLimit) {
session.status = AssessmentStatus.COMPLETED;
session.finalReport = totalElapsed >= session.totalTimeLimit
? '评测总时间已用尽,评估已自动结束'
: '单题答题时间已用尽,评估已自动结束';
if (session.finalScore === null || session.finalScore === undefined) {
session.finalScore = 0;
}
await this.sessionRepository.save(session);
this.logger.log(`[submitAnswerStream] Session ${sessionId} auto-ended due to timeout`);
observer.next({
assessmentSessionId: sessionId,
status: 'COMPLETED',
timeout: true,
finalScore: session.finalScore,
finalReport: session.finalReport,
});
observer.complete();
return;
}
}
const model = await this.getModel(session.tenantId);
const content = await this.getSessionContent(session);
await this.ensureGraphState(sessionId, session);
@@ -1037,7 +1095,7 @@ const initialState: Partial<EvaluationState> = {
const scores = finalData.scores;
const questions = finalData.questions || [];
const weightConfig = session.templateJson?.weightConfig || { prompt: 50, other: 50 };
const passingScore = session.templateJson?.passingScore || 90;
const passingScore = (session.templateJson?.passingScore ?? 90) / 10;
if (questions.length > 0 && Object.keys(scores).length > 0) {
const { finalScore, dimensionScores, radarData } = this.calculateScores(
@@ -1049,6 +1107,7 @@ const initialState: Partial<EvaluationState> = {
(session as any).dimensionScores = dimensionScores;
(session as any).radarData = radarData;
(session as any).passed = finalScore >= passingScore;
this.logger.log(
`[DimensionScoring] Session ${sessionId} Final Score: ${finalScore}, Passed: ${finalScore >= passingScore}`,
);
@@ -1188,55 +1247,46 @@ const initialState: Partial<EvaluationState> = {
const historicalMessages = this.hydrateMessages(session.messages);
const existingQuestions = session.questions_json || [];
const hasQuestionsFromBank = existingQuestions.length > 0;
const scoresRecord: Record<string, number> = {};
if (session.feedbackHistory) {
for (const fh of session.feedbackHistory) {
if (fh.score && fh.questionId) scoresRecord[fh.questionId] = fh.score;
}
}
const recoveredState: any = {
assessmentSessionId: sessionId,
knowledgeBaseId:
session.knowledgeBaseId || session.knowledgeGroupId || '',
messages: historicalMessages,
feedbackHistory: this.hydrateMessages(
session.feedbackHistory || [],
),
questions: existingQuestions,
currentQuestionIndex: session.currentQuestionIndex || 0,
followUpCount: session.followUpCount || 0,
shouldFollowUp: false,
scores: scoresRecord,
questionCount: session.templateJson?.questionCount || 5,
difficultyDistribution:
session.templateJson?.difficultyDistribution,
style: session.templateJson?.style,
keywords: session.templateJson?.keywords,
language: session.language || 'zh',
report: session.finalReport || undefined,
};
if (hasQuestionsFromBank) {
this.logger.log(
`[ensureGraphState] Using ${existingQuestions.length} questions from question bank`,
);
await this.graph.updateState(
{ configurable: { thread_id: sessionId } },
{
assessmentSessionId: sessionId,
knowledgeBaseId:
session.knowledgeBaseId || session.knowledgeGroupId || '',
messages: historicalMessages,
feedbackHistory: this.hydrateMessages(
session.feedbackHistory || [],
),
questions: existingQuestions,
currentQuestionIndex: session.currentQuestionIndex || 0,
followUpCount: session.followUpCount || 0,
questionCount: session.templateJson?.questionCount || 5,
difficultyDistribution:
session.templateJson?.difficultyDistribution,
style: session.templateJson?.style,
keywords: session.templateJson?.keywords,
},
'grader',
);
} else {
await this.graph.updateState(
{ configurable: { thread_id: sessionId } },
{
assessmentSessionId: sessionId,
knowledgeBaseId:
session.knowledgeBaseId || session.knowledgeGroupId || '',
messages: historicalMessages,
feedbackHistory: this.hydrateMessages(
session.feedbackHistory || [],
),
questions: session.questions_json || [],
currentQuestionIndex: session.currentQuestionIndex || 0,
followUpCount: session.followUpCount || 0,
questionCount: session.templateJson?.questionCount || 5,
difficultyDistribution:
session.templateJson?.difficultyDistribution,
style: session.templateJson?.style,
keywords: session.templateJson?.keywords,
},
'grader',
);
}
await this.graph.updateState(
{ configurable: { thread_id: sessionId } },
recoveredState,
'interviewer',
);
} else {
this.logger.log(`Initializing new state for session ${sessionId}`);
const content = await this.getSessionContent(session);
@@ -1350,7 +1400,7 @@ const initialState: Partial<EvaluationState> = {
}
if (session.status !== AssessmentStatus.COMPLETED) {
throw new Error('Session not completed');
throw new BadRequestException('Session not completed yet');
}
const existing = await this.certificateRepository.findOne({
@@ -1474,19 +1524,15 @@ const initialState: Partial<EvaluationState> = {
const sessions = await qb.take(100).getMany();
const dimensionScores: Record<string, number[]> = {
PROMPT: [],
LLM: [],
IDE: [],
DEV_PATTERN: [],
WORK_CAPABILITY: [],
};
const dimensionScores: Record<string, number[]> = {};
for (const session of sessions) {
const messages = session.messages || [];
for (const msg of messages) {
if (msg.dimension && msg.score !== undefined) {
dimensionScores[msg.dimension]?.push(msg.score);
const scores = (session as any).dimensionScores || {};
for (const [dim, score] of Object.entries(scores)) {
if (dimensionScores[dim]) {
dimensionScores[dim].push(score as number);
} else {
dimensionScores[dim] = [score as number];
}
}
}
@@ -1570,7 +1616,7 @@ const initialState: Partial<EvaluationState> = {
}
session.finalScore = newScore;
const passingScore = session.templateJson?.passingScore || 90;
const passingScore = (session.templateJson?.passingScore ?? 90) / 10;
(session as any).passed = newScore >= passingScore;
session.reviewedBy = reviewerId;
session.reviewedAt = new Date();
@@ -97,4 +97,16 @@ export class CreateTemplateDto {
@Max(100)
@IsOptional()
passingScore?: number;
@IsInt()
@Min(60)
@Max(7200)
@IsOptional()
totalTimeLimit?: number;
@IsInt()
@Min(30)
@Max(1800)
@IsOptional()
perQuestionTimeLimit?: number;
}
@@ -122,7 +122,7 @@ export class QuestionBankService {
page?: number,
limit?: number,
): Promise<{ data: QuestionBank[]; total: number } | QuestionBank[]> {
console.log('[QuestionBank findAll] userId:', userId, 'tenantId:', tenantId);
this.logger.log('[QuestionBank findAll] userId: ' + userId + ', tenantId: ' + tenantId);
const queryBuilder = this.bankRepository
.createQueryBuilder('bank')
.leftJoinAndSelect('bank.template', 'template');
+5 -2
View File
@@ -3,6 +3,7 @@ import {
CanActivate,
ExecutionContext,
UnauthorizedException,
Logger,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { AuthGuard } from '@nestjs/passport';
@@ -25,6 +26,8 @@ import * as path from 'path';
*/
@Injectable()
export class CombinedAuthGuard implements CanActivate {
private readonly logger = new Logger(CombinedAuthGuard.name);
// We extend AuthGuard('jwt') functionality by composition
private jwtGuard: ReturnType<typeof AuthGuard>;
@@ -55,7 +58,7 @@ export class CombinedAuthGuard implements CanActivate {
return true;
}
console.log(
this.logger.log(
`[CombinedAuthGuard] Checking auth for route: ${request.method} ${request.url}`,
);
@@ -160,7 +163,7 @@ export class CombinedAuthGuard implements CanActivate {
}
return false;
} catch (e) {
console.error(`[CombinedAuthGuard] JWT Auth Error:`, e);
this.logger.error('[CombinedAuthGuard] JWT Auth Error: ' + e);
throw e instanceof UnauthorizedException
? e
: new UnauthorizedException('Authentication required');
+25 -22
View File
@@ -1,6 +1,7 @@
import {
Body,
Controller,
Logger,
Post,
Request,
Res,
@@ -36,6 +37,8 @@ class StreamChatDto {
@Controller('chat')
@UseGuards(CombinedAuthGuard)
export class ChatController {
private readonly logger = new Logger(ChatController.name);
constructor(
private chatService: ChatService,
private modelConfigService: ModelConfigService,
@@ -49,7 +52,7 @@ export class ChatController {
@Res() res: Response,
) {
try {
console.log('Full Request Body:', JSON.stringify(body, null, 2));
this.logger.log('Full Request Body:', JSON.stringify(body, null, 2));
const {
message,
history = [],
@@ -71,22 +74,22 @@ export class ChatController {
} = body;
const userId = req.user.id;
console.log('=== Chat Debug Info ===');
console.log('User ID:', userId);
console.log('Message:', message);
console.log('User Language:', userLanguage);
console.log('Selected Embedding ID:', selectedEmbeddingId);
console.log('Selected LLM ID:', selectedLLMId);
console.log('Selected Groups:', selectedGroups);
console.log('Selected Files:', selectedFiles);
console.log('History ID:', historyId);
console.log('Temperature:', temperature);
console.log('Max Tokens:', maxTokens);
console.log('Top K:', topK);
console.log('Similarity Threshold:', similarityThreshold);
console.log('Rerank Similarity Threshold:', rerankSimilarityThreshold);
console.log('Query Expansion:', enableQueryExpansion);
console.log('HyDE:', enableHyDE);
this.logger.log('=== Chat Debug Info ===');
this.logger.log('User ID:', userId);
this.logger.log('Message:', message);
this.logger.log('User Language:', userLanguage);
this.logger.log('Selected Embedding ID:', selectedEmbeddingId);
this.logger.log('Selected LLM ID:', selectedLLMId);
this.logger.log('Selected Groups:', selectedGroups);
this.logger.log('Selected Files:', selectedFiles);
this.logger.log('History ID:', historyId);
this.logger.log('Temperature:', temperature);
this.logger.log('Max Tokens:', maxTokens);
this.logger.log('Top K:', topK);
this.logger.log('Similarity Threshold:', similarityThreshold);
this.logger.log('Rerank Similarity Threshold:', rerankSimilarityThreshold);
this.logger.log('Query Expansion:', enableQueryExpansion);
this.logger.log('HyDE:', enableHyDE);
const role = req.user.role;
const tenantId = req.user.tenantId;
@@ -105,14 +108,14 @@ export class ChatController {
if (selectedLLMId) {
// Find specifically selected model
llmModel = await this.modelConfigService.findOne(selectedLLMId);
console.log('使用选中的LLM模型:', llmModel.name);
this.logger.log('使用选中的LLM模型:', llmModel.name);
} else {
// Use organization's default LLM from Index Chat Config (strict)
llmModel = await this.modelConfigService.findDefaultByType(
tenantId,
ModelType.LLM,
);
console.log(
this.logger.log(
'最终使用的LLM模型 (默认):',
llmModel ? llmModel.name : '无',
);
@@ -162,7 +165,7 @@ export class ChatController {
res.write('data: [DONE]\n\n');
res.end();
} catch (error) {
console.error('Stream chat error:', error);
this.logger.error('Stream chat error:', error);
try {
res.write(
`data: ${JSON.stringify({ type: 'error', data: error.message || 'Server Error' })}\n\n`,
@@ -170,7 +173,7 @@ export class ChatController {
res.write('data: [DONE]\n\n');
res.end();
} catch (writeError) {
console.error('Failed to write error response:', writeError);
this.logger.error('Failed to write error response:', writeError);
}
}
}
@@ -220,7 +223,7 @@ export class ChatController {
res.write('data: [DONE]\n\n');
res.end();
} catch (error) {
console.error('Stream assist error:', error);
this.logger.error('Stream assist error:', error);
res.write(
`data: ${JSON.stringify({ type: 'error', data: error.message || 'Server Error' })}\n\n`,
);
+29 -29
View File
@@ -71,30 +71,30 @@ export class ChatService {
enableHyDE?: boolean, // New
tenantId?: string, // New: tenant isolation
): AsyncGenerator<{ type: 'content' | 'sources' | 'historyId'; data: any }> {
console.log('=== ChatService.streamChat ===');
console.log('User ID:', userId);
console.log('User language:', userLanguage);
console.log('Selected embedding model ID:', selectedEmbeddingId);
console.log('Selected groups:', selectedGroups);
console.log('Selected files:', selectedFiles);
console.log('History ID:', historyId);
console.log('Temperature:', temperature);
console.log('Max Tokens:', maxTokens);
console.log('Top K:', topK);
console.log('Similarity threshold:', similarityThreshold);
console.log('Rerank threshold:', rerankSimilarityThreshold);
console.log('Query expansion:', enableQueryExpansion);
console.log('HyDE:', enableHyDE);
console.log('Model configuration:', {
this.logger.log('=== ChatService.streamChat ===');
this.logger.log('User ID:', userId);
this.logger.log('User language:', userLanguage);
this.logger.log('Selected embedding model ID:', selectedEmbeddingId);
this.logger.log('Selected groups:', selectedGroups);
this.logger.log('Selected files:', selectedFiles);
this.logger.log('History ID:', historyId);
this.logger.log('Temperature:', temperature);
this.logger.log('Max Tokens:', maxTokens);
this.logger.log('Top K:', topK);
this.logger.log('Similarity threshold:', similarityThreshold);
this.logger.log('Rerank threshold:', rerankSimilarityThreshold);
this.logger.log('Query expansion:', enableQueryExpansion);
this.logger.log('HyDE:', enableHyDE);
this.logger.log('Model configuration:', {
name: modelConfig.name,
modelId: modelConfig.modelId,
baseUrl: modelConfig.baseUrl,
});
console.log(
this.logger.log(
'API Key prefix:',
modelConfig.apiKey?.substring(0, 10) + '...',
);
console.log('API Key length:', modelConfig.apiKey?.length);
this.logger.log('API Key length:', modelConfig.apiKey?.length);
// Get current language setting (keeping LANGUAGE_CONFIG for backward compatibility, now uses i18n service)
// Use actual language based on user settings
@@ -113,7 +113,7 @@ export class ChatService {
selectedGroups,
);
currentHistoryId = searchHistory.id;
console.log(
this.logger.log(
this.i18nService.getMessage(
'creatingHistory',
effectiveUserLanguage,
@@ -143,7 +143,7 @@ export class ChatService {
);
}
console.log(
this.logger.log(
this.i18nService.getMessage(
'usingEmbeddingModel',
effectiveUserLanguage,
@@ -156,7 +156,7 @@ export class ChatService {
);
// 2. Search using user's query directly
console.log(
this.logger.log(
this.i18nService.getMessage('startingSearch', effectiveUserLanguage),
);
yield {
@@ -204,7 +204,7 @@ export class ChatService {
// HybridSearch returns ES hit structure, but RagSearchResult is normalized
// BuildContext expects {fileName, content}. RagSearchResult has these
searchResults = ragResults;
console.log(
this.logger.log(
this.i18nService.getMessage(
'searchResultsCount',
effectiveUserLanguage,
@@ -274,7 +274,7 @@ export class ChatService {
};
}
} catch (searchError) {
console.error(
this.logger.error(
this.i18nService.getMessage(
'searchFailedLog',
effectiveUserLanguage,
@@ -461,14 +461,14 @@ ${instruction}`;
try {
// Join keywords into search string
const combinedQuery = keywords.join(' ');
console.log(
this.logger.log(
this.i18nService.getMessage('searchString', userLanguage) +
combinedQuery,
);
// Check if embedding model ID is provided
if (!embeddingModelId) {
console.log(
this.logger.log(
this.i18nService.getMessage(
'embeddingModelIdNotProvided',
userLanguage,
@@ -478,7 +478,7 @@ ${instruction}`;
}
// Use actual embedding vector
console.log(
this.logger.log(
this.i18nService.getMessage('generatingEmbeddings', userLanguage),
);
const queryEmbedding = await this.embeddingService.getEmbeddings(
@@ -486,7 +486,7 @@ ${instruction}`;
embeddingModelId,
);
const queryVector = queryEmbedding[0];
console.log(
this.logger.log(
this.i18nService.getMessage('embeddingsGenerated', userLanguage) +
this.i18nService.getMessage('dimensions', userLanguage) +
':',
@@ -494,7 +494,7 @@ ${instruction}`;
);
// Hybrid search
console.log(
this.logger.log(
this.i18nService.getMessage('performingHybridSearch', userLanguage),
);
const results = await this.elasticsearchService.hybridSearch(
@@ -507,7 +507,7 @@ ${instruction}`;
explicitFileIds, // Pass explicit file IDs
tenantId, // Pass tenant ID
);
console.log(
this.logger.log(
this.i18nService.getMessage('esSearchCompleted', userLanguage) +
this.i18nService.getMessage('resultsCount', userLanguage) +
':',
@@ -516,7 +516,7 @@ ${instruction}`;
return results.slice(0, 10);
} catch (error) {
console.error(
this.logger.error(
this.i18nService.getMessage('hybridSearchFailed', userLanguage) + ':',
error,
);
+7 -3
View File
@@ -1,3 +1,7 @@
import { Logger } from '@nestjs/common';
const logger = new Logger('JsonUtils');
/**
* Safely parses JSON from a string, handling markdown code blocks and leading/trailing text.
*/
@@ -40,9 +44,9 @@ export function safeParseJson<T = any>(text: string): T | null {
try {
return JSON.parse(jsonStr) as T;
} catch (error) {
console.error('[safeParseJson] Failed to parse JSON:', error);
console.error('[safeParseJson] Original text:', text);
console.error('[safeParseJson] Extracted string:', jsonStr);
logger.error('[safeParseJson] Failed to parse JSON:', error);
logger.error('[safeParseJson] Original text:', text);
logger.error('[safeParseJson] Extracted string:', jsonStr);
return null;
}
}
@@ -9,6 +9,7 @@ import {
UseGuards,
Request,
Query,
Logger,
} from '@nestjs/common';
import { CombinedAuthGuard } from '../auth/combined-auth.guard';
import { RolesGuard } from '../auth/roles.guard';
@@ -24,6 +25,8 @@ import { I18nService } from '../i18n/i18n.service';
@Controller('knowledge-groups')
@UseGuards(CombinedAuthGuard, RolesGuard)
export class KnowledgeGroupController {
private readonly logger = new Logger(KnowledgeGroupController.name);
constructor(
private readonly groupService: KnowledgeGroupService,
private readonly i18nService: I18nService,
@@ -43,7 +46,7 @@ export class KnowledgeGroupController {
@Post()
@Roles(UserRole.TENANT_ADMIN, UserRole.SUPER_ADMIN)
async create(@Body() createGroupDto: CreateGroupDto, @Request() req) {
console.log('[KnowledgeGroup] create called, user:', req.user);
this.logger.log('[KnowledgeGroup] create called, user: ' + JSON.stringify(req.user));
return await this.groupService.create(
req.user.id,
req.user.tenantId,
@@ -1,5 +1,6 @@
import {
Injectable,
Logger,
NotFoundException,
ForbiddenException,
Inject,
@@ -47,6 +48,8 @@ export interface PaginatedGroups {
@Injectable()
export class KnowledgeGroupService {
private readonly logger = new Logger(KnowledgeGroupService.name);
constructor(
@InjectRepository(KnowledgeGroup)
private groupRepository: Repository<KnowledgeGroup>,
@@ -62,7 +65,7 @@ export class KnowledgeGroupService {
userId: string,
tenantId: string,
): Promise<GroupWithFileCount[]> {
console.log('[KnowledgeGroup findAll] userId:', userId, 'tenantId:', tenantId);
this.logger.log('[KnowledgeGroup findAll] userId: ' + userId + ', tenantId: ' + tenantId);
// Return all groups for the tenant with file counts
const queryBuilder = this.groupRepository
.createQueryBuilder('group')
@@ -147,7 +150,7 @@ export class KnowledgeGroupService {
tenantId: string,
createGroupDto: CreateGroupDto,
): Promise<KnowledgeGroup> {
console.log('[KnowledgeGroup create] userId:', userId, 'tenantId:', tenantId);
this.logger.log('[KnowledgeGroup create] userId: ' + userId + ', tenantId: ' + tenantId);
const group = this.groupRepository.create({
...createGroupDto,
parentId: createGroupDto.parentId ?? null,
@@ -155,7 +158,7 @@ export class KnowledgeGroupService {
});
const saved = await this.groupRepository.save(group);
console.log('[KnowledgeGroup create] saved group tenantId:', saved.tenantId);
this.logger.log('[KnowledgeGroup create] saved group tenantId: ' + saved.tenantId);
return saved;
}
@@ -229,7 +232,7 @@ export class KnowledgeGroupService {
);
}
} catch (error) {
console.error(
this.logger.error(
`Failed to delete file ${file.id} when deleting group ${id}`,
error,
);
+5 -3
View File
@@ -1,4 +1,4 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { Injectable, Logger, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Note } from './note.entity';
@@ -11,6 +11,8 @@ import { I18nService } from '../i18n/i18n.service';
@Injectable()
export class NoteService {
private readonly logger = new Logger(NoteService.name);
// Directory will be created dynamically per user
private getScreenshotsDir(userId: string) {
return path.join(process.cwd(), 'uploads', 'notes-screenshots', userId);
@@ -153,7 +155,7 @@ export class NoteService {
}
// Optional: Add logging to help debug permission issues
console.log(`User ${userId} attempting to add note to group ${groupId}`);
this.logger.log('User ' + userId + ' attempting to add note to group ' + groupId);
}
if (categoryId === '') {
@@ -176,7 +178,7 @@ export class NoteService {
screenshot.buffer,
);
} catch (error) {
console.error('OCR extraction failed:', error);
this.logger.error('OCR extraction failed:', error);
// Continue without OCR text if extraction fails
}
+7 -4
View File
@@ -1,5 +1,6 @@
import {
Controller,
Logger,
Post,
UseGuards,
UseInterceptors,
@@ -14,6 +15,8 @@ import { I18nService } from '../i18n/i18n.service';
@UseGuards(CombinedAuthGuard)
@UseGuards(CombinedAuthGuard)
export class OcrController {
private readonly logger = new Logger(OcrController.name);
constructor(
private readonly ocrService: OcrService,
private readonly i18n: I18nService,
@@ -22,14 +25,14 @@ export class OcrController {
@Post('recognize')
@UseInterceptors(FileInterceptor('image'))
async recognizeText(@UploadedFile() image: Express.Multer.File) {
console.log('OCR recognition endpoint called');
this.logger.log('OCR recognition endpoint called');
if (!image) {
console.error('No image uploaded');
this.logger.error('No image uploaded');
throw new Error(this.i18n.getMessage('noImageUploaded'));
}
console.log(`Received image. Size: ${image.size} bytes`);
this.logger.log('Received image. Size: ' + image.size + ' bytes');
const text = await this.ocrService.extractTextFromImage(image.buffer);
console.log(`OCR extraction completed. Text length: ${text.length}`);
this.logger.log('OCR extraction completed. Text length: ' + text.length);
return { text };
}
}
+2 -5
View File
@@ -171,7 +171,7 @@ export class UserService implements OnModuleInit {
}
const hashedPassword = await bcrypt.hash(password, 10);
console.log(
this.logger.log(
`[UserService] Creating user: ${username}, isAdmin: ${isAdmin}`,
);
const user = await this.usersRepository.save({
@@ -403,10 +403,7 @@ export class UserService implements OnModuleInit {
role: UserRole.SUPER_ADMIN,
});
console.log('\n=== Admin account created ===');
console.log('Username: admin');
console.log('Password:', randomPassword);
console.log('========================================\n');
this.logger.log('Admin account created (username: admin, password: ' + randomPassword + ')');
}
}
}
@@ -29,6 +29,9 @@ export const AssessmentTemplateManager: React.FC = () => {
difficultyDistribution: 'Basic: 30%, Intermediate: 40%, Advanced: 30%',
style: 'Professional',
knowledgeGroupId: '',
passingScore: 6,
totalTimeLimit: 1800,
perQuestionTimeLimit: 300,
});
const [copiedId, setCopiedId] = useState<string | null>(null);
const [dimensions, setDimensions] = useState<AssessmentDimension[]>([]);
@@ -73,6 +76,9 @@ export const AssessmentTemplateManager: React.FC = () => {
: (template.difficultyDistribution || ''),
style: template.style || 'Professional',
knowledgeGroupId: template.knowledgeGroupId || '',
passingScore: template.passingScore ?? 6,
totalTimeLimit: template.totalTimeLimit ?? 1800,
perQuestionTimeLimit: template.perQuestionTimeLimit ?? 300,
});
setDimensions(template.dimensions || []);
} else {
@@ -85,6 +91,9 @@ export const AssessmentTemplateManager: React.FC = () => {
difficultyDistribution: '{"Basic": 3, "Intermediate": 4, "Advanced": 3}',
style: 'Professional',
knowledgeGroupId: '',
passingScore: 6,
totalTimeLimit: 1800,
perQuestionTimeLimit: 300,
});
setDimensions([]);
}
@@ -115,6 +124,9 @@ export const AssessmentTemplateManager: React.FC = () => {
style: formData.style,
knowledgeGroupId: formData.knowledgeGroupId || undefined,
dimensions: dimensions.length > 0 ? dimensions : undefined,
passingScore: formData.passingScore,
totalTimeLimit: formData.totalTimeLimit,
perQuestionTimeLimit: formData.perQuestionTimeLimit,
};
if (editingTemplate) {
@@ -400,17 +412,48 @@ export const AssessmentTemplateManager: React.FC = () => {
</select>
</div>
<div className="space-y-1.5 md:col-span-2">
<label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1 ml-1 flex items-center gap-2">
<Sliders size={12} className="text-indigo-500" />
{t('style')}
</label>
<input
className="w-full px-5 py-4 bg-slate-50 border border-slate-200 rounded-[1.25rem] text-sm font-bold focus:ring-4 focus:ring-indigo-500/10 focus:border-indigo-500/50 outline-none transition-all"
value={formData.style}
onChange={e => setFormData({ ...formData, style: e.target.value })}
/>
</div>
<div className="space-y-1.5 md:col-span-2">
<label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1 ml-1 flex items-center gap-2">
<Sliders size={12} className="text-indigo-500" />
{t('style')}
</label>
<input
className="w-full px-5 py-4 bg-slate-50 border border-slate-200 rounded-[1.25rem] text-sm font-bold focus:ring-4 focus:ring-indigo-500/10 focus:border-indigo-500/50 outline-none transition-all"
value={formData.style}
onChange={e => setFormData({ ...formData, style: e.target.value })}
/>
</div>
<div className="space-y-1.5">
<label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1 ml-1 flex items-center gap-2">
<Hash size={12} className="text-indigo-500" /> (0-10)
</label>
<input type="number" min="0" max="10" step="0.5"
className="w-full px-5 py-4 bg-slate-50 border border-slate-200 rounded-[1.25rem] text-sm font-bold focus:ring-4 focus:ring-indigo-500/10 focus:border-indigo-500/50 outline-none transition-all"
value={formData.passingScore}
onChange={e => setFormData({ ...formData, passingScore: parseFloat(e.target.value) || 0 })}
/>
</div>
<div className="space-y-1.5">
<label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1 ml-1 flex items-center gap-2">
<Hash size={12} className="text-indigo-500" /> ()
</label>
<input type="number" min="60" max="7200" step="60"
className="w-full px-5 py-4 bg-slate-50 border border-slate-200 rounded-[1.25rem] text-sm font-bold focus:ring-4 focus:ring-indigo-500/10 focus:border-indigo-500/50 outline-none transition-all"
value={formData.totalTimeLimit}
onChange={e => setFormData({ ...formData, totalTimeLimit: parseInt(e.target.value) || 1800 })}
/>
</div>
<div className="space-y-1.5">
<label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1 ml-1 flex items-center gap-2">
<Hash size={12} className="text-indigo-500" /> ()
</label>
<input type="number" min="30" max="1800" step="30"
className="w-full px-5 py-4 bg-slate-50 border border-slate-200 rounded-[1.25rem] text-sm font-bold focus:ring-4 focus:ring-indigo-500/10 focus:border-indigo-500/50 outline-none transition-all"
value={formData.perQuestionTimeLimit}
onChange={e => setFormData({ ...formData, perQuestionTimeLimit: parseInt(e.target.value) || 300 })}
/>
</div>
</div>
<div className="space-y-1.5 md:col-span-2">
+26 -15
View File
@@ -51,6 +51,7 @@ export const AssessmentView: React.FC<AssessmentViewProps> = ({
const [templates, setTemplates] = useState<AssessmentTemplate[]>([]);
const [selectedTemplate, setSelectedTemplate] = useState<string | null>(null);
const [timeCheck, setTimeCheck] = useState<{ totalTimeRemaining: number; questionTimeRemaining: number; isTotalTimeout: boolean; isQuestionTimeout: boolean } | null>(null);
const isTimedOut = timeCheck?.isTotalTimeout || timeCheck?.isQuestionTimeout;
const messagesEndRef = useRef<HTMLDivElement>(null);
@@ -137,7 +138,11 @@ export const AssessmentView: React.FC<AssessmentViewProps> = ({
setState(histState);
setSession(histSession);
} catch (err: any) {
setError(err.message || 'Failed to load historical assessment');
if (histSession.status === 'IN_PROGRESS') {
setError(t('cannotResumeInProgress'));
} else {
setError(err.message || 'Failed to load historical assessment');
}
} finally {
setIsLoading(false);
setLoadingHistoryId(null);
@@ -184,7 +189,7 @@ export const AssessmentView: React.FC<AssessmentViewProps> = ({
...prev,
...event.data,
messages: event.data.messages
? [...prevMessages, ...event.data.messages.filter((m: any) => !prevMessages.some((pm: any) => pm.content === m.content && pm.role === m.role))]
? [...prevMessages, ...event.data.messages.filter((m: any) => !prevMessages.some((pm: any) => (m.id && pm.id === m.id) || (pm.content === m.content && pm.role === m.role)))]
: prevMessages,
feedbackHistory: event.data.feedbackHistory
? [...(prev.feedbackHistory || []), ...event.data.feedbackHistory.filter((fh: any) => !(prev.feedbackHistory || []).some((pfh: any) => pfh.content === fh.content))]
@@ -227,7 +232,7 @@ export const AssessmentView: React.FC<AssessmentViewProps> = ({
};
const handleSubmitAnswer = async () => {
if (!session || !inputValue.trim() || isLoading) return;
if (!session || !inputValue.trim() || isLoading || isTimedOut) return;
const answer = inputValue.trim();
setInputValue('');
@@ -252,7 +257,7 @@ export const AssessmentView: React.FC<AssessmentViewProps> = ({
if (!prev) return event.data;
const prevMessages = prev.messages || [];
const mergedMessages = event.data.messages
? [...prevMessages, ...event.data.messages.filter((m: any) => !prevMessages.some((pm: any) => pm.content === m.content && pm.role === m.role))]
? [...prevMessages, ...event.data.messages.filter((m: any) => !prevMessages.some((pm: any) => (m.id && pm.id === m.id) || (pm.content === m.content && pm.role === m.role)))]
: prevMessages;
return {
@@ -428,7 +433,7 @@ export const AssessmentView: React.FC<AssessmentViewProps> = ({
{/* Assessment History Sidebar */}
{history.length > 0 && (
<div className="w-80 flex-none bg-white p-6 overflow-y-auto hidden lg:flex flex-col border-l border-slate-200/60 shadow-[4px_0_24px_rgba(0,0,0,0.02)]">
<div className="w-80 flex-none bg-white p-6 overflow-y-auto flex flex-col border-l border-slate-200/60 shadow-[4px_0_24px_rgba(0,0,0,0.02)]">
<h3 className="text-sm font-black text-slate-900 mb-6 flex items-center gap-2 uppercase tracking-widest">
<History size={18} className="text-indigo-600" />
{t('recentAssessments')}
@@ -576,26 +581,32 @@ export const AssessmentView: React.FC<AssessmentViewProps> = ({
</div>
<div className="p-6 bg-white border-t border-slate-200/60 shadow-[0_-4px_20px_-10px_rgba(0,0,0,0.05)]">
{isTimedOut && (
<div className="max-w-3xl mx-auto mb-3 px-4 py-2 bg-red-50 border border-red-200 text-red-700 text-sm font-bold rounded-xl text-center">
{t('timeLimitExceeded')}
</div>
)}
<div className="max-w-3xl mx-auto flex items-end gap-3">
<textarea
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.shiftKey) {
if (e.key === 'Enter' && !e.shiftKey && !isTimedOut) {
e.preventDefault();
handleSubmitAnswer();
}
}}
placeholder={t('typeAnswerPlaceholder')}
className="flex-1 max-h-32 p-4 bg-slate-50 border-none rounded-2xl focus:bg-white focus:ring-2 focus:ring-indigo-500/20 text-sm font-medium resize-none transition-all placeholder:text-slate-400 outline-none shadow-inner"
placeholder={isTimedOut ? t('timeLimitExceeded') : t('typeAnswerPlaceholder')}
disabled={isTimedOut}
className="flex-1 max-h-32 p-4 bg-slate-50 border-none rounded-2xl focus:bg-white focus:ring-2 focus:ring-indigo-500/20 text-sm font-medium resize-none transition-all placeholder:text-slate-400 outline-none shadow-inner disabled:opacity-50 disabled:cursor-not-allowed"
rows={1}
/>
<button
onClick={handleSubmitAnswer}
disabled={!inputValue.trim() || isLoading}
disabled={!inputValue.trim() || isLoading || isTimedOut}
className={cn(
"w-14 h-14 flex items-center justify-center rounded-2xl transition-all shadow-lg",
!inputValue.trim() || isLoading
!inputValue.trim() || isLoading || isTimedOut
? "bg-slate-100 text-slate-400 shadow-none"
: "bg-indigo-600 text-white hover:bg-indigo-700 shadow-indigo-200 active:scale-95"
)}
@@ -607,7 +618,7 @@ export const AssessmentView: React.FC<AssessmentViewProps> = ({
</div>
{/* Right: Feedback Panel */}
<div className="w-80 flex-none bg-white p-6 overflow-y-auto hidden lg:flex flex-col border-l border-slate-100">
<div className="w-80 flex-none bg-white p-6 overflow-y-auto flex flex-col border-l border-slate-100">
<h3 className="text-sm font-black text-slate-900 mb-6 flex items-center gap-2 uppercase tracking-widest">
<ClipboardCheck size={18} className="text-indigo-600" />
{t('liveFeedback')}
@@ -744,9 +755,9 @@ export const AssessmentView: React.FC<AssessmentViewProps> = ({
<span className="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-1">{t('status')}</span>
<span className={cn(
"text-2xl font-black uppercase tracking-tighter",
(state?.finalScore || 0) >= 6 ? "text-emerald-600" : "text-rose-600"
state?.passed ? "text-emerald-600" : "text-rose-600"
)}>
{(state?.finalScore || 0) >= 6 ? t('verified') : t('fail')}
{state?.passed ? t('verified') : t('fail')}
</span>
</div>
</div>
@@ -788,7 +799,7 @@ export const AssessmentView: React.FC<AssessmentViewProps> = ({
a.click();
URL.revokeObjectURL(url);
} catch (err) {
console.error('Failed to export PDF:', err);
setError(t('exportAssessmentFailed'));
}
}}
className="px-6 py-4 bg-white border-2 border-slate-100 text-slate-700 rounded-2xl font-bold hover:bg-slate-50 transition-all active:scale-[0.98]"
@@ -813,7 +824,7 @@ export const AssessmentView: React.FC<AssessmentViewProps> = ({
a.click();
URL.revokeObjectURL(url);
} catch (err) {
console.error('Failed to export Excel:', err);
setError(t('exportAssessmentFailed'));
}
}}
className="px-6 py-4 bg-white border-2 border-slate-100 text-slate-700 rounded-2xl font-bold hover:bg-slate-50 transition-all active:scale-[0.98]"
+284 -151
View File
@@ -3,35 +3,31 @@ import { createPortal } from 'react-dom';
import { useParams, useNavigate } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import {
ChevronLeft, Plus, Sparkles, Send, Check, X,
ChevronLeft, Plus, Sparkles, Send, Check, X, XCircle, Clock,
Trash2, Edit2, FileText, Loader2, BookOpen, Brain,
AlertCircle, Hash, Layers
} from 'lucide-react';
import { questionBankService, QuestionBank, QuestionBankItem, CreateQuestionBankItemDto } from '../../services/questionBankService';
import { templateService } from '../../services/templateService';
import { AssessmentTemplate } from '../../types';
import { useToast } from '../../contexts/ToastContext';
import { useConfirm } from '../../contexts/ConfirmContext';
import { useLanguage } from '../../contexts/LanguageContext';
const QUESTION_TYPES = [
{ value: 'SHORT_ANSWER', label: '简答题' },
{ value: 'MULTIPLE_CHOICE', label: '选择题' },
{ value: 'TRUE_FALSE', label: '判断题' },
{ value: 'SHORT_ANSWER', labelKey: 'shortAnswer' as const },
{ value: 'MULTIPLE_CHOICE', labelKey: 'multipleChoice' as const },
{ value: 'TRUE_FALSE', labelKey: 'trueFalse' as const },
];
const DIFFICULTIES = [
{ value: 'STANDARD', label: '标准' },
{ value: 'ADVANCED', label: '高级' },
{ value: 'SPECIALIST', label: '专家' },
{ value: 'STANDARD', labelKey: 'standard' as const },
{ value: 'ADVANCED', labelKey: 'advanced' as const },
{ value: 'SPECIALIST', labelKey: 'specialist' as const },
];
const DIMENSIONS = [
{ value: 'PROMPT', label: 'Prompt' },
{ value: 'LLM', label: 'LLM' },
{ value: 'IDE', label: 'IDE' },
{ value: 'DEV_PATTERN', label: '开发模式' },
{ value: 'WORK_CAPABILITY', label: '工作能力' },
];
const typeIcons: Record<string, React.ReactNode> = {
type TypeIcon = { [key: string]: React.ReactNode };
const typeIcons: TypeIcon = {
SHORT_ANSWER: <FileText size={12} />,
MULTIPLE_CHOICE: <Layers size={12} />,
TRUE_FALSE: <Check size={12} />,
@@ -40,14 +36,19 @@ const typeIcons: Record<string, React.ReactNode> = {
export default function QuestionBankDetailView() {
const { id: bankId } = useParams<{ id: string }>();
const navigate = useNavigate();
const { t } = useLanguage();
const { showSuccess, showError } = useToast();
const { confirm } = useConfirm();
if (!bankId) {
return (
<div className="p-6">
<button onClick={() => navigate('/question-banks')} className="flex items-center gap-2 text-gray-600 hover:text-gray-900 mb-4">
<ChevronLeft size={20} />
<button onClick={() => navigate('/question-banks')} className="flex items-center gap-2 text-slate-400 hover:text-slate-600 transition-colors mb-4">
<ChevronLeft size={18} /><span className="text-xs font-black uppercase tracking-widest">{t('backToBankList')}</span>
</button>
<div className="text-red-500">ID</div>
<div className="flex items-center gap-2 text-red-500 bg-red-50 rounded-2xl p-4 border border-red-100">
<AlertCircle size={18} /><span className="text-sm font-bold">{t('invalidBankId')}</span>
</div>
</div>
);
}
@@ -55,6 +56,7 @@ export default function QuestionBankDetailView() {
const [bank, setBank] = useState<QuestionBank | null>(null);
const [items, setItems] = useState<QuestionBankItem[]>([]);
const [templates, setTemplates] = useState<AssessmentTemplate[]>([]);
const [template, setTemplate] = useState<AssessmentTemplate | null>(null);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState('');
@@ -72,40 +74,66 @@ export default function QuestionBankDetailView() {
});
const [keyPointsInput, setKeyPointsInput] = useState('');
const [generateForm, setGenerateForm] = useState({
count: 5,
knowledgeBaseContent: '',
});
const [generateForm, setGenerateForm] = useState({ count: 5, knowledgeBaseContent: '' });
const [generating, setGenerating] = useState(false);
useEffect(() => { fetchData(); fetchTemplates(); }, [bankId]);
const fetchData = async () => {
try { setLoading(true);
try {
setLoading(true);
const bankData = await questionBankService.getBank(bankId);
setBank(bankData);
const itemsData = await questionBankService.getBankItems(bankId);
setItems(itemsData);
} catch (err: any) { setError(err.message || '加载失败');
} finally { setLoading(false); }
} catch (err: any) {
setError(err.message || t('actionFailed'));
showError(err.message || t('actionFailed'));
} finally {
setLoading(false);
}
};
const fetchTemplates = async () => {
try { const data = await templateService.getAll(); setTemplates(data);
} catch (err) { console.error('加载模板失败:', err); }
try {
const data = await templateService.getAll();
setTemplates(data);
const bankData = await questionBankService.getBank(bankId);
if (bankData.templateId) {
const tpl = data.find(tpl => tpl.id === bankData.templateId);
setTemplate(tpl || null);
}
} catch {
// silent
}
};
const dimensionOptions = template?.dimensions?.map(d => ({ value: d.name || d.label, label: d.label || d.name }))
|| [
{ value: 'PROMPT', label: 'Prompt' },
{ value: 'LLM', label: 'LLM' },
{ value: 'IDE', label: 'IDE' },
{ value: 'DEV_PATTERN', label: 'Dev Pattern' },
{ value: 'WORK_CAPABILITY', label: 'Work Capability' },
];
const handleCreateItem = async (e: React.FormEvent) => {
e.preventDefault();
if (!itemForm.questionText.trim()) return;
setSaving(true);
try {
await questionBankService.createItem(bankId, { ...itemForm, keyPoints: keyPointsInput.split('\n').filter(k => k.trim()) });
await questionBankService.createItem(bankId, {
...itemForm,
keyPoints: keyPointsInput.split('\n').filter(k => k.trim()),
});
closeItemForm();
showSuccess(t('questionAdded'));
fetchData();
} catch (err: any) { alert('创建失败: ' + (err.message || '未知错误'));
} finally { setSaving(false); }
} catch (err: any) {
showError(err.message || t('actionFailed'));
} finally {
setSaving(false);
}
};
const handleUpdateItem = async (e: React.FormEvent) => {
@@ -113,77 +141,133 @@ export default function QuestionBankDetailView() {
if (!editingItem || !itemForm.questionText.trim()) return;
setSaving(true);
try {
await questionBankService.updateItem(bankId, editingItem.id, { ...itemForm, keyPoints: keyPointsInput.split('\n').filter(k => k.trim()) });
await questionBankService.updateItem(bankId, editingItem.id, {
...itemForm,
keyPoints: keyPointsInput.split('\n').filter(k => k.trim()),
});
closeItemForm();
showSuccess(t('questionUpdated'));
fetchData();
} catch (err: any) { alert('更新失败: ' + (err.message || '未知错误'));
} finally { setSaving(false); }
} catch (err: any) {
showError(err.message || t('actionFailed'));
} finally {
setSaving(false);
}
};
const handleDeleteItem = async (itemId: string) => {
if (!confirm('确定要删除这道题目吗?')) return;
try { await questionBankService.deleteItem(bankId, itemId); fetchData();
} catch (err: any) { alert('删除失败: ' + (err.message || '未知错误')); }
const ok = await confirm({ message: t('confirmDeleteQuestion'), confirmLabel: t('delete'), cancelLabel: t('cancel') });
if (!ok) return;
try {
await questionBankService.deleteItem(bankId, itemId);
showSuccess(t('questionDeleted'));
fetchData();
} catch (err: any) {
showError(err.message || t('actionFailed'));
}
};
const handleGenerate = async () => {
setGenerating(true);
try {
await questionBankService.generateQuestions(bankId, generateForm.count, generateForm.knowledgeBaseContent);
const result = await questionBankService.generateQuestions(bankId, generateForm.count, generateForm.knowledgeBaseContent);
setShowGenerate(false);
setGenerateForm({ count: 5, knowledgeBaseContent: '' });
showSuccess(t('generatedQuestions').replace('$1', String(generateForm.count)));
fetchData();
} catch (err: any) { alert('生成失败: ' + (err.message || '未知错误'));
} finally { setGenerating(false); }
} catch (err: any) {
showError(err.message || t('actionFailed'));
} finally {
setGenerating(false);
}
};
const handleSubmitForReview = async () => {
if (!confirm('确定要提交审核吗?')) return;
try { await questionBankService.submitForReview(bankId); fetchData();
} catch (err: any) { alert('提交失败: ' + (err.message || '未知错误')); }
const ok = await confirm({ message: t('confirmSubmitReview'), confirmLabel: t('submitForReview'), cancelLabel: t('cancel') });
if (!ok) return;
try {
await questionBankService.submitForReview(bankId);
showSuccess(t('bankSubmittedForReview'));
fetchData();
} catch (err: any) {
showError(err.message || t('actionFailed'));
}
};
const handlePublish = async () => {
if (!confirm('确定要发布题库吗?')) return;
try { await questionBankService.publishBank(bankId); fetchData();
} catch (err: any) { alert('发布失败: ' + (err.message || '未知错误')); }
const isPendingReview = bank?.status === 'PENDING_REVIEW';
const label = isPendingReview ? t('approve') : t('republish');
const msg = isPendingReview ? t('confirmApproveBank') : t('confirmRepublishBank');
const ok = await confirm({ message: msg, confirmLabel: label, cancelLabel: t('cancel') });
if (!ok) return;
try {
if (isPendingReview) {
await questionBankService.approveBank(bankId);
} else {
await questionBankService.publishBank(bankId);
}
showSuccess(isPendingReview ? t('bankApproved') : t('bankRepublished'));
fetchData();
} catch (err: any) {
showError(err.message || t('actionFailed'));
}
};
const handleApproveItem = async (itemId: string) => {
try { await questionBankService.updateItem(bankId, itemId, { status: 'PUBLISHED' } as any); fetchData();
} catch (err: any) { alert('操作失败: ' + (err.message || '未知错误')); }
try {
await questionBankService.updateItem(bankId, itemId, { status: 'PUBLISHED' } as any);
showSuccess(t('questionApproved'));
fetchData();
} catch (err: any) {
showError(err.message || t('actionFailed'));
}
};
const handleRejectItem = async (itemId: string) => {
try {
await questionBankService.batchReviewItems(bankId, [itemId], false);
showSuccess(t('questionReturned'));
fetchData();
} catch (err: any) {
showError(err.message || t('actionFailed'));
}
};
const openEditItem = (item: QuestionBankItem) => {
setEditingItem(item);
setItemForm({ questionText: item.questionText, questionType: item.questionType, options: item.options || [], keyPoints: item.keyPoints, difficulty: item.difficulty, dimension: item.dimension });
setItemForm({
questionText: item.questionText,
questionType: item.questionType,
options: item.options || [],
keyPoints: item.keyPoints,
difficulty: item.difficulty,
dimension: item.dimension,
});
setKeyPointsInput(item.keyPoints.join('\n'));
setShowAddItem(true);
};
const closeItemForm = () => { setShowAddItem(false); setEditingItem(null); };
const getStatusBadge = (status: string) => {
switch (status) {
case 'PUBLISHED': return <span className="px-2.5 py-1 text-[10px] font-black uppercase tracking-widest rounded-full bg-emerald-50 text-emerald-600 border border-emerald-200/50"></span>;
case 'PENDING_REVIEW': return <span className="px-2.5 py-1 text-[10px] font-black uppercase tracking-widest rounded-full bg-amber-50 text-amber-600 border border-amber-200/50"></span>;
default: return <span className="px-2.5 py-1 text-[10px] font-black uppercase tracking-widest rounded-full bg-slate-50 text-slate-500 border border-slate-200/50">稿</span>;
}
};
if (loading) {
return (
<div className="flex items-center justify-center h-64">
<Loader2 className="w-8 h-8 animate-spin text-blue-600 opacity-30" />
<div className="flex items-center justify-center py-20">
<Loader2 className="w-8 h-8 animate-spin text-blue-600 opacity-20" />
</div>
);
}
if (error) {
return (
<div className="p-6">
<button onClick={() => navigate('/question-banks')} className="flex items-center gap-2 text-gray-600 hover:text-gray-900 mb-4"><ChevronLeft size={20} /> </button>
<div className="flex items-center gap-2 text-red-500 bg-red-50 rounded-2xl p-4 border border-red-100"><AlertCircle size={18} /><span className="text-sm font-bold">{error}</span></div>
<div className="space-y-4">
<button onClick={() => navigate('/question-banks')} className="flex items-center gap-2 text-slate-400 hover:text-slate-600 transition-colors">
<ChevronLeft size={18} /><span className="text-xs font-black uppercase tracking-widest">{t('backToBankList')}</span>
</button>
<div className="flex items-center gap-3 text-red-500 bg-red-50 rounded-2xl p-6 border border-red-100">
<AlertCircle size={20} />
<span className="text-sm font-bold">{error}</span>
<button onClick={fetchData} className="ml-auto text-xs font-black text-red-600 hover:text-red-700 uppercase tracking-widest">{t('retry')}</button>
</div>
</div>
);
}
@@ -191,100 +275,148 @@ export default function QuestionBankDetailView() {
const pendingItems = items.filter(i => i.status === 'PENDING_REVIEW');
const publishedItems = items.filter(i => i.status === 'PUBLISHED');
const statusColors: Record<string, { bg: string; text: string; border: string; label: string; blur: string; icon: React.ReactNode }> = {
PUBLISHED: { bg: 'bg-emerald-50', text: 'text-emerald-600', border: 'border-emerald-200/50', label: t('published'), blur: 'bg-emerald-500/5', icon: <Check size={12} /> },
PENDING_REVIEW: { bg: 'bg-amber-50', text: 'text-amber-600', border: 'border-amber-200/50', label: t('pendingReview'), blur: 'bg-amber-500/5', icon: <Clock size={12} /> },
DRAFT: { bg: 'bg-slate-50', text: 'text-slate-500', border: 'border-slate-200/50', label: t('draft'), blur: 'bg-blue-500/5', icon: <FileText size={12} /> },
REJECTED: { bg: 'bg-red-50', text: 'text-red-500', border: 'border-red-200/50', label: t('rejected'), blur: 'bg-red-500/5', icon: <XCircle size={12} /> },
};
const bankStatus = statusColors[bank?.status || 'DRAFT'] || statusColors.DRAFT;
const statCards = [
{ label: t('questionList'), value: items.length, icon: <FileText size={18} />, classes: 'bg-slate-50 border-slate-200/50 text-slate-700' },
{ label: t('published'), value: publishedItems.length, icon: <Check size={18} />, classes: 'bg-emerald-50 border-emerald-200/50 text-emerald-700' },
{ label: t('pendingReview'), value: pendingItems.length, icon: <Clock size={18} />, classes: 'bg-amber-50 border-amber-200/50 text-amber-700' },
];
return (
<div className="space-y-6">
<button onClick={() => navigate('/question-banks')} className="flex items-center gap-2 text-slate-400 hover:text-slate-600 transition-colors mb-2">
<ChevronLeft size={18} /><span className="text-xs font-black uppercase tracking-widest"></span>
<button onClick={() => navigate('/question-banks')} className="flex items-center gap-2 text-slate-400 hover:text-slate-600 transition-colors">
<ChevronLeft size={18} /><span className="text-xs font-black uppercase tracking-widest">{t('backToBankList')}</span>
</button>
<div className="flex items-start justify-between">
<div className="flex flex-col sm:flex-row sm:items-start justify-between gap-4">
<div className="flex items-center gap-4">
<div className="w-14 h-14 bg-blue-50 text-blue-600 rounded-2xl flex items-center justify-center shadow-sm"><BookOpen size={28} /></div>
<div className="w-14 h-14 bg-blue-50 text-blue-600 rounded-2xl flex items-center justify-center shadow-sm shrink-0"><BookOpen size={28} /></div>
<div>
<h1 className="text-2xl font-black text-slate-900">{bank?.name}</h1>
<p className="text-sm text-slate-500 mt-1">{bank?.description || '暂无描述'}</p>
<div className="flex items-center gap-3 mt-2">
<span className="text-[10px] font-bold text-slate-400 uppercase tracking-widest flex items-center gap-1.5"><Brain size={12} className="text-blue-500" />{templates.find(t => t.id === bank?.templateId)?.name || '未关联模板'}</span>
{getStatusBadge(bank?.status || 'DRAFT')}
<p className="text-sm text-slate-500 mt-1">{bank?.description || t('noDescription')}</p>
<div className="flex items-center gap-3 mt-2 flex-wrap">
{template && (
<span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-purple-50 text-purple-600 text-[10px] font-bold rounded-lg border border-purple-100/50">
<Brain size={12} />{template.name}
</span>
)}
<span className={`inline-flex items-center gap-1 px-2.5 py-1 text-[10px] font-black uppercase tracking-widest rounded-full border ${bankStatus.bg} ${bankStatus.text} ${bankStatus.border}`}>
{bankStatus.icon}{bankStatus.label}
</span>
</div>
</div>
</div>
<div className="flex gap-2">
<div className="flex gap-2 shrink-0">
{bank?.status === 'DRAFT' && (
<button onClick={handleSubmitForReview} className="px-5 py-3 bg-amber-500 text-white rounded-xl text-xs font-black uppercase tracking-widest flex items-center gap-2 shadow-lg shadow-amber-100 hover:bg-amber-600 transition-all active:scale-95">
<Send size={16} />
<Send size={16} /> {t('submitForReview')}
</button>
)}
{bank?.status === 'PENDING_REVIEW' && (
{(bank?.status === 'PENDING_REVIEW' || bank?.status === 'REJECTED') && (
<button onClick={handlePublish} className="px-5 py-3 bg-emerald-600 text-white rounded-xl text-xs font-black uppercase tracking-widest flex items-center gap-2 shadow-lg shadow-emerald-100 hover:bg-emerald-700 transition-all active:scale-95">
<Check size={16} />
<Check size={16} /> {bank?.status === 'PENDING_REVIEW' ? t('approve') : t('republish')}
</button>
)}
<button onClick={() => setShowGenerate(true)} className="px-5 py-3 bg-purple-600 text-white rounded-xl text-xs font-black uppercase tracking-widest flex items-center gap-2 shadow-lg shadow-purple-100 hover:bg-purple-700 transition-all active:scale-95">
<Sparkles size={16} /> AI生成
<Sparkles size={16} /> {t('aiGenerate')}
</button>
</div>
</div>
<div className="grid grid-cols-3 gap-4">
{[
{ label: '总题目数', value: items.length, color: 'blue', icon: <FileText size={16} /> },
{ label: '待审核', value: pendingItems.length, color: 'amber', icon: <Send size={16} /> },
{ label: '已发布', value: publishedItems.length, color: 'emerald', icon: <Check size={16} /> },
].map((stat, i) => (
<motion.div key={stat.label} initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: i * 0.1 }}
className={`bg-${stat.color}-50/50 border border-${stat.color}-100/50 rounded-2xl p-4`}>
{statCards.map((stat, i) => (
<motion.div key={stat.label} initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: i * 0.08 }}
className={`rounded-2xl border p-4 ${stat.classes}`}>
<div className="flex items-center justify-between mb-2">
<span className={`text-[10px] font-black uppercase tracking-widest text-${stat.color}-500`}>{stat.label}</span>
<span className={`text-${stat.color}-500`}>{stat.icon}</span>
<span className="text-[10px] font-black uppercase tracking-widest opacity-70">{stat.label}</span>
{stat.icon}
</div>
<div className={`text-3xl font-black text-${stat.color}-700`}>{stat.value}</div>
<div className="text-3xl font-black">{stat.value}</div>
</motion.div>
))}
</div>
<div className="flex items-center justify-between">
<h2 className="text-lg font-black text-slate-900"></h2>
<button onClick={() => { setShowAddItem(true); setEditingItem(null); setKeyPointsInput(''); setItemForm({ questionText: '', questionType: 'SHORT_ANSWER', keyPoints: [], difficulty: 'STANDARD', dimension: 'WORK_CAPABILITY' }); }}
<h2 className="text-lg font-black text-slate-900">{t('questionList')}</h2>
<button onClick={() => { setShowAddItem(true); setEditingItem(null); setKeyPointsInput(''); setItemForm({ questionText: '', questionType: 'SHORT_ANSWER', keyPoints: [], difficulty: 'STANDARD', dimension: (dimensionOptions[0]?.value as any) || 'WORK_CAPABILITY' }); }}
className="px-5 py-3 bg-blue-600 text-white rounded-xl text-xs font-black uppercase tracking-widest flex items-center gap-2 shadow-lg shadow-blue-100 hover:bg-blue-700 transition-all active:scale-95">
<Plus size={16} />
<Plus size={16} /> {t('addQuestion')}
</button>
</div>
{items.length === 0 ? (
<div className="bg-slate-50 rounded-[2rem] border-2 border-dashed border-slate-200 p-16 text-center">
<FileText className="w-14 h-14 text-slate-200 mx-auto mb-4" />
<p className="text-slate-400 font-bold uppercase tracking-widest text-xs"></p>
<p className="text-slate-300 text-xs mt-2">使AI生成</p>
<div className="w-14 h-14 bg-slate-100 rounded-2xl flex items-center justify-center mx-auto mb-4">
<FileText size={28} className="text-slate-300" />
</div>
<p className="text-slate-400 font-black uppercase tracking-widest text-xs mb-1">{t('noQuestions')}</p>
<p className="text-slate-300 text-xs">{t('noQuestionsDesc')}</p>
</div>
) : (
<div className="grid grid-cols-1 gap-4">
<div className="space-y-4">
<AnimatePresence mode="popLayout">
{items.map((item, idx) => (
<motion.div key={item.id} layout initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, scale: 0.95 }} transition={{ delay: idx * 0.03 }}
className="bg-white border border-slate-200 rounded-2xl p-5 shadow-sm hover:shadow-md transition-all group relative overflow-hidden">
<div className="absolute top-0 right-0 w-32 h-32 bg-blue-500/5 rounded-full blur-3xl -mr-16 -mt-16" />
<div className="flex items-start justify-between relative z-10">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-2.5 flex-wrap">
<span className="inline-flex items-center gap-1 px-2.5 py-1 bg-slate-50 text-slate-600 text-[10px] font-bold rounded-lg border border-slate-100">{typeIcons[item.questionType]}{QUESTION_TYPES.find(t => t.value === item.questionType)?.label}</span>
<span className="inline-flex items-center gap-1 px-2.5 py-1 bg-blue-50 text-blue-600 text-[10px] font-bold rounded-lg border border-blue-100"><Hash size={10} />{DIFFICULTIES.find(d => d.value === item.difficulty)?.label}</span>
<span className="inline-flex items-center gap-1 px-2.5 py-1 bg-purple-50 text-purple-600 text-[10px] font-bold rounded-lg border border-purple-100"><Brain size={10} />{DIMENSIONS.find(d => d.value === item.dimension)?.label}</span>
{getStatusBadge(item.status)}
</div>
<p className="font-bold text-slate-900 leading-relaxed">{item.questionText}</p>
{item.keyPoints.length > 0 && (
<div className="mt-3 flex flex-wrap gap-1.5">
<span className="text-[10px] font-black text-slate-400 uppercase tracking-widest mr-1">:</span>
{item.keyPoints.map((kp, i) => <span key={i} className="px-2.5 py-1 bg-amber-50 text-amber-700 text-[10px] font-bold rounded-lg border border-amber-100/50">{kp}</span>)}
{items.map((item, idx) => {
const itemStat = item.status === 'PUBLISHED' ? statusColors.PUBLISHED : statusColors.PENDING_REVIEW;
return (
<motion.div key={item.id} layout initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, scale: 0.95 }}
transition={{ delay: Math.min(idx * 0.03, 0.3) }}
className="bg-white border border-slate-200 rounded-2xl p-5 shadow-sm hover:shadow-md transition-all group relative overflow-hidden">
<div className={`absolute top-0 right-0 w-40 h-40 rounded-full blur-3xl -mr-20 -mt-20 ${itemStat.blur}`} />
<div className="relative z-10 flex items-start justify-between">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-2.5 flex-wrap">
<span className="inline-flex items-center gap-1 px-2.5 py-1 bg-slate-50 text-slate-600 text-[10px] font-bold rounded-lg border border-slate-100">
{typeIcons[item.questionType]}
{t(QUESTION_TYPES.find(qt => qt.value === item.questionType)?.labelKey || 'shortAnswer')}
</span>
<span className="inline-flex items-center gap-1 px-2.5 py-1 bg-blue-50 text-blue-600 text-[10px] font-bold rounded-lg border border-blue-100">
<Hash size={10} />
{t(DIFFICULTIES.find(d => d.value === item.difficulty)?.labelKey || 'standard')}
</span>
<span className="inline-flex items-center gap-1 px-2.5 py-1 bg-purple-50 text-purple-600 text-[10px] font-bold rounded-lg border border-purple-100">
<Brain size={10} />
{dimensionOptions.find(d => d.value === item.dimension)?.label || item.dimension}
</span>
<span className={`inline-flex items-center gap-1 px-2.5 py-1 text-[10px] font-black uppercase tracking-widest rounded-full border ${itemStat.bg} ${itemStat.text} ${itemStat.border}`}>
{itemStat.icon}{itemStat.label}
</span>
</div>
)}
{item.basis && <div className="mt-2 flex items-center gap-1.5 text-[10px] text-slate-400"><FileText size={10} /><span className="font-medium"></span><span>{item.basis}</span></div>}
<p className="font-bold text-slate-900 leading-relaxed">{item.questionText}</p>
{item.keyPoints.length > 0 && (
<div className="mt-3 flex flex-wrap gap-1.5 items-center">
<span className="text-[10px] font-black text-slate-400 uppercase tracking-widest mr-1">{t('gradingPoints')}</span>
{item.keyPoints.map((kp, i) => <span key={i} className="px-2.5 py-1 bg-amber-50 text-amber-700 text-[10px] font-bold rounded-lg border border-amber-100/50">{kp}</span>)}
</div>
)}
{item.basis && (
<div className="mt-2 flex items-center gap-1.5 text-[10px] text-slate-400">
<FileText size={10} /><span className="font-medium">{t('basis')}</span><span>{item.basis}</span>
</div>
)}
</div>
<div className="flex items-center gap-1 ml-4 shrink-0 opacity-0 group-hover:opacity-100 transition-opacity">
{item.status === 'PENDING_REVIEW' && (
<>
<button onClick={() => handleApproveItem(item.id)} className="p-2 text-emerald-600 hover:bg-emerald-50 rounded-xl transition-all" title={t('approve')}><Check size={15} /></button>
<button onClick={() => handleRejectItem(item.id)} className="p-2 text-red-500 hover:bg-red-50 rounded-xl transition-all" title={t('rejected')}><X size={15} /></button>
</>
)}
<button onClick={() => openEditItem(item)} className="p-2 text-blue-600 hover:bg-blue-50 rounded-xl transition-all" title={t('edit')}><Edit2 size={15} /></button>
<button onClick={() => handleDeleteItem(item.id)} className="p-2 text-red-500 hover:bg-red-50 rounded-xl transition-all" title={t('delete')}><Trash2 size={15} /></button>
</div>
</div>
<div className="flex gap-1 ml-4 shrink-0">
{item.status === 'PENDING_REVIEW' && <button onClick={() => handleApproveItem(item.id)} className="p-2 text-emerald-600 hover:bg-emerald-50 rounded-xl transition-all" title="通过"><Check size={15} /></button>}
<button onClick={() => openEditItem(item)} className="p-2 text-blue-600 hover:bg-blue-50 rounded-xl transition-all" title="编辑"><Edit2 size={15} /></button>
<button onClick={() => handleDeleteItem(item.id)} className="p-2 text-red-600 hover:bg-red-50 rounded-xl transition-all" title="删除"><Trash2 size={15} /></button>
</div>
</div>
</motion.div>
))}
</motion.div>
);
})}
</AnimatePresence>
</div>
)}
@@ -299,51 +431,51 @@ export default function QuestionBankDetailView() {
<div className="p-8 pb-4 flex items-center justify-between border-b border-slate-100">
<div className="flex items-center gap-3">
<div className="w-12 h-12 bg-blue-50 text-blue-600 rounded-2xl flex items-center justify-center">{editingItem ? <Edit2 size={24} /> : <Plus size={24} />}</div>
<h3 className="text-xl font-black text-slate-900">{editingItem ? '编辑题目' : '添加题目'}</h3>
<h3 className="text-xl font-black text-slate-900">{editingItem ? t('editQuestion') : t('addQuestionTitle')}</h3>
</div>
<button onClick={closeItemForm} className="p-2 text-slate-400 hover:text-slate-600 hover:bg-slate-50 rounded-xl transition-all"><X size={20} /></button>
</div>
<form id="item-form" onSubmit={editingItem ? handleUpdateItem : handleCreateItem} className="p-8 space-y-5">
<div className="space-y-1.5">
<label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1 ml-1 flex items-center gap-2"><FileText size={12} className="text-blue-500" /> *</label>
<textarea value={itemForm.questionText} onChange={(e) => setItemForm({...itemForm, questionText: e.target.value})}
className="w-full px-5 py-4 bg-slate-50 border border-slate-200 rounded-[1.25rem] text-sm font-bold focus:ring-4 focus:ring-blue-500/10 focus:border-blue-500/50 outline-none transition-all placeholder:text-slate-300" placeholder="输入题目内容" rows={3} required />
<label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1 ml-1 flex items-center gap-2"><FileText size={12} className="text-blue-500" /> {t('questionContent')} <span className="text-red-500">*</span></label>
<textarea value={itemForm.questionText} onChange={(e) => setItemForm({ ...itemForm, questionText: e.target.value })}
className="w-full px-5 py-4 bg-slate-50 border border-slate-200 rounded-[1.25rem] text-sm font-bold focus:ring-4 focus:ring-blue-500/10 focus:border-blue-500/50 outline-none transition-all placeholder:text-slate-300"
placeholder={t('questionContent')} rows={3} required />
</div>
<div className="grid grid-cols-2 gap-5">
<div className="space-y-1.5">
<label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1 ml-1 flex items-center gap-2"><Layers size={12} className="text-blue-500" /> </label>
<select value={itemForm.questionType} onChange={(e) => setItemForm({...itemForm, questionType: e.target.value as any})}
className="w-full px-5 py-4 bg-slate-50 border border-slate-200 rounded-[1.25rem] text-sm font-bold focus:ring-4 focus:ring-blue-500/10 focus:border-blue-500/50 outline-none transition-all appearance-none cursor-pointer">
{QUESTION_TYPES.map(t => <option key={t.value} value={t.value}>{t.label}</option>)}
<label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1 ml-1 flex items-center gap-2"><Layers size={12} className="text-blue-500" /> {t('questionType')}</label>
<select value={itemForm.questionType} onChange={(e) => setItemForm({ ...itemForm, questionType: e.target.value as any })}
className="w-full px-5 py-4 bg-slate-50 border border-slate-200 rounded-[1.25rem] text-sm font-bold focus:ring-4 focus:ring-blue-500/10 focus:border-blue-500/50 outline-none transition-all cursor-pointer">
{QUESTION_TYPES.map(qt => <option key={qt.value} value={qt.value}>{t(qt.labelKey)}</option>)}
</select>
</div>
<div className="space-y-1.5">
<label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1 ml-1 flex items-center gap-2"><Hash size={12} className="text-blue-500" /> </label>
<select value={itemForm.difficulty} onChange={(e) => setItemForm({...itemForm, difficulty: e.target.value as any})}
className="w-full px-5 py-4 bg-slate-50 border border-slate-200 rounded-[1.25rem] text-sm font-bold focus:ring-4 focus:ring-blue-500/10 focus:border-blue-500/50 outline-none transition-all appearance-none cursor-pointer">
{DIFFICULTIES.map(d => <option key={d.value} value={d.value}>{d.label}</option>)}
<label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1 ml-1 flex items-center gap-2"><Hash size={12} className="text-blue-500" /> {t('difficultyDistribution')}</label>
<select value={itemForm.difficulty} onChange={(e) => setItemForm({ ...itemForm, difficulty: e.target.value as any })}
className="w-full px-5 py-4 bg-slate-50 border border-slate-200 rounded-[1.25rem] text-sm font-bold focus:ring-4 focus:ring-blue-500/10 focus:border-blue-500/50 outline-none transition-all cursor-pointer">
{DIFFICULTIES.map(d => <option key={d.value} value={d.value}>{t(d.labelKey)}</option>)}
</select>
</div>
</div>
<div className="space-y-1.5">
<label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1 ml-1 flex items-center gap-2"><Brain size={12} className="text-blue-500" /> </label>
<select value={itemForm.dimension} onChange={(e) => setItemForm({...itemForm, dimension: e.target.value as any})}
className="w-full px-5 py-4 bg-slate-50 border border-slate-200 rounded-[1.25rem] text-sm font-bold focus:ring-4 focus:ring-blue-500/10 focus:border-blue-500/50 outline-none transition-all appearance-none cursor-pointer">
{DIMENSIONS.map(d => <option key={d.value} value={d.value}>{d.label}</option>)}
<label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1 ml-1 flex items-center gap-2"><Brain size={12} className="text-blue-500" /> {t('dimension')}</label>
<select value={itemForm.dimension} onChange={(e) => setItemForm({ ...itemForm, dimension: e.target.value as any })}
className="w-full px-5 py-4 bg-slate-50 border border-slate-200 rounded-[1.25rem] text-sm font-bold focus:ring-4 focus:ring-blue-500/10 focus:border-blue-500/50 outline-none transition-all cursor-pointer">
{dimensionOptions.map(d => <option key={d.value} value={d.value}>{d.label}</option>)}
</select>
</div>
<div className="space-y-1.5">
<label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1 ml-1 flex items-center gap-2"><AlertCircle size={12} className="text-blue-500" /> </label>
<label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1 ml-1 flex items-center gap-2"><AlertCircle size={12} className="text-blue-500" /> {t('gradingPoints')}</label>
<textarea value={keyPointsInput} onChange={(e) => setKeyPointsInput(e.target.value)}
className="w-full px-5 py-4 bg-slate-50 border border-slate-200 rounded-[1.25rem] text-sm font-bold focus:ring-4 focus:ring-blue-500/10 focus:border-blue-500/50 outline-none transition-all placeholder:text-slate-300" placeholder="要点1
要点2
要点3" rows={4} />
className="w-full px-5 py-4 bg-slate-50 border border-slate-200 rounded-[1.25rem] text-sm font-bold focus:ring-4 focus:ring-blue-500/10 focus:border-blue-500/50 outline-none transition-all placeholder:text-slate-300"
placeholder={'1\n2\n3'} rows={4} />
</div>
<div className="flex justify-end gap-3 pt-4">
<button type="button" onClick={closeItemForm} className="px-6 py-4 text-sm font-black text-slate-500 hover:text-slate-700 transition-colors"></button>
<button type="button" onClick={closeItemForm} className="px-6 py-4 text-sm font-black text-slate-500 hover:text-slate-700 transition-colors">{t('cancel')}</button>
<button type="submit" form="item-form" disabled={saving}
className="px-10 py-4 bg-blue-600 text-white rounded-[1.25rem] font-black uppercase tracking-widest text-xs shadow-xl shadow-blue-100 hover:bg-blue-700 transition-all active:scale-95 flex items-center gap-2">
{saving && <Loader2 size={16} className="animate-spin" />}{saving ? '保存中...' : (editingItem ? '更新' : '添加')}</button>
{saving && <Loader2 size={16} className="animate-spin" />}{saving ? t('saving') : (editingItem ? t('save') : t('addQuestion'))}</button>
</div>
</form>
</motion.div>
@@ -363,26 +495,27 @@ export default function QuestionBankDetailView() {
<div className="p-8 pb-4 flex items-center justify-between border-b border-slate-100">
<div className="flex items-center gap-3">
<div className="w-12 h-12 bg-purple-50 text-purple-600 rounded-2xl flex items-center justify-center"><Sparkles size={24} /></div>
<h3 className="text-xl font-black text-slate-900">AI生成题目</h3>
<h3 className="text-xl font-black text-slate-900">{t('aiGenerateTitle')}</h3>
</div>
<button onClick={() => setShowGenerate(false)} className="p-2 text-slate-400 hover:text-slate-600 hover:bg-slate-50 rounded-xl transition-all"><X size={20} /></button>
</div>
<div className="p-8 space-y-5">
<div className="space-y-1.5">
<label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1 ml-1 flex items-center gap-2"><Hash size={12} className="text-purple-500" /> </label>
<input type="number" value={generateForm.count} onChange={(e) => setGenerateForm({...generateForm, count: parseInt(e.target.value) || 5})}
<label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1 ml-1 flex items-center gap-2"><Hash size={12} className="text-purple-500" /> {t('generateCount')}</label>
<input type="number" value={generateForm.count} onChange={(e) => setGenerateForm({ ...generateForm, count: parseInt(e.target.value) || 5 })}
className="w-full px-5 py-4 bg-slate-50 border border-slate-200 rounded-[1.25rem] text-sm font-bold focus:ring-4 focus:ring-purple-500/10 focus:border-purple-500/50 outline-none transition-all" min={1} max={20} />
</div>
<div className="space-y-1.5">
<label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1 ml-1 flex items-center gap-2"><FileText size={12} className="text-purple-500" /> </label>
<textarea value={generateForm.knowledgeBaseContent} onChange={(e) => setGenerateForm({...generateForm, knowledgeBaseContent: e.target.value})}
className="w-full px-5 py-4 bg-slate-50 border border-slate-200 rounded-[1.25rem] text-sm font-bold focus:ring-4 focus:ring-purple-500/10 focus:border-purple-500/50 outline-none transition-all placeholder:text-slate-300" placeholder="输入知识库内容作为生成依据..." rows={4} />
<label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1 ml-1 flex items-center gap-2"><FileText size={12} className="text-purple-500" /> {t('knowledgeBaseContentOptional')}</label>
<textarea value={generateForm.knowledgeBaseContent} onChange={(e) => setGenerateForm({ ...generateForm, knowledgeBaseContent: e.target.value })}
className="w-full px-5 py-4 bg-slate-50 border border-slate-200 rounded-[1.25rem] text-sm font-bold focus:ring-4 focus:ring-purple-500/10 focus:border-purple-500/50 outline-none transition-all placeholder:text-slate-300"
placeholder={t('knowledgeBaseContentOptional')} rows={4} />
</div>
<div className="flex gap-3 pt-4">
<button onClick={() => setShowGenerate(false)} className="flex-1 px-6 py-4 text-sm font-black text-slate-500 hover:text-slate-700 transition-colors"></button>
<button onClick={() => setShowGenerate(false)} className="flex-1 px-6 py-4 text-sm font-black text-slate-500 hover:text-slate-700 transition-colors">{t('cancel')}</button>
<button onClick={handleGenerate} disabled={generating}
className="flex-1 px-6 py-4 bg-purple-600 text-white rounded-[1.25rem] font-black uppercase tracking-widest text-xs shadow-xl shadow-purple-100 hover:bg-purple-700 transition-all active:scale-95 flex items-center justify-center gap-2">
{generating ? <><Loader2 size={16} className="animate-spin" /> ...</> : <><Sparkles size={16} /> </>}</button>
{generating ? <><Loader2 size={16} className="animate-spin" /> {t('generating')}</> : <><Sparkles size={16} /> {t('generate')}</>}</button>
</div>
</div>
</motion.div>
@@ -393,4 +526,4 @@ export default function QuestionBankDetailView() {
)}
</div>
);
}
}
+275 -179
View File
@@ -1,16 +1,19 @@
import React, { useState, useEffect } from 'react';
import React, { useState, useEffect, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { Plus, BookOpen, ChevronRight, Trash2, Edit2 } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { BookOpen, FileText, Layers, Loader2, Plus, Search, Trash2, Edit2, AlertCircle, Check, Clock, XCircle } from 'lucide-react';
import { apiClient } from '../../services/apiClient';
import { templateService } from '../../services/templateService';
import { questionBankService } from '../../services/questionBankService';
import { AssessmentTemplate } from '../../types';
import { useToast } from '../../contexts/ToastContext';
import { useConfirm } from '../../contexts/ConfirmContext';
import { useLanguage } from '../../contexts/LanguageContext';
interface QuestionBankViewProps {
isAdmin?: boolean;
}
interface QuestionBank {
interface QuestionBankItem {
id: string;
name: string;
description?: string;
@@ -19,25 +22,27 @@ interface QuestionBank {
createdAt: string;
}
export default function QuestionBankView({ isAdmin }: QuestionBankViewProps) {
type StatusFilter = 'ALL' | 'DRAFT' | 'PENDING_REVIEW' | 'PUBLISHED';
export default function QuestionBankView({ isAdmin: _isAdmin }: QuestionBankViewProps) {
const navigate = useNavigate();
const [banks, setBanks] = useState<QuestionBank[]>([]);
const { t } = useLanguage();
const { showSuccess, showError } = useToast();
const { confirm } = useConfirm();
const [banks, setBanks] = useState<QuestionBankItem[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [showDrawer, setShowDrawer] = useState(false);
const [formData, setFormData] = useState({
name: '',
description: '',
templateId: ''
});
const [formData, setFormData] = useState({ name: '', description: '', templateId: '' });
const [saving, setSaving] = useState(false);
const [templates, setTemplates] = useState<AssessmentTemplate[]>([]);
const [loadingTemplates, setLoadingTemplates] = useState(false);
const [deletingId, setDeletingId] = useState<string | null>(null);
const [statusFilter, setStatusFilter] = useState<StatusFilter>('ALL');
const [searchQuery, setSearchQuery] = useState('');
useEffect(() => {
fetchData();
}, []);
useEffect(() => { fetchData(); }, []);
const fetchData = async () => {
try {
@@ -47,7 +52,8 @@ export default function QuestionBankView({ isAdmin }: QuestionBankViewProps) {
const data = await res.json();
setBanks(Array.isArray(data) ? data : (data.data || []));
} catch (err: any) {
setError(err.message || '加载失败');
setError(err.message || t('actionFailed'));
showError(err.message || t('actionFailed'));
} finally {
setLoading(false);
}
@@ -58,7 +64,7 @@ export default function QuestionBankView({ isAdmin }: QuestionBankViewProps) {
setLoadingTemplates(true);
templateService.getAll()
.then(data => setTemplates(data))
.catch(err => console.error('加载模板失败:', err))
.catch(() => showError(t('actionFailed')))
.finally(() => setLoadingTemplates(false));
setShowDrawer(true);
};
@@ -66,17 +72,10 @@ export default function QuestionBankView({ isAdmin }: QuestionBankViewProps) {
const handleCreate = async (e: React.FormEvent) => {
e.preventDefault();
if (!formData.name.trim()) return;
setSaving(true);
try {
const payload: any = {
name: formData.name,
description: formData.description,
};
if (formData.templateId) {
payload.templateId = formData.templateId;
}
const payload: any = { name: formData.name, description: formData.description };
if (formData.templateId) payload.templateId = formData.templateId;
const res = await apiClient.request('/question-banks', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
@@ -88,12 +87,11 @@ export default function QuestionBankView({ isAdmin }: QuestionBankViewProps) {
try { const parsed = JSON.parse(errBody); if (parsed.message) msg = parsed.message; } catch {}
throw new Error(msg);
}
setShowDrawer(false);
showSuccess(t('questionBankCreated'));
fetchData();
} catch (err: any) {
console.error('创建失败:', err);
alert('创建失败: ' + (err.message || '未知错误'));
showError(err.message || t('actionFailed'));
} finally {
setSaving(false);
}
@@ -101,182 +99,280 @@ export default function QuestionBankView({ isAdmin }: QuestionBankViewProps) {
const handleDelete = async (e: React.MouseEvent, bankId: string, bankName: string) => {
e.stopPropagation();
if (!confirm(`确定要删除题库"${bankName}"吗?此操作不可恢复。`)) return;
const ok = await confirm({ message: t('confirmDeleteBank').replace('$1', bankName), confirmLabel: t('delete'), cancelLabel: t('cancel') });
if (!ok) return;
setDeletingId(bankId);
try {
await questionBankService.deleteBank(bankId);
const res = await apiClient.request(`/question-banks/${bankId}`, { method: 'DELETE' });
if (!res.ok) {
const errBody = await res.text().catch(() => '');
let msg = res.status.toString();
try { const parsed = JSON.parse(errBody); if (parsed.message) msg = parsed.message; } catch {}
throw new Error(msg);
}
showSuccess(t('confirm'));
fetchData();
} catch (err: any) {
console.error('删除失败:', err);
alert('删除失败: ' + (err.message || '未知错误'));
showError(err.message || t('questionBankDeleteFailed'));
} finally {
setDeletingId(null);
}
};
const handleCardClick = (bank: QuestionBank) => {
const handleCardClick = (bank: QuestionBankItem) => {
navigate(`/question-banks/${bank.id}`);
};
const filteredBanks = useMemo(() => {
let result = banks;
if (statusFilter !== 'ALL') result = result.filter(b => b.status === statusFilter);
if (searchQuery.trim()) {
const q = searchQuery.toLowerCase();
result = result.filter(b => b.name.toLowerCase().includes(q) || (b.description || '').toLowerCase().includes(q));
}
return result;
}, [banks, statusFilter, searchQuery]);
const STATUS_TABS: { key: StatusFilter; label: string; icon: React.ReactNode; count: (b: QuestionBankItem[]) => number }[] = [
{ key: 'ALL', label: t('all'), icon: <Layers size={14} />, count: (b) => b.length },
{ key: 'PUBLISHED', label: t('published'), icon: <Check size={14} />, count: (b) => b.filter(i => i.status === 'PUBLISHED').length },
{ key: 'DRAFT', label: t('draft'), icon: <FileText size={14} />, count: (b) => b.filter(i => i.status === 'DRAFT').length },
{ key: 'PENDING_REVIEW', label: t('pendingReview'), icon: <Clock size={14} />, count: (b) => b.filter(i => i.status === 'PENDING_REVIEW').length },
];
const stats = useMemo(() => ({
total: banks.length,
published: banks.filter(b => b.status === 'PUBLISHED').length,
draft: banks.filter(b => b.status === 'DRAFT').length,
pending: banks.filter(b => b.status === 'PENDING_REVIEW').length,
}), [banks]);
const statusLabels: Record<string, string> = {
PUBLISHED: t('published'),
PENDING_REVIEW: t('pendingReview'),
REJECTED: t('rejected'),
DRAFT: t('draft'),
};
return (
<div className="p-6 bg-white min-h-screen">
<div className="flex items-center justify-between mb-6">
<h1 className="text-2xl font-bold"></h1>
<button
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-black text-slate-900">{t('questionBankManagement')}</h1>
<p className="text-sm text-slate-500 mt-1">{t('questionBankManagementDesc')}</p>
</div>
<button
onClick={openDrawer}
className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
className="px-5 py-3 bg-blue-600 text-white rounded-2xl text-sm font-black uppercase tracking-widest flex items-center gap-2 shadow-lg shadow-blue-600/20 hover:bg-blue-700 transition-all active:scale-[0.98]"
>
<Plus size={18} />
<span></span>
{t('createQuestionBank')}
</button>
</div>
{loading ? (
<div className="text-center py-8 text-gray-500">...</div>
) : error ? (
<div className="text-center py-8 text-red-500">: {error}</div>
) : banks.length === 0 ? (
<div className="text-center py-8 text-gray-500">
<BookOpen size={48} className="mx-auto mb-4 text-gray-300" />
<p></p>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{banks.map((bank) => (
<div
key={bank.id}
className="border rounded-lg p-4 hover:shadow-md transition-shadow cursor-pointer group relative"
onClick={() => handleCardClick(bank)}
>
<div className="absolute top-3 right-3 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
<button
onClick={(e) => { e.stopPropagation(); handleCardClick(bank); }}
className="p-1.5 text-gray-400 hover:text-blue-600 rounded-md bg-white border shadow-sm"
title="编辑"
>
<Edit2 size={14} />
</button>
<button
onClick={(e) => handleDelete(e, bank.id, bank.name)}
disabled={deletingId === bank.id}
className="p-1.5 text-gray-400 hover:text-red-600 rounded-md bg-white border shadow-sm disabled:opacity-50"
title="删除"
>
{deletingId === bank.id ? (
<span className="w-3.5 h-3.5 border-2 border-red-500 border-t-transparent rounded-full animate-spin block"></span>
) : (
<Trash2 size={14} />
)}
</button>
{!loading && !error && banks.length > 0 && (
<div className="grid grid-cols-4 gap-4">
{[
{ label: t('totalBanks'), value: stats.total, color: 'bg-slate-50 border-slate-200 text-slate-700', icon: <Layers size={16} className="text-slate-500" /> },
{ label: t('published'), value: stats.published, color: 'bg-emerald-50 border-emerald-200/50 text-emerald-700', icon: <Check size={16} className="text-emerald-500" /> },
{ label: t('draft'), value: stats.draft, color: 'bg-slate-50 border-slate-200 text-slate-700', icon: <FileText size={16} className="text-slate-500" /> },
{ label: t('pendingReview'), value: stats.pending, color: 'bg-amber-50 border-amber-200/50 text-amber-700', icon: <Clock size={16} className="text-amber-500" /> },
].map((stat, i) => (
<motion.div key={stat.label} initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: i * 0.05 }}
className={`${stat.color} rounded-2xl border p-4`}>
<div className="flex items-center justify-between mb-1">
<span className="text-[10px] font-black uppercase tracking-widest opacity-70">{stat.label}</span>
{stat.icon}
</div>
<h3 className="font-semibold pr-16">{bank.name}</h3>
<p className="text-sm text-gray-500 mt-1">{bank.description || '暂无描述'}</p>
<div className="flex items-center justify-between mt-3 pt-3 border-t">
<span className={`text-xs px-2 py-0.5 rounded-full ${
bank.status === 'PUBLISHED' ? 'bg-green-100 text-green-700' :
bank.status === 'PENDING_REVIEW' ? 'bg-yellow-100 text-yellow-700' :
bank.status === 'REJECTED' ? 'bg-red-100 text-red-700' :
'bg-gray-100 text-gray-600'
}`}>
{bank.status === 'PUBLISHED' ? '已发布' :
bank.status === 'PENDING_REVIEW' ? '待审核' :
bank.status === 'REJECTED' ? '已否决' : '草稿'}
</span>
<span className="text-xs text-gray-400">
{new Date(bank.createdAt).toLocaleDateString()}
</span>
</div>
</div>
<div className="text-2xl font-black">{stat.value}</div>
</motion.div>
))}
</div>
)}
{/* Drawer */}
<>
{showDrawer && (
<div
className="fixed inset-0 bg-black/20 backdrop-blur-sm z-40 transition-opacity duration-300"
onClick={() => setShowDrawer(false)}
/>
)}
<div
className={`fixed right-0 top-0 h-full w-full max-w-md bg-white shadow-2xl z-50 transform transition-transform duration-300 ease-out ${showDrawer ? 'translate-x-0' : 'translate-x-full'}`}
>
<div className="flex flex-col h-full">
<div className="flex items-center justify-between px-6 py-4 border-b bg-slate-50">
<h2 className="text-xl font-semibold text-slate-800 flex items-center gap-2">
<Plus className="w-6 h-6 text-blue-600" />
</h2>
<button
onClick={() => setShowDrawer(false)}
className="p-2 text-slate-400 hover:text-slate-600 hover:bg-slate-200 rounded-full transition-colors"
>
<ChevronRight size={24} />
</button>
</div>
<div className="flex-1 overflow-y-auto p-6">
<form id="create-form" onSubmit={handleCreate} className="space-y-6">
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">
<span className="text-red-500">*</span>
</label>
<input
type="text"
value={formData.name}
onChange={(e) => setFormData({...formData, name: e.target.value})}
className="w-full px-4 py-3 border rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 bg-slate-50"
placeholder="输入题库名称"
required
autoFocus
/>
</div>
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">
</label>
<input
type="text"
value={formData.description}
onChange={(e) => setFormData({...formData, description: e.target.value})}
className="w-full px-4 py-3 border rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 bg-slate-50"
placeholder="输入描述"
/>
</div>
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">
</label>
<select
value={formData.templateId}
onChange={(e) => setFormData({...formData, templateId: e.target.value})}
className="w-full px-4 py-3 border rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 bg-slate-50"
disabled={loadingTemplates}
>
<option value=""></option>
{templates.map(t => (
<option key={t.id} value={t.id}>{t.name}</option>
))}
</select>
{loadingTemplates && <span className="text-xs text-slate-500">...</span>}
</div>
</form>
</div>
<div className="p-6 border-t bg-slate-50">
<button
type="submit"
form="create-form"
disabled={saving || !formData.name.trim()}
className="w-full flex items-center justify-center gap-2 px-6 py-3 bg-blue-600 text-white font-medium rounded-xl hover:bg-blue-700 active:scale-[0.98] transition-all disabled:opacity-50 disabled:cursor-not-allowed shadow-lg shadow-blue-600/20"
>
<Plus size={20} />
{saving ? '创建中...' : '创建'}
</button>
</div>
{!loading && !error && banks.length > 0 && (
<div className="flex items-center gap-4">
<div className="relative flex-1 max-w-sm">
<Search size={16} className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400" />
<input
type="text"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder={t('searchQuestionBanksPlaceholder')}
className="w-full pl-10 pr-4 py-3 bg-slate-50 border border-slate-200 rounded-2xl text-sm font-bold focus:ring-4 focus:ring-blue-500/10 focus:border-blue-500/50 outline-none transition-all placeholder:text-slate-300"
/>
</div>
<div className="flex gap-1 bg-slate-50 rounded-2xl p-1 border border-slate-200">
{STATUS_TABS.map((tab) => {
const active = statusFilter === tab.key;
return (
<button
key={tab.key}
onClick={() => setStatusFilter(tab.key)}
className={`flex items-center gap-1.5 px-4 py-2 rounded-xl text-xs font-bold transition-all ${
active
? 'bg-white text-slate-900 shadow-sm border border-slate-200/50'
: 'text-slate-500 hover:text-slate-700'
}`}
>
{tab.icon}
{tab.label}
<span className={`${active ? 'bg-slate-100 text-slate-600' : 'bg-white/50 text-slate-400'} px-1.5 py-0.5 rounded-lg text-[10px] font-black`}>
{tab.count(banks)}
</span>
</button>
);
})}
</div>
</div>
</>
)}
{loading ? (
<div className="flex items-center justify-center py-20">
<Loader2 className="w-8 h-8 animate-spin text-blue-600 opacity-20" />
</div>
) : error ? (
<div className="flex items-center gap-3 text-red-500 bg-red-50 rounded-2xl p-6 border border-red-100">
<AlertCircle size={20} />
<span className="text-sm font-bold">{t('actionFailed')}</span>
<button onClick={fetchData} className="ml-auto text-xs font-black text-red-600 hover:text-red-700 uppercase tracking-widest">{t('retry')}</button>
</div>
) : banks.length === 0 ? (
<div className="bg-slate-50 rounded-[2rem] border-2 border-dashed border-slate-200 p-20 text-center">
<div className="w-16 h-16 bg-slate-100 rounded-3xl flex items-center justify-center mx-auto mb-6">
<BookOpen size={32} className="text-slate-300" />
</div>
<p className="text-slate-400 font-black uppercase tracking-widest text-xs mb-2">{t('noQuestionBanks')}</p>
<p className="text-slate-300 text-xs mb-6">{t('createFirstBank')}</p>
<button onClick={openDrawer} className="inline-flex items-center gap-2 px-6 py-3 bg-blue-600 text-white rounded-2xl text-sm font-black uppercase tracking-widest hover:bg-blue-700 transition-all active:scale-[0.98] shadow-lg shadow-blue-600/20">
<Plus size={18} /> {t('createQuestionBank')}
</button>
</div>
) : filteredBanks.length === 0 ? (
<div className="bg-slate-50 rounded-[2rem] border-2 border-dashed border-slate-200 p-20 text-center">
<Search size={32} className="text-slate-300 mx-auto mb-4" />
<p className="text-slate-400 font-bold text-xs uppercase tracking-widest">{t('noMatchingQuestionBanks')}</p>
<p className="text-slate-300 text-xs mt-2">{t('tryChangingFilter')}</p>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
<AnimatePresence mode="popLayout">
{filteredBanks.map((bank) => (
<motion.div
key={bank.id}
layout
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.95 }}
onClick={() => handleCardClick(bank)}
className="bg-white border border-slate-200 rounded-3xl p-5 shadow-sm hover:shadow-md transition-all cursor-pointer group relative overflow-hidden"
>
<div className={`absolute top-0 right-0 w-32 h-32 rounded-full blur-3xl -mr-16 -mt-16 ${
bank.status === 'PUBLISHED' ? 'bg-emerald-500/5' :
bank.status === 'PENDING_REVIEW' ? 'bg-amber-500/5' :
bank.status === 'REJECTED' ? 'bg-red-500/5' : 'bg-blue-500/5'
}`} />
<div className="relative z-10">
<div className="flex items-start justify-between mb-3">
<h3 className="font-black text-base text-slate-900 pr-8 line-clamp-1">{bank.name}</h3>
<div className="flex gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity absolute top-0 right-0">
<button onClick={(e) => { e.stopPropagation(); handleCardClick(bank); }}
className="p-1.5 text-slate-400 hover:text-blue-600 hover:bg-blue-50 rounded-xl transition-all" title={t('edit')}>
<Edit2 size={13} />
</button>
<button onClick={(e) => handleDelete(e, bank.id, bank.name)} disabled={deletingId === bank.id}
className="p-1.5 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded-xl transition-all disabled:opacity-50" title={t('delete')}>
{deletingId === bank.id ? <Loader2 size={13} className="animate-spin" /> : <Trash2 size={13} />}
</button>
</div>
</div>
<p className="text-xs text-slate-500 mb-4 line-clamp-2 h-8">{bank.description || t('noDescription')}</p>
<div className="flex items-center justify-between pt-3 border-t border-slate-50">
<span className={`px-2.5 py-1 text-[10px] font-black uppercase tracking-widest rounded-full border ${
bank.status === 'PUBLISHED' ? 'bg-emerald-50 text-emerald-600 border-emerald-200/50' :
bank.status === 'PENDING_REVIEW' ? 'bg-amber-50 text-amber-600 border-amber-200/50' :
bank.status === 'REJECTED' ? 'bg-red-50 text-red-500 border-red-200/50' :
'bg-slate-50 text-slate-500 border-slate-200/50'
}`}>
{statusLabels[bank.status] || bank.status}
</span>
<span className="text-[10px] text-slate-400 font-medium">
{new Date(bank.createdAt).toLocaleDateString('zh-CN')}
</span>
</div>
</div>
</motion.div>
))}
</AnimatePresence>
</div>
)}
<AnimatePresence>
{showDrawer && (
<>
<motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
onClick={() => setShowDrawer(false)} className="fixed inset-0 bg-slate-900/40 backdrop-blur-sm z-40" />
<motion.div initial={{ x: '100%' }} animate={{ x: 0 }} exit={{ x: '100%' }}
transition={{ type: 'spring', damping: 25, stiffness: 200 }}
className="fixed right-0 top-0 h-full w-full max-w-md bg-white shadow-2xl z-50 flex flex-col">
<div className="flex items-center justify-between px-6 py-4 border-b border-slate-100">
<div className="flex items-center gap-3">
<div className="w-10 h-10 bg-blue-50 text-blue-600 rounded-2xl flex items-center justify-center"><Plus size={22} /></div>
<h2 className="text-lg font-black text-slate-900">{t('createQuestionBank')}</h2>
</div>
<button onClick={() => setShowDrawer(false)} className="p-2 text-slate-400 hover:text-slate-600 hover:bg-slate-50 rounded-xl transition-all"><XCircle size={22} /></button>
</div>
<div className="flex-1 overflow-y-auto p-6">
<form id="create-form" onSubmit={handleCreate} className="space-y-5">
<div className="space-y-1.5">
<label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1 ml-1 flex items-center gap-2">
<BookOpen size={12} className="text-blue-500" /> {t('name')} <span className="text-red-500">*</span>
</label>
<input type="text" value={formData.name} onChange={(e) => setFormData({ ...formData, name: e.target.value })}
className="w-full px-5 py-4 bg-slate-50 border border-slate-200 rounded-[1.25rem] text-sm font-bold focus:ring-4 focus:ring-blue-500/10 focus:border-blue-500/50 outline-none transition-all placeholder:text-slate-300"
placeholder={t('name')} required autoFocus />
</div>
<div className="space-y-1.5">
<label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1 ml-1 flex items-center gap-2">
<FileText size={12} className="text-blue-500" /> {t('description')}
</label>
<input type="text" value={formData.description} onChange={(e) => setFormData({ ...formData, description: e.target.value })}
className="w-full px-5 py-4 bg-slate-50 border border-slate-200 rounded-[1.25rem] text-sm font-bold focus:ring-4 focus:ring-blue-500/10 focus:border-blue-500/50 outline-none transition-all placeholder:text-slate-300"
placeholder={t('description')} />
</div>
<div className="space-y-1.5">
<label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1 ml-1 flex items-center gap-2">
<Layers size={12} className="text-blue-500" /> {t('linkTemplate')}
</label>
<select value={formData.templateId} onChange={(e) => setFormData({ ...formData, templateId: e.target.value })}
className="w-full px-5 py-4 bg-slate-50 border border-slate-200 rounded-[1.25rem] text-sm font-bold focus:ring-4 focus:ring-blue-500/10 focus:border-blue-500/50 outline-none transition-all cursor-pointer"
disabled={loadingTemplates}>
<option value="">{t('noTemplate')}</option>
{templates.map((t) => <option key={t.id} value={t.id}>{t.name}</option>)}
</select>
{loadingTemplates && (
<div className="flex items-center gap-2 px-2 py-1">
<Loader2 size={12} className="animate-spin text-slate-400" />
<span className="text-[10px] text-slate-400 font-medium">{t('loading')}</span>
</div>
)}
</div>
</form>
</div>
<div className="p-6 border-t border-slate-100">
<button type="submit" form="create-form" disabled={saving || !formData.name.trim()}
className="w-full flex items-center justify-center gap-2 px-6 py-4 bg-blue-600 text-white font-black uppercase tracking-widest text-xs rounded-[1.25rem] hover:bg-blue-700 active:scale-[0.98] transition-all disabled:opacity-50 disabled:cursor-not-allowed shadow-xl shadow-blue-100">
{saving ? <Loader2 size={18} className="animate-spin" /> : <Plus size={18} />}
{saving ? t('creating') : t('createQuestionBank')}
</button>
</div>
</motion.div>
</>
)}
</AnimatePresence>
</div>
);
}
}
+3
View File
@@ -26,6 +26,9 @@ export interface AssessmentState {
status?: 'IN_PROGRESS' | 'COMPLETED';
report?: string;
finalScore?: number;
passed?: boolean;
dimensionScores?: Record<string, number>;
radarData?: Record<string, number>;
}
export interface Certificate {
+6
View File
@@ -350,6 +350,9 @@ export interface AssessmentTemplate {
knowledgeGroupId?: string;
knowledgeGroup?: KnowledgeGroup;
dimensions?: AssessmentDimension[];
passingScore?: number;
totalTimeLimit?: number;
perQuestionTimeLimit?: number;
isActive: boolean;
version: number;
creatorId: string;
@@ -367,6 +370,9 @@ export interface CreateTemplateData {
knowledgeBaseId?: string;
knowledgeGroupId?: string;
dimensions?: AssessmentDimension[];
passingScore?: number;
totalTimeLimit?: number;
perQuestionTimeLimit?: number;
}
export interface UpdateTemplateData extends Partial<CreateTemplateData> {
+210
View File
@@ -834,6 +834,8 @@ export const translations = {
deleteAssessmentSuccess: "评测记录已成功删除",
deleteAssessmentFailed: '删除评估记录失败',
view: '查看',
exportAssessmentFailed: '导出评估报告失败',
cannotResumeInProgress: '此评估进行中,无法恢复查看',
// Plugins
pluginTitle: "插件中心",
@@ -939,6 +941,74 @@ export const translations = {
allFormats: "所有格式支持",
visualVision: "视觉识别",
releaseToIngest: "释放以注入",
// Question Bank Management
questionBankManagement: "题库管理",
questionBankManagementDesc: "管理和创建评测题库",
createQuestionBank: "创建题库",
searchQuestionBanksPlaceholder: "搜索题库名称或描述...",
noQuestionBanks: "暂无题库",
noMatchingQuestionBanks: "未找到匹配的题库",
createFirstBank: "点击上方按钮创建第一个题库",
totalBanks: "总题库",
pendingReview: "待审核",
rejected: "已否决",
draft: "草稿",
published: "已发布",
description: "描述",
linkTemplate: "关联模板",
noTemplate: "不选择模板",
tryChangingFilter: "尝试修改筛选条件",
// Question Bank Detail
backToBankList: "返回题库列表",
invalidBankId: "无效的题库ID",
questionList: "题目列表",
addQuestion: "添加题目",
noQuestions: "暂无题目",
noQuestionsDesc: "点击上方按钮添加或使用 AI 生成",
editQuestion: "编辑题目",
addQuestionTitle: "添加题目",
gradingPoints: "评分要点",
questionContent: "题目内容",
questionType: "题型",
shortAnswer: "简答题",
multipleChoice: "选择题",
trueFalse: "判断题",
advanced: "进阶",
specialist: "专家",
standard: "标准",
dimension: "维度",
basis: "依据:",
submitForReview: "提交审核",
approve: "审核通过",
republish: "重新发布",
aiGenerate: "AI生成",
aiGenerateTitle: "AI 生成题目",
generateCount: "生成数量",
knowledgeBaseContentOptional: "知识库内容(可选)",
generate: "生成",
generating: "生成中...",
// Question Bank Toasts
questionBankCreated: "题库已创建",
questionBankDeleteFailed: "删除失败",
questionAdded: "题目已添加",
questionUpdated: "题目已更新",
questionDeleted: "题目已删除",
bankSubmittedForReview: "题库已提交审核",
bankApproved: "题库已审核通过",
bankRepublished: "题库已重新发布",
questionApproved: "题目已通过审核",
questionReturned: "题目已退回",
generatedQuestions: "成功生成 $1 道题目",
// Question Bank Confirm
confirmDeleteBank: "确定要删除题库「$1」吗?此操作不可恢复。",
confirmDeleteQuestion: "确定要删除这道题目吗?",
confirmSubmitReview: "确定要提交审核吗?提交后将进入待审核状态。",
confirmApproveBank: "确定要审核通过此题库吗?",
confirmRepublishBank: "确定要重新发布此题库吗?",
},
en: {
aiCommandsError: "An error occurred",
@@ -1777,6 +1847,8 @@ export const translations = {
deleteAssessmentSuccess: "Assessment record deleted successfully",
deleteAssessmentFailed: 'Failed to delete assessment record',
view: 'View',
exportAssessmentFailed: 'Failed to export assessment report',
cannotResumeInProgress: 'Assessment in progress, cannot view',
// Plugins
pluginTitle: "Plugin Store",
@@ -1889,6 +1961,74 @@ export const translations = {
allFormats: "All Formats Supported",
visualVision: "Visual Recognition",
releaseToIngest: "Release to Ingest",
// Question Bank Management
questionBankManagement: "Question Bank Management",
questionBankManagementDesc: "Manage and create assessment question banks",
createQuestionBank: "Create Question Bank",
searchQuestionBanksPlaceholder: "Search bank name or description...",
noQuestionBanks: "No question banks",
noMatchingQuestionBanks: "No matching question banks found",
createFirstBank: "Click the button above to create your first bank",
totalBanks: "Total Banks",
pendingReview: "Pending Review",
rejected: "Rejected",
draft: "Draft",
published: "Published",
description: "Description",
linkTemplate: "Linked Template",
noTemplate: "No template",
tryChangingFilter: "Try changing the filter criteria",
// Question Bank Detail
backToBankList: "Back to Bank List",
invalidBankId: "Invalid question bank ID",
questionList: "Question List",
addQuestion: "Add Question",
noQuestions: "No questions",
noQuestionsDesc: "Click the button above to add or use AI to generate",
editQuestion: "Edit Question",
addQuestionTitle: "Add Question",
gradingPoints: "Scoring Points",
questionContent: "Question Content",
questionType: "Question Type",
shortAnswer: "Short Answer",
multipleChoice: "Multiple Choice",
trueFalse: "True/False",
advanced: "Advanced",
specialist: "Specialist",
standard: "Standard",
dimension: "Dimension",
basis: "Basis:",
submitForReview: "Submit for Review",
approve: "Approve",
republish: "Republish",
aiGenerate: "AI Generate",
aiGenerateTitle: "AI Generate Questions",
generateCount: "Generation Count",
knowledgeBaseContentOptional: "Knowledge Base Content (optional)",
generate: "Generate",
generating: "Generating...",
// Question Bank Toasts
questionBankCreated: "Question bank created",
questionBankDeleteFailed: "Delete failed",
questionAdded: "Question added",
questionUpdated: "Question updated",
questionDeleted: "Question deleted",
bankSubmittedForReview: "Bank submitted for review",
bankApproved: "Bank approved",
bankRepublished: "Bank republished",
questionApproved: "Question approved",
questionReturned: "Question returned",
generatedQuestions: "Successfully generated $1 questions",
// Question Bank Confirm
confirmDeleteBank: "Are you sure you want to delete \"$1\"? This cannot be undone.",
confirmDeleteQuestion: "Are you sure you want to delete this question?",
confirmSubmitReview: "Submit this bank for review? It will enter pending review status.",
confirmApproveBank: "Approve this question bank?",
confirmRepublishBank: "Republish this question bank?",
},
ja: {
aiCommandsError: "エラーが発生しました",
@@ -2722,6 +2862,8 @@ export const translations = {
deleteAssessmentSuccess: "評価記録が正常に削除されました",
deleteAssessmentFailed: 'アセスメント記録の削除に失敗しました',
view: '表示',
exportAssessmentFailed: '評価レポートのエクスポートに失敗しました',
cannotResumeInProgress: '評価進行中、表示できません',
// Plugins
pluginTitle: "プラグインストア",
@@ -2836,5 +2978,73 @@ export const translations = {
allFormats: "すべてのフォーマット対応",
visualVision: "視覚認識",
releaseToIngest: "離して取り込む",
// Question Bank Management
questionBankManagement: "問題バンク管理",
questionBankManagementDesc: "評価問題バンクの管理と作成",
createQuestionBank: "問題バンクを作成",
searchQuestionBanksPlaceholder: "バンク名または説明を検索...",
noQuestionBanks: "問題バンクがありません",
noMatchingQuestionBanks: "一致する問題バンクが見つかりません",
createFirstBank: "上のボタンをクリックして最初の問題バンクを作成",
totalBanks: "総バンク数",
pendingReview: "審査待ち",
rejected: "却下",
draft: "下書き",
published: "公開済み",
description: "説明",
linkTemplate: "関連テンプレート",
noTemplate: "テンプレートなし",
tryChangingFilter: "フィルター条件を変更してみてください",
// Question Bank Detail
backToBankList: "問題バンクリストに戻る",
invalidBankId: "無効な問題バンクID",
questionList: "問題リスト",
addQuestion: "問題を追加",
noQuestions: "問題がありません",
noQuestionsDesc: "上のボタンをクリックして追加するか、AIで生成してください",
editQuestion: "問題を編集",
addQuestionTitle: "問題を追加",
gradingPoints: "採点ポイント",
questionContent: "問題内容",
questionType: "問題タイプ",
shortAnswer: "記述式",
multipleChoice: "選択式",
trueFalse: "正誤式",
advanced: "上級",
specialist: "専門家",
standard: "標準",
dimension: "ディメンション",
basis: "根拠:",
submitForReview: "審査を依頼",
approve: "承認",
republish: "再公開",
aiGenerate: "AI生成",
aiGenerateTitle: "AI問題生成",
generateCount: "生成数",
knowledgeBaseContentOptional: "ナレッジベース内容(任意)",
generate: "生成",
generating: "生成中...",
// Question Bank Toasts
questionBankCreated: "問題バンクが作成されました",
questionBankDeleteFailed: "削除に失敗しました",
questionAdded: "問題が追加されました",
questionUpdated: "問題が更新されました",
questionDeleted: "問題が削除されました",
bankSubmittedForReview: "バンクが審査に提出されました",
bankApproved: "バンクが承認されました",
bankRepublished: "バンクが再公開されました",
questionApproved: "問題が承認されました",
questionReturned: "問題が差し戻されました",
generatedQuestions: "$1問の問題を生成しました",
// Question Bank Confirm
confirmDeleteBank: "「$1」を削除してもよろしいですか?この操作は元に戻せません。",
confirmDeleteQuestion: "この問題を削除してもよろしいですか?",
confirmSubmitReview: "審査に提出しますか?審査待ち状態になります。",
confirmApproveBank: "この問題バンクを承認しますか?",
confirmRepublishBank: "この問題バンクを再公開しますか?",
},
};