mirror of
https://github.com/margrop/wrong-notebook.git
synced 2026-12-06 09:39:44 +08:00
fix: 同步 MCP 共享错题本读写权限
- list_notebooks 返回自有与已接受共享错题本及 owner/edit/read 角色 - list_questions 与 get_question 可读共享错题本,修复列表可见但详情报未找到 - add/update/delete/move 批量工具按错题本与题目可写性校验,只读成员写入返回失败 - 补充共享读取与只读写入拦截的 MCP 集成测试,同步中英文 MCP 手册
This commit is contained in:
@@ -106,11 +106,11 @@ curl --fail-with-body http://localhost:3000/api/mcp \
|
||||
|
||||
| 工具 | 作用 | 主要参数 |
|
||||
| --- | --- | --- |
|
||||
| `list_notebooks` | 列出错题本与题目数 | 无 |
|
||||
| `list_notebooks` | 列出自有与已接受共享的错题本、题目数与角色 | 无 |
|
||||
| `create_notebook` | 创建错题本 | `name`、`stage`、`subjectKey`、`tagSet` |
|
||||
| `list_questions` | 筛选、搜索与分页错题 | `notebookId`、`query`、`tag`、`chapter`、`mastery`、`timeRange`、`gradeSemester`、`paperLevel`、`questionTypes`、`page`、`pageSize` |
|
||||
| `get_question` | 读取单题正文、答案、解析、标签与掌握状态 | `id`(CUID 或 6 位短 ID)、`includeImage` |
|
||||
| `add_question` | 新增错题;未知知识点会按标签体系创建 | 题目文字/图片、`knowledgePoints`、`notebookId` 或 `subjectName`、`gradeSemester`、难度与题型、`figureSvg`、`figureImage`、`figureSource` 等 |
|
||||
| `list_questions` | 筛选、搜索与分页自有及共享错题 | `notebookId`、`query`、`tag`、`chapter`、`mastery`、`timeRange`、`gradeSemester`、`paperLevel`、`questionTypes`、`page`、`pageSize` |
|
||||
| `get_question` | 读取自有及共享单题正文、答案、解析、标签与掌握状态 | `id`(CUID 或 6 位短 ID)、`includeImage` |
|
||||
| `add_question` | 在可写错题本新增错题;未知知识点会按标签体系创建 | 题目文字/图片、`knowledgePoints`、`notebookId` 或 `subjectName`、`gradeSemester`、难度与题型、`figureSvg`、`figureImage`、`figureSource` 等 |
|
||||
| `list_tags` | 列出知识点标签 | `subject`、`tagSet`、`query`、`flat`(默认叶子列表) |
|
||||
| `list_due_reviews` | 今日待复习错题 | `notebookId`、`page`、`pageSize` |
|
||||
| `get_weak_tags` | 薄弱知识点排行 | `notebookId`、`range`(`7d`/`30d`/`6m`/`all`)、`limit` |
|
||||
@@ -124,9 +124,9 @@ curl --fail-with-body http://localhost:3000/api/mcp \
|
||||
| `list_review_candidates` | 按知识点、上次作答结果与题量选到期复习题 | `notebookId`、`tag`、`lastResult`、`page`、`pageSize` |
|
||||
| `get_mastery_stats` | 按学科、年级与知识点返回掌握分布与薄弱点 | `notebookId`、`gradeSemester`、`tag`、`range`、`limit` |
|
||||
| `add_questions_batch` | 一次新增最多 100 题,逐条复用判重、标签与年级规则 | `notebookId` 或 `subjectName`、`questions`(每题字段同 `add_question`) |
|
||||
| `update_questions_batch` | 一次修改最多 100 题;逐题独立事务并返回逐条结果 | `ids`(CUID 或 6 位短 ID)、`source`、`gradeSemester`、`paperLevel`、`knowledgePoints`(`null` 清空)、`questionType`、`difficultyStars`、`mistakeStatus`、`masteryLevel` |
|
||||
| `delete_questions_batch` | 一次删除最多 100 题 | `ids` |
|
||||
| `move_questions_batch` | 一次把最多 100 题移动到指定错题本,标签保持不变 | `ids`、`subjectId` |
|
||||
| `update_questions_batch` | 一次修改最多 100 道可写错题;逐题独立事务并返回逐条结果 | `ids`(CUID 或 6 位短 ID)、`source`、`gradeSemester`、`paperLevel`、`knowledgePoints`(`null` 清空)、`questionType`、`difficultyStars`、`mistakeStatus`、`masteryLevel` |
|
||||
| `delete_questions_batch` | 一次删除最多 100 道可写错题 | `ids` |
|
||||
| `move_questions_batch` | 一次把最多 100 道可写错题移动到可写错题本,标签保持不变 | `ids`、`subjectId` |
|
||||
| `create_import_task` | 创建文字或图片识别导入任务,后台 OCR/解析并入库或等待校对 | `questionText` 或 `imageBase64`、`clientRequestId`、`notebookId`、`referenceNotebookId`、`paperLevel`、`source`、`language`、`mode` |
|
||||
| `get_import_task` | 读取导入任务状态、识别结果、错误与已入库题目 | `id` |
|
||||
| `retry_import_task` | 重试失败的导入任务;已有识别结果时只重试保存 | `id` |
|
||||
@@ -143,6 +143,7 @@ curl --fail-with-body http://localhost:3000/api/mcp \
|
||||
补充约定:
|
||||
|
||||
- 工具结果均为 JSON 文本;客户端按 JSON 解析。调用失败返回 `isError: true`。
|
||||
- 共享错题本:`list_notebooks`、`list_questions`、`get_question` 可读自有与已接受共享(`role` 为 `owner`/`edit`/`read`);`add_question`、`add_questions_batch`、`update_questions_batch`、`delete_questions_batch`、`move_questions_batch` 要求错题本与题目可写(`owner` 或 `edit`),只读成员的写入按失败返回。
|
||||
- `add_question` 沿用「添加错题」接口的判重、年级与卷别规则;重复题返回 `duplicate` 并记录一次做错。未填 `gradeSemester` 且账号使用「AI 识别」年级规则时,会补充一次 AI 识别并计入每日用量;账号尚未同意 AI 数据授权时,需要 AI 的调用失败。
|
||||
- `get_question` 默认不返回原图;`includeImage: true` 时可能返回很大的 Base64 data URL。
|
||||
- `add_question` 的配图可用 `figureSvg`(AI 重绘)与 `figureImage`(裁剪原图,PNG data URI)分别传入,`figureSource` 选择界面显示来源(`svg` 默认,`image` 为原图)。`figureSvg` 支持内嵌位图,即 `<image href="data:image/png;base64,…">`(PNG/JPEG/GIF/WebP/AVIF),外部链接会被净化掉。
|
||||
|
||||
@@ -106,11 +106,11 @@ Change `method` to `tools/list` to list tools. Call a tool:
|
||||
|
||||
| Tool | Purpose | Main arguments |
|
||||
| --- | --- | --- |
|
||||
| `list_notebooks` | List notebooks with question counts | none |
|
||||
| `list_notebooks` | List owned and accepted shared notebooks with question counts and role | none |
|
||||
| `create_notebook` | Create a notebook | `name`, `stage`, `subjectKey`, `tagSet` |
|
||||
| `list_questions` | Filter, search and paginate questions | `notebookId`, `query`, `tag`, `chapter`, `mastery`, `timeRange`, `gradeSemester`, `paperLevel`, `questionTypes`, `page`, `pageSize` |
|
||||
| `get_question` | Read one question's text, answer, analysis, tags and mastery status | `id` (CUID or 6-character short ID), `includeImage` |
|
||||
| `add_question` | Add a question; unknown knowledge points are created in the tag set | question text/image, `knowledgePoints`, `notebookId` or `subjectName`, `gradeSemester`, difficulty and type, `figureSvg`, `figureImage`, `figureSource`, etc. |
|
||||
| `list_questions` | Filter, search and paginate questions in owned and shared notebooks | `notebookId`, `query`, `tag`, `chapter`, `mastery`, `timeRange`, `gradeSemester`, `paperLevel`, `questionTypes`, `page`, `pageSize` |
|
||||
| `get_question` | Read one question from an owned or shared notebook with text, answer, analysis, tags and mastery status | `id` (CUID or 6-character short ID), `includeImage` |
|
||||
| `add_question` | Add a question to a writable notebook; unknown knowledge points are created in the tag set | question text/image, `knowledgePoints`, `notebookId` or `subjectName`, `gradeSemester`, difficulty and type, `figureSvg`, `figureImage`, `figureSource`, etc. |
|
||||
| `list_tags` | List knowledge tags | `subject`, `tagSet`, `query`, `flat` (leaf list by default) |
|
||||
| `list_due_reviews` | Questions due for review today | `notebookId`, `page`, `pageSize` |
|
||||
| `get_weak_tags` | Rank weak knowledge points | `notebookId`, `range` (`7d`/`30d`/`6m`/`all`), `limit` |
|
||||
@@ -124,9 +124,9 @@ Change `method` to `tools/list` to list tools. Call a tool:
|
||||
| `list_review_candidates` | Select due reviews by tag, last result and question count | `notebookId`, `tag`, `lastResult`, `page`, `pageSize` |
|
||||
| `get_mastery_stats` | Mastery distribution and weak points by subject, grade and tag | `notebookId`, `gradeSemester`, `tag`, `range`, `limit` |
|
||||
| `add_questions_batch` | Add up to 100 questions in one call, reusing duplicate, tag and grade rules per item | `notebookId` or `subjectName`, `questions` (same fields as `add_question`) |
|
||||
| `update_questions_batch` | Update up to 100 questions; each item in its own transaction with per-item results | `ids` (CUID or 6-character short ID), `source`, `gradeSemester`, `paperLevel`, `knowledgePoints` (`null` clears), `questionType`, `difficultyStars`, `mistakeStatus`, `masteryLevel` |
|
||||
| `delete_questions_batch` | Delete up to 100 questions in one call | `ids` |
|
||||
| `move_questions_batch` | Move up to 100 questions to a target notebook, keeping tags | `ids`, `subjectId` |
|
||||
| `update_questions_batch` | Update up to 100 writable questions; each item in its own transaction with per-item results | `ids` (CUID or 6-character short ID), `source`, `gradeSemester`, `paperLevel`, `knowledgePoints` (`null` clears), `questionType`, `difficultyStars`, `mistakeStatus`, `masteryLevel` |
|
||||
| `delete_questions_batch` | Delete up to 100 writable questions in one call | `ids` |
|
||||
| `move_questions_batch` | Move up to 100 writable questions to a writable target notebook, keeping tags | `ids`, `subjectId` |
|
||||
| `create_import_task` | Create a text or image OCR/analysis import task that saves or waits for review | `questionText` or `imageBase64`, `clientRequestId`, `notebookId`, `referenceNotebookId`, `paperLevel`, `source`, `language`, `mode` |
|
||||
| `get_import_task` | Read import task status, recognized result, error and saved question | `id` |
|
||||
| `retry_import_task` | Retry a failed import task; only saving is retried when a result exists | `id` |
|
||||
@@ -143,6 +143,7 @@ Change `method` to `tools/list` to list tools. Call a tool:
|
||||
Notes:
|
||||
|
||||
- Tool results are JSON text; clients parse the JSON. Failures return `isError: true`.
|
||||
- Shared notebooks: `list_notebooks`, `list_questions` and `get_question` can read owned and accepted shared notebooks (`role` is `owner`/`edit`/`read`); `add_question`, `add_questions_batch`, `update_questions_batch`, `delete_questions_batch` and `move_questions_batch` require a writable notebook and question (`owner` or `edit`), so read-only member writes are returned as failures.
|
||||
- `add_question` follows the same duplicate detection, grade and paper-group rules as the Add Question API. A duplicate returns `duplicate` and records another wrong attempt. When `gradeSemester` is omitted and the account uses AI grade recognition, one extra AI call counts against the daily quota; if the account has not accepted AI data consent, AI-dependent calls fail.
|
||||
- `get_question` omits the original image by default; `includeImage: true` may return a large Base64 data URL.
|
||||
- `add_question` accepts figures separately: `figureSvg` (AI redraw) and `figureImage` (the cropped original figure as a PNG data URI), with `figureSource` selecting the displayed source (`svg` by default; `image` for the original crop). `figureSvg` may embed a bitmap via `<image href="data:image/png;base64,…">` (PNG/JPEG/GIF/WebP/AVIF); external links are stripped by sanitization.
|
||||
|
||||
@@ -159,6 +159,39 @@ async function addErrorItem(questionText = '解方程 x+1=2') {
|
||||
return data.question.id;
|
||||
}
|
||||
|
||||
/** 创建他人错题本并共享给 MCP 固定账号(user-1),返回其中的错题 */
|
||||
async function createSharedQuestion(role: 'read' | 'edit') {
|
||||
const owner = await database.user.create({
|
||||
data: { id: 'owner-2', email: 'owner2@example.com', password: 'test-only', name: 'Owner2', masteryThreshold: 50 },
|
||||
});
|
||||
const notebook = await database.subject.create({
|
||||
data: {
|
||||
id: 'shared-math',
|
||||
name: '共享数学',
|
||||
userId: owner.id,
|
||||
subjectKey: 'math',
|
||||
tagSet: 'default',
|
||||
stage: 'junior_high',
|
||||
},
|
||||
});
|
||||
const item = await database.errorItem.create({
|
||||
data: {
|
||||
id: 'shared-item',
|
||||
shortId: 'abc123',
|
||||
userId: owner.id,
|
||||
subjectId: notebook.id,
|
||||
originalImageUrl: 'data:image/png;base64,AA==',
|
||||
questionText: '共享错题',
|
||||
answerText: '42',
|
||||
gradeSemester: '七年级上',
|
||||
},
|
||||
});
|
||||
await database.notebookShare.create({
|
||||
data: { subjectId: notebook.id, memberId: 'user-1', invitedById: owner.id, role, status: 'active' },
|
||||
});
|
||||
return item;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
directory = mkdtempSync(join(tmpdir(), 'wrong-notebook-mcp-test-'));
|
||||
const url = `file:${join(directory, 'test.db')}`;
|
||||
@@ -547,6 +580,60 @@ describe('MCP 服务', () => {
|
||||
expect(detailData.question.subject.name).toBe('数学');
|
||||
});
|
||||
|
||||
it('共享错题本可读:list_notebooks 带角色,list_questions 与 get_question 一致', async () => {
|
||||
await createSharedQuestion('read');
|
||||
|
||||
const notebooks = toolJson((await callTool('list_notebooks')).result!) as {
|
||||
notebooks: { id: string; role: string }[];
|
||||
};
|
||||
expect(notebooks.notebooks).toContainEqual(expect.objectContaining({ id: 'math', role: 'owner' }));
|
||||
expect(notebooks.notebooks).toContainEqual(expect.objectContaining({ id: 'shared-math', role: 'read' }));
|
||||
|
||||
const list = await callTool('list_questions', {});
|
||||
const listData = toolJson(list.result!) as { items: { id: string; questionText: string }[] };
|
||||
expect(listData.items).toContainEqual(expect.objectContaining({ id: 'shared-item', questionText: '共享错题' }));
|
||||
|
||||
const detail = await callTool('get_question', { id: 'abc123' });
|
||||
const detailData = toolJson(detail.result!) as { question: { questionText: string; subject: { name: string } } };
|
||||
expect(detailData.question.questionText).toBe('共享错题');
|
||||
expect(detailData.question.subject.name).toBe('共享数学');
|
||||
});
|
||||
|
||||
it('只读共享成员通过 MCP 写入被拒绝,可编辑成员可修改', async () => {
|
||||
await createSharedQuestion('read');
|
||||
|
||||
const add = await callTool('add_question', { notebookId: 'shared-math', questionText: '只读成员新增' });
|
||||
expect(add.result?.isError).toBe(true);
|
||||
expect(add.result?.content[0].text).toContain('not writable');
|
||||
|
||||
const update = await callTool('update_questions_batch', { ids: ['abc123'], source: '只读修改' });
|
||||
const updateData = toolJson(update.result!) as { updated: number; failed: number; results: { error?: string }[] };
|
||||
expect(updateData.updated).toBe(0);
|
||||
expect(updateData.failed).toBe(1);
|
||||
expect(updateData.results[0].error).toContain('not writable');
|
||||
|
||||
const deleted = await callTool('delete_questions_batch', { ids: ['abc123'] });
|
||||
const deleteData = toolJson(deleted.result!) as { deleted: number; failed: string[] };
|
||||
expect(deleteData.deleted).toBe(0);
|
||||
expect(deleteData.failed).toEqual(['abc123']);
|
||||
|
||||
const moved = await callTool('move_questions_batch', { ids: ['abc123'], subjectId: 'math' });
|
||||
const moveData = toolJson(moved.result!) as { moved: number; failed: string[] };
|
||||
expect(moveData.moved).toBe(0);
|
||||
expect(moveData.failed).toEqual(['abc123']);
|
||||
expect(await database.errorItem.findUnique({ where: { id: 'shared-item' } })).not.toBeNull();
|
||||
|
||||
await database.notebookShare.update({
|
||||
where: { subjectId_memberId: { subjectId: 'shared-math', memberId: 'user-1' } },
|
||||
data: { role: 'edit' },
|
||||
});
|
||||
const edited = await callTool('update_questions_batch', { ids: ['abc123'], source: '可编辑修改' });
|
||||
const editedData = toolJson(edited.result!) as { updated: number; failed: number };
|
||||
expect(editedData.updated).toBe(1);
|
||||
expect(editedData.failed).toBe(0);
|
||||
expect((await database.errorItem.findUnique({ where: { id: 'shared-item' } }))?.source).toBe('可编辑修改');
|
||||
});
|
||||
|
||||
it('list_tags 返回叶子知识点标签', async () => {
|
||||
await database.knowledgeTag.create({
|
||||
data: { name: '一元一次方程', subject: 'math', isSystem: false, userId: 'user-1', tagSet: 'default' },
|
||||
|
||||
@@ -83,7 +83,7 @@ export function createMcpServer(user: User): McpServer {
|
||||
"list_notebooks",
|
||||
{
|
||||
title: "List notebooks",
|
||||
description: "List the user's wrong-notebooks (错题本) with stage, subject and question count. Returns JSON.",
|
||||
description: "List wrong-notebooks (错题本) the account owns or has accepted shared access to, with stage, subject, question count and role (owner/edit/read). Returns JSON.",
|
||||
annotations: { readOnlyHint: true },
|
||||
},
|
||||
async () => jsonResult({ notebooks: await listNotebooks(user.id) }),
|
||||
@@ -110,7 +110,7 @@ export function createMcpServer(user: User): McpServer {
|
||||
"list_questions",
|
||||
{
|
||||
title: "List / search questions",
|
||||
description: "List error questions with filters and pagination. Use notebookId, query text, tag name, mastery status, time range, grade semester, paper level or question types. Returns compact cards as JSON with masteryStatus.",
|
||||
description: "List error questions in owned and accepted shared notebooks with filters and pagination. Use notebookId, query text, tag name, mastery status, time range, grade semester, paper level or question types. Returns compact cards as JSON with masteryStatus.",
|
||||
inputSchema: {
|
||||
notebookId: z.string().optional().describe("Notebook (subject) id"),
|
||||
query: z.string().optional().describe("Text search in question, analysis, wrong answer and knowledge points; a 6-character short id also matches"),
|
||||
@@ -133,7 +133,7 @@ export function createMcpServer(user: User): McpServer {
|
||||
"get_question",
|
||||
{
|
||||
title: "Get question",
|
||||
description: "Get one question by CUID id or 6-character shortId, including question text, answer, analysis, mistake notes, tags, notebook and mastery status. Set includeImage=true to also return the original image data URL or URL. Returns JSON.",
|
||||
description: "Get one question from an owned or accepted shared notebook by CUID id or 6-character shortId, including question text, answer, analysis, mistake notes, tags, notebook and mastery status. Set includeImage=true to also return the original image data URL or URL. Returns JSON.",
|
||||
inputSchema: {
|
||||
id: z.string().min(1).describe("Question CUID or shortId"),
|
||||
includeImage: z.boolean().optional().describe("Include originalImageUrl (may be large base64)"),
|
||||
@@ -149,7 +149,7 @@ export function createMcpServer(user: User): McpServer {
|
||||
"add_question",
|
||||
{
|
||||
title: "Add question",
|
||||
description: "Add an error question to a notebook. Provide questionText and/or originalImageUrl. knowledgePoints are tag names; unknown names are created under the notebook's tag set. Duplicate detection applies. If gradeSemester is omitted and the account uses AI grade recognition, one AI call counts against quota. Returns JSON with created or duplicate status.",
|
||||
description: "Add an error question to an owned or editable shared notebook. Provide questionText and/or originalImageUrl. knowledgePoints are tag names; unknown names are created under the notebook's tag set. Duplicate detection applies. If gradeSemester is omitted and the account uses AI grade recognition, one AI call counts against quota. Returns JSON with created or duplicate status.",
|
||||
inputSchema: {
|
||||
notebookId: z.string().optional().describe("Target notebook id; omit to use subjectName"),
|
||||
subjectName: z.string().optional().describe("Notebook name; creates it if missing when notebookId is omitted"),
|
||||
@@ -441,7 +441,7 @@ export function createMcpServer(user: User): McpServer {
|
||||
"update_questions_batch",
|
||||
{
|
||||
title: "Update questions in batch",
|
||||
description: "Update up to 100 owned questions by CUID or 6-character shortId. Fields: source, gradeSemester, paperLevel, knowledgePoints (null clears tags), questionType, difficultyStars, mistakeStatus, masteryLevel. At least one field is required. Each item is updated independently; returns JSON with total/updated/failed and per-id results including tags.",
|
||||
description: "Update up to 100 writable questions (owned notebooks or edit-role shared notebooks) by CUID or 6-character shortId. Fields: source, gradeSemester, paperLevel, knowledgePoints (null clears tags), questionType, difficultyStars, mistakeStatus, masteryLevel. At least one field is required. Each item is updated independently; returns JSON with total/updated/failed and per-id results including tags.",
|
||||
inputSchema: {
|
||||
ids: z.array(z.string().trim().min(1)).min(1).max(100).describe("CUID or 6-character shortId list"),
|
||||
source: z.string().trim().max(200).nullable().optional(),
|
||||
@@ -461,7 +461,7 @@ export function createMcpServer(user: User): McpServer {
|
||||
"delete_questions_batch",
|
||||
{
|
||||
title: "Delete questions in batch",
|
||||
description: "Delete up to 100 owned questions by CUID or 6-character shortId in one call. Returns JSON with deleted count and failed ids (not found or owned by another user).",
|
||||
description: "Delete up to 100 writable questions (owned notebooks or edit-role shared notebooks) by CUID or 6-character shortId in one call. Returns JSON with deleted count and failed ids (not found or not writable).",
|
||||
inputSchema: {
|
||||
ids: z.array(z.string().trim().min(1)).min(1).max(100),
|
||||
},
|
||||
@@ -473,10 +473,10 @@ export function createMcpServer(user: User): McpServer {
|
||||
"move_questions_batch",
|
||||
{
|
||||
title: "Move questions to notebook in batch",
|
||||
description: "Move up to 100 owned questions to another owned notebook by CUID or 6-character shortId. Knowledge tags are kept. Returns JSON with moved count and failed ids.",
|
||||
description: "Move up to 100 writable questions to another writable notebook by CUID or 6-character shortId. Knowledge tags are kept. Returns JSON with moved count and failed ids.",
|
||||
inputSchema: {
|
||||
ids: z.array(z.string().trim().min(1)).min(1).max(100),
|
||||
subjectId: z.string().trim().min(1).describe("Target notebook id owned by the user"),
|
||||
subjectId: z.string().trim().min(1).describe("Target notebook id with owner or edit role"),
|
||||
},
|
||||
},
|
||||
async (args) => jsonResult(await moveQuestionsBatch(user, args)),
|
||||
|
||||
@@ -2,6 +2,8 @@ import "server-only";
|
||||
|
||||
import type { User } from "@prisma/client";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { accessibleSubjectWhere, isNotebookShareRole } from "@/lib/notebook-access";
|
||||
import type { NotebookRole } from "@/lib/notebook-access";
|
||||
import type { NotebookStage, NotebookSubject } from "@/lib/notebook-scope";
|
||||
import { createNotebookSchema } from "@/lib/schemas/notebooks";
|
||||
import { McpToolError } from "./shared";
|
||||
@@ -14,18 +16,37 @@ export interface NotebookSummary {
|
||||
tagSet: string;
|
||||
questionCount: number;
|
||||
createdAt: Date;
|
||||
role: NotebookRole | null;
|
||||
}
|
||||
|
||||
export async function listNotebooks(userId: string): Promise<NotebookSummary[]> {
|
||||
const notebooks = await prisma.subject.findMany({
|
||||
where: { userId },
|
||||
include: { _count: { select: { errorItems: true } } },
|
||||
where: accessibleSubjectWhere(userId),
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
stage: true,
|
||||
subjectKey: true,
|
||||
tagSet: true,
|
||||
createdAt: true,
|
||||
userId: true,
|
||||
shares: {
|
||||
where: { memberId: userId, status: "active" },
|
||||
select: { role: true },
|
||||
take: 1,
|
||||
},
|
||||
_count: { select: { errorItems: true } },
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
return notebooks.map(({ _count, ...notebook }) => ({
|
||||
...notebook,
|
||||
questionCount: _count.errorItems,
|
||||
}));
|
||||
return notebooks.map(({ _count, userId: ownerId, shares, ...notebook }) => {
|
||||
const shareRole = shares[0]?.role;
|
||||
return {
|
||||
...notebook,
|
||||
questionCount: _count.errorItems,
|
||||
role: ownerId === userId ? "owner" : isNotebookShareRole(shareRole) ? shareRole : null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export interface CreateNotebookInput {
|
||||
@@ -55,5 +76,5 @@ export async function createNotebook(user: User, input: CreateNotebookInput): Pr
|
||||
include: { _count: { select: { errorItems: true } } },
|
||||
});
|
||||
const { _count, ...created } = notebook;
|
||||
return { ...created, questionCount: _count.errorItems };
|
||||
return { ...created, questionCount: _count.errorItems, role: "owner" };
|
||||
}
|
||||
|
||||
@@ -9,6 +9,15 @@ import { buildErrorListWhere, parseErrorListQueryParams } from "@/lib/error-list
|
||||
import type { ErrorListQueryParams } from "@/lib/error-list/error-list-query";
|
||||
import { ERROR_ITEM_LIST_SELECT } from "@/lib/error-list/error-list-select";
|
||||
import { getErrorMessage } from "@/lib/error-message";
|
||||
import {
|
||||
accessibleErrorItemOwnerOrShareWhere,
|
||||
canWriteNotebook,
|
||||
getNotebookAccessSets,
|
||||
getNotebookRole,
|
||||
resolveErrorItemRole,
|
||||
subjectAccessSelect,
|
||||
writableErrorItemWhere,
|
||||
} from "@/lib/notebook-access";
|
||||
import { PRACTICE_RECORD_COUNT, masteryStatusOf } from "@/lib/mastery-status";
|
||||
import type { MasteryStatus } from "@/lib/mastery-status";
|
||||
import { normalizeMistakeStatusForSave } from "@/lib/question/mistake-status";
|
||||
@@ -48,7 +57,8 @@ export async function listQuestions(user: User, input: ListQuestionsInput) {
|
||||
if (input.pageSize !== undefined) params.set("pageSize", String(input.pageSize));
|
||||
|
||||
const query: ErrorListQueryParams = parseErrorListQueryParams(params);
|
||||
const where = await buildErrorListWhere(query, user.id, user.masteryThreshold, prisma);
|
||||
const { readIds } = await getNotebookAccessSets(user.id);
|
||||
const where = await buildErrorListWhere(query, user.id, user.masteryThreshold, prisma, readIds);
|
||||
|
||||
const select = {
|
||||
...ERROR_ITEM_LIST_SELECT,
|
||||
@@ -102,22 +112,30 @@ export async function getQuestion(userId: string, masteryThreshold: number, inpu
|
||||
masteryReason: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
subject: { select: { id: true, name: true } },
|
||||
userId: true,
|
||||
subjectId: true,
|
||||
subject: { select: { id: true, name: true, ...subjectAccessSelect(userId) } },
|
||||
tags: { select: { id: true, name: true } },
|
||||
_count: PRACTICE_RECORD_COUNT,
|
||||
...(input.includeImage ? { originalImageUrl: true } : {}),
|
||||
} satisfies Prisma.ErrorItemSelect;
|
||||
|
||||
const item = await prisma.errorItem.findFirst({
|
||||
where: { userId, OR: [{ id: input.id }, { shortId: input.id }] },
|
||||
where: {
|
||||
AND: [
|
||||
{ OR: [{ id: input.id }, { shortId: input.id }] },
|
||||
accessibleErrorItemOwnerOrShareWhere(userId),
|
||||
],
|
||||
},
|
||||
select,
|
||||
});
|
||||
if (!item) {
|
||||
if (!item || !resolveErrorItemRole(userId, item)) {
|
||||
throw new McpToolError(`Question "${input.id}" not found`);
|
||||
}
|
||||
const { _count, ...rest } = item;
|
||||
const { _count, userId: _ownerId, subjectId: _subjectId, subject, ...rest } = item;
|
||||
return {
|
||||
...rest,
|
||||
subject: subject ? { id: subject.id, name: subject.name } : null,
|
||||
practiceRecordCount: _count.practiceRecords,
|
||||
masteryStatus: masteryStatusOf(_count.practiceRecords, item.masteryProbability, masteryThreshold),
|
||||
};
|
||||
@@ -149,12 +167,9 @@ export interface AddQuestionInput {
|
||||
|
||||
export async function addQuestion(user: User, input: AddQuestionInput): Promise<SaveQuestionResult> {
|
||||
if (input.notebookId) {
|
||||
const notebook = await prisma.subject.findFirst({
|
||||
where: { id: input.notebookId, userId: user.id },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!notebook) {
|
||||
throw new McpToolError(`Notebook "${input.notebookId}" not found for this user`);
|
||||
const role = await getNotebookRole(user.id, input.notebookId);
|
||||
if (!canWriteNotebook(role)) {
|
||||
throw new McpToolError(`Notebook "${input.notebookId}" not found or not writable for this user`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -297,13 +312,19 @@ export async function updateQuestionsBatch(user: User, input: BatchUpdateQuestio
|
||||
}
|
||||
}
|
||||
|
||||
const { writeIds } = await getNotebookAccessSets(user.id);
|
||||
const results: BatchUpdateQuestionsResult["results"] = [];
|
||||
let updated = 0;
|
||||
let failed = 0;
|
||||
|
||||
for (const id of ids) {
|
||||
const item = await prisma.errorItem.findFirst({
|
||||
where: { userId: user.id, OR: [{ id }, { shortId: id }] },
|
||||
where: {
|
||||
AND: [
|
||||
{ OR: [{ id }, { shortId: id }] },
|
||||
writableErrorItemWhere(user.id, writeIds),
|
||||
],
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
shortId: true,
|
||||
@@ -314,7 +335,7 @@ export async function updateQuestionsBatch(user: User, input: BatchUpdateQuestio
|
||||
});
|
||||
if (!item) {
|
||||
failed += 1;
|
||||
results.push({ id, status: "failed", error: "Question not found for this user" });
|
||||
results.push({ id, status: "failed", error: "Question not found or not writable for this user" });
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -367,10 +388,20 @@ export async function updateQuestionsBatch(user: User, input: BatchUpdateQuestio
|
||||
return { total: ids.length, updated, failed, results };
|
||||
}
|
||||
|
||||
/** 把输入 id(CUID 或短 ID)映射到当前用户的错题;返回归属映射与失败列表 */
|
||||
async function resolveOwnedErrorItems(userId: string, ids: string[]): Promise<{ ownedIds: string[]; failed: string[] }> {
|
||||
/** 把输入 id(CUID 或短 ID)映射到当前用户可写的错题;返回映射、可写错题本集合与失败列表 */
|
||||
async function resolveWritableErrorItems(userId: string, ids: string[]): Promise<{
|
||||
writableIds: string[];
|
||||
writeIds: string[];
|
||||
failed: string[];
|
||||
}> {
|
||||
const { writeIds } = await getNotebookAccessSets(userId);
|
||||
const found = await prisma.errorItem.findMany({
|
||||
where: { userId, OR: [{ id: { in: ids } }, { shortId: { in: ids } }] },
|
||||
where: {
|
||||
AND: [
|
||||
{ OR: [{ id: { in: ids } }, { shortId: { in: ids } }] },
|
||||
writableErrorItemWhere(userId, writeIds),
|
||||
],
|
||||
},
|
||||
select: { id: true, shortId: true },
|
||||
});
|
||||
const byInput = new Map<string, string>();
|
||||
@@ -378,22 +409,29 @@ async function resolveOwnedErrorItems(userId: string, ids: string[]): Promise<{
|
||||
byInput.set(item.id, item.id);
|
||||
if (item.shortId) byInput.set(item.shortId, item.id);
|
||||
}
|
||||
const ownedIds = [...new Set(ids.map((id) => byInput.get(id)).filter((id): id is string => !!id))];
|
||||
const writableIds = [...new Set(ids.map((id) => byInput.get(id)).filter((id): id is string => !!id))];
|
||||
const failed = ids.filter((id) => !byInput.has(id));
|
||||
return { ownedIds, failed };
|
||||
return { writableIds, writeIds, failed };
|
||||
}
|
||||
|
||||
export type BatchDeleteQuestionsInput = z.input<typeof batchDeleteSchema>;
|
||||
|
||||
/** 一次删除多道错题;返回实际删除数与未找到/不属于当前用户的 id */
|
||||
/** 一次删除多道错题;返回实际删除数与未找到/不可写的 id */
|
||||
export async function deleteQuestionsBatch(user: User, input: BatchDeleteQuestionsInput) {
|
||||
const parsed = batchDeleteSchema.safeParse(input);
|
||||
if (!parsed.success) {
|
||||
throw new McpToolError(parsed.error.issues[0]?.message ?? "Invalid batch delete input");
|
||||
}
|
||||
const { ownedIds, failed } = await resolveOwnedErrorItems(user.id, parsed.data.ids);
|
||||
const deleted = ownedIds.length > 0
|
||||
? (await prisma.errorItem.deleteMany({ where: { id: { in: ownedIds }, userId: user.id } })).count
|
||||
const { writableIds, writeIds, failed } = await resolveWritableErrorItems(user.id, parsed.data.ids);
|
||||
const deleted = writableIds.length > 0
|
||||
? (await prisma.errorItem.deleteMany({
|
||||
where: {
|
||||
AND: [
|
||||
{ id: { in: writableIds } },
|
||||
writableErrorItemWhere(user.id, writeIds),
|
||||
],
|
||||
},
|
||||
})).count
|
||||
: 0;
|
||||
return { deleted, failed };
|
||||
}
|
||||
@@ -407,17 +445,19 @@ export async function moveQuestionsBatch(user: User, input: BatchMoveQuestionsIn
|
||||
throw new McpToolError(parsed.error.issues[0]?.message ?? "Invalid batch move input");
|
||||
}
|
||||
const { ids, subjectId } = parsed.data;
|
||||
const target = await prisma.subject.findUnique({
|
||||
where: { id: subjectId },
|
||||
select: { userId: true },
|
||||
});
|
||||
if (!target || target.userId !== user.id) {
|
||||
throw new McpToolError(`Notebook "${subjectId}" not found for this user`);
|
||||
const targetRole = await getNotebookRole(user.id, subjectId);
|
||||
if (!canWriteNotebook(targetRole)) {
|
||||
throw new McpToolError(`Notebook "${subjectId}" not found or not writable for this user`);
|
||||
}
|
||||
const { ownedIds, failed } = await resolveOwnedErrorItems(user.id, ids);
|
||||
const moved = ownedIds.length > 0
|
||||
const { writableIds, writeIds, failed } = await resolveWritableErrorItems(user.id, ids);
|
||||
const moved = writableIds.length > 0
|
||||
? (await prisma.errorItem.updateMany({
|
||||
where: { id: { in: ownedIds }, userId: user.id },
|
||||
where: {
|
||||
AND: [
|
||||
{ id: { in: writableIds } },
|
||||
writableErrorItemWhere(user.id, writeIds),
|
||||
],
|
||||
},
|
||||
data: { subjectId },
|
||||
})).count
|
||||
: 0;
|
||||
|
||||
Reference in New Issue
Block a user