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 { const requestBody: Record = { limit: { start: params.limit?.start ?? 0, count: params.limit?.count ?? 20, }, }; const conditions: string[] = []; if (params.keyword?.trim()) { const kw = params.keyword.trim().replace(/"/g, '\\"'); conditions.push(`(id == "${kw}" || name == "${kw}")`); } if (params.state?.trim()) { const st = params.state.trim().replace(/"/g, '\\"'); conditions.push(`state == "${st}"`); } if (conditions.length > 0) { requestBody.filterBy = conditions.join(" && "); } 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 { if (!corpId || !corpId.trim()) { throw new BusinessError("必须指定企业 ID"); } const cleanId = corpId.trim(); const normalizedId = cleanId.startsWith("$") ? cleanId : `$${cleanId}`; try { const res = await client .get(`corporation/${normalizedId}/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 { if (!corpId || !corpId.trim()) { throw new BusinessError("必须指定企业 ID"); } const cleanId = corpId.trim(); const normalizedId = cleanId.startsWith("$") ? cleanId : `$${cleanId}`; try { const res = await client .post(`assistPlatform/${normalizedId}/search`, { json: { query: {} }, }) .json<{ items?: Array> }>(); 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; const rawStatus = item.state ?? item.status; const stateStr = rawStatus !== undefined && rawStatus !== null ? String(rawStatus) : "未知状态"; 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: stateStr, 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 { 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> }>(); 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 { const { ticketId, corporationId, isAdmin, staffId } = params; if (!ticketId) throw new BusinessError("缺少协助授权码 ticketId"); if (!corporationId) throw new BusinessError("缺少企业 ID corporationId"); const body: Record = { 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)}` ); } } export interface CreateAssistTicketApiParams { corporationId: string; applyMessage?: string; assistTime?: number; // 毫秒,默认 24 小时 } export interface CreateAssistTicketApiResponse { id: string; corporationId: string; applyMessage: string; assistTime: number; userName?: string; responsibleUserName?: string; status: number; } export async function createAssistTicketApi( client: KyInstance, params: CreateAssistTicketApiParams ): Promise { const { corporationId, applyMessage, assistTime } = params; if (!corporationId || !corporationId.trim()) { throw new BusinessError("必须指定目标企业 ID"); } const durationMs = assistTime ?? 24 * 3600 * 1000; const message = applyMessage?.trim() || "自动化联调与测试"; try { const res = await client .post("assistPlatform/create", { json: { corporationId: corporationId.trim(), applyMessage: message, assistTime: durationMs, }, }) .json<{ value?: Record; }>(); const val = res.value || {}; return { id: String(val.id || ""), corporationId: String(val.corporationId || corporationId), applyMessage: String(val.applyMessage || message), assistTime: typeof val.assistTime === "number" ? val.assistTime : durationMs, userName: val.userName ? String(val.userName) : undefined, responsibleUserName: val.responsibleUserName ? String(val.responsibleUserName) : undefined, status: typeof val.status === "number" ? val.status : 0, }; } catch (error) { if (error instanceof Error && (error.name === "AuthenticationError" || error.name === "BusinessError")) { throw error; } throw new EkbApiError( `发起协助工单申请失败: ${error instanceof Error ? error.message : String(error)}` ); } } export interface ApproveAssistTicketApiParams { ticketId: string; corporationId: string; status?: number; // 默认 1 (通过授权 / 已提供) } export interface ApproveAssistTicketApiResponse { id: string; corporationId: string; status: number; active: boolean; startTime: number; endTime: number; applyMessage: string; userName?: string; responsibleUserName?: string; } export async function approveAssistTicketApi( client: KyInstance, params: ApproveAssistTicketApiParams ): Promise { const { ticketId, corporationId, status = 1 } = params; if (!ticketId || !ticketId.trim()) { throw new BusinessError("必须指定协助工单编号 (ticketId)"); } if (!corporationId || !corporationId.trim()) { throw new BusinessError("必须指定目标企业 ID (corporationId)"); } const cleanTicketId = ticketId.trim(); const cleanCorpId = corporationId.trim(); try { const res = await client .put(`api/assistPlatform/$${cleanTicketId}/updateStatus`, { searchParams: { corpId: cleanCorpId, }, json: { id: cleanTicketId, status, }, }) .json<{ value?: Record; }>(); const val = res.value || {}; return { id: String(val.id || cleanTicketId), corporationId: String(val.corporationId || cleanCorpId), status: typeof val.status === "number" ? val.status : status, active: Boolean(val.active), startTime: Number(val.startTime || 0), endTime: Number(val.endTime || 0), applyMessage: String(val.applyMessage || ""), userName: val.userName ? String(val.userName) : undefined, responsibleUserName: val.responsibleUserName ? String(val.responsibleUserName) : undefined, }; } catch (error) { if (error instanceof Error && (error.name === "AuthenticationError" || error.name === "BusinessError")) { throw error; } throw new EkbApiError( `审批协助工单失败: ${error instanceof Error ? error.message : String(error)}` ); } }