fix: 只读与被移除共享成员不再改写他人错题掌握度

- Refs: https://github.com/margrop/wrong-notebook/issues/190
This commit is contained in:
margrop
2026-12-05 02:32:31 +08:00
parent 9cbb5f0641
commit c9598db1bf
12 changed files with 156 additions and 9 deletions

View File

@@ -12,6 +12,7 @@ const mocks = vi.hoisted(() => {
tx,
user: { findUnique: vi.fn() },
examPaper: { findUnique: vi.fn() },
errorItem: { findMany: vi.fn() },
practiceRecord: { findUnique: vi.fn(), update: vi.fn() },
transaction: vi.fn(async (arg: (client: typeof tx) => Promise<unknown>) => arg(tx)),
gradeExamAnswer: vi.fn(),
@@ -26,6 +27,7 @@ vi.mock('@/lib/prisma', () => ({
prisma: {
user: mocks.user,
examPaper: mocks.examPaper,
errorItem: mocks.errorItem,
practiceRecord: mocks.practiceRecord,
$transaction: mocks.transaction,
},
@@ -77,6 +79,9 @@ describe('/api/exams/:id/grade', () => {
mocks.gradeExamAnswer.mockResolvedValue({ verdict: 'correct', score: 80, comment: '解题完整', subResults: [] });
mocks.consumeAiQuota.mockResolvedValue(null);
mocks.tx.practiceRecord.create.mockResolvedValue({ id: 'record-1' });
// 掌握度触发前按 id 查询写权限;默认当前用户为各错题所有者
mocks.errorItem.findMany.mockImplementation(async ({ where }: { where: { id?: { in?: string[] } } }) =>
(where.id?.in ?? []).map((id) => ({ id, userId: 'user-1', subjectId: null })));
});
it('单题批改:写入判定、按分值换算得分与评语,并重新评估掌握概率', async () => {

View File

@@ -75,6 +75,9 @@ describe('/api/exams', () => {
mocks.user.findUnique.mockResolvedValue({ id: 'user-1' });
// 后台生成在测试中立即结束
mocks.examPaper.findUnique.mockResolvedValue(null);
// 掌握度触发前按 id 查询写权限;默认当前用户为各错题所有者
mocks.errorItem.findMany.mockImplementation(async ({ where }: { where: { id?: { in?: string[] } } }) =>
(where.id?.in ?? []).map((id) => ({ id, userId: 'user-1', subjectId: null })));
});
describe('POST 创建试卷', () => {

View File

@@ -694,6 +694,13 @@ describe('MCP 服务', () => {
select: { answerText: true, figureSvg: true, svgAnimation: true, geogebraCommands: true },
})).toMatchObject({ answerText: '42', figureSvg: null, svgAnimation: null, geogebraCommands: null });
// 只读成员可通过练习工具记录自己的作答,但错题掌握度不变
const masteryFields = { masteryProbability: true, masteryLevel: true, masterySource: true, masteryReason: true, masteryEvaluatedAt: true } as const;
const masteryBefore = await database.errorItem.findUnique({ where: { id: 'shared-item' }, select: masteryFields });
const recorded = await callTool('record_practice_result', { errorItemId: 'abc123', result: 'correct' });
expect(recorded.result?.isError).toBeFalsy();
expect(await database.errorItem.findUnique({ where: { id: 'shared-item' }, select: masteryFields })).toEqual(masteryBefore);
// 提升为可编辑成员后可以正常改写
await database.notebookShare.update({
where: { subjectId_memberId: { subjectId: 'shared-math', memberId: 'user-1' } },

View File

@@ -13,6 +13,7 @@ const mocks = vi.hoisted(() => ({
prisma: undefined as PrismaClient | undefined,
session: null as null | { user: { id: string; email: string; role: string }; expires: string },
logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },
scheduleMasteryEvaluation: vi.fn(),
}));
vi.mock('@/lib/prisma', () => ({ get prisma() { return mocks.prisma; } }));
@@ -23,7 +24,7 @@ vi.mock('@/lib/config', () => ({ getAppTimeZone: () => 'Asia/Shanghai' }));
vi.mock('@/lib/mastery', () => ({
PRACTICE_RESULTS: ['correct', 'wrong', 'not_attempted'],
getMasteryThreshold: vi.fn(async () => 50),
scheduleMasteryEvaluation: vi.fn(),
scheduleMasteryEvaluation: mocks.scheduleMasteryEvaluation,
}));
import { GET as LIST_NOTEBOOKS } from '@/app/api/notebooks/route';
@@ -36,6 +37,8 @@ import { POST as BATCH_DELETE } from '@/app/api/error-items/batch-delete/route';
import { POST as CREATE_EXAM } from '@/app/api/exams/route';
import { GET as REVIEW_DUE } from '@/app/api/review/due/route';
import { POST as RECORD_PRACTICE } from '@/app/api/practice/record/route';
import { PATCH as PATCH_PRACTICE_RECORD, DELETE as DELETE_PRACTICE_RECORD } from '@/app/api/practice/record/[id]/route';
import { POST as RECORD_EXAM_RESULTS } from '@/app/api/exams/[id]/results/route';
import { GET as GENERATE_PRACTICE_GET, POST as GENERATE_PRACTICE_POST } from '@/app/api/practice/generate/route';
import { GET as ANALYTICS } from '@/app/api/analytics/route';
import { GET as PRACTICE_STATS } from '@/app/api/stats/practice/route';
@@ -288,6 +291,61 @@ describe('错题本共享', () => {
expect((await GENERATE_PRACTICE_POST(new Request('http://localhost/api/practice/generate', json({ errorItemId: item.id, source: 'bank' })))).status).toBe(404);
});
it('只读与被移除成员改删练习记录、试卷录分不触发掌握度评估', async () => {
const { notebook, item } = await seedNotebook(alice.id);
signInAs(alice);
const invited = await (await INVITE(new Request(`http://localhost/api/notebooks/${notebook.id}/shares`, json({ email: bob.email, role: 'read' })), params(notebook.id))).json();
signInAs(bob);
await RESPOND_INVITATION(new Request('http://localhost/api/notebooks/invitations', json({ shareId: invited.id, action: 'accept' })));
const masteryFields = { masteryProbability: true, masteryLevel: true, masterySource: true, masteryReason: true, masteryEvaluatedAt: true } as const;
const masteryBefore = await database.errorItem.findUnique({ where: { id: item.id }, select: masteryFields });
// 只读成员录入并人工修正自己的练习记录:记录可写,但错题掌握度不被评估
const recorded = await RECORD_PRACTICE(new Request('http://localhost/api/practice/record', json({
errorItemId: item.id, result: 'wrong', source: 'practice',
})));
expect(recorded.status).toBe(200);
const record = await database.practiceRecord.findFirstOrThrow({ where: { errorItemId: item.id, userId: bob.id }, select: { id: true } });
mocks.scheduleMasteryEvaluation.mockClear();
const patched = await PATCH_PRACTICE_RECORD(new Request(`http://localhost/api/practice/record/${record.id}`, {
method: 'PATCH', body: JSON.stringify({ result: 'correct' }), headers: { 'Content-Type': 'application/json' },
}), params(record.id));
expect(patched.status).toBe(200);
expect(mocks.scheduleMasteryEvaluation).not.toHaveBeenCalled();
// 只读成员组卷后,被移除再录分:录分写入自己的试卷记录,但不触发所有者错题评估
const created = await CREATE_EXAM(new Request('http://localhost/api/exams', json({
subjectIds: [notebook.id], scope: 'all', count: 1, mode: 'original',
})));
expect(created.status).toBe(201);
const paper: { id: string } = await created.json();
const question = await database.examQuestion.findFirstOrThrow({ where: { paperId: paper.id }, select: { id: true } });
signInAs(alice);
const removed = await REMOVE_SHARE(new Request(`http://localhost/api/notebooks/${notebook.id}/shares?shareId=${invited.id}`), params(notebook.id));
expect(removed.status).toBe(200);
signInAs(bob);
mocks.scheduleMasteryEvaluation.mockClear();
const results = await RECORD_EXAM_RESULTS(new Request(`http://localhost/api/exams/${paper.id}/results`, json({
results: [{ questionId: question.id, result: 'correct' }],
})), params(paper.id));
expect(results.status).toBe(200);
expect(mocks.scheduleMasteryEvaluation).not.toHaveBeenCalled();
// 被移除成员仍可改删自己的历史练习记录,但不触发掌握度评估
const patchedAfterRemoval = await PATCH_PRACTICE_RECORD(new Request(`http://localhost/api/practice/record/${record.id}`, {
method: 'PATCH', body: JSON.stringify({ result: 'wrong' }), headers: { 'Content-Type': 'application/json' },
}), params(record.id));
expect(patchedAfterRemoval.status).toBe(200);
expect(mocks.scheduleMasteryEvaluation).not.toHaveBeenCalled();
const deleted = await DELETE_PRACTICE_RECORD(new Request(`http://localhost/api/practice/record/${record.id}`), params(record.id));
expect(deleted.status).toBe(200);
expect(mocks.scheduleMasteryEvaluation).not.toHaveBeenCalled();
expect(await database.errorItem.findUnique({ where: { id: item.id }, select: masteryFields })).toEqual(masteryBefore);
});
it('共享错题本可用于组卷、复习、练习与统计,并发编辑返回冲突', async () => {
const { notebook, item } = await seedNotebook(alice.id);
signInAs(alice);

View File

@@ -8,6 +8,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
const mocks = vi.hoisted(() => ({
mockPrismaErrorItem: {
findUnique: vi.fn(),
findMany: vi.fn(),
update: vi.fn(),
},
mockPrismaPracticeQuestion: {
@@ -1217,6 +1218,7 @@ describe('/api/practice', () => {
it('删除自己的记录并重新评估原题', async () => {
mocks.mockPrismaPracticeRecord.findUnique.mockResolvedValue({ userId: 'user-123', errorItemId: 'error-item-1' });
mocks.mockPrismaErrorItem.findMany.mockResolvedValue([{ id: 'error-item-1', userId: 'user-123', subjectId: null }]);
const response = await RECORD_DELETE(new Request('http://localhost'), params('record-1'));

View File

@@ -28,6 +28,7 @@ import { getAIService } from '@/lib/ai';
import { DEFAULT_MASTERY_THRESHOLD, computeRuleMastery, countByMasteryStatus, evaluateErrorItemMastery, isPracticeResult, masteryLevelFor } from '@/lib/mastery';
const record = (result: string, difficulty = 'medium', day = 1) => ({
userId: 'user-1',
result,
difficulty,
source: 'practice',
@@ -110,6 +111,7 @@ describe('evaluateErrorItemMastery', () => {
userId: 'user-1',
questionText: '题目',
mistakeStatus: 'wrong_attempt',
subjectId: null,
user: { masteryThreshold: 50, aiDataConsentAt: new Date() },
tags: [{ name: '方程' }],
practiceRecords: [record('correct', 'hard', 1), record('correct', 'hard', 2)],
@@ -132,8 +134,10 @@ describe('evaluateErrorItemMastery', () => {
it('按错题所属用户的阈值标记 masteryLevel', async () => {
mocks.findUnique.mockResolvedValue({
id: 'item-1',
userId: 'user-1',
questionText: '题目',
mistakeStatus: null,
subjectId: null,
user: { masteryThreshold: 90, aiDataConsentAt: new Date() },
tags: [],
practiceRecords: [record('correct', 'hard', 1)],
@@ -148,8 +152,10 @@ describe('evaluateErrorItemMastery', () => {
it('用户未同意 AI 数据授权时不调用 AI,按规则估算', async () => {
mocks.findUnique.mockResolvedValue({
id: 'item-1',
userId: 'user-1',
questionText: '题目',
mistakeStatus: null,
subjectId: null,
user: { masteryThreshold: 50, aiDataConsentAt: null },
tags: [],
practiceRecords: [record('correct', 'hard', 1)],
@@ -164,8 +170,10 @@ describe('evaluateErrorItemMastery', () => {
it('AI 失败时使用规则公式兜底', async () => {
mocks.findUnique.mockResolvedValue({
id: 'item-1',
userId: 'user-1',
questionText: '题目',
mistakeStatus: null,
subjectId: null,
user: { masteryThreshold: 50 },
tags: [],
practiceRecords: [record('wrong')],
@@ -180,8 +188,33 @@ describe('evaluateErrorItemMastery', () => {
expect(data.masteryProbability).toBe(computeRuleMastery([{ result: 'wrong', difficulty: 'medium' }]));
});
it('共享错题本只纳入所有者与可编辑成员的练习记录', async () => {
mocks.findUnique.mockResolvedValue({
id: 'item-1',
userId: 'owner-1',
questionText: '题目',
mistakeStatus: null,
subjectId: 'nb-1',
subject: { userId: 'owner-1', shares: [{ memberId: 'editor-1' }] },
user: { masteryThreshold: 50, aiDataConsentAt: null },
tags: [],
practiceRecords: [
{ ...record('correct', 'hard', 1), userId: 'reader-1' },
{ ...record('wrong', 'hard', 2), userId: 'editor-1' },
{ ...record('correct', 'hard', 3), userId: 'removed-1' },
],
});
await evaluateErrorItemMastery('item-1');
// 只读与被移除成员的记录不参与规则估算,历史只剩编辑成员的一次做错
const data = mocks.update.mock.calls[0][0].data;
expect(data.masteryProbability).toBe(computeRuleMastery([{ result: 'wrong', difficulty: 'hard' }]));
expect(data.masteryReason).toBe('共练习 1 次,做对 0 次(规则估算)');
});
it('记录全部删除后清空掌握概率,恢复为待复习', async () => {
mocks.findUnique.mockResolvedValue({ id: 'item-1', questionText: '', mistakeStatus: null, user: { masteryThreshold: 50 }, tags: [], practiceRecords: [] });
mocks.findUnique.mockResolvedValue({ id: 'item-1', userId: 'user-1', subjectId: null, questionText: '', mistakeStatus: null, user: { masteryThreshold: 50 }, tags: [], practiceRecords: [] });
await evaluateErrorItemMastery('item-1');

View File

@@ -4,6 +4,7 @@ import { notFound, validationError, internalError } from "@/lib/api-errors";
import { createLogger } from "@/lib/logger";
import { recordExamResults } from "@/lib/exam/exam";
import { PRACTICE_RESULTS, scheduleMasteryEvaluation } from "@/lib/mastery";
import { getWritableErrorItemIds } from "@/lib/notebook-access";
import { withUser } from "@/lib/api-handler";
import type { AuthenticatedContext } from "@/lib/api-handler";
@@ -40,7 +41,9 @@ export const POST = withUser(async (
const takenAt = parsed.data.takenAt ? new Date(parsed.data.takenAt) : new Date();
const affected = await recordExamResults(id, user.id, takenAt, parsed.data.results);
scheduleMasteryEvaluation(affected);
// 只读或被移除成员录分时不得覆写共享错题本所有者的掌握度
const writableAffected = await getWritableErrorItemIds(user.id, affected);
if (writableAffected.length > 0) scheduleMasteryEvaluation(writableAffected);
return NextResponse.json({ success: true, affectedCount: affected.length });
} catch (error) {

View File

@@ -6,6 +6,7 @@ import type { AuthenticatedContext } from "@/lib/api-handler";
import { internalError, notFound, validationError } from "@/lib/api-errors";
import { createLogger } from "@/lib/logger";
import { scheduleMasteryEvaluation } from "@/lib/mastery";
import { getWritableErrorItemIds } from "@/lib/notebook-access";
import { MAX_SUB_RESULT_TEXT_LENGTH } from "@/lib/question/sub-results";
const logger = createLogger('api:practice:record:id');
@@ -57,7 +58,9 @@ export const PATCH = withUser<RouteContext>(async (req, ctx) => {
},
});
if (record.errorItemId) {
scheduleMasteryEvaluation([record.errorItemId]);
// 只读或被移除成员改删自己的练习记录时不得覆写他人错题的掌握度
const writableIds = await getWritableErrorItemIds(user.id, [record.errorItemId]);
if (writableIds.length > 0) scheduleMasteryEvaluation(writableIds);
}
return NextResponse.json({ success: true });
@@ -85,7 +88,9 @@ async function handleDelete(
await prisma.practiceRecord.delete({ where: { id } });
if (record.errorItemId) {
scheduleMasteryEvaluation([record.errorItemId]);
// 只读或被移除成员删除自己的练习记录时不得覆写他人错题的掌握度
const writableIds = await getWritableErrorItemIds(user.id, [record.errorItemId]);
if (writableIds.length > 0) scheduleMasteryEvaluation(writableIds);
}
return NextResponse.json({ success: true });

View File

@@ -14,6 +14,7 @@ import { consumeAiQuota, quotaRejectionCode } from "@/lib/ai-quota";
import { getErrorMessage } from "@/lib/error-message";
import { createLogger } from "@/lib/logger";
import { scheduleMasteryEvaluation } from "@/lib/mastery";
import { getWritableErrorItemIds } from "@/lib/notebook-access";
import { prisma } from "@/lib/prisma";
import { parseSubQuestions, splitSubQuestions } from "@/lib/question/sub-questions";
import type { SubQuestion } from "@/lib/question/sub-questions";
@@ -379,7 +380,9 @@ export async function gradeExamQuestions(input: GradeExamQuestionsInput): Promis
};
await Promise.all(Array.from({ length: Math.min(EXAM_GRADING_CONCURRENCY, requested.length) }, worker));
if (affected.size > 0) scheduleMasteryEvaluation([...affected]);
// 只读或被移除成员批改时不得覆写共享错题本所有者的掌握度
const writableAffected = await getWritableErrorItemIds(userId, [...affected]);
if (writableAffected.length > 0) scheduleMasteryEvaluation(writableAffected);
const graded: ExamGradingSuccess[] = [];
const failures: ExamGradingFailure[] = [];

View File

@@ -78,12 +78,20 @@ export async function evaluateErrorItemMastery(errorItemId: string): Promise<voi
userId: true,
questionText: true,
mistakeStatus: true,
subjectId: true,
subject: {
select: {
userId: true,
// 仅 active edit 成员有权改写错题本内错题的掌握度;只读与已移除成员的历史记录不参与计算
shares: { where: { status: 'active', role: 'edit' }, select: { memberId: true } },
},
},
user: { select: { masteryThreshold: true, aiDataConsentAt: true } },
tags: { select: { name: true } },
practiceRecords: {
where: { result: { not: null } },
orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
select: { result: true, difficulty: true, source: true, createdAt: true },
select: { userId: true, result: true, difficulty: true, source: true, createdAt: true },
},
},
});
@@ -91,8 +99,13 @@ export async function evaluateErrorItemMastery(errorItemId: string): Promise<voi
return;
}
// 无错题本的旧数据按创建者;有错题本时按错题本所有者与可编辑成员,排除只读/已移除成员的记录
const writableUserIds = item.subjectId && item.subject
? new Set([item.subject.userId, ...item.subject.shares.map((share) => share.memberId)])
: new Set([item.userId]);
const history: MasteryHistoryEntry[] = item.practiceRecords
.filter((record) => isPracticeResult(record.result))
.filter((record) => writableUserIds.has(record.userId) && isPracticeResult(record.result))
.map((record) => ({
date: record.createdAt.toISOString(),
difficulty: record.difficulty,

View File

@@ -7,6 +7,7 @@ import { consumeAiQuota } from "@/lib/ai-quota";
import { getAppTimeZone } from "@/lib/config";
import { formatDateTime } from "@/lib/date-time";
import { PRACTICE_RESULTS, scheduleMasteryEvaluation } from "@/lib/mastery";
import { getWritableErrorItemIds } from "@/lib/notebook-access";
import {
createExamPaperFromSources,
generateExamPaper,
@@ -295,7 +296,9 @@ export async function recordExamResultsForUser(user: User, input: RecordExamResu
const takenAt = parsed.data.takenAt ? new Date(parsed.data.takenAt) : new Date();
try {
const affected = await recordExamResults(parsed.data.paperId, user.id, takenAt, parsed.data.results);
scheduleMasteryEvaluation(affected);
// 只读或被移除成员录分时不得覆写共享错题本所有者的掌握度
const writableAffected = await getWritableErrorItemIds(user.id, affected);
if (writableAffected.length > 0) scheduleMasteryEvaluation(writableAffected);
return { affectedCount: affected.length, affectedIds: affected };
} catch (error) {
if (error instanceof Error && error.message === 'EXAM_NOT_FOUND') {

View File

@@ -138,6 +138,18 @@ export function errorItemAccessSelect(userId: string) {
} as const;
}
/** 按 id 批量筛出当前用户可写的错题(所有者或 active edit 成员);用于触发掌握度重评估前过滤 */
export async function getWritableErrorItemIds(userId: string, itemIds: string[]): Promise<string[]> {
if (itemIds.length === 0) return [];
const items = await prisma.errorItem.findMany({
where: { id: { in: itemIds } },
select: { id: true, ...errorItemAccessSelect(userId) },
});
return items
.filter((item) => canWriteNotebook(resolveErrorItemRole(userId, item)))
.map((item) => item.id);
}
/** 错题本访问判定所需字段;shared 查询按当前用户与 active 过滤 */
export function subjectAccessSelect(userId: string) {
return {