import { KyInstance } from "ky"; import { RawBillSearchResponseSchema, RawBillBatchGetResponseSchema, EntityListResponseSchema, type RawBillSearchResponse, type RawBillItem, type EntityMeta, } from "./types.js"; function quoted(value: string): string { return JSON.stringify(value); } function flowLookupSelect(): string { return "flowId(form(code,title),`...`),`...`"; } function flowDetailSelect(): string { return "flowId(form(`...`),logs(operatorId,nextOperatorId,`...`),plan(`...`),`...`),`...`"; } export async function listActiveStaffCatalog( client: KyInstance, corpId: string ): Promise[]> { const response = await client.get("api/v1/organization/staffs/actives", { searchParams: { start: "0", count: "2999", corpId }, }); const json = (await response.json()) as { items?: unknown[] }; return Array.isArray(json.items) ? json.items.filter((item): item is Record => Boolean(item && typeof item === "object")) : []; } export async function getDepartmentTree( client: KyInstance, corpId: string ): Promise[]> { const response = await client.get("api/v1/organization/departments/tree/actives", { searchParams: { corpId }, }); const json = (await response.json()) as { items?: unknown[] } | unknown[]; if (Array.isArray(json)) return json.filter((item): item is Record => Boolean(item && typeof item === "object")); return Array.isArray(json.items) ? json.items.filter((item): item is Record => Boolean(item && typeof item === "object")) : []; } export async function getFeeTypeTree( client: KyInstance, corpId: string ): Promise[]> { const response = await client.get("api/v1/form/feeTypes/tree/active", { searchParams: { corpId }, }); const json = (await response.json()) as { items?: unknown[] } | unknown[]; if (Array.isArray(json)) return json.filter((item): item is Record => Boolean(item && typeof item === "object")); return Array.isArray(json.items) ? json.items.filter((item): item is Record => Boolean(item && typeof item === "object")) : []; } export async function getRawBillFlow( client: KyInstance, corpId: string, target: string ): Promise | undefined> { let match: Record | undefined; const filters = [ `(id==${quoted(target)})||((flowId.id==${quoted(target)})||(flowId.form.code==${quoted(target)}))`, `(state.in("APPROVING","PROCESSED","REJECTED","DRAFT"))`, ]; for (const filterBy of filters) { try { const lookup = await client.post("api/flow/v2/backlogs/search", { searchParams: { corpId }, json: { filterBy, limit: { start: 0, count: 100 }, select: flowLookupSelect(), }, }); const lookupJson = (await lookup.json()) as { items?: Record[] }; match = (lookupJson.items ?? []).find((item) => { const flow = item.flowId && typeof item.flowId === "object" ? item.flowId as Record : {}; const form = flow.form && typeof flow.form === "object" ? flow.form as Record : {}; return item.id === target || flow.id === target || form.code === target; }); if (match) break; } catch { // Fall through to the broad status lookup or direct detail request. } } const backlogId = typeof match?.id === "string" ? match.id : target; const detail = await client.post("api/flow/v2/backlogs/id", { searchParams: (() => { const params = new URLSearchParams({ corpId }); for (const join of [ "flowId.logs.operatorId,operatorId,/v1/organization/staffs?select=id,name,code", "flowId.logs.nextOperatorId,nextOperatorId,/v1/organization/staffs?select=id,name,code", "flowId.plan.nodes.approverId,approverId,/v1/organization/staffs?select=id,name,code", "flowId.plan.nodes.counterSigners.signerId,signerId,/v1/organization/staffs?select=id,name,code", ]) params.append("join", join); return params; })(), json: { filterBy: `(id==${quoted(backlogId)})`, select: flowDetailSelect(), }, }); const json = (await detail.json()) as { value?: Record; items?: Record[] }; return json.value ?? json.items?.[0]; } export async function getRawBillRisk( client: KyInstance, corpId: string, flowId: string, submitterId?: string ): Promise> { const searchParams = (extra: Record = {}) => ({ corpId, ...extra }); const requests: Array> = [ client.get("api/credit/v2/model", { searchParams: searchParams() }).then((response) => response.json()), client.get(`api/credit/v2/rules/byFlowId/withGroup/$${flowId}`, { searchParams: searchParams({ flowId }) }).then((response) => response.json()), client.get(`api/credit/v2/notes/byFlowId/$${flowId}`, { searchParams: searchParams({ flowId }) }).then((response) => response.json()), client.get(`api/flow/v2/riskwarning/coalition/info/$${flowId}`, { searchParams: searchParams({ flowId, privilegeId: "", newUI: "v2" }) }).then((response) => response.json()), client.get(`api/flow/v3/riskwarning/invoice/riskWarning/[${flowId}]`, { searchParams: searchParams({ flowId }) }).then((response) => response.json()), client.get(`api/v1/budget/report/flow/$${flowId}/status`, { searchParams: searchParams({ id: flowId }) }).then((response) => response.json()), ]; if (submitterId) { requests.push(client.get(`api/credit/v2/stafflog/point/$${submitterId}`, { searchParams: searchParams({ submitterId }) }).then((response) => response.json())); } const results = await Promise.allSettled(requests); const values = results.map((result) => result.status === "fulfilled" ? result.value : {}); return { creditModel: values[0] as Record, rules: values[1] as Record, notes: values[2] as Record, coalition: values[3] as Record, invoice: values[4] as Record, budget: values[5] as Record, staff: (submitterId ? values[6] : {}) as Record, }; } // ── 原始单据检索 API ────────────────────────────────────────────────────────── export async function searchRawBills( client: KyInstance, corpId: string, options: { start?: number; count?: number } = {} ): Promise { const response = await client.post("api/v2/invoice/search", { searchParams: { corporationId: corpId, corpId }, json: { limit: { start: options.start ?? 0, count: options.count ?? 50, }, }, }); const json = await response.json(); return RawBillSearchResponseSchema.parse(json); } // ── 按 ID 列表精确拉取单据详情 API ───────────────────────────────────────────── export async function getRawBillsByIds( client: KyInstance, corpId: string, ids: string[] ): Promise { if (ids.length === 0) return []; const response = await client.post("api/v2/invoice", { searchParams: { corporationId: corpId, corpId }, json: { ids }, }); const json = await response.json(); const parsed = RawBillBatchGetResponseSchema.parse(json); return parsed.items; } // ── 单据实体与字段元数据字典 API ─────────────────────────────────────────────── export async function listEntitySchemas( client: KyInstance, corpId: string, options: { start?: number; count?: number } = {} ): Promise { const response = await client.post("api/v2/datalink/entity/search", { searchParams: { corporationId: corpId, corpId }, json: { limit: { start: options.start ?? 0, count: options.count ?? 100, }, }, }); const json = await response.json(); const parsed = EntityListResponseSchema.parse(json); return parsed.items; }