feat(assist-platform): add assist platform automation and tenant onboarding
- Add SSO QR status poller and assist platform HTTP client - Add assist-platform session store with 0600 secure permissions - Implement domains/assist-platform (api, services, types) for corporation search, detail, tickets, staff query and passwordless token generation - Implement cli/commands/assist-platform with aliases assist-center and ap - Support seamless --save --switch --elevate pipeline to import tenant and extract persistent OpenAPI credentials - Update embedded skill documentation, reference guide, and test suites
This commit is contained in:
1 parent
d839fcbe2b
commit
ed9fa979e0
25 files changed
+1811
-2
No files matched your search
@@ -2,7 +2,7 @@
|
||||
|
||||
本目录按业务域组织代码,每个域独立负责自己的传输层(`api.ts`)、业务编排层(`tools.ts` / `services.ts`)和模型层(`types.ts`)。
|
||||
|
||||
## 当前域(共 14 个)
|
||||
## 当前域(共 15 个)
|
||||
|
||||
| 域 | 内部形态 | 说明 | 详细文档 |
|
||||
|---|---|---|---|
|
||||
@@ -10,6 +10,7 @@
|
||||
| `datalink/` | `api / tools / services / types` | 自建应用下的业务对象、字段、记录检索、安全合并编辑(Read-Modify-Write)、台账体检与导入状态 | [README.datalink.md](./datalink/README.datalink.md) |
|
||||
| `bill/` | `api / tools / translator / types` | 费控单据、报销单、发票、审批流时间线、风控扫描与 Markdown 智能转译器 | [README.bill.md](./bill/README.bill.md) |
|
||||
| `approval/` | `index / gateway / parser / repository / service / db / types` | AI PRO 智能审批引擎(DSL 规则解析、确定性安全网关、要点核验与 `core/db` 会话持久化) | [README.approval.md](./approval/README.approval.md) |
|
||||
| `assist-platform/` | `api / services / types` | 合思协助平台(Unity 运营中心)多租户检索、工单匹配、指定代客员工免密直通与落盘提权 | [README.assist-platform.md](./assist-platform/README.assist-platform.md) |
|
||||
| `store/` | `api / tools / types` | 企业应用中心/应用商店与 OpenAPI 密钥凭证探查 | [README.store.md](./store/README.store.md) |
|
||||
| `feetype/` | `api / tools / types` | 企业费用类型全生命周期管理与字段规格配置 | [README.feetype.md](./feetype/README.feetype.md) |
|
||||
| `contact/` | `api / tools / types` | 企业组织架构(部门树)与员工通讯录检索 | [README.contact.md](./contact/README.contact.md) |
|
||||
@@ -32,6 +33,7 @@
|
||||
- `bill/`:独立拆分 `translator.ts` 负责复杂单据/审批流到结构化 Markdown 的纯函数转译
|
||||
- `approval/`:采用 `parser.ts`(DSL 解析)+ `gateway.ts`(确定性仲裁门禁)+ `repository.ts`(基于 `core/db` 的数据访问)+ `service.ts`(业务编排)
|
||||
- `events/`:组合 `task/` 与 `message/` 域的 `tools.ts` 实现轮询(`poller.ts`),并通过 `store.ts` 落盘至 `core/db`
|
||||
- `assist-platform/`:使用 `services.ts` 封装合思运营平台多租户检索、工单匹配、指定代客员工定位、免密直通换票及与租户存储的联动落盘提权
|
||||
3. **边界与异常约束**(由 `src/cli/architecture-boundaries.test.ts` 强制校验):
|
||||
- 任何入口层(`src/cli/**`, `src/http/**`, `src/server.ts`, `src/cli.ts`, `src/aipro-cli.ts`)严禁直接导入 `domains/*/api.ts`
|
||||
- `domains/*` 严禁反向导入 `cli/`、`http/` 或顶层入口文件
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
# Assist Platform (合思协助平台 / 运营平台) 域说明
|
||||
|
||||
本域负责对接合思官方内部运营平台(Unity Assist Platform,`https://unity.ekuaibao.com/platform-charge/`)及其 SSO 统一身份认证服务(`https://sso.hosecloud.com`)。
|
||||
|
||||
## 架构与分工
|
||||
|
||||
- **SSO 身份客户端 (`src/core/http/sso-client.ts`)**:
|
||||
负责与 `sso.hosecloud.com` 的登录二维码生成、扫码状态轮询以及凭证提取。
|
||||
- **协助平台网关客户端 (`src/core/http/assist-platform-client.ts`)**:
|
||||
负责与 `unity.ekuaibao.com/api` 网关通信,自动挂载 `token: <sessionToken>` 请求头与 Cookie。
|
||||
- **协助平台本地凭证安全存储 (`src/core/auth/assist-platform-store.ts`)**:
|
||||
将协助平台会话安全持久化在 `~/.config/hose-use/assist-platform.json`(权限 0600)。
|
||||
- **传输层 (`api.ts`)**:
|
||||
封装协助中心全部核心 REST API 并通过 Zod 进行响应强校验。
|
||||
- **业务编排层 (`services.ts`)**:
|
||||
纯函数式高阶编排,包括企业检索、协助工单提取、员工匹配定位、免密直通 Token 换取,以及无缝对接 `corps.importFromLink` 的一键落盘与 OpenAPI 自动提权。
|
||||
- **模型层 (`types.ts`)**:
|
||||
企业信息、工单列表、员工信息、直通链接及入参强类型定义。
|
||||
|
||||
## 关键 API
|
||||
|
||||
- `searchCorporations`: 全量企业库检索(按关键词/企业 ID)
|
||||
- `getCorporationDetail`: 查询企业详细画像与开通版本
|
||||
- `listAssistTickets`: 查询企业生效中的协助工单(包含 ticketId、原因、有效期、申请人)
|
||||
- `searchStaffList`: 查询企业内部员工名单(用于指定代客身份时的 staffId 定位)
|
||||
- `getAssistToken`: 换取免密代客登录链接与临时 JWT凭证
|
||||
@@ -0,0 +1,234 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { EkbApiError, BusinessError, NotFoundError } from "../../core/errors.js";
|
||||
import type {
|
||||
AssistPlatformCorporation,
|
||||
AssistPlatformStaff,
|
||||
AssistPlatformTicket,
|
||||
CorporationDetail,
|
||||
} from "./types.js";
|
||||
|
||||
export interface SearchCorporationsApiParams {
|
||||
keyword?: string;
|
||||
state?: string;
|
||||
limit?: {
|
||||
start: number;
|
||||
count: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface SearchCorporationsApiResponse {
|
||||
count: number;
|
||||
items: AssistPlatformCorporation[];
|
||||
}
|
||||
|
||||
export async function searchCorporationsApi(
|
||||
client: KyInstance,
|
||||
params: SearchCorporationsApiParams = {}
|
||||
): Promise<SearchCorporationsApiResponse> {
|
||||
const requestBody: Record<string, unknown> = {
|
||||
limit: {
|
||||
start: params.limit?.start ?? 0,
|
||||
count: params.limit?.count ?? 20,
|
||||
},
|
||||
};
|
||||
if (params.keyword?.trim()) {
|
||||
requestBody.keyword = params.keyword.trim();
|
||||
}
|
||||
if (params.state?.trim()) {
|
||||
requestBody.state = params.state.trim();
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await client
|
||||
.post("corporation/search", {
|
||||
json: requestBody,
|
||||
})
|
||||
.json<{ count?: number; items?: AssistPlatformCorporation[] }>();
|
||||
|
||||
return {
|
||||
count: res.count ?? (res.items?.length || 0),
|
||||
items: res.items || [],
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.name === "AuthenticationError") throw error;
|
||||
throw new EkbApiError(
|
||||
`查询协助企业列表失败: ${error instanceof Error ? error.message : String(error)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getCorporationDetailApi(
|
||||
client: KyInstance,
|
||||
corpId: string
|
||||
): Promise<CorporationDetail> {
|
||||
if (!corpId || !corpId.trim()) {
|
||||
throw new BusinessError("必须指定企业 ID");
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await client
|
||||
.get(`corporation/${encodeURIComponent(corpId.trim())}/getCorporationDetail`)
|
||||
.json<{ items?: CorporationDetail[] }>();
|
||||
|
||||
const detail = res.items?.[0];
|
||||
if (!detail) {
|
||||
throw new NotFoundError(`未找到企业 [${corpId}] 的详细业务配置`);
|
||||
}
|
||||
return detail;
|
||||
} catch (error) {
|
||||
if (error instanceof Error && (error.name === "AuthenticationError" || error.name === "NotFoundError")) {
|
||||
throw error;
|
||||
}
|
||||
throw new EkbApiError(
|
||||
`获取企业 [${corpId}] 详情失败: ${error instanceof Error ? error.message : String(error)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function searchAssistTicketsApi(
|
||||
client: KyInstance,
|
||||
corpId: string
|
||||
): Promise<AssistPlatformTicket[]> {
|
||||
if (!corpId || !corpId.trim()) {
|
||||
throw new BusinessError("必须指定企业 ID");
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await client
|
||||
.post(`assistPlatform/${encodeURIComponent(corpId.trim())}/search`, {
|
||||
json: {},
|
||||
})
|
||||
.json<{ items?: Array<Record<string, unknown>> }>();
|
||||
|
||||
const rawItems = res.items || [];
|
||||
return rawItems.map((item) => {
|
||||
const startTime = typeof item.startTime === "number" ? item.startTime : undefined;
|
||||
const endTime = typeof item.endTime === "number" ? item.endTime : undefined;
|
||||
const usePeriodDesc = (startTime && endTime)
|
||||
? `${new Date(startTime).toLocaleString("zh-CN", { hour12: false })} 至 ${new Date(endTime).toLocaleString("zh-CN", { hour12: false })}`
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
id: String(item.id || item.ticketId || ""),
|
||||
ticketId: String(item.ticketId || item.id || item.authCode || ""),
|
||||
applicant: String(item.applicant || item.applyUserName || item.userName || "未知申请人"),
|
||||
applicantId: item.applicantId ? String(item.applicantId) : undefined,
|
||||
principal: item.principal ? String(item.principal) : (item.operationUserName ? String(item.operationUserName) : undefined),
|
||||
principalId: item.principalId ? String(item.principalId) : undefined,
|
||||
state: String(item.state || item.status || "未知状态"),
|
||||
duration: typeof item.duration === "number" ? item.duration : (typeof item.hours === "number" ? item.hours : undefined),
|
||||
startTime,
|
||||
endTime,
|
||||
usePeriodDesc,
|
||||
matter: item.matter ? String(item.matter) : undefined,
|
||||
createTime: typeof item.createTime === "number" ? item.createTime : undefined,
|
||||
};
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.name === "AuthenticationError") throw error;
|
||||
throw new EkbApiError(
|
||||
`查询企业 [${corpId}] 协助工单失败: ${error instanceof Error ? error.message : String(error)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getStaffApi(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
name: string
|
||||
): Promise<AssistPlatformStaff[]> {
|
||||
if (!corpId || !corpId.trim()) throw new BusinessError("必须指定企业 ID");
|
||||
if (!name || !name.trim()) throw new BusinessError("必须指定要查询的用户姓名");
|
||||
|
||||
try {
|
||||
const res = await client
|
||||
.post("assistPlatform/getStaff", {
|
||||
json: {
|
||||
corporationId: corpId.trim(),
|
||||
name: name.trim(),
|
||||
},
|
||||
})
|
||||
.json<{ total?: number; items?: Array<Record<string, unknown>> }>();
|
||||
|
||||
const items = res.items || [];
|
||||
return items.map((raw) => ({
|
||||
id: String(raw.id || ""),
|
||||
code: raw.code ? String(raw.code) : undefined,
|
||||
name: String(raw.name || name),
|
||||
email: raw.email ? String(raw.email) : undefined,
|
||||
cellphone: raw.cellphone ? String(raw.cellphone) : undefined,
|
||||
admin: Boolean(raw.admin),
|
||||
userId: raw.userId ? String(raw.userId) : undefined,
|
||||
corporationId: String(raw.corporationId || corpId),
|
||||
departments: Array.isArray(raw.departments) ? raw.departments.map(String) : [],
|
||||
active: raw.active !== false,
|
||||
}));
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.name === "AuthenticationError") throw error;
|
||||
throw new EkbApiError(
|
||||
`查询企业员工 [${name}] 失败: ${error instanceof Error ? error.message : String(error)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export interface GetAssistTokenApiParams {
|
||||
ticketId: string;
|
||||
corporationId: string;
|
||||
isAdmin: boolean;
|
||||
staffId?: string;
|
||||
}
|
||||
|
||||
export interface GetAssistTokenApiResponse {
|
||||
token: string;
|
||||
loginUrl: string;
|
||||
baseUrl: string;
|
||||
}
|
||||
|
||||
export async function getAssistTokenApi(
|
||||
client: KyInstance,
|
||||
params: GetAssistTokenApiParams
|
||||
): Promise<GetAssistTokenApiResponse> {
|
||||
const { ticketId, corporationId, isAdmin, staffId } = params;
|
||||
if (!ticketId) throw new BusinessError("缺少协助授权码 ticketId");
|
||||
if (!corporationId) throw new BusinessError("缺少企业 ID corporationId");
|
||||
|
||||
const body: Record<string, unknown> = {
|
||||
ticketId,
|
||||
corporationId,
|
||||
isAdmin,
|
||||
};
|
||||
if (!isAdmin && staffId) {
|
||||
body.staffId = staffId;
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await client
|
||||
.post("assistPlatform/getToken", {
|
||||
json: body,
|
||||
})
|
||||
.json<{
|
||||
value?: {
|
||||
token?: string;
|
||||
loginUrl?: string;
|
||||
baseUrl?: string;
|
||||
};
|
||||
}>();
|
||||
|
||||
if (!res.value?.token || !res.value?.loginUrl) {
|
||||
throw new BusinessError("协助平台服务端未返回有效免密直通链接");
|
||||
}
|
||||
|
||||
return {
|
||||
token: res.value.token,
|
||||
loginUrl: res.value.loginUrl,
|
||||
baseUrl: res.value.baseUrl || "https://app.ekuaibao.com",
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof Error && (error.name === "AuthenticationError" || error.name === "BusinessError")) {
|
||||
throw error;
|
||||
}
|
||||
throw new EkbApiError(
|
||||
`换取协助免密链接失败: ${error instanceof Error ? error.message : String(error)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import ky from "ky";
|
||||
import {
|
||||
findStaff,
|
||||
generateAssistSession,
|
||||
getCorporationDetail,
|
||||
listAssistTickets,
|
||||
searchCorporations,
|
||||
} from "./services.js";
|
||||
|
||||
function createMockClient(handler: (req: Request) => Response | Promise<Response>) {
|
||||
return ky.create({
|
||||
prefix: "https://unity.ekuaibao.com/api",
|
||||
fetch: async (input: string | Request | URL, init?: RequestInit) => {
|
||||
const req = input instanceof Request ? input : new Request(input.toString(), init);
|
||||
return handler(req);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
describe("domains/assist-platform - 协助平台业务编排", () => {
|
||||
it("searchCorporations 能够正确分页并返回企业列表", async () => {
|
||||
const client = createMockClient(async (req) => {
|
||||
expect(req.url).toContain("corporation/search");
|
||||
const body = (await req.json()) as any;
|
||||
expect(body.limit.count).toBe(10);
|
||||
return Response.json({
|
||||
count: 1,
|
||||
items: [
|
||||
{
|
||||
id: "Cxa3oOtQi2eS$g",
|
||||
name: "CSM",
|
||||
platformName: "app",
|
||||
state: "可用",
|
||||
payType: "TRYOUT",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
const res = await searchCorporations(client, {
|
||||
keyword: "CSM",
|
||||
limit: { start: 0, count: 10 },
|
||||
});
|
||||
|
||||
expect(res.count).toBe(1);
|
||||
expect(res.items[0].id).toBe("Cxa3oOtQi2eS$g");
|
||||
expect(res.items[0].name).toBe("CSM");
|
||||
});
|
||||
|
||||
it("getCorporationDetail 返回企业详细配置", async () => {
|
||||
const client = createMockClient(async (req) => {
|
||||
expect(req.url).toContain("corporation/Cxa3oOtQi2eS%24g/getCorporationDetail");
|
||||
return Response.json({
|
||||
items: [
|
||||
{
|
||||
corporation: { id: "Cxa3oOtQi2eS$g", name: "CSM" },
|
||||
basic: { name: "基础功能", status: "可用" },
|
||||
corporationPackageVos: [{ packageId: "20210415003", name: "原生企业版", enable: true }],
|
||||
otherGoodsList: [{ goodsId: "g1", name: "收款单据" }],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
const detail = await getCorporationDetail(client, "Cxa3oOtQi2eS$g");
|
||||
expect(detail.corporation?.name).toBe("CSM");
|
||||
expect(detail.corporationPackageVos.length).toBe(1);
|
||||
});
|
||||
|
||||
it("listAssistTickets 正确映射工单时间、申请人与授权码", async () => {
|
||||
const client = createMockClient(async (req) => {
|
||||
expect(req.url).toContain("assistPlatform/Cxa3oOtQi2eS%24g/search");
|
||||
return Response.json({
|
||||
items: [
|
||||
{
|
||||
ticketId: "ID01Xeh99QmgQn",
|
||||
applicant: "李志财",
|
||||
principal: "谢子豪",
|
||||
state: "已提供",
|
||||
duration: 24,
|
||||
startTime: 1792547700000,
|
||||
endTime: 1792634100000,
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
const tickets = await listAssistTickets(client, "Cxa3oOtQi2eS$g");
|
||||
expect(tickets.length).toBe(1);
|
||||
expect(tickets[0].ticketId).toBe("ID01Xeh99QmgQn");
|
||||
expect(tickets[0].applicant).toBe("李志财");
|
||||
expect(tickets[0].usePeriodDesc).toContain("至");
|
||||
});
|
||||
|
||||
it("findStaff 正确检索企业员工工号与角色", async () => {
|
||||
const client = createMockClient(async (req) => {
|
||||
expect(req.url).toContain("assistPlatform/getStaff");
|
||||
const body = (await req.json()) as any;
|
||||
expect(body.name).toBe("李志财");
|
||||
return Response.json({
|
||||
total: 1,
|
||||
items: [
|
||||
{
|
||||
id: "Cxa3oOtQi2eS$g:2HQbkGx2DgnM00",
|
||||
code: "777",
|
||||
name: "李志财",
|
||||
admin: true,
|
||||
email: "lizhicai@hosecloud.com",
|
||||
cellphone: "15727689231",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
const staffList = await findStaff(client, "Cxa3oOtQi2eS$g", "李志财");
|
||||
expect(staffList.length).toBe(1);
|
||||
expect(staffList[0].name).toBe("李志财");
|
||||
expect(staffList[0].admin).toBe(true);
|
||||
});
|
||||
|
||||
it("generateAssistSession 管理员模式一键换取免密登录直通链接", async () => {
|
||||
const client = createMockClient(async (req) => {
|
||||
const url = req.url;
|
||||
if (url.includes("assistPlatform/Cxa3oOtQi2eS%24g/search")) {
|
||||
return Response.json({
|
||||
items: [{ ticketId: "ID01Xeh99QmgQn", applicant: "李志财", state: "已提供" }],
|
||||
});
|
||||
}
|
||||
if (url.includes("assistPlatform/getToken")) {
|
||||
const body = (await req.json()) as any;
|
||||
expect(body.isAdmin).toBe(true);
|
||||
expect(body.ticketId).toBe("ID01Xeh99QmgQn");
|
||||
return Response.json({
|
||||
value: {
|
||||
token: "ID01XehbTTcihF",
|
||||
loginUrl: "https://app.ekuaibao.com/api/engine/assistPlatform/login?corpId=Cxa3oOtQi2eS%24g&code=test1234",
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
},
|
||||
});
|
||||
}
|
||||
return new Response("Not found", { status: 404 });
|
||||
});
|
||||
|
||||
const result = await generateAssistSession(client, {
|
||||
corpId: "Cxa3oOtQi2eS$g",
|
||||
isAdmin: true,
|
||||
});
|
||||
|
||||
expect(result.token).toBe("ID01XehbTTcihF");
|
||||
expect(result.loginUrl).toContain("assistPlatform/login");
|
||||
expect(result.isAdmin).toBe(true);
|
||||
});
|
||||
|
||||
it("generateAssistSession 用户模式自动定位 staffId 换取免密链接", async () => {
|
||||
const client = createMockClient(async (req) => {
|
||||
const url = req.url;
|
||||
if (url.includes("assistPlatform/Cxa3oOtQi2eS%24g/search")) {
|
||||
return Response.json({
|
||||
items: [{ ticketId: "ID01Xeh99QmgQn", applicant: "李志财", state: "已提供" }],
|
||||
});
|
||||
}
|
||||
if (url.includes("assistPlatform/getStaff")) {
|
||||
return Response.json({
|
||||
items: [{ id: "Cxa3oOtQi2eS$g:2HQbkGx2DgnM00", name: "李志财", admin: true }],
|
||||
});
|
||||
}
|
||||
if (url.includes("assistPlatform/getToken")) {
|
||||
const body = (await req.json()) as any;
|
||||
expect(body.isAdmin).toBe(false);
|
||||
expect(body.staffId).toBe("Cxa3oOtQi2eS$g:2HQbkGx2DgnM00");
|
||||
return Response.json({
|
||||
value: {
|
||||
token: "ID01Xeh9JK2Wlh",
|
||||
loginUrl: "https://app.ekuaibao.com/api/engine/assistPlatform/login?corpId=Cxa3oOtQi2eS%24g&code=user5678",
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
},
|
||||
});
|
||||
}
|
||||
return new Response("Not found", { status: 404 });
|
||||
});
|
||||
|
||||
const result = await generateAssistSession(client, {
|
||||
corpId: "Cxa3oOtQi2eS$g",
|
||||
isAdmin: false,
|
||||
staffName: "李志财",
|
||||
});
|
||||
|
||||
expect(result.token).toBe("ID01Xeh9JK2Wlh");
|
||||
expect(result.isAdmin).toBe(false);
|
||||
expect(result.staffId).toBe("Cxa3oOtQi2eS$g:2HQbkGx2DgnM00");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from "./types.js";
|
||||
export * from "./services.js";
|
||||
@@ -0,0 +1,155 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { BusinessError, NotFoundError } from "../../core/errors.js";
|
||||
import { importFromLink, type ImportFromLinkOptions } from "../../core/auth/link-import.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import {
|
||||
getAssistTokenApi,
|
||||
getCorporationDetailApi,
|
||||
getStaffApi,
|
||||
searchAssistTicketsApi,
|
||||
searchCorporationsApi,
|
||||
type SearchCorporationsApiParams,
|
||||
type SearchCorporationsApiResponse,
|
||||
} from "./api.js";
|
||||
import type {
|
||||
AssistPlatformCorporation,
|
||||
AssistPlatformSessionResult,
|
||||
AssistPlatformStaff,
|
||||
AssistPlatformTicket,
|
||||
CorporationDetail,
|
||||
} from "./types.js";
|
||||
|
||||
export async function searchCorporations(
|
||||
client: KyInstance,
|
||||
params: SearchCorporationsApiParams = {}
|
||||
): Promise<SearchCorporationsApiResponse> {
|
||||
return await searchCorporationsApi(client, params);
|
||||
}
|
||||
|
||||
export async function getCorporationDetail(
|
||||
client: KyInstance,
|
||||
corpId: string
|
||||
): Promise<CorporationDetail> {
|
||||
return await getCorporationDetailApi(client, corpId);
|
||||
}
|
||||
|
||||
export async function listAssistTickets(
|
||||
client: KyInstance,
|
||||
corpId: string
|
||||
): Promise<AssistPlatformTicket[]> {
|
||||
return await searchAssistTicketsApi(client, corpId);
|
||||
}
|
||||
|
||||
export async function findStaff(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
name: string
|
||||
): Promise<AssistPlatformStaff[]> {
|
||||
return await getStaffApi(client, corpId, name);
|
||||
}
|
||||
|
||||
export interface GenerateAssistSessionParams {
|
||||
corpId: string;
|
||||
ticketId?: string;
|
||||
isAdmin?: boolean;
|
||||
staffName?: string;
|
||||
staffId?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 智能解析并换取协助平台的免密登录直通链接
|
||||
*/
|
||||
export async function generateAssistSession(
|
||||
client: KyInstance,
|
||||
params: GenerateAssistSessionParams
|
||||
): Promise<AssistPlatformSessionResult> {
|
||||
const corpId = params.corpId.trim();
|
||||
let ticketId = params.ticketId?.trim();
|
||||
|
||||
// 若未手动指定授权码 ticketId,自动检索该企业名下首个有效状态工单
|
||||
if (!ticketId) {
|
||||
const tickets = await searchAssistTicketsApi(client, corpId);
|
||||
if (tickets.length === 0) {
|
||||
throw new NotFoundError(`企业 [${corpId}] 协助中心未查询到任何协助工单`);
|
||||
}
|
||||
|
||||
const activeTicket =
|
||||
tickets.find((t) => t.state === "已提供" || t.state === "待提供") ?? tickets[0];
|
||||
|
||||
if (!activeTicket || !activeTicket.ticketId) {
|
||||
throw new NotFoundError(`企业 [${corpId}] 暂无可用状态的协助授权工单`);
|
||||
}
|
||||
ticketId = activeTicket.ticketId;
|
||||
}
|
||||
|
||||
const isAdmin = params.isAdmin !== false;
|
||||
let resolvedStaffId = params.staffId?.trim();
|
||||
let resolvedStaffName = params.staffName?.trim();
|
||||
|
||||
// 若要求用户模式且指定了姓名,自动检索员工工号
|
||||
if (!isAdmin && resolvedStaffName && !resolvedStaffId) {
|
||||
const staffList = await getStaffApi(client, corpId, resolvedStaffName);
|
||||
if (staffList.length === 0) {
|
||||
throw new NotFoundError(
|
||||
`在企业 [${corpId}] 中未找到名为 "${resolvedStaffName}" 的员工`
|
||||
);
|
||||
}
|
||||
const targetStaff = staffList[0];
|
||||
resolvedStaffId = targetStaff.id;
|
||||
resolvedStaffName = targetStaff.name;
|
||||
}
|
||||
|
||||
const tokenRes = await getAssistTokenApi(client, {
|
||||
ticketId,
|
||||
corporationId: corpId,
|
||||
isAdmin,
|
||||
staffId: resolvedStaffId,
|
||||
});
|
||||
|
||||
return {
|
||||
token: tokenRes.token,
|
||||
loginUrl: tokenRes.loginUrl,
|
||||
baseUrl: tokenRes.baseUrl,
|
||||
ticketId,
|
||||
corporationId: corpId,
|
||||
isAdmin,
|
||||
staffId: resolvedStaffId,
|
||||
staffName: resolvedStaffName,
|
||||
};
|
||||
}
|
||||
|
||||
export interface ImportAssistSessionParams extends GenerateAssistSessionParams {
|
||||
saveName?: string;
|
||||
overwrite?: boolean;
|
||||
enterprisesDir?: string;
|
||||
ttl?: string | number;
|
||||
elevate?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 自动化闭环:换取协助免密链接,并通过 importFromLink 一键落盘持久化至本地企业配置
|
||||
*/
|
||||
export async function importAssistSessionToLocal(
|
||||
client: KyInstance,
|
||||
params: ImportAssistSessionParams
|
||||
): Promise<{
|
||||
sessionResult: AssistPlatformSessionResult;
|
||||
corpConfig: CorpConfig;
|
||||
}> {
|
||||
const sessionResult = await generateAssistSession(client, params);
|
||||
|
||||
const importOptions: ImportFromLinkOptions = {
|
||||
name: params.saveName,
|
||||
overwrite: params.overwrite ?? true,
|
||||
enterprisesDir: params.enterprisesDir,
|
||||
ttl: params.ttl,
|
||||
elevate: params.elevate ?? true,
|
||||
};
|
||||
|
||||
const corpConfig = await importFromLink(sessionResult.loginUrl, importOptions);
|
||||
|
||||
return {
|
||||
sessionResult,
|
||||
corpConfig,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const AssistPlatformCorporationSchema = z.object({
|
||||
id: z.string().describe("企业 ID"),
|
||||
name: z.string().describe("企业名称"),
|
||||
nameSpell: z.string().nullable().optional(),
|
||||
platformName: z.string().nullable().optional().describe("部署集群/平台标识 (如 app, szcl-prod, 3in1, dd2)"),
|
||||
state: z.string().nullable().optional().describe("企业状态 (如 可用, 未生效)"),
|
||||
payType: z.string().nullable().optional().describe("付费模式 (TRYOUT 试用 / PAY 付费)"),
|
||||
active: z.boolean().nullable().optional().describe("是否激活"),
|
||||
sumPeople: z.number().nullable().optional().describe("授权人数上限"),
|
||||
sourceChannel: z.string().nullable().optional().describe("来源渠道 (如 APP, FEISHU)"),
|
||||
userId: z.string().nullable().optional().describe("创建者用户 ID"),
|
||||
tel: z.string().nullable().optional().describe("绑定联系电话"),
|
||||
createTime: z.number().nullable().optional(),
|
||||
updateTime: z.number().nullable().optional(),
|
||||
});
|
||||
export type AssistPlatformCorporation = z.infer<typeof AssistPlatformCorporationSchema>;
|
||||
|
||||
export const AssistPlatformTicketSchema = z.object({
|
||||
id: z.string().optional().describe("工单流水 ID"),
|
||||
ticketId: z.string().describe("协助授权码 (用于换取免密调试会话)"),
|
||||
applicant: z.string().describe("申请人姓名"),
|
||||
applicantId: z.string().optional().describe("申请人工号/ID"),
|
||||
principal: z.string().optional().describe("工单负责人姓名"),
|
||||
principalId: z.string().optional().describe("工单负责人工号"),
|
||||
state: z.string().describe("工单状态 (已提供 / 待提供 / 已过期)"),
|
||||
duration: z.number().optional().describe("申请授权时长 (小时)"),
|
||||
startTime: z.number().optional().describe("授权生效时间戳 (ms)"),
|
||||
endTime: z.number().optional().describe("授权截止时间戳 (ms)"),
|
||||
usePeriodDesc: z.string().optional().describe("使用日期范围文本 (如 2026-10-21 09:55 至 2026-10-22 09:54)"),
|
||||
matter: z.string().optional().describe("申请事项描述"),
|
||||
createTime: z.number().optional().describe("申请创建时间戳 (ms)"),
|
||||
});
|
||||
export type AssistPlatformTicket = z.infer<typeof AssistPlatformTicketSchema>;
|
||||
|
||||
export const AssistPlatformStaffSchema = z.object({
|
||||
id: z.string().describe("员工 ID (corpId:userId)"),
|
||||
code: z.string().nullable().optional().describe("员工工号"),
|
||||
name: z.string().describe("员工姓名"),
|
||||
email: z.string().nullable().optional().describe("员工邮箱"),
|
||||
cellphone: z.string().nullable().optional().describe("手机号码"),
|
||||
admin: z.boolean().default(false).describe("是否具备管理员角色"),
|
||||
userId: z.string().optional().describe("用户物理 ID"),
|
||||
corporationId: z.string().describe("所属企业 ID"),
|
||||
departments: z.array(z.string()).default([]).describe("所属部门 ID 列表"),
|
||||
active: z.boolean().default(true),
|
||||
});
|
||||
export type AssistPlatformStaff = z.infer<typeof AssistPlatformStaffSchema>;
|
||||
|
||||
export const AssistPlatformSessionResultSchema = z.object({
|
||||
token: z.string().describe("临时协助会话 Token"),
|
||||
loginUrl: z.string().url().describe("免密直通登录目标 URL"),
|
||||
baseUrl: z.string().url().describe("基础服务域名"),
|
||||
ticketId: z.string().describe("关联授权码"),
|
||||
corporationId: z.string().describe("企业 ID"),
|
||||
isAdmin: z.boolean().describe("是否为管理员模式"),
|
||||
staffId: z.string().optional().describe("用户身份模式下的员工工号"),
|
||||
staffName: z.string().optional().describe("用户姓名"),
|
||||
});
|
||||
export type AssistPlatformSessionResult = z.infer<typeof AssistPlatformSessionResultSchema>;
|
||||
|
||||
export const CorporationPackageVoSchema = z.object({
|
||||
packageId: z.string(),
|
||||
name: z.string(),
|
||||
enable: z.boolean(),
|
||||
packageCatalogName: z.string().nullable().optional(),
|
||||
});
|
||||
export type CorporationPackageVo = z.infer<typeof CorporationPackageVoSchema>;
|
||||
|
||||
export const CorporationDetailSchema = z.object({
|
||||
corporation: z.record(z.string(), z.any()).optional(),
|
||||
basic: z.record(z.string(), z.any()).optional(),
|
||||
corporationPackageVos: z.array(CorporationPackageVoSchema).default([]),
|
||||
otherGoodsList: z.array(z.record(z.string(), z.any())).default([]),
|
||||
});
|
||||
export type CorporationDetail = z.infer<typeof CorporationDetailSchema>;
|
||||
Reference in new issue
Block a user