mirror of
https://github.com/margrop/wrong-notebook.git
synced 2026-12-05 08:19:51 +08:00
fix: 清空练习历史时重置错题掌握度
- 在同一事务内删除练习记录并重置已无剩余记录的错题掌握字段。 - 共享错题仍有其他成员记录时提交后重新评估,避免长期停留在虚假已掌握状态。 - 补充事务重置与共享错题重新评估的测试。 - Refs: https://github.com/margrop/wrong-notebook/issues/198
This commit is contained in:
@@ -43,6 +43,7 @@ import { GET as GENERATE_PRACTICE_GET, POST as GENERATE_PRACTICE_POST } from '@/
|
||||
import { GET as ANALYTICS } from '@/app/api/analytics/route';
|
||||
import { GET as PRACTICE_STATS } from '@/app/api/stats/practice/route';
|
||||
import { DELETE as CLEAR_ITEMS } from '@/app/api/error-items/clear/route';
|
||||
import { DELETE as CLEAR_PRACTICE_STATS } from '@/app/api/stats/practice/clear/route';
|
||||
|
||||
let database: PrismaClient;
|
||||
let directory: string;
|
||||
@@ -434,4 +435,48 @@ describe('错题本共享', () => {
|
||||
const stored = await database.errorItem.findUnique({ where: { id: item.id }, select: { questionText: true } });
|
||||
expect(['并发提交 A', '并发提交 B']).toContain(stored?.questionText);
|
||||
});
|
||||
|
||||
it('清空练习历史时重置无剩余记录的错题并重新评估仍有记录的共享错题', async () => {
|
||||
const { notebook, item } = await seedNotebook(alice.id);
|
||||
const sharedItem = await database.errorItem.create({
|
||||
data: {
|
||||
userId: alice.id,
|
||||
subjectId: notebook.id,
|
||||
questionText: '仍有成员记录的共享题',
|
||||
shortId: 'clear6',
|
||||
originalImageUrl: 'data:image/png;base64,AA==',
|
||||
},
|
||||
});
|
||||
await database.practiceRecord.createMany({
|
||||
data: [
|
||||
{ userId: alice.id, errorItemId: item.id, result: 'correct' },
|
||||
{ userId: bob.id, errorItemId: item.id, result: 'correct' },
|
||||
{ userId: alice.id, errorItemId: sharedItem.id, result: 'wrong' },
|
||||
],
|
||||
});
|
||||
await database.errorItem.updateMany({
|
||||
where: { id: { in: [item.id, sharedItem.id] } },
|
||||
data: { masteryLevel: 2, masteryProbability: 1, masteryReason: '已掌握', masterySource: 'rule' },
|
||||
});
|
||||
|
||||
signInAs(alice);
|
||||
const response = await CLEAR_PRACTICE_STATS();
|
||||
const body = await response.json();
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(body.count).toBe(2);
|
||||
// 共享题仍有 Bob 的记录:只重置 alice 独占的题,共享题交给后台重新评估
|
||||
expect(body.masteryResetCount).toBe(1);
|
||||
expect(mocks.scheduleMasteryEvaluation).toHaveBeenCalledWith([item.id]);
|
||||
expect(await database.practiceRecord.findMany({ where: { userId: alice.id } })).toHaveLength(0);
|
||||
expect(await database.practiceRecord.findMany({ where: { userId: bob.id } })).toHaveLength(1);
|
||||
expect(await database.errorItem.findUnique({
|
||||
where: { id: sharedItem.id },
|
||||
select: { masteryLevel: true, masteryProbability: true, masteryReason: true, masterySource: true, masteryEvaluatedAt: true },
|
||||
})).toEqual({ masteryLevel: 0, masteryProbability: null, masteryReason: null, masterySource: null, masteryEvaluatedAt: null });
|
||||
expect(await database.errorItem.findUnique({
|
||||
where: { id: item.id },
|
||||
select: { masteryLevel: true, masteryProbability: true, masteryReason: true, masterySource: true },
|
||||
})).toMatchObject({ masteryLevel: 2, masteryProbability: 1, masteryReason: '已掌握', masterySource: 'rule' });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -18,7 +18,9 @@ const mocks = vi.hoisted(() => ({
|
||||
},
|
||||
mockPrismaErrorItem: {
|
||||
deleteMany: vi.fn(),
|
||||
updateMany: vi.fn(),
|
||||
},
|
||||
scheduleMasteryEvaluation: vi.fn(),
|
||||
mockPrismaSubject: {
|
||||
findFirst: vi.fn(),
|
||||
},
|
||||
@@ -39,8 +41,15 @@ vi.mock('@/lib/prisma', () => ({
|
||||
practiceRecord: mocks.mockPrismaPracticeRecord,
|
||||
errorItem: mocks.mockPrismaErrorItem,
|
||||
subject: mocks.mockPrismaSubject,
|
||||
$transaction: vi.fn(async (callback: (client: unknown) => Promise<unknown>) => callback({
|
||||
practiceRecord: mocks.mockPrismaPracticeRecord,
|
||||
errorItem: mocks.mockPrismaErrorItem,
|
||||
})),
|
||||
},
|
||||
}));
|
||||
vi.mock('@/lib/mastery', () => ({
|
||||
scheduleMasteryEvaluation: mocks.scheduleMasteryEvaluation,
|
||||
}));
|
||||
|
||||
// Mock next-auth
|
||||
vi.mock('next-auth', () => ({
|
||||
@@ -73,6 +82,10 @@ describe('/api/stats', () => {
|
||||
name: 'Test User',
|
||||
masteryThreshold: 50,
|
||||
});
|
||||
// 清空练习历史:默认无受影响错题、无剩余记录
|
||||
mocks.mockPrismaPracticeRecord.findMany.mockResolvedValue([]);
|
||||
mocks.mockPrismaPracticeRecord.groupBy.mockResolvedValue([]);
|
||||
mocks.mockPrismaErrorItem.updateMany.mockResolvedValue({ count: 0 });
|
||||
});
|
||||
|
||||
describe('GET /api/stats/practice (获取练习统计)', () => {
|
||||
@@ -613,6 +626,53 @@ describe('/api/stats', () => {
|
||||
expect(data.count).toBe(50);
|
||||
});
|
||||
|
||||
it('清空后无剩余记录的错题重置掌握度', async () => {
|
||||
mocks.mockPrismaPracticeRecord.findMany.mockResolvedValue([
|
||||
{ errorItemId: 'e1' }, { errorItemId: 'e2' },
|
||||
]);
|
||||
mocks.mockPrismaPracticeRecord.deleteMany.mockResolvedValue({ count: 5 });
|
||||
mocks.mockPrismaPracticeRecord.groupBy.mockResolvedValue([]);
|
||||
|
||||
const response = await DELETE_PRACTICE_STATS();
|
||||
const data = await response.json();
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(data.count).toBe(5);
|
||||
expect(data.masteryResetCount).toBe(2);
|
||||
expect(mocks.mockPrismaErrorItem.updateMany).toHaveBeenCalledWith({
|
||||
where: { id: { in: ['e1', 'e2'] } },
|
||||
data: {
|
||||
masteryLevel: 0,
|
||||
masteryProbability: null,
|
||||
masteryReason: null,
|
||||
masterySource: null,
|
||||
masteryEvaluatedAt: null,
|
||||
},
|
||||
});
|
||||
expect(mocks.scheduleMasteryEvaluation).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('仍有其他成员练习记录时只重置空错题并重新评估其余错题', async () => {
|
||||
mocks.mockPrismaPracticeRecord.findMany.mockResolvedValue([
|
||||
{ errorItemId: 'e1' }, { errorItemId: 'e2' },
|
||||
]);
|
||||
mocks.mockPrismaPracticeRecord.deleteMany.mockResolvedValue({ count: 3 });
|
||||
mocks.mockPrismaPracticeRecord.groupBy.mockResolvedValue([
|
||||
{ errorItemId: 'e2', _count: { id: 2 } },
|
||||
]);
|
||||
|
||||
const response = await DELETE_PRACTICE_STATS();
|
||||
const data = await response.json();
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(data.masteryResetCount).toBe(1);
|
||||
expect(mocks.mockPrismaErrorItem.updateMany).toHaveBeenCalledWith({
|
||||
where: { id: { in: ['e1'] } },
|
||||
data: expect.objectContaining({ masteryLevel: 0 }),
|
||||
});
|
||||
expect(mocks.scheduleMasteryEvaluation).toHaveBeenCalledWith(['e2']);
|
||||
});
|
||||
|
||||
it('应该返回清除的记录数量', async () => {
|
||||
mocks.mockPrismaPracticeRecord.deleteMany.mockResolvedValue({ count: 100 });
|
||||
|
||||
|
||||
@@ -2,22 +2,69 @@ import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { internalError } from "@/lib/api-errors";
|
||||
import { createLogger } from "@/lib/logger";
|
||||
import { scheduleMasteryEvaluation } from "@/lib/mastery";
|
||||
import { withUser } from "@/lib/api-handler";
|
||||
import type { AuthenticatedContext } from "@/lib/api-handler";
|
||||
|
||||
const logger = createLogger('api:stats:practice:clear');
|
||||
|
||||
/**
|
||||
* 清空练习历史:删除当前用户的练习记录,并在同一事务内重置已无剩余记录的错题掌握度。
|
||||
* 共享错题仍有其他成员的练习记录时,事务提交后重新评估,避免掌握度停留在旧值。
|
||||
*/
|
||||
export const DELETE = withUser(async (_req: Request, { user }: AuthenticatedContext) => {
|
||||
const userId = user.id;
|
||||
|
||||
try {
|
||||
const result = await prisma.practiceRecord.deleteMany({
|
||||
where: { userId },
|
||||
// 先取受影响的错题 ID;删除后无法再从记录反查
|
||||
const affected = await prisma.practiceRecord.findMany({
|
||||
where: { userId, errorItemId: { not: null } },
|
||||
select: { errorItemId: true },
|
||||
distinct: ['errorItemId'],
|
||||
});
|
||||
const itemIds = affected.flatMap(({ errorItemId }) => errorItemId ? [errorItemId] : []);
|
||||
|
||||
const result = await prisma.$transaction(async (tx) => {
|
||||
const deleted = await tx.practiceRecord.deleteMany({
|
||||
where: { userId },
|
||||
});
|
||||
|
||||
if (itemIds.length === 0) {
|
||||
return { count: deleted.count, resetIds: [] as string[], reevaluateIds: [] as string[] };
|
||||
}
|
||||
|
||||
// 事务内复查剩余记录:无任何记录的重置为「待复习」,仍有记录的交给后台重新评估
|
||||
const remaining = await tx.practiceRecord.groupBy({
|
||||
by: ['errorItemId'],
|
||||
where: { errorItemId: { in: itemIds } },
|
||||
_count: { id: true },
|
||||
});
|
||||
const remainingIds = new Set(remaining.flatMap(({ errorItemId }) => errorItemId ? [errorItemId] : []));
|
||||
const resetIds = itemIds.filter((id) => !remainingIds.has(id));
|
||||
const reevaluateIds = itemIds.filter((id) => remainingIds.has(id));
|
||||
|
||||
if (resetIds.length > 0) {
|
||||
await tx.errorItem.updateMany({
|
||||
where: { id: { in: resetIds } },
|
||||
data: {
|
||||
masteryLevel: 0,
|
||||
masteryProbability: null,
|
||||
masteryReason: null,
|
||||
masterySource: null,
|
||||
masteryEvaluatedAt: null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return { count: deleted.count, resetIds, reevaluateIds };
|
||||
});
|
||||
|
||||
if (result.reevaluateIds.length > 0) scheduleMasteryEvaluation(result.reevaluateIds);
|
||||
|
||||
return NextResponse.json({
|
||||
message: "Practice history cleared successfully",
|
||||
count: result.count
|
||||
count: result.count,
|
||||
masteryResetCount: result.resetIds.length,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error({ error }, 'Error clearing practice stats');
|
||||
|
||||
Reference in New Issue
Block a user