Files
hose-use/src/domains/assist-platform/api.ts
T
gitea ed9fa979e0 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
2026-10-21 10:33:27 +08:00

235 lines
7.3 KiB
TypeScript

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)}`
);
}
}