diff --git a/src/cli/commands/assist-platform.test.ts b/src/cli/commands/assist-platform.test.ts index d60718b..d888380 100644 --- a/src/cli/commands/assist-platform.test.ts +++ b/src/cli/commands/assist-platform.test.ts @@ -255,9 +255,21 @@ describe("CLI Commands - assist-platform (合思协助平台)", () => { raw: ["assist-platform", "transfer", "ID01ofWoOC1wiX", "ID01Xenwiu9w0D", "--to", "陈龙", "--dry-run"], }; - const res = await handleAssistPlatformCommand(parsed, runtime); - expect(res.stdout).toContain("[DRY-RUN]"); - expect(res.stdout).toContain("ID01Xenwiu9w0D"); - expect(res.stdout).toContain("陈龙"); + const originalFetch = globalThis.fetch; + globalThis.fetch = (async () => Response.json({ + items: [{ + id: "role-chenlong", + userId: { id: "chenlong3016", name: "陈龙", code: "3016" }, + }], + })) as unknown as typeof globalThis.fetch; + try { + const res = await handleAssistPlatformCommand(parsed, runtime); + expect(res.stdout).toContain("[DRY-RUN]"); + expect(res.stdout).toContain("ID01Xenwiu9w0D"); + expect(res.stdout).toContain("陈龙"); + expect(res.stdout).toContain("chenlong3016"); + } finally { + globalThis.fetch = originalFetch; + } }); }); diff --git a/src/cli/commands/assist-platform/approve.ts b/src/cli/commands/assist-platform/approve.ts index f109a88..ff41841 100644 --- a/src/cli/commands/assist-platform/approve.ts +++ b/src/cli/commands/assist-platform/approve.ts @@ -13,10 +13,8 @@ export async function handleApprove( parsed: CliParsedArgs, runtime: CliRuntime ): Promise { - const explicitCorpId = - stringOption(parsed.options, ["corp", "corpid", "id"]) || - parsed.args[0] || - runtime.selectedCorp?.id; + const corpOption = stringOption(parsed.options, ["corp", "corpid", "id"]); + const explicitCorpId = corpOption || parsed.args[0] || runtime.selectedCorp?.id; if (!explicitCorpId) { return { @@ -31,22 +29,38 @@ export async function handleApprove( // 1. 识别 corpId 与 ticketId const allCorps = runtime.corpContext?.getAllCorps?.() || []; - let targetCorp = - allCorps.find((c) => c.id === explicitCorpId || c.corpId === explicitCorpId) || - (runtime.selectedCorp?.id === explicitCorpId || runtime.selectedCorp?.corpId === explicitCorpId + const findCorp = (id: string) => + allCorps.find((c) => c.id === id || c.corpId === id) || + (runtime.selectedCorp?.id === id || runtime.selectedCorp?.corpId === id ? runtime.selectedCorp : undefined); - - let ticketId = stringOption(parsed.options, ["ticket", "ticket-id"]); + let targetCorp = findCorp(explicitCorpId); + const ticketOption = stringOption(parsed.options, ["ticket", "ticket-id"]); + let positionalTicketId: string | undefined; // 如果第 0 个参数不是企业,可能是工单编号 - if (!targetCorp && parsed.args[0]) { - ticketId = parsed.args[0]; + if (corpOption) { + // 显式企业选项下,唯一位置参数始终是工单,不能被本地企业命中结果覆盖。 + positionalTicketId = parsed.args[0]; + } else if (!targetCorp && parsed.args[0]) { + positionalTicketId = parsed.args[0]; targetCorp = runtime.selectedCorp ?? undefined; } else if (targetCorp && parsed.args[1]) { - ticketId = parsed.args[1]; + positionalTicketId = parsed.args[1]; } + const maxArgs = !corpOption && parsed.args[0] && findCorp(parsed.args[0]) ? 2 : 1; + if (parsed.args.length > maxArgs || + (ticketOption && positionalTicketId && ticketOption !== positionalTicketId)) { + return { + stdout: "", + stderr: "[ERROR] 企业或工单参数存在歧义或冲突。请使用 approve <工单ID> --corp <企业ID>,且 --ticket 必须与位置工单一致。\n", + exitCode: 1, + }; + } + + let ticketId = ticketOption || positionalTicketId; + if (!targetCorp) { return { stdout: "", diff --git a/src/cli/commands/assist-platform/transfer.ts b/src/cli/commands/assist-platform/transfer.ts index dae3d14..4316ebd 100644 --- a/src/cli/commands/assist-platform/transfer.ts +++ b/src/cli/commands/assist-platform/transfer.ts @@ -86,20 +86,11 @@ export async function handleTransfer( try { resolvedRecipient = await resolveTransferRecipient(client, targetRecipient); } catch (err) { - if (isDryRun(parsed, runtime)) { - resolvedRecipient = { - id: targetRecipient, - name: targetRecipient, - userRoleId: "", - roles: [], - }; - } else { - return { - stdout: "", - stderr: `[ERROR] ${err instanceof Error ? err.message : String(err)}\n`, - exitCode: 1, - }; - } + return { + stdout: "", + stderr: `[ERROR] ${err instanceof Error ? err.message : String(err)}\n`, + exitCode: 1, + }; } if (!ticketId) { @@ -136,7 +127,7 @@ export async function handleTransfer( parsed, runtime, operation, - `hose-use assist-platform transfer ${targetCorpId} ${ticketId} --to "${resolvedRecipient.name}" --yes` + `hose-use assist-platform transfer ${targetCorpId} ${ticketId} --to "${resolvedRecipient.id}" --yes` ); const result = await transferAssistTicket(client, { diff --git a/src/cli/commands/assist-targets.test.ts b/src/cli/commands/assist-targets.test.ts new file mode 100644 index 0000000..4e341c1 --- /dev/null +++ b/src/cli/commands/assist-targets.test.ts @@ -0,0 +1,161 @@ +import { afterEach, beforeEach, describe, expect, it } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { CorpConfig } from "../../core/config/types.js"; +import { parseArgs } from "../parser.js"; +import type { CliRuntime } from "../types.js"; +import { handleApprove } from "./assist-platform/approve.js"; +import { handleTransfer } from "./assist-platform/transfer.js"; + +const corp: CorpConfig = { + id: "CORP", corpId: "CORP", name: "测试企业", source: "manual", + baseUrl: "https://corp.invalid", + credentials: { accessToken: "mock-token", corpId: "CORP", staffId: "ADMIN" }, +}; +const otherCorp: CorpConfig = { ...corp, id: "OTHER-CORP", corpId: "OTHER-CORP" }; +const sameNameUsers = [ + { id: "ROLE1", userId: { id: "user3016", name: "张三", code: "3016" } }, + { id: "ROLE2", userId: { id: "user3020", name: "张三", code: "3020" } }, +]; + +function runtime(selectedCorp: CorpConfig | null = corp): CliRuntime { + return { + jsonMode: true, selectedCorp, + corpContext: { getAllCorps: () => [corp, otherCorp] } as CliRuntime["corpContext"], + }; +} + +let originalFetch: typeof globalThis.fetch; +let originalStore: string | undefined; +let stateDir: string; +let requests: Request[]; +let responses: (request: Request) => Response | Promise; + +beforeEach(() => { + originalFetch = globalThis.fetch; + originalStore = process.env.HOSE_ASSIST_PLATFORM_FILE; + stateDir = mkdtempSync(join(tmpdir(), "hose-assist-targets-")); + process.env.HOSE_ASSIST_PLATFORM_FILE = join(stateDir, "session.json"); + requests = []; + responses = () => Response.json({ items: [{ ticketId: "OTHER-TICKET", state: "0" }] }); + globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => { + const request = input instanceof Request ? input : new Request(input.toString(), init); + // Bun 的 Request.clone 声明采用 undici Headers;运行态仍是同一个 Request 类型。 + requests.push(request.clone() as unknown as Request); + return responses(request); + }) as typeof globalThis.fetch; +}); + +afterEach(() => { + globalThis.fetch = originalFetch; + if (originalStore === undefined) delete process.env.HOSE_ASSIST_PLATFORM_FILE; + else process.env.HOSE_ASSIST_PLATFORM_FILE = originalStore; + rmSync(stateDir, { recursive: true, force: true }); +}); + +describe("assist-platform approve 的明确工单目标", () => { + it.each([ + ["REQUESTED", "--corp", "CORP"], + ["CORP", "REQUESTED"], + ["CORP", "--ticket", "REQUESTED"], + ["--corp", "CORP", "--ticket", "REQUESTED"], + ["REQUESTED"], + ["--ticket", "REQUESTED"], + ["REQUESTED", "--corp", "CORP", "--ticket", "REQUESTED"], + ].map((args) => ({ args })))("预览保留工单参数 %j,不自动查询其他工单", async ({ args }) => { + const result = await handleApprove(parseArgs(["assist-platform", "approve", ...args, "--dry-run"]), runtime()); + expect(result.exitCode).toBe(0); + expect(JSON.parse(result.stdout).changes["工单编号"]).toBe("REQUESTED"); + expect(requests).toHaveLength(0); + }); + + it("显式 --corp 下首参即使也是已知企业 ID,仍作为工单", async () => { + const parsed = parseArgs(["assist-platform", "approve", "OTHER-CORP", "--corp", "CORP", "--dry-run"]); + const result = await handleApprove(parsed, runtime()); + expect(JSON.parse(result.stdout).changes["工单编号"]).toBe("OTHER-CORP"); + expect(requests).toHaveLength(0); + }); + + it("--yes 真实提交路径只审批显式工单,不能自动替换为列表首项", async () => { + responses = (request) => request.method === "PUT" + ? Response.json({ value: { id: "REQUESTED", corporationId: "CORP" } }) + : Response.json({ items: [{ ticketId: "OTHER-TICKET", state: "0" }] }); + const result = await handleApprove( + parseArgs(["assist-platform", "approve", "REQUESTED", "--corp", "CORP", "--yes"]), runtime() + ); + expect(result.exitCode).toBe(0); + expect(requests).toHaveLength(1); + expect(requests[0].method).toBe("PUT"); + expect(requests[0].url).toContain("/$REQUESTED/updateStatus?corpId=CORP"); + expect(await requests[0].json()).toEqual({ id: "REQUESTED", status: 1 }); + }); + + it.each([ + ["REQUESTED", "--corp", "CORP", "--ticket", "OTHER-TICKET"], + ["CORP", "REQUESTED", "--ticket", "OTHER-TICKET"], + ["UNKNOWN-CORP", "REQUESTED"], + ["CORP", "REQUESTED", "--corp", "OTHER-CORP"], + ["CORP", "REQUESTED", "EXTRA"], + ].map((args) => ({ args })))("拒绝歧义或冲突参数 %j,且不查询或提交", async ({ args }) => { + const result = await handleApprove(parseArgs(["assist-platform", "approve", ...args, "--yes"]), runtime()); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain("歧义或冲突"); + expect(requests).toHaveLength(0); + }); + + it("显式企业未知时不能回退当前企业", async () => { + const result = await handleApprove( + parseArgs(["assist-platform", "approve", "REQUESTED", "--corp", "UNKNOWN", "--yes"]), runtime() + ); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain("UNKNOWN"); + expect(requests).toHaveLength(0); + }); + + it("只有未指定工单时才自动查询待授权工单", async () => { + const result = await handleApprove(parseArgs([ + "assist-platform", "approve", "--corp", "CORP", "--token", "mock-token", "--dry-run", + ]), runtime()); + expect(result.exitCode).toBe(0); + expect(JSON.parse(result.stdout).changes["工单编号"]).toBe("OTHER-TICKET"); + expect(requests).toHaveLength(1); + expect(requests[0].url).toContain("assistPlatform/$CORP/search"); + }); +}); + +describe("assist-platform transfer 预览与执行的收件人解析", () => { + it.each(["--dry-run", "--yes"])("%s 遇到同名用户都拒绝且不提交", async (mode) => { + responses = () => Response.json({ items: sameNameUsers }); + const result = await handleTransfer(parseArgs([ + "assist-platform", "transfer", "CORP", "TICKET", "--to", "张三", "--token", "mock-token", mode, + ]), runtime()); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain("唯一工号或账号"); + expect(requests).toHaveLength(1); + expect(requests[0].url).toContain("userRole/search"); + }); + + it("查询失败的 dry-run 也不能显示成功解析的预览", async () => { + responses = () => new Response("unauthorized", { status: 401 }); + const result = await handleTransfer(parseArgs([ + "assist-platform", "transfer", "CORP", "TICKET", "--to", "user3016", "--token", "mock-token", "--dry-run", + ]), runtime()); + expect(result.exitCode).toBe(1); + expect(result.stdout).toBe(""); + }); + + it("唯一工号的 dry-run 显示实际账号,与 --yes 的请求一致", async () => { + responses = (request) => request.url.includes("userRole/search") + ? Response.json({ items: sameNameUsers }) + : Response.json({ value: true }); + const args = ["assist-platform", "transfer", "CORP", "TICKET", "--to", "3016", "--token", "mock-token"]; + const preview = await handleTransfer(parseArgs([...args, "--dry-run"]), runtime()); + expect(JSON.parse(preview.stdout).changes.recipientId).toBe("user3016"); + const result = await handleTransfer(parseArgs([...args, "--yes"]), runtime()); + expect(result.exitCode).toBe(0); + const writes = requests.filter((request) => request.url.includes("assistPlatform/transfer")); + expect(writes).toHaveLength(1); + expect(await writes[0].json()).toEqual({ assistId: "TICKET", recipient: "user3016" }); + }); +}); diff --git a/src/domains/assist-platform/README.assist-platform.md b/src/domains/assist-platform/README.assist-platform.md index 8c753c1..89e8d5b 100644 --- a/src/domains/assist-platform/README.assist-platform.md +++ b/src/domains/assist-platform/README.assist-platform.md @@ -35,3 +35,9 @@ - 已知管理员、角色或高权限证据仍显示 HIGH/MEDIUM;导入时补用 JWT 已确认的身份。同一员工的历史权限及高风险状态不会因本次探测不完整而被降级,其他员工的画像不会被沿用。 SDK 消费者应处理画像布尔值的 null 和新增的 UNKNOWN 风险枚举;会话结果顶层 `isAdmin` 仍表示请求的授权模式,其 boolean 类型不变。 + +## 审批与转交目标解析 + +- `approve <工单ID> --corp <企业ID>`:显式 `--corp` 下,唯一位置参数始终为工单 ID;也支持 `approve <企业ID> <工单ID>`、`approve <企业ID> --ticket <工单ID>`,以及使用当前企业的 `approve <工单ID>` / `approve --ticket <工单ID>`。位置工单与 `--ticket` 不一致或位置参数多余时拒绝执行;只有完全未指定工单时才自动查询待授权工单。 +- 转交收件人依次按账号 ID、工号、姓名精确匹配,再尝试模糊匹配。同一账号的多条角色记录按用户 ID 去重;同一匹配级别命中多个用户时拒绝选择,须改用唯一工号或账号。 +- 转交的 dry-run 与执行使用相同的收件人解析规则。歧义、未找到人员或查询失败都会终止,不会将未解析的输入直接提交给转交接口。 diff --git a/src/domains/assist-platform/services.ts b/src/domains/assist-platform/services.ts index bb82f04..df67dd4 100644 --- a/src/domains/assist-platform/services.ts +++ b/src/domains/assist-platform/services.ts @@ -431,31 +431,39 @@ export async function resolveTransferRecipient( } const candidates = await listTransferCandidates(client); - const exactMatches = candidates.filter( - (c) => c.name === cleanTarget || c.code === cleanTarget || c.id === cleanTarget - ); - if (exactMatches.length === 1) { - return exactMatches[0]; - } - if (exactMatches.length > 1) { - return exactMatches[0]; + // 一个用户可能有多条角色记录;先匹配,再按稳定账号 ID 去重。 + const uniqueUsers = (matches: TransferCandidate[]) => + [...new Map(matches.map((candidate) => [candidate.id, candidate])).values()]; + const rejectAmbiguous = (matches: TransferCandidate[]): never => { + const names = matches + .slice(0, 5) + .map((m) => `${m.name}(${m.id}${m.code ? `, 工号: ${m.code}` : ""})`) + .join("、"); + throw new BusinessError(`匹配到多个可转交人员 [${names}],请指定唯一工号或账号`); + }; + + // 账号 ID 优先于工号、姓名,避免一个人的姓名覆盖另一个人的明确账号。 + for (const matches of [ + candidates.filter((c) => c.id === cleanTarget), + candidates.filter((c) => c.code === cleanTarget), + candidates.filter((c) => c.name === cleanTarget), + ]) { + const users = uniqueUsers(matches); + if (users.length === 1) return users[0]; + if (users.length > 1) rejectAmbiguous(users); } - const fuzzyMatches = candidates.filter( + const fuzzyMatches = uniqueUsers(candidates.filter( (c) => c.name.includes(cleanTarget) || (c.code && c.code.includes(cleanTarget)) || c.id.includes(cleanTarget) - ); + )); if (fuzzyMatches.length === 1) { return fuzzyMatches[0]; } if (fuzzyMatches.length > 1) { - const names = fuzzyMatches - .slice(0, 5) - .map((m) => `${m.name}(${m.code || m.id})`) - .join("、"); - throw new BusinessError(`匹配到多个可转交人员 [${names}],请指定具体工号或全名`); + rejectAmbiguous(fuzzyMatches); } throw new NotFoundError(`未在具备协助权限的人员库中找到匹配的人员: "${cleanTarget}"`); @@ -469,16 +477,9 @@ export async function transferAssistTicket( remarks?: string; } ): Promise { - let resolvedRecipientId = params.recipient; - let recipientName: string | undefined; - - try { - const candidate = await resolveTransferRecipient(client, params.recipient); - resolvedRecipientId = candidate.id; - recipientName = candidate.name; - } catch { - // 若解析不到,仍尝试直接以原值请求 - } + const candidate = await resolveTransferRecipient(client, params.recipient); + const resolvedRecipientId = candidate.id; + const recipientName = candidate.name; await transferAssistTicketApi(client, { ticketId: params.ticketId, diff --git a/src/domains/assist-platform/transfer-recipient.test.ts b/src/domains/assist-platform/transfer-recipient.test.ts new file mode 100644 index 0000000..ea34368 --- /dev/null +++ b/src/domains/assist-platform/transfer-recipient.test.ts @@ -0,0 +1,98 @@ +import { describe, expect, it } from "bun:test"; +import ky from "ky"; +import { BusinessError, EkbApiError, NotFoundError } from "../../core/errors.js"; +import { resolveTransferRecipient, transferAssistTicket } from "./services.js"; + +type User = { id: string; name: string; code?: string }; +const first: User = { id: "zhang3016", name: "张三", code: "3016" }; +const second: User = { id: "zhang3020", name: "张三", code: "3020" }; + +function mockClient(users: User[], failSearch = false) { + const writes: unknown[] = []; + const client = ky.create({ + prefix: "https://assist.invalid/api", + retry: 0, + fetch: async (input, init) => { + const request = input instanceof Request ? input : new Request(input.toString(), init); + if (request.url.endsWith("userRole/search")) { + if (failSearch) return new Response("unavailable", { status: 503 }); + return Response.json({ items: users.map((userId, i) => ({ + id: `role-row-${i}`, + userId, + roleIds: [{ id: `role-${i}`, name: `角色${i}` }], + })) }); + } + if (request.url.endsWith("assistPlatform/transfer")) { + writes.push(await request.json()); + return Response.json({ value: true }); + } + throw new Error(`Unexpected request: ${request.url}`); + }, + }); + return { client, writes }; +} + +describe("assist-platform 转交目标解析", () => { + it("同名不同账号拒绝精确匹配,错误提示唯一工号或账号", async () => { + const { client } = mockClient([first, second]); + await expect(resolveTransferRecipient(client, "张三")).rejects.toBeInstanceOf(BusinessError); + await expect(resolveTransferRecipient(client, "张三")).rejects.toThrow("唯一工号或账号"); + }); + + it("相同工号的不同用户也拒绝选择第一人", async () => { + const { client } = mockClient([first, { ...second, code: first.code }]); + await expect(resolveTransferRecipient(client, "3016")).rejects.toThrow("多个可转交人员"); + }); + + it("账号精确匹配优先于其他人的工号和姓名", async () => { + const { client } = mockClient([ + { ...second, code: first.id }, + { id: "other", name: first.id }, + first, + ]); + expect((await resolveTransferRecipient(client, first.id)).id).toBe(first.id); + }); + + it("工号精确匹配优先于其他人的姓名", async () => { + const { client } = mockClient([{ ...second, name: "3016" }, first]); + expect((await resolveTransferRecipient(client, "3016")).id).toBe(first.id); + }); + + it.each(["张三", "3016", "zhang3016", "zhang", " 3016 "])( + "同一稳定账号的多条角色记录不会令 %s 产生歧义", + async (target) => { + const { client } = mockClient([first, first]); + expect((await resolveTransferRecipient(client, target)).id).toBe(first.id); + } + ); + + it("模糊匹配存在多个用户时拒绝", async () => { + const { client } = mockClient([first, second]); + await expect(resolveTransferRecipient(client, "zhang")).rejects.toThrow("多个可转交人员"); + }); + + it.each(["张三", "不存在的账号"])("执行转交时 %s 解析失败不提交原始值", async (recipient) => { + const { client, writes } = mockClient([first, second]); + const ErrorClass = recipient === "张三" ? BusinessError : NotFoundError; + await expect(transferAssistTicket(client, { ticketId: "TICKET", recipient })) + .rejects.toBeInstanceOf(ErrorClass); + expect(writes).toEqual([]); + }); + + it("查询候选人失败时不以原始账号继续写入", async () => { + const { client, writes } = mockClient([], true); + await expect(transferAssistTicket(client, { ticketId: "TICKET", recipient: first.id })) + .rejects.toBeInstanceOf(EkbApiError); + expect(writes).toEqual([]); + }); + + it("使用唯一工号时写入稳定账号 ID", async () => { + const { client, writes } = mockClient([first, first, second]); + const result = await transferAssistTicket(client, { + ticketId: "TICKET", recipient: "3016", remarks: "交接", + }); + expect(result.recipient).toBe(first.id); + expect(result.recipientName).toBe(first.name); + expect(writes).toEqual([{ assistId: "TICKET", recipient: first.id, remarks: "交接" }]); + }); +});