feat(assist): 支持协助工单权限转交 (transfer) 并实测交接给陈龙

- 实现 domains/assist-platform 转交 API: searchTransferCandidatesApi (POST /api/userRole/search) 与 transferAssistTicketApi (POST /api/assistPlatform/transfer)
- 提供智能接收人解析 (resolveTransferRecipient): 支持姓名模糊匹配、工号或账号精确匹配
- 实现 CLI 命令 hose-use assist-platform transfer: 支持 --candidates 人员字典查询与 --dry-run 安全预览
- 实测将沈玥妍测试企业有效工单 ID01Xenwiu9w0D 成功转交至陈龙 (chenlong3016, 工号 3016)
- 补充 domains 与 cli 全套单元测试并在 SKILL.md 与 assist-platform.md 沉淀转交指南
This commit is contained in:
gitea committed 2026-10-21 11:57:52 +08:00
1 parent 82fa0fca0c
commit 7a396f8a95
11 files changed
+1036 -473

No files matched your search

+485 -469
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -81,7 +81,7 @@ metadata:
| 首次登录 / 账密认证 / Token过期 / 多账号 | `hose-use auth login`, `hose-use auth status`, `hose-use auth refresh` | [references/auth.md](references/auth.md) |
| 生成企业合思 Web 免密登录直达链接 (`thirdparty.html`) | `hose-use corps link [企业ID|名称]`, `hose-use auth hose-link` | [references/auth.md](references/auth.md) |
| 第三方免密/协助链接一键导入(自动提取持久化密钥) | `hose-use corps add-link <url> --yes`, `hose-use corps elevate [企业ID] --yes` | [references/auth.md](references/auth.md) |
| 合思协助平台(Unity 运营平台)扫码登录/租户全量库/工单/指定身份直通 | `hose-use assist-platform login/search/detail/tickets/staff/enter` | [references/assist-platform.md](references/assist-platform.md) |
| 合思协助平台(Unity 运营平台)扫码登录/租户全量库/工单/指定身份直通/权限转交 | `hose-use assist-platform login/search/detail/tickets/staff/apply/enter/transfer` | [references/assist-platform.md](references/assist-platform.md) |
| OpenAPI 密钥持久化接入 / 从链接提取密钥 | `hose-use corps add-persistent`, `hose-use corps extract-keys <url>` | [references/auth.md](references/auth.md) |
| 代客协助凭证导入 / 探针连通性诊断 | `hose-use auth import`, `hose-use probe` | [references/auth.md](references/auth.md) |
| 企业租户切换 / 查看当前企业 | `hose-use corps list`, `hose-use corps switch <id>` | [references/auth.md](references/auth.md) |
@@ -167,3 +167,36 @@ hose-use assist-platform enter <企业ID> --name "李志财" --save --switch --e
| `--switch` | 导入后自动切换为当前活跃企业租户 |
| `--elevate` | 导入后自动探测并保存持久化 OpenAPI Key 与 Secret,实现长期免密接入 |
| `--json` | 输出结构化 JSON 结果 |
---
## 8. 协助工单转交 (`transfer`)
当已获得客户授权的工单需要移交给其他运维、实施或研发同事时,可使用转交功能直接将权限移交给目标人员,**无需客户侧重新发起审批授权**。
```bash
# 查看具备协助权限的可转交人员列表
hose-use assist-platform transfer --candidates
hose-use assist-platform transfer --candidates "陈龙"
# 查看转交预览(安全 Dry-Run)
hose-use assist-platform transfer <企业ID> --to "陈龙" --dry-run
# 一键转交指定企业的当前生效协助工单
hose-use assist-platform transfer <企业ID> --to "陈龙" --remarks "排障任务交接" --yes
# 显式指定工单号转交
hose-use assist-platform transfer <企业ID> <工单ID> --to "陈龙" --yes
```
### 参数说明
| 参数 | 说明 |
|---|---|
| `<corpId>` | 目标企业 ID(必填) |
| `[ticketId]` | 指定转交的协助工单编号(缺省时自动采用企业当前生效的工单) |
| `--to <姓名\|工号\|账号>` | 转交接收人,支持输入姓名(如“陈龙”)、工号(如“3016”)或账号(如“chenlong3016”) |
| `--candidates` | 查询内部具备协助权限的可转交人员名单 |
| `--remarks <备注>` | 添加转交附言或任务交接说明(100 字以内) |
| `--dry-run` | 预览转交参数与接收人匹配结果,不发起网络写操作 |
| `--yes, -y` | 显式确认执行转交 |
+7 -3
View File
@@ -783,6 +783,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
"apply": "向目标企业发起新的协助授权工单申请",
"approve": "审批通过协助授权工单申请(端内管理员授权)",
"enter": "一键换取免密直通链接并落盘为本地工作企业",
"transfer": "转交协助工单权限给其他同事",
"help": "查看帮助信息"
},
"aliases": [
@@ -811,11 +812,14 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
"pass": "approve",
"import": "enter",
"token": "enter",
"get-token": "enter"
"get-token": "enter",
"transfer": "transfer",
"transmit": "transfer",
"forward": "transfer"
},
flags: {
...flagList("token t user name u hose-token jwt ticket ticket-id auth-code staff alias corp-name count limit n start offset state status corpid id keyword query q message msg reason matter hours hour duration days day", "value"),
...flagList("logout admin save import persist switch current overwrite", "boolean")
...flagList("token t user name u hose-token jwt ticket ticket-id auth-code staff alias corp-name count limit n start offset state status corpid id keyword query q message msg reason matter hours hour duration days day to recipient target remarks comment corp", "value"),
...flagList("logout admin save import persist switch current overwrite candidates list-candidates", "boolean")
}
}
};
+43
View File
@@ -217,4 +217,47 @@ describe("CLI Commands - assist-platform (合思协助平台)", () => {
expect(res.stdout).toContain("[DRY-RUN]");
expect(res.stdout).toContain("24 小时");
});
it("assist-platform transfer 缺少 --to 参数时报错提示", async () => {
saveAssistPlatformSession({
token: "mock-token",
userName: "测试人员",
baseUrl: "https://unity.ekuaibao.com/api",
updatedAt: Date.now(),
});
const runtime = createMockRuntime(tempDir);
const parsed: CliParsedArgs = {
action: "transfer",
args: ["ID01ofWoOC1wiX"],
options: {},
raw: ["assist-platform", "transfer", "ID01ofWoOC1wiX"],
};
const res = await handleAssistPlatformCommand(parsed, runtime);
expect(res.exitCode).toBe(1);
expect(res.stderr).toContain("必须通过 --to 指定接收人员姓名、工号或账号");
});
it("assist-platform transfer --dry-run 能够输出工单转交变更预览", async () => {
saveAssistPlatformSession({
token: "mock-token",
userName: "测试人员",
baseUrl: "https://unity.ekuaibao.com/api",
updatedAt: Date.now(),
});
const runtime = createMockRuntime(tempDir);
const parsed: CliParsedArgs = {
action: "transfer",
args: ["ID01ofWoOC1wiX", "ID01Xenwiu9w0D"],
options: { to: "陈龙", dryRun: true },
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("陈龙");
});
});
@@ -7,6 +7,7 @@ import { handleStaff } from "./staff.js";
import { handleEnter } from "./enter.js";
import { handleApply } from "./apply.js";
import { handleApprove } from "./approve.js";
import { handleTransfer } from "./transfer.js";
export async function handleAssistPlatformCommand(
parsed: CliParsedArgs,
@@ -59,6 +60,11 @@ export async function handleAssistPlatformCommand(
case "pass":
return handleApprove(parsed, runtime);
case "transfer":
case "transmit":
case "forward":
return handleTransfer(parsed, runtime);
case "help":
case "--help":
case "-h":
@@ -84,6 +90,7 @@ function printHelp(): CliResult {
apply <企业ID> 向目标企业发起新的协助授权工单申请(待客户管理员审批)
approve [工单ID] 审批通过协助授权工单申请(端内管理员通过授权)
enter <企业ID> 一键换取协助免密直通链接并进入(可选 --save 落盘为本地工作企业)
transfer <企业ID> 转交协助工单权限给其他同事(可指定 --to 与 --ticket,支持 --candidates 查询人员)
常用选项:
--token, -t <TOKEN> 显式指定当前操作使用的协助平台 Token
@@ -0,0 +1,175 @@
import {
listAssistTickets,
listTransferCandidates,
resolveTransferRecipient,
transferAssistTicket,
} from "../../../domains/assist-platform/services.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
import { booleanOption, stringOption } from "../../parser.js";
import { printJson, printKeyValue } from "../../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { resolveAssistClient } from "./common.js";
export async function handleTransfer(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const client = resolveAssistClient(parsed, runtime);
const isListMode = booleanOption(parsed.options, ["candidates", "list-candidates"]);
// 1. 列出可转交候选人员清单
if (isListMode) {
const keyword = stringOption(parsed.options, ["keyword", "query", "q", "name"]) || parsed.args[0];
const candidates = await listTransferCandidates(client, keyword);
if (runtime.jsonMode) {
return {
stdout: printJson({ count: candidates.length, items: candidates }),
stderr: "",
exitCode: 0,
};
}
if (candidates.length === 0) {
return {
stdout: `未找到匹配的可转交人员${keyword ? ` (关键词: ${keyword})` : ""}。\n`,
stderr: "",
exitCode: 0,
};
}
const lines = candidates.map(
(c) => ` • ${c.name.padEnd(8, " ")} | 账号: ${c.id.padEnd(16, " ")} | 工号: ${c.code || "-"} | 角色: ${c.roles.join("、") || "-"}`
);
return {
stdout:
`====== 协助平台可转交人员列表 (共 ${candidates.length} 人) ======\n` +
lines.join("\n") +
"\n",
stderr: "",
exitCode: 0,
};
}
// 2. 转交指定工单
const targetCorpId = parsed.args[0] || stringOption(parsed.options, ["corp", "corpid", "id"]);
const targetRecipient = stringOption(parsed.options, ["to", "recipient", "target", "user", "name"]);
const remarks = stringOption(parsed.options, ["remarks", "message", "msg", "comment"]);
if (!targetCorpId) {
return {
stdout: "",
stderr:
"[ERROR] 必须指定企业 ID 或工单编号。\n" +
"用法:\n" +
" hose-use assist-platform transfer <企业ID> [--ticket <工单号>] --to <姓名|工号|账号> [--remarks <备注>] --yes\n" +
" hose-use assist-platform transfer --candidates [关键词] (查看可转交人员列表)\n",
exitCode: 1,
};
}
if (!targetRecipient) {
return {
stdout: "",
stderr:
"[ERROR] 必须通过 --to 指定接收人员姓名、工号或账号。\n" +
"可运行 hose-use assist-platform transfer --candidates 查询人员名录。\n",
exitCode: 1,
};
}
// 解析工单编号:如果 args[1] 提供了则用 args[1],或 --ticket,否则自动在指定企业中查找当前生效中的工单
let ticketId = parsed.args[1] || stringOption(parsed.options, ["ticket", "ticket-id"]);
let resolvedRecipient;
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,
};
}
}
if (!ticketId) {
if (isDryRun(parsed, runtime)) {
ticketId = "PREVIEW-ACTIVE-TICKET";
} else {
const tickets = await listAssistTickets(client, targetCorpId);
const activeTicket = tickets.find((t) => t.state === "已提供" || t.state === "1");
if (!activeTicket) {
return {
stdout: "",
stderr: `[ERROR] 企业 ${targetCorpId} 下未找到处于“已提供”生效状态的协助工单。\n可通过 hose-use assist-platform tickets ${targetCorpId} 查看历史工单。\n`,
exitCode: 1,
};
}
ticketId = activeTicket.ticketId;
}
}
const operation = "协助工单转交";
const target = `企业 ${targetCorpId} 的工单 [${ticketId}] 转交给 ${resolvedRecipient.name} (${resolvedRecipient.id})`;
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, operation, target, {
ticketId,
recipientId: resolvedRecipient.id,
recipientName: resolvedRecipient.name,
recipientCode: resolvedRecipient.code,
remarks,
});
}
requireMutationConfirmation(
parsed,
runtime,
operation,
`hose-use assist-platform transfer ${targetCorpId} ${ticketId} --to "${resolvedRecipient.name}" --yes`
);
const result = await transferAssistTicket(client, {
ticketId,
recipient: resolvedRecipient.id,
remarks,
});
if (runtime.jsonMode) {
return {
stdout: printJson({
success: true,
ticketId,
corpId: targetCorpId,
recipient: resolvedRecipient,
remarks,
}),
stderr: "",
exitCode: 0,
};
}
const pairs: Record<string, string> = {
转交状态: "🟢 转交成功",
目标工单: ticketId,
所属企业: targetCorpId,
转交接收人: `${resolvedRecipient.name} (${resolvedRecipient.id}${resolvedRecipient.code ? `, 工号: ${resolvedRecipient.code}` : ""})`,
};
if (remarks) pairs["转交备注"] = remarks;
return {
stdout: `[SUCCESS] 协助工单转交成功!\n${printKeyValue(pairs)}\n`,
stderr: "",
exitCode: 0,
};
}
+99
View File
@@ -6,6 +6,8 @@ import type {
AssistPlatformTicket,
CorporationDetail,
StaffRoleItem,
TransferCandidate,
TransferTicketParams,
} from "./types.js";
export interface SearchCorporationsApiParams {
@@ -476,3 +478,100 @@ export async function getStaffMeAndRolesApi(
departmentName,
};
}
export async function searchTransferCandidatesApi(
client: KyInstance,
keyword?: string
): Promise<TransferCandidate[]> {
try {
const res = await client
.post("userRole/search", {
json: {
filterBy: "(active==true)",
orderBy: [{ value: "createTime", order: "DESC" }],
limit: { start: 0, count: 1000 },
select: "userId(id, name,code),roleIds(id, name),`...`",
permissions: ["charge-assistance", "charge-assistance-non-admin"],
},
})
.json<{
items?: Array<{
id: string;
userId?: { id?: string; name?: string; code?: string };
roleIds?: Array<{ id?: string; name?: string }>;
}>;
}>();
const candidates: TransferCandidate[] = [];
if (Array.isArray(res.items)) {
for (const item of res.items) {
if (!item.userId?.id || !item.userId?.name) continue;
const name = String(item.userId.name);
const code = item.userId.code ? String(item.userId.code) : undefined;
const id = String(item.userId.id);
if (
keyword &&
!name.includes(keyword) &&
!id.includes(keyword) &&
(!code || !code.includes(keyword))
) {
continue;
}
candidates.push({
id,
name,
code,
userRoleId: String(item.id || ""),
roles: Array.isArray(item.roleIds)
? item.roleIds.map((r) => String(r.name || "")).filter(Boolean)
: [],
});
}
}
return candidates;
} catch (err) {
if (err instanceof BusinessError || err instanceof NotFoundError) {
throw err;
}
throw new EkbApiError(
`查询可转交人员列表失败: ${err instanceof Error ? err.message : String(err)}`
);
}
}
export async function transferAssistTicketApi(
client: KyInstance,
params: TransferTicketParams
): Promise<{ success: boolean; value?: unknown }> {
try {
const res = await client
.post("assistPlatform/transfer", {
json: {
assistId: params.ticketId,
recipient: params.recipient,
remarks: params.remarks,
},
})
.json<{
errorCode?: number;
errorMessage?: string;
value?: unknown;
}>();
if (res.errorCode) {
throw new BusinessError(res.errorMessage || "工单转交失败");
}
return {
success: true,
value: res.value,
};
} catch (err) {
if (err instanceof BusinessError || err instanceof NotFoundError) {
throw err;
}
throw new EkbApiError(
`工单转交失败: ${err instanceof Error ? err.message : String(err)}`
);
}
}
@@ -9,7 +9,10 @@ import {
getCorporationDetail,
inspectAssistIdentity,
listAssistTickets,
listTransferCandidates,
resolveTransferRecipient,
searchCorporations,
transferAssistTicket,
} from "./services.js";
function createMockClient(handler: (req: Request) => Response | Promise<Response>) {
@@ -298,4 +301,79 @@ describe("domains/assist-platform - 协助平台业务编排", () => {
expect(risk.riskWarning).toContain("特权人员");
});
});
describe("transferAssistTicket - 协助工单转交服务", () => {
it("listTransferCandidates 正确解析候选人清单", async () => {
const client = createMockClient(async (req) => {
expect(req.url).toContain("userRole/search");
return Response.json({
count: 1,
items: [
{
id: "ID01TZKdvh3nAz",
userId: { id: "chenlong3016", name: "陈龙", code: "3016" },
roleIds: [{ id: "r1", name: "COE-协助链接" }],
},
],
});
});
const candidates = await listTransferCandidates(client, "陈龙");
expect(candidates.length).toBe(1);
expect(candidates[0].name).toBe("陈龙");
expect(candidates[0].id).toBe("chenlong3016");
expect(candidates[0].code).toBe("3016");
});
it("resolveTransferRecipient 能够按姓名或工号精确定位人员", async () => {
const client = createMockClient(async () => {
return Response.json({
items: [
{
id: "ID01TZKdvh3nAz",
userId: { id: "chenlong3016", name: "陈龙", code: "3016" },
roleIds: [{ id: "r1", name: "COE-协助链接" }],
},
],
});
});
const recipient = await resolveTransferRecipient(client, "陈龙");
expect(recipient.id).toBe("chenlong3016");
expect(recipient.name).toBe("陈龙");
});
it("transferAssistTicket 能够向服务端发起转交请求并成功返回", async () => {
const client = createMockClient(async (req) => {
if (req.url.includes("userRole/search")) {
return Response.json({
items: [
{
id: "ID01TZKdvh3nAz",
userId: { id: "chenlong3016", name: "陈龙", code: "3016" },
},
],
});
}
if (req.url.includes("assistPlatform/transfer")) {
const body = (await req.json()) as any;
expect(body.assistId).toBe("ID01Xenwiu9w0D");
expect(body.recipient).toBe("chenlong3016");
expect(body.remarks).toBe("转交给陈龙测试");
return Response.json({ value: true });
}
return new Response("Not found", { status: 404 });
});
const res = await transferAssistTicket(client, {
ticketId: "ID01Xenwiu9w0D",
recipient: "陈龙",
remarks: "转交给陈龙测试",
});
expect(res.success).toBe(true);
expect(res.recipient).toBe("chenlong3016");
expect(res.recipientName).toBe("陈龙");
});
});
});
+86
View File
@@ -12,6 +12,8 @@ import {
getStaffMeAndRolesApi,
searchAssistTicketsApi,
searchCorporationsApi,
searchTransferCandidatesApi,
transferAssistTicketApi,
type ApproveAssistTicketApiParams,
type ApproveAssistTicketApiResponse,
type CreateAssistTicketApiParams,
@@ -27,6 +29,9 @@ import type {
AssistPlatformTicket,
CorporationDetail,
StaffRoleItem,
TransferCandidate,
TransferTicketParams,
TransferTicketResult,
} from "./types.js";
export const PERMISSION_LABEL_MAP: Record<string, string> = {
@@ -365,3 +370,84 @@ export async function importAssistSessionToLocal(
corpConfig,
};
}
export async function listTransferCandidates(
client: KyInstance,
keyword?: string
): Promise<TransferCandidate[]> {
return searchTransferCandidatesApi(client, keyword);
}
export async function resolveTransferRecipient(
client: KyInstance,
target: string
): Promise<TransferCandidate> {
const cleanTarget = target.trim();
if (!cleanTarget) {
throw new BusinessError("必须指定转交接收人(姓名、工号或账号)");
}
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];
}
const fuzzyMatches = 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}],请指定具体工号或全名`);
}
throw new NotFoundError(`未在具备协助权限的人员库中找到匹配的人员: "${cleanTarget}"`);
}
export async function transferAssistTicket(
client: KyInstance,
params: {
ticketId: string;
recipient: string;
remarks?: string;
}
): Promise<TransferTicketResult> {
let resolvedRecipientId = params.recipient;
let recipientName: string | undefined;
try {
const candidate = await resolveTransferRecipient(client, params.recipient);
resolvedRecipientId = candidate.id;
recipientName = candidate.name;
} catch {
// 若解析不到,仍尝试直接以原值请求
}
await transferAssistTicketApi(client, {
ticketId: params.ticketId,
recipient: resolvedRecipientId,
remarks: params.remarks,
});
return {
success: true,
ticketId: params.ticketId,
recipient: resolvedRecipientId,
recipientName,
remarks: params.remarks,
};
}
+22
View File
@@ -101,3 +101,25 @@ export const CorporationDetailSchema = z.object({
otherGoodsList: z.array(z.record(z.string(), z.any())).default([]),
});
export type CorporationDetail = z.infer<typeof CorporationDetailSchema>;
export interface TransferCandidate {
id: string;
name: string;
code?: string;
userRoleId: string;
roles: string[];
}
export interface TransferTicketParams {
ticketId: string;
recipient: string;
remarks?: string;
}
export interface TransferTicketResult {
success: boolean;
ticketId: string;
recipient: string;
recipientName?: string;
remarks?: string;
}