From c9598db1bfbed3348a91d29b0c5ffc74a82a1aa2 Mon Sep 17 00:00:00 2001 From: margrop <1731827+margrop@users.noreply.github.com> Date: Sat, 5 Dec 2026 02:32:31 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E5=8F=AA=E8=AF=BB=E4=B8=8E=E8=A2=AB?= =?UTF-8?q?=E7=A7=BB=E9=99=A4=E5=85=B1=E4=BA=AB=E6=88=90=E5=91=98=E4=B8=8D?= =?UTF-8?q?=E5=86=8D=E6=94=B9=E5=86=99=E4=BB=96=E4=BA=BA=E9=94=99=E9=A2=98?= =?UTF-8?q?=E6=8E=8C=E6=8F=A1=E5=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Refs: https://github.com/margrop/wrong-notebook/issues/190 --- .../integration/exam-grading.test.ts | 5 ++ src/__tests__/integration/exams.test.ts | 3 + src/__tests__/integration/mcp.test.ts | 7 +++ .../integration/notebook-sharing.test.ts | 60 ++++++++++++++++++- src/__tests__/integration/practice.test.ts | 2 + src/__tests__/unit/mastery.test.ts | 35 ++++++++++- src/app/api/exams/[id]/results/route.ts | 5 +- src/app/api/practice/record/[id]/route.ts | 9 ++- src/lib/exam/exam-grading.ts | 5 +- src/lib/mastery.ts | 17 +++++- src/lib/mcp/tools/exams.ts | 5 +- src/lib/notebook-access.ts | 12 ++++ 12 files changed, 156 insertions(+), 9 deletions(-) diff --git a/src/__tests__/integration/exam-grading.test.ts b/src/__tests__/integration/exam-grading.test.ts index 4d38aff5..31bc3401 100644 --- a/src/__tests__/integration/exam-grading.test.ts +++ b/src/__tests__/integration/exam-grading.test.ts @@ -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) => 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 () => { diff --git a/src/__tests__/integration/exams.test.ts b/src/__tests__/integration/exams.test.ts index 0a7aca96..f7242120 100644 --- a/src/__tests__/integration/exams.test.ts +++ b/src/__tests__/integration/exams.test.ts @@ -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 创建试卷', () => { diff --git a/src/__tests__/integration/mcp.test.ts b/src/__tests__/integration/mcp.test.ts index 1da47c2b..412db960 100644 --- a/src/__tests__/integration/mcp.test.ts +++ b/src/__tests__/integration/mcp.test.ts @@ -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' } }, diff --git a/src/__tests__/integration/notebook-sharing.test.ts b/src/__tests__/integration/notebook-sharing.test.ts index d41ef003..35eac7e9 100644 --- a/src/__tests__/integration/notebook-sharing.test.ts +++ b/src/__tests__/integration/notebook-sharing.test.ts @@ -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); diff --git a/src/__tests__/integration/practice.test.ts b/src/__tests__/integration/practice.test.ts index 2f1ffb1c..a959c282 100644 --- a/src/__tests__/integration/practice.test.ts +++ b/src/__tests__/integration/practice.test.ts @@ -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')); diff --git a/src/__tests__/unit/mastery.test.ts b/src/__tests__/unit/mastery.test.ts index ecee7082..553a1a21 100644 --- a/src/__tests__/unit/mastery.test.ts +++ b/src/__tests__/unit/mastery.test.ts @@ -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'); diff --git a/src/app/api/exams/[id]/results/route.ts b/src/app/api/exams/[id]/results/route.ts index 54008af7..219f696e 100644 --- a/src/app/api/exams/[id]/results/route.ts +++ b/src/app/api/exams/[id]/results/route.ts @@ -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) { diff --git a/src/app/api/practice/record/[id]/route.ts b/src/app/api/practice/record/[id]/route.ts index 9c890726..4b1d2375 100644 --- a/src/app/api/practice/record/[id]/route.ts +++ b/src/app/api/practice/record/[id]/route.ts @@ -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(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 }); diff --git a/src/lib/exam/exam-grading.ts b/src/lib/exam/exam-grading.ts index 25862205..abddbaab 100644 --- a/src/lib/exam/exam-grading.ts +++ b/src/lib/exam/exam-grading.ts @@ -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[] = []; diff --git a/src/lib/mastery.ts b/src/lib/mastery.ts index 1d24f10f..c45d727f 100644 --- a/src/lib/mastery.ts +++ b/src/lib/mastery.ts @@ -78,12 +78,20 @@ export async function evaluateErrorItemMastery(errorItemId: string): Promise 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, diff --git a/src/lib/mcp/tools/exams.ts b/src/lib/mcp/tools/exams.ts index 09e54122..e5097f01 100644 --- a/src/lib/mcp/tools/exams.ts +++ b/src/lib/mcp/tools/exams.ts @@ -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') { diff --git a/src/lib/notebook-access.ts b/src/lib/notebook-access.ts index 77910977..dd6badfa 100644 --- a/src/lib/notebook-access.ts +++ b/src/lib/notebook-access.ts @@ -138,6 +138,18 @@ export function errorItemAccessSelect(userId: string) { } as const; } +/** 按 id 批量筛出当前用户可写的错题(所有者或 active edit 成员);用于触发掌握度重评估前过滤 */ +export async function getWritableErrorItemIds(userId: string, itemIds: string[]): Promise { + 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 {