feat: add student learning report dashboard

This commit is contained in:
Codex
2026-06-30 00:30:38 +08:00
parent 3905e3cb77
commit 4a13715f29
8 changed files with 440 additions and 19 deletions

View File

@@ -3,17 +3,86 @@ import Taro from '@tarojs/taro';
import { Button, Input, Text, View } from '@tarojs/components';
import { logout } from '@/services/auth';
import { checkActivationCode, loadEntitlements, loadOrders, loadSvipPlans, redeemActivationCode, type OrderItem, type SvipPlan } from '@/services/commerce';
import { loadLeaderboard } from '@/services/learning';
import {
loadLeaderboard,
loadLearningStats,
loadLearningTrend,
loadPracticeHistory,
type LeaderboardItem,
type LearningStats,
type LearningTrendItem,
type PracticeHistoryItem,
} from '@/services/learning';
import { checkIn, loadBadges, loadExamCountdowns, loadProfile, type StudentProfile } from '@/services/profile';
import '../student.css';
function percent(value?: number | null) {
return `${Math.round((value || 0) * 100)}%`;
}
function shortDate(value?: string | null) {
if (!value) return '';
return value.slice(5, 10);
}
function dateText(value?: string | null) {
if (!value) return '暂无记录';
return value.slice(0, 10);
}
function practiceTitle(item: PracticeHistoryItem) {
return item.blueprintName || item.collectionName || item.contentNodeName || item.entryName || modeLabel(item.mode);
}
function modeLabel(mode?: string | null) {
const normalized = String(mode || '');
if (normalized === 'mock_exam') return '全真模拟';
if (normalized === 'random') return '随机练习';
if (normalized === 'wrong_review') return '错题复习';
if (normalized === 'favorites') return '收藏练习';
return '顺序练习';
}
function maxTrendAnswers(items: LearningTrendItem[]) {
return Math.max(1, ...items.map(item => item.answeredCount || 0));
}
function trendBucket(value: number, maxValue: number) {
if (value <= 0) return 'h-bucket-0';
const ratio = maxValue ? value / maxValue : 0;
const bucket = Math.max(1, Math.min(12, Math.ceil(ratio * 12)));
return `h-bucket-${bucket}`;
}
function progressBucket(value: number) {
const ratio = Math.max(0, Math.min(1, value || 0));
const bucket = Math.max(0, Math.min(10, Math.round(ratio * 10)));
return `w-bucket-${bucket}`;
}
function sessionStatusLabel(status?: string | null) {
if (status === 'active') return '进行中';
if (status === 'expired') return '已过期';
return '已完成';
}
function sessionStatusClass(status?: string | null) {
if (status === 'active') return 'warning';
if (status === 'expired') return 'danger';
return '';
}
export default function StudentProfilePage() {
const [profile, setProfile] = useState<StudentProfile | null>(null);
const [plans, setPlans] = useState<SvipPlan[]>([]);
const [orders, setOrders] = useState<OrderItem[]>([]);
const [badges, setBadges] = useState<Record<string, unknown>[]>([]);
const [countdowns, setCountdowns] = useState<Record<string, unknown>[]>([]);
const [leaderboard, setLeaderboard] = useState<Record<string, unknown>[]>([]);
const [leaderboard, setLeaderboard] = useState<LeaderboardItem[]>([]);
const [currentRank, setCurrentRank] = useState<LeaderboardItem | null>(null);
const [learningStats, setLearningStats] = useState<LearningStats | null>(null);
const [learningTrend, setLearningTrend] = useState<LearningTrendItem[]>([]);
const [practiceHistory, setPracticeHistory] = useState<PracticeHistoryItem[]>([]);
const [activationCode, setActivationCode] = useState('');
const [message, setMessage] = useState('');
const [error, setError] = useState('');
@@ -25,15 +94,32 @@ export default function StudentProfilePage() {
loadOrders().catch(() => ({ items: [] })),
loadBadges().catch(() => ({ items: [] })),
loadExamCountdowns().catch(() => ({ items: [] })),
loadLeaderboard('questions').catch(() => ({ items: [] })),
loadLeaderboard('questions').catch(() => ({ items: [], currentUser: null })),
loadLearningStats(30).catch(() => ({ item: undefined })),
loadLearningTrend(14).catch(() => ({ items: [] })),
loadPracticeHistory({ limit: 6 }).catch(() => ({ items: [] })),
loadEntitlements().catch(() => ({ summary: {} })),
]).then(([profilePayload, planPayload, orderPayload, badgePayload, countdownPayload, leaderboardPayload]) => {
]).then(([
profilePayload,
planPayload,
orderPayload,
badgePayload,
countdownPayload,
leaderboardPayload,
statsPayload,
trendPayload,
historyPayload,
]) => {
setProfile(profilePayload.item || null);
setPlans(planPayload.items || []);
setOrders(orderPayload.items || []);
setBadges(badgePayload.items || []);
setCountdowns(countdownPayload.items || []);
setLeaderboard(leaderboardPayload.items || []);
setCurrentRank(leaderboardPayload.currentUser || null);
setLearningStats(statsPayload.item || null);
setLearningTrend(trendPayload.items || []);
setPracticeHistory(historyPayload.items || []);
}).catch(nextError => setError(nextError instanceof Error ? nextError.message : '个人中心加载失败'));
}
@@ -68,6 +154,14 @@ export default function StudentProfilePage() {
Taro.redirectTo({ url: '/pages/student/login/index' });
}
const maxAnswers = maxTrendAnswers(learningTrend);
const answerStats = learningStats?.answers;
const reportStats = learningStats?.reports;
const wrongBook = learningStats?.wrongBook;
const favoriteStats = learningStats?.favorites;
const questionTypes = learningStats?.questionTypes || [];
const bestPlan = plans[0];
return (
<View className='student-page'>
<View className='student-topbar'>
@@ -80,10 +174,104 @@ export default function StudentProfilePage() {
</View>
<View className='grid-two'>
<View className='metric'><Text className='metric-value'>{String((profile?.stats?.answers as Record<string, unknown> | undefined)?.totalAnswered ?? 0)}</Text><Text className='metric-label'></Text></View>
<View className='metric'><Text className='metric-value'>{String(answerStats?.totalAnswered ?? (profile?.stats?.answers as Record<string, unknown> | undefined)?.totalAnswered ?? 0)}</Text><Text className='metric-label'></Text></View>
<View className='metric'><Text className='metric-value'>{String((profile?.stats?.vocabulary as Record<string, unknown> | undefined)?.masteredWords ?? 0)}</Text><Text className='metric-label'></Text></View>
</View>
<View className='section-block'>
<Text className='section-heading'></Text>
<View className='report-panel learning-report-panel'>
<View className='grid-two'>
<View className='metric compact-metric'>
<Text className='metric-value'>{percent(answerStats?.accuracy)}</Text>
<Text className='metric-label'></Text>
</View>
<View className='metric compact-metric'>
<Text className='metric-value'>{String(answerStats?.todayAnswered ?? 0)}</Text>
<Text className='metric-label'></Text>
</View>
<View className='metric compact-metric'>
<Text className='metric-value'>{String(wrongBook?.unresolvedWrong ?? 0)}</Text>
<Text className='metric-label'></Text>
</View>
<View className='metric compact-metric'>
<Text className='metric-value'>{String(reportStats?.bestScore ?? 0)}</Text>
<Text className='metric-label'>/</Text>
</View>
</View>
<Text className='row-meta report-summary-line'>
{String(learningStats?.windowDays || 30)} · {dateText(answerStats?.latestAnsweredAt)} · {String(reportStats?.reportCount || 0)}
</Text>
</View>
</View>
<View className='section-block'>
<Text className='section-heading'>14 </Text>
{learningTrend.length ? (
<View className='trend-chart'>
{learningTrend.map(item => {
return (
<View className='trend-column' key={item.date}>
<Text className='trend-value'>{String(item.answeredCount || 0)}</Text>
<View className='trend-bar-track'>
<View className={`trend-bar-fill ${trendBucket(item.answeredCount || 0, maxAnswers)}`} />
</View>
<Text className='trend-label'>{shortDate(item.date)}</Text>
</View>
);
})}
</View>
) : <View className='empty-state'></View>}
</View>
<View className='section-block'>
<Text className='section-heading'></Text>
{questionTypes.length ? (
<View className='list-stack'>
{questionTypes.slice(0, 6).map(item => (
<View className='list-row' key={item.questionType}>
<View className='split-row'>
<Text className='row-main'>{item.typeLabel || item.questionType}</Text>
<Text className='status-badge'>{percent(item.accuracy)}</Text>
</View>
<Text className='row-meta'> {String(item.answeredCount)} · {String(item.correctCount)} · {String(item.wrongCount)}</Text>
<View className='progress-track'>
<View className={`progress-fill ${progressBucket(item.accuracy)}`} />
</View>
</View>
))}
</View>
) : <View className='empty-state'></View>}
</View>
<View className='section-block'>
<Text className='section-heading'></Text>
{practiceHistory.length ? (
<View className='list-stack'>
{practiceHistory.map(item => (
<View className='list-row' key={item.id}>
<View className='split-row'>
<Text className='row-main'>{practiceTitle(item)}</Text>
<Text className={`status-badge ${sessionStatusClass(item.status)}`}>{sessionStatusLabel(item.status)}</Text>
</View>
<Text className='row-meta'>
{modeLabel(item.mode)} · {String(item.answeredCount || 0)} / {String(item.questionCount || 0)} · {percent(item.accuracy)}
</Text>
<Text className='row-meta'> {dateText(item.startedAt)}{item.submittedAt ? ` · 交卷 ${dateText(item.submittedAt)}` : ''}</Text>
<View className='toolbar compact-toolbar'>
{item.status === 'active' ? (
<Button className='primary-button' onClick={() => Taro.navigateTo({ url: `/pages/student/practice/index?practiceSessionId=${item.id}` })}></Button>
) : null}
{item.reportId ? (
<Button className='secondary-button' onClick={() => Taro.navigateTo({ url: `/pages/student/reports/index?practiceSessionId=${item.id}` })}></Button>
) : null}
</View>
</View>
))}
</View>
) : <View className='empty-state'></View>}
</View>
<View className='section-block'>
<Text className='section-heading'></Text>
<View className='list-stack'>
@@ -117,7 +305,7 @@ export default function StudentProfilePage() {
))}
</View>
<View className='toolbar wrap'>
<Button className='primary-button' onClick={() => Taro.navigateTo({ url: `/pages/student/checkout/index${profile?.target?.regionId ? `?regionId=${encodeURIComponent(profile.target.regionId)}` : ''}` })}></Button>
<Button className='primary-button' onClick={() => Taro.navigateTo({ url: `/pages/student/checkout/index${bestPlan?.id ? `?planId=${encodeURIComponent(bestPlan.id)}` : profile?.target?.regionId ? `?regionId=${encodeURIComponent(profile.target.regionId)}` : ''}` })}></Button>
</View>
</View>
@@ -142,14 +330,16 @@ export default function StudentProfilePage() {
</View>
<View className='section-block'>
<Text className='section-heading'></Text>
<Text className='section-heading'></Text>
<View className='toolbar'>
<Button className='primary-button' onClick={handleCheckIn}></Button>
<Button className='secondary-button' onClick={() => Taro.navigateTo({ url: '/pages/student/catalog/index' })}></Button>
</View>
<View className='grid-two'>
<View className='metric'><Text className='metric-value'>{String(badges.length)}</Text><Text className='metric-label'></Text></View>
<View className='metric'><Text className='metric-value'>{String(leaderboard.length)}</Text><Text className='metric-label'></Text></View>
<View className='metric'><Text className='metric-value'>{currentRank ? `${String(currentRank.rank)}` : String(leaderboard.length)}</Text><Text className='metric-label'>{currentRank ? `7 日答题榜 · ${String(currentRank.value)}` : '排行榜样本'}</Text></View>
<View className='metric'><Text className='metric-value'>{String(favoriteStats?.favoriteQuestions ?? 0)}</Text><Text className='metric-label'></Text></View>
<View className='metric'><Text className='metric-value'>{percent(reportStats?.avgAccuracy)}</Text><Text className='metric-label'></Text></View>
</View>
</View>

View File

@@ -121,6 +121,10 @@
background: #eff6ff;
}
.learning-report-panel {
background: #f8fbff;
}
.list-stack {
display: flex;
flex-direction: column;
@@ -139,6 +143,18 @@
background: #eff6ff;
}
.split-row {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
}
.split-row .row-main {
flex: 1;
min-width: 0;
}
.composite-subquestion {
margin-top: 0;
}
@@ -219,6 +235,10 @@
background: #fff;
}
.compact-metric {
padding: 18px;
}
.metric-value {
display: block;
color: #0f172a;
@@ -233,6 +253,10 @@
font-size: 22px;
}
.report-summary-line {
margin-top: 18px;
}
.empty-state {
padding: 38px 26px;
border: 1px dashed #cbd5e1;
@@ -308,6 +332,19 @@
margin-top: 18px;
}
.compact-toolbar {
margin-top: 14px;
padding-bottom: 0;
}
.compact-toolbar .primary-button,
.compact-toolbar .secondary-button {
min-width: 104px;
height: 56px;
font-size: 22px;
line-height: 56px;
}
.amount-row {
display: flex;
align-items: center;
@@ -337,11 +374,107 @@
font-weight: 750;
}
.status-badge.warning {
background: #fffbeb;
color: #92400e;
}
.status-badge.danger {
background: #fff1f2;
color: #be123c;
}
.trend-chart {
display: grid;
grid-template-columns: repeat(14, minmax(0, 1fr));
gap: 10px;
align-items: end;
padding: 22px;
border: 1px solid #e2e8f0;
border-radius: 8px;
background: #fff;
}
.trend-column {
min-width: 0;
text-align: center;
}
.trend-value {
display: block;
min-height: 28px;
color: #334155;
font-size: 20px;
font-weight: 760;
line-height: 1.2;
}
.trend-bar-track {
display: flex;
align-items: flex-end;
justify-content: center;
height: 136px;
margin-top: 8px;
border-radius: 8px;
background: #f1f5f9;
}
.trend-bar-fill {
width: 100%;
max-width: 28px;
border-radius: 8px 8px 0 0;
background: #2563eb;
}
.trend-bar-fill.h-bucket-0 { height: 0; }
.trend-bar-fill.h-bucket-1 { height: 10px; }
.trend-bar-fill.h-bucket-2 { height: 20px; }
.trend-bar-fill.h-bucket-3 { height: 30px; }
.trend-bar-fill.h-bucket-4 { height: 40px; }
.trend-bar-fill.h-bucket-5 { height: 50px; }
.trend-bar-fill.h-bucket-6 { height: 62px; }
.trend-bar-fill.h-bucket-7 { height: 74px; }
.trend-bar-fill.h-bucket-8 { height: 86px; }
.trend-bar-fill.h-bucket-9 { height: 98px; }
.trend-bar-fill.h-bucket-10 { height: 110px; }
.trend-bar-fill.h-bucket-11 { height: 122px; }
.trend-bar-fill.h-bucket-12 { height: 132px; }
.trend-label {
display: block;
margin-top: 8px;
color: #64748b;
font-size: 18px;
line-height: 1.2;
}
.progress-track {
width: 100%;
height: 12px;
margin-top: 16px;
overflow: hidden;
border-radius: 999px;
background: #e2e8f0;
}
.progress-fill {
height: 100%;
border-radius: 999px;
background: #10b981;
}
.progress-fill.w-bucket-0 { width: 0; }
.progress-fill.w-bucket-1 { width: 10%; }
.progress-fill.w-bucket-2 { width: 20%; }
.progress-fill.w-bucket-3 { width: 30%; }
.progress-fill.w-bucket-4 { width: 40%; }
.progress-fill.w-bucket-5 { width: 50%; }
.progress-fill.w-bucket-6 { width: 60%; }
.progress-fill.w-bucket-7 { width: 70%; }
.progress-fill.w-bucket-8 { width: 80%; }
.progress-fill.w-bucket-9 { width: 90%; }
.progress-fill.w-bucket-10 { width: 100%; }
.handbook-entry-body {
margin-top: 14px;
}

View File

@@ -119,19 +119,24 @@ export interface PracticeReport {
export interface PracticeHistoryItem {
id: string;
mode: string;
blueprintName?: string | null;
collectionName?: string | null;
entryName?: string | null;
contentNodeName?: string | null;
questionCount?: number;
durationMinutes?: number | null;
accessMode?: string | null;
answeredCount?: number;
correctCount?: number;
wrongCount?: number;
status?: string;
reportId?: string | null;
score?: number | null;
reportTotalScore?: number | null;
accuracy?: number | null;
startedAt?: string;
finishedAt?: string | null;
submittedAt?: string | null;
}
export interface WrongQuestionReviewItem {
@@ -165,6 +170,86 @@ export interface VocabularyWord {
note?: string | null;
}
export interface LearningStats {
windowDays: number;
answers: {
totalAnswered: number;
correctCount: number;
wrongCount: number;
todayAnswered: number;
accuracy: number;
latestAnsweredAt?: string | null;
};
sessions: {
totalSessions: number;
activeSessions: number;
finishedSessions: number;
latestStartedAt?: string | null;
};
reports: {
reportCount: number;
avgAccuracy: number;
bestScore: number;
latestSubmittedAt?: string | null;
};
wrongBook: {
unresolvedWrong: number;
resolvedWrong: number;
totalWrongBook: number;
};
favorites: {
favoriteQuestions: number;
};
questionTypes: LearningQuestionTypeStats[];
}
export interface LearningQuestionTypeStats {
questionType: string;
typeLabel?: string | null;
answeredCount: number;
correctCount: number;
wrongCount: number;
accuracy: number;
}
export interface LearningTrendItem {
date: string;
answeredCount: number;
correctCount: number;
wrongCount: number;
accuracy: number;
sessionCount: number;
reportCount: number;
score: number;
totalScore: number;
}
export interface LeaderboardItem {
rank: number;
userId: string;
displayName: string;
avatarUrl?: string | null;
primaryRole?: string;
regionId?: string | null;
regionName?: string | null;
classIds?: string[];
classNames?: string[];
value: number;
secondaryValue?: number | null;
latestAt?: string | null;
isCurrentUser?: boolean;
}
export interface LeaderboardPayload {
metric: 'questions' | 'score' | 'vocabulary' | 'mock_exam';
label: string;
unit: string;
period: 'all' | '7d' | '30d';
items?: LeaderboardItem[];
currentUser?: LeaderboardItem | null;
generatedAt?: string;
}
export async function createPracticeSession(body: {
blueprintId?: string;
collectionId?: string;
@@ -252,16 +337,20 @@ export async function loadFavoriteQuestions(limit = 30) {
return apiRequest<{ items?: QuestionItem[] }>('/api/learning/favorites/questions', { query: { limit } });
}
export async function loadLearningStats() {
return apiRequest<{ item?: Record<string, unknown> }>('/api/learning/stats');
export async function loadLearningStats(days = 30) {
return apiRequest<{ item?: LearningStats }>('/api/learning/stats', { query: { days } });
}
export async function loadLeaderboard(metric: 'questions' | 'score' | 'vocabulary' | 'mock_exam' = 'questions') {
return apiRequest<{ items?: Record<string, unknown>[]; currentUserRank?: unknown }>('/api/learning/leaderboard', {
return apiRequest<LeaderboardPayload>('/api/learning/leaderboard', {
query: { metric, period: '7d', scope: 'tenant' },
});
}
export async function loadLearningTrend(days = 14) {
return apiRequest<{ items?: LearningTrendItem[] }>('/api/learning/trend', { query: { days } });
}
export async function loadVocabularyReviewPlan(unitId?: string) {
return apiRequest<{ item?: { words?: VocabularyWord[]; dueCount?: number; newCount?: number; totalPlanned?: number } }>(
'/api/learning/vocabulary/review-plan',