diff --git a/README.en.md b/README.en.md index 1aa78ee3..e8c56b26 100644 --- a/README.en.md +++ b/README.en.md @@ -182,7 +182,7 @@ Practice statistics show total practice, accuracy (correct / attempted) and acti ### Management and statistics -- **👥 Notebook sharing**: a notebook owner can invite other accounts by email as members, choosing **Read-only** or **Can edit**. After a member accepts the invitation on the notebook home page, the notebook and its questions appear in that member's list, readable or editable by role; questions the member adds belong to the notebook and are visible to all members by role. The owner can change roles or remove members at any time, and members can leave sharing themselves. Only the owner can rename or delete the notebook and manage members; read-only members can view, print and export questions but cannot modify them or run bulk operations. Sharing relationships are exported with the owner's backup and rebuilt by member email on import; members whose email is not present on the target instance are skipped. +- **👥 Notebook sharing**: a notebook owner can invite other accounts by email as members, choosing **Read-only** or **Can edit**. After a member accepts the invitation on the notebook home page, the notebook and its questions appear in that member's list, readable or editable by role; questions the member adds belong to the notebook and are visible to all members by role. The owner can change roles or remove members at any time, and members can leave sharing themselves. Only the owner can rename or delete the notebook and manage members; read-only members can view, print and export questions but cannot modify them or run bulk operations. All members can create exam papers from the shared notebook, answer questions in the due-review queue and record their own practice; statistics filtered by a shared notebook cover only that notebook and label its owner, while practice and weak-tag evidence are counted for the current account. If two people edit the same question, a stale version gets a conflict response and can be saved after reloading. Sharing relationships are exported with the owner's backup and rebuilt by member email on import; members whose email is not present on the target instance are skipped. - **🔍 Filters**: filter by mastery, date range, knowledge point, question type, grade and term, paper level and more; supports bulk actions and comparing the similarity of two questions. Selected questions can have their source, grade/term and knowledge tags edited in bulk, be moved to another notebook (tags stay unchanged), or exported as JSON, Excel or Word (the Excel columns match the question bank import template, so the file can be re-imported directly; Word embeds the question's own figures by default, with the original photo as a separate option); **Select all filtered results** selects up to 2,000 items across pages, and operations above 100 items submit in batches with progress and retry for failed items. - **📊 Statistics**: mastery rate, trends and subject distribution for both mistakes and practice, with time-range and subject filters. - **⏳ Background tasks**: the button at the bottom right shows the progress of long-running jobs such as recognition, AI generation, animation voice, bulk tagging and exam generation. Jobs keep running on the server after you leave the page. Photo recognition results are also kept in **Recognition**. diff --git a/README.md b/README.md index 752e790e..72e61d0c 100644 --- a/README.md +++ b/README.md @@ -182,7 +182,7 @@ ### 管理与统计 -- **👥 错题本共享**:错题本所有者可按账号邮箱邀请其他用户成为成员,并选择「只读」或「可编辑」。成员在错题本首页接受邀请后,该错题本及其中的题目会出现在自己的列表中,按角色读取或修改;成员新增的题目归属该错题本,所有成员按角色可见。所有者可随时调整成员角色或移除成员,成员也可主动退出共享。只有所有者能改名、删除错题本和管理成员;只读成员可查看题目、打印和导出,但不能修改题目或执行批量操作。共享关系随所有者数据备份导出,导入时按成员邮箱重建;本机不存在该邮箱的成员会跳过。 +- **👥 错题本共享**:错题本所有者可按账号邮箱邀请其他用户成为成员,并选择「只读」或「可编辑」。成员在错题本首页接受邀请后,该错题本及其中的题目会出现在自己的列表中,按角色读取或修改;成员新增的题目归属该错题本,所有成员按角色可见。所有者可随时调整成员角色或移除成员,成员也可主动退出共享。只有所有者能改名、删除错题本和管理成员;只读成员可查看题目、打印和导出,但不能修改题目或执行批量操作。成员都可从共享错题本组卷、在今日复习中作答并记录自己的练习;统计中心按共享错题本筛选时只统计该错题本并标注所有者,练习与薄弱知识点按当前账号的作答记录计算。两人同时修改同一题时,过期版本返回冲突,重新加载后可保存。共享关系随所有者数据备份导出,导入时按成员邮箱重建;本机不存在该邮箱的成员会跳过。 - **🔍 多维度筛选**:按掌握状态、时间范围、知识点、题型、年级学期、试卷等级等条件筛选,支持批量操作和两题相似度比较;选中的错题可批量修改来源、年级学期和知识点标签,移动到其他错题本(标签保持不变),也可导出为 JSON、Excel 或 Word(Excel 列与题库导入模板一致,可往返导入;Word 默认嵌入题目自带配图,拍照原图需另行勾选);「全选筛选结果」可跨页选中上千道题,超过 100 道时按批提交并显示进度,失败项可重试。 - **📊 数据统计**:错题与练习的掌握率、趋势和学科分布,支持时间范围与学科筛选。错题列表支持用地址参数预设掌握状态(`?mastery=new|reviewing|mastered`)和知识点标签(`?tag=标签名`)筛选。 - **⏳ 后台任务**:页面右下角的按钮可查看识别、AI 生成、动画语音生成、批量标注、组卷等耗时事务的进度;离开页面后事务仍在服务器上继续。拍照识别的结果另在「识别任务」中持久保存。 diff --git a/doc/wiki/User-Guide.md b/doc/wiki/User-Guide.md index 5a2b5263..0fa8b5a1 100644 --- a/doc/wiki/User-Guide.md +++ b/doc/wiki/User-Guide.md @@ -18,6 +18,8 @@ 只有所有者能重命名、删除错题本和管理成员;可编辑成员可新增、修改、删除题目、批量操作和重新标注知识点;只读成员可查看、打印和导出,但不能修改题目。共享关系随所有者数据备份导出(记录成员邮箱与角色),导入时按邮箱重建;同一错题本与成员已存在时按备份更新角色,本机不存在该邮箱的成员会跳过。成员退出共享只删除关系,题目保留;所有者删除错题本会连带删除其中的题目。 +共享错题本也用于组卷、复习与练习:成员可在试卷抽屉选择共享错题本出题,今日复习会列出其中的到期题目;只读成员同样可作答并记录自己的练习结果,记录归属当前账号。统计中心按共享错题本筛选时只统计该错题本,并在学科下拉中标注所有者;练习统计与薄弱知识点按当前账号的作答证据计算,不混入其他成员的练习记录。两人同时编辑同一题时,保存时带上读取版本,服务端发现已被他人更新会返回冲突,重新加载后再保存即可。 + ## 录入题目 | 入口 | 适用情况 | diff --git a/doc/wiki/en/User-Guide-en.md b/doc/wiki/en/User-Guide-en.md index 4ca47b8d..880e58e0 100644 --- a/doc/wiki/en/User-Guide-en.md +++ b/doc/wiki/en/User-Guide-en.md @@ -18,6 +18,8 @@ A notebook owner can invite other accounts by email from the **Shared members** Only the owner can rename or delete the notebook and manage members. Members with edit rights can add, modify and delete questions, run bulk actions and retag knowledge points; read-only members can view, print and export questions but cannot modify them. Sharing relationships are exported with the owner's backup (member email and role) and rebuilt by email on import; an existing notebook-member pair has its role updated from the backup, while members whose email is absent on the target instance are skipped. A member leaving sharing removes only the relationship and keeps the questions; the owner deleting a notebook also deletes its questions. +Shared notebooks also feed exam papers, review and practice: members can pick a shared notebook when creating an exam, and the due-review queue lists its due questions; read-only members can answer and record their own practice results, owned by the current account. Statistics filtered by a shared notebook cover only that notebook and label its owner in the subject selector; practice statistics and weak tags count the current account's own evidence, not other members' records. When two people edit the same question, saves carry the version they read; if someone else already updated it, the server returns a conflict and the edit can be saved after reloading. + ## Add questions | Entry | When to use | diff --git a/src/__tests__/integration/analytics.test.ts b/src/__tests__/integration/analytics.test.ts index 3c17118f..62fa7c3c 100644 --- a/src/__tests__/integration/analytics.test.ts +++ b/src/__tests__/integration/analytics.test.ts @@ -54,6 +54,14 @@ function makeRequest(url: string): Request { return new Request(url); } +/** 统计查询的可读错题条件:自有或已接受共享错题本 */ +const ACCESS_WHERE = { + OR: [ + { userId: 'user-123' }, + { subject: { shares: { some: { memberId: 'user-123', status: 'active' } } } }, + ], +}; + describe('/api/analytics', () => { beforeEach(() => { vi.clearAllMocks(); @@ -210,7 +218,7 @@ describe('/api/analytics', () => { expect(mocks.mockPrismaErrorItem.count).toHaveBeenCalledWith({ where: { AND: [ - { userId: 'user-123', subjectId: 'sub-1', createdAt: { gte: expect.any(Date) } }, + { ...ACCESS_WHERE, subjectId: 'sub-1', createdAt: { gte: expect.any(Date) } }, expect.any(Object), ], }, @@ -232,7 +240,7 @@ describe('/api/analytics', () => { // 验证 7 天范围的查询条件 expect(mocks.mockPrismaErrorItem.findMany).toHaveBeenCalledWith(expect.objectContaining({ where: { - userId: 'user-123', + ...ACCESS_WHERE, createdAt: { gte: new Date('2026-10-12T16:00:00Z') }, }, select: { id: true, createdAt: true }, @@ -311,7 +319,7 @@ describe('/api/analytics', () => { expect(mocks.mockPrismaErrorItem.groupBy).toHaveBeenCalledWith({ by: ['subjectId'], - where: { userId: 'user-123', createdAt: { gte: expect.any(Date) } }, + where: { ...ACCESS_WHERE, createdAt: { gte: expect.any(Date) } }, _count: { id: true }, }); }); @@ -422,12 +430,12 @@ describe('/api/analytics', () => { expect(mocks.mockPrismaErrorItem.count).toHaveBeenCalledTimes(4); // newCount 查询条件:practiceRecords none expect(mocks.mockPrismaErrorItem.count).toHaveBeenCalledWith({ - where: { AND: [{ userId: 'user-123', createdAt: { gte: expect.any(Date) } }, { practiceRecords: { none: { result: { not: null } } } }] }, + where: { AND: [{ ...ACCESS_WHERE, createdAt: { gte: expect.any(Date) } }, { practiceRecords: { none: { result: { not: null } } } }] }, }); // reviewingCount 查询条件:有记录但掌握概率低于阈值或为 null expect(mocks.mockPrismaErrorItem.count).toHaveBeenCalledWith({ where: { - AND: [{ userId: 'user-123', createdAt: { gte: expect.any(Date) } }, { + AND: [{ ...ACCESS_WHERE, createdAt: { gte: expect.any(Date) } }, { practiceRecords: { some: { result: { not: null } } }, OR: [{ masteryProbability: null }, { masteryProbability: { lt: 0.5 } }], }], @@ -436,7 +444,7 @@ describe('/api/analytics', () => { // masteredCount 查询条件:有记录且掌握概率达到阈值 expect(mocks.mockPrismaErrorItem.count).toHaveBeenCalledWith({ where: { - AND: [{ userId: 'user-123', createdAt: { gte: expect.any(Date) } }, { + AND: [{ ...ACCESS_WHERE, createdAt: { gte: expect.any(Date) } }, { practiceRecords: { some: { result: { not: null } } }, masteryProbability: { gte: 0.5 }, }], @@ -591,7 +599,7 @@ describe('/api/analytics', () => { expect(mocks.mockPrismaErrorItem.findMany).toHaveBeenCalledTimes(2); expect(mocks.mockPrismaErrorItem.findMany).toHaveBeenNthCalledWith(2, expect.objectContaining({ where: { - userId: 'user-123', + ...ACCESS_WHERE, subjectId: 'sub-1', masteryEvaluatedAt: { gte: expect.any(Date) }, AND: [{ @@ -753,7 +761,7 @@ describe('/api/analytics', () => { by: ['difficultyStars'], where: { AND: [ - { userId: 'user-123', createdAt: { gte: expect.any(Date) } }, + { ...ACCESS_WHERE, createdAt: { gte: expect.any(Date) } }, { practiceRecords: { some: { result: { not: null } } }, masteryProbability: { gte: 0.5 } }, ], }, @@ -779,7 +787,7 @@ describe('/api/analytics', () => { expect(mocks.mockPrismaErrorItem.groupBy).toHaveBeenCalledWith({ by: ['difficultyStars'], - where: { userId: 'user-123', createdAt: { gte: expect.any(Date) } }, + where: { ...ACCESS_WHERE, createdAt: { gte: expect.any(Date) } }, _count: { id: true }, }); }); @@ -828,7 +836,7 @@ describe('/api/analytics', () => { expect(mocks.mockPrismaErrorItem.groupBy).toHaveBeenCalledWith({ by: ['mistakeStatus'], - where: { userId: 'user-123', createdAt: { gte: expect.any(Date) } }, + where: { ...ACCESS_WHERE, createdAt: { gte: expect.any(Date) } }, _count: { id: true }, }); }); @@ -904,7 +912,7 @@ describe('/api/analytics', () => { expect(mocks.mockPrismaErrorItem.groupBy).toHaveBeenCalledWith({ by: ['errorType'], - where: { userId: 'user-123', createdAt: { gte: expect.any(Date) } }, + where: { ...ACCESS_WHERE, createdAt: { gte: expect.any(Date) } }, _count: { id: true }, }); }); diff --git a/src/__tests__/integration/exams.test.ts b/src/__tests__/integration/exams.test.ts index 18e77f95..4a9ccd1e 100644 --- a/src/__tests__/integration/exams.test.ts +++ b/src/__tests__/integration/exams.test.ts @@ -202,7 +202,12 @@ describe('/api/exams', () => { const response = await CREATE(json('http://localhost/api/exams', 'POST', options)); expect(response.status).toBe(400); - expect(mocks.subject.findMany.mock.calls[0][0].where.userId).toBe('user-1'); + expect(mocks.subject.findMany.mock.calls[0][0].where).toMatchObject({ + OR: [ + { userId: 'user-1' }, + { shares: { some: { memberId: 'user-1', status: 'active' } } }, + ], + }); }); it('校验题量、范围与抽题规则', async () => { diff --git a/src/__tests__/integration/notebook-sharing.test.ts b/src/__tests__/integration/notebook-sharing.test.ts index fabc00a3..a7d7bc2e 100644 --- a/src/__tests__/integration/notebook-sharing.test.ts +++ b/src/__tests__/integration/notebook-sharing.test.ts @@ -19,6 +19,12 @@ vi.mock('@/lib/prisma', () => ({ get prisma() { return mocks.prisma; } })); vi.mock('@/lib/logger', () => ({ createLogger: () => mocks.logger })); vi.mock('@/lib/auth', () => ({ authOptions: {} })); vi.mock('next-auth', () => ({ getServerSession: vi.fn(() => Promise.resolve(mocks.session)) })); +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(), +})); import { GET as LIST_NOTEBOOKS } from '@/app/api/notebooks/route'; import { GET as GET_NOTEBOOK, PUT as RENAME_NOTEBOOK, DELETE as DELETE_NOTEBOOK } from '@/app/api/notebooks/[id]/route'; @@ -27,6 +33,11 @@ import { GET as LIST_INVITATIONS, POST as RESPOND_INVITATION } from '@/app/api/n import { GET as LIST_ITEMS } from '@/app/api/error-items/list/route'; import { GET as GET_ITEM, PUT as UPDATE_ITEM } from '@/app/api/error-items/[id]/route'; 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 { GET as ANALYTICS } from '@/app/api/analytics/route'; +import { GET as PRACTICE_STATS } from '@/app/api/stats/practice/route'; let database: PrismaClient; let directory: string; @@ -74,7 +85,15 @@ async function seedNotebook(ownerId: string, name = '共享数学') { data: { userId: ownerId, name, stage: 'junior_high', subjectKey: 'math' }, }); const item = await database.errorItem.create({ - data: { userId: ownerId, subjectId: notebook.id, questionText: '共享题目', originalImageUrl: 'data:image/png;base64,AA==' }, + data: { + userId: ownerId, + subjectId: notebook.id, + questionText: '共享题目', + originalImageUrl: 'data:image/png;base64,AA==', + shortId: notebook.id.slice(-6), + // 三天前录入:今日复习应到期 + createdAt: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000), + }, }); return { notebook, item }; } @@ -181,4 +200,61 @@ describe('错题本共享', () => { const members = await (await LIST_SHARES(new Request(`http://localhost/api/notebooks/${notebook.id}/shares`), params(notebook.id))).json(); expect(members.shares).toContainEqual(expect.objectContaining({ memberId: bob.id, status: 'active', memberName: 'Bob' })); }); + + 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' }))); + + // 只读成员可从共享错题本组卷(原题直出,不调用 AI) + 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 = await created.json(); + const question = await database.examQuestion.findFirst({ + where: { paperId: paper.id }, + select: { errorItemId: true, sourceShortId: true }, + }); + expect(question).toMatchObject({ errorItemId: item.id, sourceShortId: item.shortId }); + expect((await database.examPaper.findUnique({ where: { id: paper.id } }))?.userId).toBe(bob.id); + + // 今日复习包含共享错题 + const due = await (await REVIEW_DUE(new Request('http://localhost/api/review/due'))).json(); + expect(due.items.map((row: { id: string }) => row.id)).toContain(item.id); + + // 只读成员可记录自己的作答,记录归属成员而非所有者 + const recorded = await RECORD_PRACTICE(new Request('http://localhost/api/practice/record', json({ + errorItemId: item.id, result: 'correct', source: 'review', + }))); + expect(recorded.status).toBe(200); + const record = await database.practiceRecord.findFirst({ where: { errorItemId: item.id } }); + expect(record).toMatchObject({ userId: bob.id, errorItemId: item.id, result: 'correct' }); + + // 统计可按共享错题本筛选,且不串入他人的私有错题本 + const analytics = await (await ANALYTICS(new Request(`http://localhost/api/analytics?subjectId=${notebook.id}`))).json(); + expect(analytics.totalErrors).toBe(1); + const practiceStats = await (await PRACTICE_STATS(new Request(`http://localhost/api/stats/practice?subjectId=${notebook.id}&range=all`))).json(); + expect(practiceStats.overallStats.total).toBe(1); + + // 所有者改为可编辑后,两人同时编辑同一题:过期版本返回 409,重新读取后可保存 + signInAs(alice); + await UPDATE_ROLE(new Request(`http://localhost/api/notebooks/${notebook.id}/shares`, json({ shareId: invited.id, role: 'edit' })), params(notebook.id)); + signInAs(bob); + const stale = await (await GET_ITEM(new Request(`http://localhost/api/error-items/${item.id}`), params(item.id))).json(); + signInAs(alice); + expect((await UPDATE_ITEM(new Request(`http://localhost/api/error-items/${item.id}`, json({ questionText: '所有者改题' })), params(item.id))).status).toBe(200); + signInAs(bob); + const conflictResponse = await UPDATE_ITEM(new Request(`http://localhost/api/error-items/${item.id}`, json({ + questionText: '成员旧版改题', expectedUpdatedAt: stale.updatedAt, + })), params(item.id)); + expect(conflictResponse.status).toBe(409); + const current = await (await GET_ITEM(new Request(`http://localhost/api/error-items/${item.id}`), params(item.id))).json(); + const saved = await UPDATE_ITEM(new Request(`http://localhost/api/error-items/${item.id}`, json({ + questionText: '成员新版改题', expectedUpdatedAt: current.updatedAt, + })), params(item.id)); + expect(saved.status).toBe(200); + }); }); diff --git a/src/__tests__/integration/review.test.ts b/src/__tests__/integration/review.test.ts index 3e8b9441..f64c31e4 100644 --- a/src/__tests__/integration/review.test.ts +++ b/src/__tests__/integration/review.test.ts @@ -24,6 +24,14 @@ import { GET } from '@/app/api/review/due/route'; const get = (query = '') => GET(new Request(`http://localhost/api/review/due${query}`)); +/** 复习候选:自有或已接受共享错题本 */ +const ACCESS_WHERE = { + OR: [ + { userId: 'user-1' }, + { subject: { shares: { some: { memberId: 'user-1', status: 'active' } } } }, + ], +}; + const candidates = [ // 录入两天前、没有作答:昨天到期 { id: 'new', createdAt: new Date('2026-10-18T02:00:00Z') }, @@ -66,7 +74,7 @@ describe('GET /api/review/due', () => { expect(data.items.map((item: { id: string }) => item.id)).toEqual(['old', 'new']); expect(data.items[0]).toMatchObject({ reviewStage: 0, masteryStatus: 'reviewing', nextReviewAt: '2026-09-10T16:00:00.000Z' }); expect(data.items[1]).toMatchObject({ reviewStage: 0, masteryStatus: 'new' }); - expect(mocks.errorItem.findMany).toHaveBeenNthCalledWith(1, expect.objectContaining({ where: { userId: 'user-1' } })); + expect(mocks.errorItem.findMany).toHaveBeenNthCalledWith(1, expect.objectContaining({ where: ACCESS_WHERE })); // 作答记录用平铺查询 + 正向白名单:嵌套关系的否定过滤会让 Prisma 无法拆分查询,错题多时报参数上限 expect(mocks.practiceRecord.findMany).toHaveBeenCalledWith(expect.objectContaining({ where: { userId: 'user-1', errorItemId: { in: ['new', 'fresh', 'old'] }, result: { in: ['correct', 'wrong'] } }, @@ -77,7 +85,7 @@ describe('GET /api/review/due', () => { const response = await get('?subjectId=math&page=2&pageSize=1'); const data = await response.json(); - expect(mocks.errorItem.findMany).toHaveBeenNthCalledWith(1, expect.objectContaining({ where: { userId: 'user-1', subjectId: 'math' } })); + expect(mocks.errorItem.findMany).toHaveBeenNthCalledWith(1, expect.objectContaining({ where: { ...ACCESS_WHERE, subjectId: 'math' } })); expect(data).toMatchObject({ total: 2, page: 2, pageSize: 1, totalPages: 2 }); expect(data.items.map((item: { id: string }) => item.id)).toEqual(['new']); }); diff --git a/src/__tests__/integration/weak-tags.test.ts b/src/__tests__/integration/weak-tags.test.ts index 4c1867fa..dde687b8 100644 --- a/src/__tests__/integration/weak-tags.test.ts +++ b/src/__tests__/integration/weak-tags.test.ts @@ -41,6 +41,14 @@ function makeRequest(url: string): Request { return new Request(url); } +/** 薄弱知识点查询的可读错题条件:自有或已接受共享错题本 */ +const ACCESS_WHERE = { + OR: [ + { userId: 'user-123' }, + { subject: { shares: { some: { memberId: 'user-123', status: 'active' } } } }, + ], +}; + describe('/api/stats/weak-tags', () => { beforeEach(() => { vi.clearAllMocks(); @@ -85,11 +93,12 @@ describe('/api/stats/weak-tags', () => { 'subjectId', 'tags', ]); - // result 非空的总记录数 + // result 非空且属于当前账号的记录数 expect(query.select._count).toEqual({ - select: { practiceRecords: { where: { result: { not: null } } } }, + select: { practiceRecords: { where: { result: { not: null }, userId: 'user-123' } } }, }); // 近 30 天窗口用正向白名单:嵌套关系的否定过滤会让 Prisma 无法拆分查询(错题多时触发参数上限) + expect(query.select.practiceRecords.where.userId).toBe('user-123'); expect(query.select.practiceRecords.where.result).toEqual({ in: ['correct', 'wrong', 'not_attempted'] }); expect(query.select.practiceRecords.where.createdAt).toEqual({ gte: expect.any(Date), @@ -122,7 +131,7 @@ describe('/api/stats/weak-tags', () => { it('all 范围不过滤 createdAt', async () => { await GET(makeRequest('http://localhost/api/stats/weak-tags?range=all')); const query = mocks.mockPrismaErrorItem.findMany.mock.calls[0][0]; - expect(query.where).toEqual({ userId: 'user-123' }); + expect(query.where).toEqual(ACCESS_WHERE); }); it('传入合法 subjectId 时按学科筛选,并返回学科信息', async () => { @@ -148,7 +157,7 @@ describe('/api/stats/weak-tags', () => { const query = mocks.mockPrismaErrorItem.findMany.mock.calls[0][0]; expect(query.where).toEqual({ - userId: 'user-123', + ...ACCESS_WHERE, subjectId: 'sub-1', createdAt: { gte: expect.any(Date) }, }); @@ -171,18 +180,19 @@ describe('/api/stats/weak-tags', () => { const query = mocks.mockPrismaErrorItem.findMany.mock.calls[0][0]; expect(query.where).toEqual({ - userId: 'user-123', + ...ACCESS_WHERE, createdAt: { gte: expect.any(Date) }, }); }); - it('只查询当前用户的错题(userId 隔离他人数据)', async () => { + it('查询自有与共享错题本(不串入其他账号的私有错题本)', async () => { await GET(makeRequest('http://localhost/api/stats/weak-tags')); const query = mocks.mockPrismaErrorItem.findMany.mock.calls[0][0]; - expect(query.where.userId).toBe('user-123'); - // 查询条件里没有 OR/AND 之类的跨用户入口 - expect(Object.keys(query.where).sort()).toEqual(['createdAt', 'userId']); + expect(query.where).toEqual({ + ...ACCESS_WHERE, + createdAt: { gte: expect.any(Date) }, + }); }); it('聚合返回排序后的前 10 条且不含已掌握组', async () => { diff --git a/src/app/api/analytics/route.ts b/src/app/api/analytics/route.ts index 7108368b..9ed9d663 100644 --- a/src/app/api/analytics/route.ts +++ b/src/app/api/analytics/route.ts @@ -9,6 +9,7 @@ import { masteryStatusWhere } from "@/lib/mastery-status"; import { normalizeMistakeStatus } from "@/lib/question/mistake-status"; import { parseStatsRange, resolveStatsRange } from "@/lib/stats/stats-range"; import { resolveStatsSubjectId } from "@/lib/stats/stats-filter"; +import { accessibleErrorItemOwnerOrShareWhere } from "@/lib/notebook-access"; import { withUser } from "@/lib/api-handler"; import type { AuthenticatedContext } from "@/lib/api-handler"; @@ -75,9 +76,9 @@ export const GET = withUser(async (req: Request, { user }: AuthenticatedContext) const subjectId = subject?.id ?? null; const subjectName = subject?.name ?? null; - // 构建基础查询条件 + // 构建基础查询条件:自有错题或已接受共享错题本中的错题 const baseWhere = { - userId, + ...accessibleErrorItemOwnerOrShareWhere(userId), ...(subjectId ? { subjectId } : {}), }; diff --git a/src/app/api/error-items/[id]/route.ts b/src/app/api/error-items/[id]/route.ts index c8203f3a..2a5bd702 100644 --- a/src/app/api/error-items/[id]/route.ts +++ b/src/app/api/error-items/[id]/route.ts @@ -1,7 +1,7 @@ import { NextResponse } from "next/server"; import { prisma } from "@/lib/prisma"; import type { Prisma } from "@prisma/client"; -import { forbidden, notFound, badRequest, validationError, internalError } from "@/lib/api-errors"; +import { forbidden, notFound, badRequest, validationError, conflict, internalError } from "@/lib/api-errors"; import { withUser } from "@/lib/api-handler"; import type { AuthenticatedContext } from "@/lib/api-handler"; import { createLogger } from "@/lib/logger"; @@ -56,7 +56,7 @@ export const PUT = withUser(async (req: Request, { user, params }: RouteContext if (!parsed.success) { return validationError("Invalid request body", parsed.error.issues); } - const { knowledgePoints, gradeSemester, paperLevel, questionText, answerText, analysis, subjectId, wrongAnswerText, mistakeAnalysis, mistakeStatus, geogebraCommands, difficultyStars, questionType, source, subQuestions } = parsed.data; + const { knowledgePoints, gradeSemester, paperLevel, questionText, answerText, analysis, subjectId, wrongAnswerText, mistakeAnalysis, mistakeStatus, geogebraCommands, difficultyStars, questionType, source, subQuestions, expectedUpdatedAt } = parsed.data; const { figureScale, figureAlign, figureSource } = parsed.data; if (figureScale !== undefined && !isValidFigureScale(figureScale)) { return badRequest("figureScale must be an integer from 10 to 200"); @@ -96,6 +96,11 @@ export const PUT = withUser(async (req: Request, { user, params }: RouteContext return forbidden("Not authorized to update this item"); } + // 共享成员可能同时编辑同一题:客户端带上读取时的 updatedAt,过期则返回 409 由前端重新加载 + if (expectedUpdatedAt && errorItem.updatedAt.getTime() !== new Date(expectedUpdatedAt).getTime()) { + return conflict("ITEM_UPDATED_BY_OTHER"); + } + // 构建更新数据 const updateData: Prisma.ErrorItemUncheckedUpdateInput = {}; if (figureScale !== undefined) updateData.figureScale = figureScale; diff --git a/src/app/api/exams/route.ts b/src/app/api/exams/route.ts index 1fb38436..6b6a3d78 100644 --- a/src/app/api/exams/route.ts +++ b/src/app/api/exams/route.ts @@ -10,6 +10,7 @@ import { DEFAULT_EXAM_SOURCE, getExamSourceProvider } from "@/lib/exam/exam-sour import { parseQuestionIdEntries } from "@/lib/exam/exam-question-ids"; import { getAppTimeZone } from "@/lib/config"; import { formatDateTime } from "@/lib/date-time"; +import { accessibleSubjectWhere } from "@/lib/notebook-access"; import { consumeAiQuota } from "@/lib/ai-quota"; import { withUser } from "@/lib/api-handler"; import type { AuthenticatedContext } from "@/lib/api-handler"; @@ -109,19 +110,27 @@ async function createExam(req: Request, { user }: AuthenticatedContext): Promise return validationError("Unknown exam source", [{ code: 'invalid_source', path: ['source'], message: `Unknown exam source: ${source}` }]); } - // 只允许使用自己的错题本 + // 可选自有或已接受共享的错题本;共享成员可用其中的题目组卷 const notebooks = await prisma.subject.findMany({ - where: { id: { in: subjectIds }, userId: user.id }, - select: { id: true, name: true }, + where: { id: { in: subjectIds }, ...accessibleSubjectWhere(user.id) }, + select: { id: true, name: true, userId: true }, }); if (notebooks.length === 0) { return badRequest("NO_SOURCE_ITEMS"); } + // 共享错题本中的题由所有者创建,选题时需按共享归属一并取题 + const sharedSubjectIds = notebooks + .filter((notebook) => typeof notebook.userId === 'string' && notebook.userId !== user.id) + .map((notebook) => notebook.id); - // 校验卷别分组属于当前用户 + // 校验卷别分组属于当前用户或所选共享错题本的所有者 if (paperLevelIds && paperLevelIds.length > 0) { + const ownerIds = new Set([user.id]); + for (const notebook of notebooks) { + if (typeof notebook.userId === 'string') ownerIds.add(notebook.userId); + } const validGroups = await prisma.paperGroup.count({ - where: { id: { in: paperLevelIds }, userId: user.id }, + where: { id: { in: paperLevelIds }, userId: { in: [...ownerIds] } }, }); if (validGroups !== paperLevelIds.length) { return validationError("Invalid paperLevelIds", [{ code: 'invalid_paper_level', path: ['paperLevelIds'], message: 'Invalid paper level group' }]); @@ -131,6 +140,7 @@ async function createExam(req: Request, { user }: AuthenticatedContext): Promise // A/B 卷一次多取最多 2×count 道互不重复的源题 const sources = await provider.select(user.id, { subjectIds: notebooks.map((notebook) => notebook.id), + accessibleSubjectIds: sharedSubjectIds, tagNames, paperLevelIds, questionTypes, diff --git a/src/app/api/practice/grade/route.ts b/src/app/api/practice/grade/route.ts index 23977b10..c6f17295 100644 --- a/src/app/api/practice/grade/route.ts +++ b/src/app/api/practice/grade/route.ts @@ -7,6 +7,7 @@ import { internalError, notFound, validationError } from "@/lib/api-errors"; import { parseLastPractice } from "@/lib/last-practice"; import { createLogger } from "@/lib/logger"; import { prisma } from "@/lib/prisma"; +import { resolveErrorItemRole, subjectAccessSelect } from "@/lib/notebook-access"; import { consumeAiQuota } from "@/lib/ai-quota"; import { withRecoverableResponse } from "@/lib/recoverable-response"; import { trackPracticeGrading } from "@/lib/telemetry/events"; @@ -46,9 +47,14 @@ async function handlePost(req: Request, { user }: AuthenticatedContext) { } else if (errorItemId) { const item = await prisma.errorItem.findUnique({ where: { id: errorItemId }, - select: { userId: true, lastPractice: true }, + select: { + userId: true, + subjectId: true, + lastPractice: true, + subject: { select: subjectAccessSelect(user.id) }, + }, }); - practice = item && item.userId === user.id ? parseLastPractice(item.lastPractice) : null; + practice = item && resolveErrorItemRole(user.id, item) ? parseLastPractice(item.lastPractice) : null; } if (!practice) { return notFound("Practice question not found"); diff --git a/src/app/api/practice/record/route.ts b/src/app/api/practice/record/route.ts index 4936572c..0393f9fa 100644 --- a/src/app/api/practice/record/route.ts +++ b/src/app/api/practice/record/route.ts @@ -8,6 +8,7 @@ import { createLogger } from "@/lib/logger"; import { PRACTICE_RESULTS, scheduleMasteryEvaluation } from "@/lib/mastery"; import { masteryLevelOf } from "@/lib/mastery-status"; import { MAX_FIGURE_SVG_LENGTH, sanitizeFigureSvg } from "@/lib/figure-svg"; +import { resolveErrorItemRole, subjectAccessSelect } from "@/lib/notebook-access"; const logger = createLogger('api:practice:record'); @@ -69,13 +70,17 @@ async function handlePost(req: Request, { user }: AuthenticatedContext) { questionFigureSvg = sanitizeFigureSvg(question.figureSvg); } - // 关联原题时校验归属,防止写入他人的错题 + // 关联原题时校验访问角色,防止写入不可见的错题;只读共享成员也可记录自己的作答 if (errorItemId) { const item = await prisma.errorItem.findUnique({ where: { id: errorItemId }, - select: { userId: true, subject: { select: { name: true } } }, + select: { + userId: true, + subjectId: true, + subject: { select: { name: true, ...subjectAccessSelect(userId) } }, + }, }); - if (!item || item.userId !== userId) { + if (!item || !resolveErrorItemRole(userId, item)) { return notFound("Item not found"); } subject ??= item.subject?.name ?? null; diff --git a/src/app/api/review/due/route.ts b/src/app/api/review/due/route.ts index 8b7b638a..4d2fcae5 100644 --- a/src/app/api/review/due/route.ts +++ b/src/app/api/review/due/route.ts @@ -9,6 +9,7 @@ import { createLogger } from "@/lib/logger"; import { getMasteryThreshold } from "@/lib/mastery"; import { PRACTICE_RECORD_COUNT, masteryStatusOf } from "@/lib/mastery-status"; import { prisma } from "@/lib/prisma"; +import { accessibleErrorItemOwnerOrShareWhere } from "@/lib/notebook-access"; import { getReviewPlan, isReviewDue } from "@/lib/review-schedule"; import type { ReviewRecord } from "@/lib/review-schedule"; @@ -41,7 +42,7 @@ async function handleGet(req: Request, { user }: AuthenticatedContext) { // 作答记录单独平铺查询,并按错题分批读取,避免一次把所有用户历史和父级 ID 放进内存/SQL 参数。 for (let skip = 0; ; skip += REVIEW_ITEM_BATCH_SIZE) { const candidates = await prisma.errorItem.findMany({ - where: { userId: user.id, ...(subjectId ? { subjectId } : {}) }, + where: { ...accessibleErrorItemOwnerOrShareWhere(user.id), ...(subjectId ? { subjectId } : {}) }, orderBy: [{ createdAt: 'asc' }, { id: 'asc' }], skip, take: REVIEW_ITEM_BATCH_SIZE, diff --git a/src/app/api/stats/activity/route.ts b/src/app/api/stats/activity/route.ts index a790abb1..29f9ffc4 100644 --- a/src/app/api/stats/activity/route.ts +++ b/src/app/api/stats/activity/route.ts @@ -6,6 +6,7 @@ import { formatDateTime } from "@/lib/date-time"; import { internalError } from "@/lib/api-errors"; import { createLogger } from "@/lib/logger"; import { resolveStatsSubjectId, practiceSubjectWhere, EXCLUDE_DUPLICATE_IMPORT } from "@/lib/stats/stats-filter"; +import { accessibleErrorItemOwnerOrShareWhere } from "@/lib/notebook-access"; import { computeStreaks } from "@/lib/stats/stats-streak"; import { addDays } from "date-fns"; import { withUser } from "@/lib/api-handler"; @@ -46,9 +47,9 @@ export const GET = withUser(async (req: Request, { user }: AuthenticatedContext) startUtc.setUTCDate(mondayUtc.getUTCDate() - (WEEKS - 1) * DAYS_PER_WEEK); const startStr = formatDateTime(startUtc, 'yyyy-MM-dd', 'UTC'); - // 学科筛选条件 + // 学科筛选条件:自有错题或共享错题本中的错题;练习记录仍按当前账号 const errorWhere: Prisma.ErrorItemWhereInput = { - userId, + ...accessibleErrorItemOwnerOrShareWhere(userId), ...(subjectId ? { subjectId } : {}), }; const practiceWhere: Prisma.PracticeRecordWhereInput = { diff --git a/src/app/api/stats/weak-tags/route.ts b/src/app/api/stats/weak-tags/route.ts index 8498fd74..cbbdb422 100644 --- a/src/app/api/stats/weak-tags/route.ts +++ b/src/app/api/stats/weak-tags/route.ts @@ -5,9 +5,9 @@ import { getDayRange } from "@/lib/date-time"; import { internalError } from "@/lib/api-errors"; import { createLogger } from "@/lib/logger"; import { getMasteryThreshold } from "@/lib/mastery"; -import { PRACTICE_RECORD_COUNT } from "@/lib/mastery-status"; import { parseStatsRange, getRangeStart } from "@/lib/stats/stats-range"; import { resolveStatsSubjectId } from "@/lib/stats/stats-filter"; +import { accessibleErrorItemOwnerOrShareWhere } from "@/lib/notebook-access"; import { buildWeakTags, type WeakTagSourceItem } from "@/lib/tags/weak-tags"; import { withUser } from "@/lib/api-handler"; import type { AuthenticatedContext } from "@/lib/api-handler"; @@ -42,7 +42,7 @@ export const GET = withUser(async (req: Request, { user }: AuthenticatedContext) const sourceItems: WeakTagSourceItem[] = []; const where = { - userId, + ...accessibleErrorItemOwnerOrShareWhere(userId), ...(subjectId ? { subjectId } : {}), ...(rangeStart ? { createdAt: { gte: rangeStart } } : {}), }; @@ -59,9 +59,10 @@ export const GET = withUser(async (req: Request, { user }: AuthenticatedContext) subject: { select: { name: true } }, masteryProbability: true, tags: { select: { name: true, tagSet: true } }, - _count: PRACTICE_RECORD_COUNT, + _count: { select: { practiceRecords: { where: { result: { not: null }, userId } } } }, practiceRecords: { where: { + userId, result: { in: ['correct', 'wrong', 'not_attempted'] }, createdAt: { gte: recentStart, lt: recentEnd }, }, diff --git a/src/app/error-items/[id]/page.tsx b/src/app/error-items/[id]/page.tsx index 9d83cd76..cb0d5418 100644 --- a/src/app/error-items/[id]/page.tsx +++ b/src/app/error-items/[id]/page.tsx @@ -88,11 +88,14 @@ export default function ErrorDetailPage() { setItem((current) => current && { ...current, ...fields }); }, []); - // 保存字段并合并到页面状态,失败时抛出,由各卡片提示 + // 保存字段并合并到页面状态,失败时抛出,由各卡片提示;带上读取时的 updatedAt 供并发编辑校验 const saveFields = async (fields: Partial) => { if (!item) return; - await apiClient.put(`/api/error-items/${item.id}`, fields); - updateItem(fields); + const updated = await apiClient.put>(`/api/error-items/${item.id}`, { + ...fields, + ...(item.updatedAt ? { expectedUpdatedAt: item.updatedAt } : {}), + }); + updateItem({ ...fields, ...(updated.updatedAt ? { updatedAt: updated.updatedAt } : {}) }); }; const reload = async () => { diff --git a/src/components/error-detail/types.ts b/src/components/error-detail/types.ts index 047116b4..d22bc419 100644 --- a/src/components/error-detail/types.ts +++ b/src/components/error-detail/types.ts @@ -8,6 +8,8 @@ export interface KnowledgeTag { /** 错题详情页使用的错题数据(GET /api/error-items/[id]) */ export interface ErrorItemDetail { id: string; + /** 服务端最后更新时间;保存时用作并发编辑校验 */ + updatedAt?: string; shortId?: string | null; seqNo?: number | null; questionText: string; diff --git a/src/components/stats/stats-filter-bar.tsx b/src/components/stats/stats-filter-bar.tsx index 182d5f5b..98b14309 100644 --- a/src/components/stats/stats-filter-bar.tsx +++ b/src/components/stats/stats-filter-bar.tsx @@ -99,7 +99,11 @@ export function StatsFilterBar() { {t.stats?.allSubjects || "All Subjects"} {subjects.map(s => ( - {s.name} + + {s.role && s.role !== "owner" && s.ownerName + ? `${s.name} · ${t.notebooks.sharing.sharedBy.replace("{name}", s.ownerName)}` + : s.name} + ))} diff --git a/src/lib/exam/exam-source-bank.ts b/src/lib/exam/exam-source-bank.ts index 3d7884e4..0bbd0d68 100644 --- a/src/lib/exam/exam-source-bank.ts +++ b/src/lib/exam/exam-source-bank.ts @@ -66,8 +66,11 @@ export interface BankExamSourceItem { * 只使用错题本的学段与学科限定题库范围;题库没有掌握度,scope 与 lastResult 不参与筛选。 */ export async function selectBankExamSourceItems(userId: string, selection: ExamSelection): Promise { + const sharedIds = selection.accessibleSubjectIds ?? []; const notebooks = await prisma.subject.findMany({ - where: { id: { in: selection.subjectIds }, userId }, + where: sharedIds.length > 0 + ? { id: { in: selection.subjectIds }, OR: [{ userId }, { id: { in: sharedIds } }] } + : { id: { in: selection.subjectIds }, userId }, select: { stage: true, subjectKey: true }, }); if (notebooks.length === 0) return []; diff --git a/src/lib/exam/exam.ts b/src/lib/exam/exam.ts index c8aeb403..f1485599 100644 --- a/src/lib/exam/exam.ts +++ b/src/lib/exam/exam.ts @@ -60,6 +60,11 @@ export interface ExamSelection { difficulty?: string; /** 排除已选的原题 ID(A/B 卷平行组卷时避免两卷题目重复) */ excludeIds?: string[]; + /** + * 当前账号已接受共享的错题本 ID。组卷时按 userId 或这些共享错题本取题, + * 由调用方在验证 subjectIds 可访问后传入;为空时保持只取自己的错题。 + */ + accessibleSubjectIds?: string[]; /** * 指定题号(流水号、6 位短 ID 或 CUID)。提供时按输入顺序出题, * 忽略范围、知识点、卷别、题型与抽题规则,count 由调用方按题号数量设置。 @@ -68,9 +73,12 @@ export interface ExamSelection { } /** 构造抽题条件:限定错题本、掌握范围(按用户的已掌握阈值),可选按知识点标签和卷别分组 */ -export function buildSourceWhere(userId: string, selection: ExamSelection, masteryThreshold = DEFAULT_MASTERY_THRESHOLD): Prisma.ErrorItemWhereInput { +export function buildSourceWhere(userId: string, selection: ExamSelection, masteryThreshold = DEFAULT_MASTERY_THRESHOLD, accessibleSubjectIds: string[] = []): Prisma.ErrorItemWhereInput { const where: Prisma.ErrorItemWhereInput = { - userId, + // 共享错题本中的题由所有者创建,按 userId 或已接受共享的错题本归属取题 + ...(accessibleSubjectIds.length > 0 + ? { OR: [{ userId }, { subjectId: { in: accessibleSubjectIds } }] } + : { userId }), subjectId: { in: selection.subjectIds }, shortId: { not: null }, }; @@ -175,7 +183,9 @@ async function selectExplicitQuestionIds(userId: string, selection: ExamSelectio if (or.length === 0) return []; const rows = await prisma.errorItem.findMany({ - where: { userId, OR: or }, + where: selection.accessibleSubjectIds?.length + ? { AND: [{ OR: [{ userId }, { subjectId: { in: selection.accessibleSubjectIds } }] }, { OR: or }] } + : { userId, OR: or }, select: { id: true, shortId: true, @@ -211,7 +221,7 @@ export async function selectSourceItems(userId: string, selection: ExamSelection if (selection.questionIds && selection.questionIds.length > 0) { return selectExplicitQuestionIds(userId, selection); } - const where = buildSourceWhere(userId, selection, await getMasteryThreshold(userId)); + const where = buildSourceWhere(userId, selection, await getMasteryThreshold(userId), selection.accessibleSubjectIds ?? []); if (selection.excludeIds && selection.excludeIds.length > 0) { where.id = { notIn: selection.excludeIds }; } diff --git a/src/lib/notebook-access.ts b/src/lib/notebook-access.ts index a0f7f940..c9690911 100644 --- a/src/lib/notebook-access.ts +++ b/src/lib/notebook-access.ts @@ -149,6 +149,19 @@ export function subjectAccessSelect(userId: string) { } as const; } +/** + * 可读错题条件:自己创建的题,或位于已接受共享的错题本中的题。 + * 用关系过滤直接按当前用户与 active 共享判断,适合统计、复习等不预先取错题本 ID 的查询。 + */ +export function accessibleErrorItemOwnerOrShareWhere(userId: string): Prisma.ErrorItemWhereInput { + return { + OR: [ + { userId }, + { subject: { shares: { some: { memberId: userId, status: "active" } } } }, + ], + }; +} + /** 可读错题条件:自己创建的题,或位于可读错题本(自有/共享)中的题 */ export function accessibleErrorItemWhere(userId: string, readIds: string[]): Prisma.ErrorItemWhereInput { if (readIds.length === 0) return { userId }; diff --git a/src/lib/schemas/error-items.ts b/src/lib/schemas/error-items.ts index fcfab4c8..11ea3bf2 100644 --- a/src/lib/schemas/error-items.ts +++ b/src/lib/schemas/error-items.ts @@ -28,6 +28,8 @@ export const updateErrorItemSchema = z.object({ { message: "figureAlign must be left, center, or right" }, ), figureSource: z.enum(["svg", "image", "upload"]).optional(), + /** 并发编辑保护:客户端读取时的 updatedAt;服务端已更新则返回 409 */ + expectedUpdatedAt: z.string().datetime({ offset: true }).optional(), /** 人工修正后的小问列表;null 表示恢复为整题(旧单问题目) */ subQuestions: z.union([ z.array(SubQuestionSchema).max(MAX_SUB_QUESTIONS), diff --git a/src/lib/stats/stats-filter.ts b/src/lib/stats/stats-filter.ts index 8300a7d2..cc7d3b23 100644 --- a/src/lib/stats/stats-filter.ts +++ b/src/lib/stats/stats-filter.ts @@ -1,11 +1,13 @@ import { prisma } from "@/lib/prisma"; import type { Prisma } from "@prisma/client"; +import { accessibleSubjectWhere } from "@/lib/notebook-access"; /** 重复导入产生的记录不计入练习统计 */ export const EXCLUDE_DUPLICATE_IMPORT = { source: { not: 'duplicate_import' } } satisfies Prisma.PracticeRecordWhereInput; /** - * 校验 subjectId 是否属于当前用户;不属于时返回 null(当作未筛选)。 + * 校验 subjectId 是否属于当前用户或已接受共享的错题本;不属于时返回 null(当作未筛选)。 + * 共享错题本的统计按该错题本本身归属,不串入其他账号的错题本。 */ export async function resolveStatsSubjectId( userId: string, @@ -13,7 +15,7 @@ export async function resolveStatsSubjectId( ): Promise<{ id: string; name: string } | null> { if (!subjectIdParam) return null; const subject = await prisma.subject.findFirst({ - where: { id: subjectIdParam, userId }, + where: { id: subjectIdParam, ...accessibleSubjectWhere(userId) }, select: { id: true, name: true }, }); return subject;