590 lines
18 KiB
TypeScript
590 lines
18 KiB
TypeScript
import type { KyInstance } from "ky";
|
|
import { EkbApiError, BusinessError, NotFoundError } from "../../core/errors.js";
|
|
import type {
|
|
AssistPlatformCorporation,
|
|
AssistPlatformStaff,
|
|
AssistPlatformTicket,
|
|
CorporationDetail,
|
|
StaffRoleItem,
|
|
AssistIdentityUnavailableField,
|
|
TransferCandidate,
|
|
TransferTicketParams,
|
|
} 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,
|
|
},
|
|
};
|
|
|
|
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<CorporationDetail> {
|
|
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<AssistPlatformTicket[]> {
|
|
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<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;
|
|
|
|
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<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)}`
|
|
);
|
|
}
|
|
}
|
|
|
|
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<CreateAssistTicketApiResponse> {
|
|
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<string, unknown>;
|
|
}>();
|
|
|
|
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<ApproveAssistTicketApiResponse> {
|
|
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<string, unknown>;
|
|
}>();
|
|
|
|
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)}`
|
|
);
|
|
}
|
|
}
|
|
|
|
export async function getStaffMeAndRolesApi(
|
|
client: KyInstance,
|
|
corpId: string,
|
|
staffId?: string
|
|
): Promise<{
|
|
staff: Record<string, unknown>;
|
|
permissions: string[];
|
|
roles: StaffRoleItem[];
|
|
departmentName?: string;
|
|
unavailableFields: AssistIdentityUnavailableField[];
|
|
}> {
|
|
let staff: Record<string, unknown> = {};
|
|
let permissions: string[] = [];
|
|
const unavailableFields = new Set<AssistIdentityUnavailableField>(["staff", "admin", "permissions", "roles"]);
|
|
|
|
try {
|
|
const meRes = await client
|
|
.get("api/v1/organization/staffs/me", {
|
|
searchParams: { corpId },
|
|
})
|
|
.json<{
|
|
value?: {
|
|
staff?: Record<string, unknown>;
|
|
permissions?: string[];
|
|
};
|
|
}>();
|
|
if (meRes.value?.staff) {
|
|
staff = meRes.value.staff;
|
|
if (staff.id) unavailableFields.delete("staff");
|
|
if (typeof staff.admin === "boolean") unavailableFields.delete("admin");
|
|
}
|
|
if (Array.isArray(meRes.value?.permissions) && meRes.value.permissions.every((permission) => typeof permission === "string")) {
|
|
permissions = meRes.value.permissions.map(String);
|
|
unavailableFields.delete("permissions");
|
|
}
|
|
} catch {
|
|
// 允许容错降级
|
|
}
|
|
|
|
const effectiveStaffId = String(staff.id || staffId || "");
|
|
|
|
const roles: StaffRoleItem[] = [];
|
|
if (effectiveStaffId) {
|
|
try {
|
|
const cleanStaffId = effectiveStaffId.startsWith("$") ? effectiveStaffId : `$${effectiveStaffId}`;
|
|
const rolesRes = await client
|
|
.get(`api/v1/organization/staffs/${cleanStaffId}/roles`, {
|
|
searchParams: { corpId },
|
|
})
|
|
.json<{
|
|
items?: Array<{
|
|
roleDefId?: string;
|
|
roleDefName?: string;
|
|
roleDefCode?: string;
|
|
}>;
|
|
}>();
|
|
|
|
if (Array.isArray(rolesRes.items)) {
|
|
if (rolesRes.items.every((item) => item && typeof item.roleDefName === "string")) {
|
|
unavailableFields.delete("roles");
|
|
}
|
|
for (const item of rolesRes.items) {
|
|
if (item?.roleDefName) {
|
|
roles.push({
|
|
id: String(item.roleDefId || ""),
|
|
name: String(item.roleDefName),
|
|
code: item.roleDefCode ? String(item.roleDefCode) : undefined,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
} catch {
|
|
// 允许容错降级
|
|
}
|
|
}
|
|
|
|
let departmentName: string | undefined;
|
|
const deptId = String(
|
|
staff.defaultDepartment || (Array.isArray(staff.departments) ? staff.departments[0] : "") || ""
|
|
);
|
|
if (deptId) {
|
|
unavailableFields.add("department");
|
|
try {
|
|
const cleanDeptId = deptId.startsWith("$") ? deptId : `$${deptId}`;
|
|
const deptRes = await client
|
|
.get(`api/v1/organization/departments/${cleanDeptId}`, {
|
|
searchParams: { corpId },
|
|
})
|
|
.json<{ value?: { name?: string } }>();
|
|
if (deptRes.value?.name) {
|
|
departmentName = deptRes.value.name;
|
|
unavailableFields.delete("department");
|
|
}
|
|
} catch {
|
|
// 允许容错降级
|
|
}
|
|
}
|
|
|
|
return {
|
|
staff,
|
|
permissions,
|
|
roles,
|
|
departmentName,
|
|
unavailableFields: [...unavailableFields],
|
|
};
|
|
}
|
|
|
|
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)}`
|
|
);
|
|
}
|
|
}
|