440 lines
15 KiB
TypeScript
440 lines
15 KiB
TypeScript
import { KyInstance } from "ky";
|
|
import { z } from "zod";
|
|
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(specificationId(id,name,code),`...`),logs(operatorId,nextOperatorId,`...`),plan(`...`),`...`),`...`";
|
|
}
|
|
|
|
export async function listActiveStaffCatalog(
|
|
client: KyInstance,
|
|
corpId: string
|
|
): Promise<Record<string, unknown>[]> {
|
|
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<string, unknown> => Boolean(item && typeof item === "object")) : [];
|
|
}
|
|
|
|
export async function getDepartmentTree(
|
|
client: KyInstance,
|
|
corpId: string
|
|
): Promise<Record<string, unknown>[]> {
|
|
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<string, unknown> => Boolean(item && typeof item === "object"));
|
|
return Array.isArray(json.items) ? json.items.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === "object")) : [];
|
|
}
|
|
|
|
export async function getFeeTypeTree(
|
|
client: KyInstance,
|
|
corpId: string
|
|
): Promise<Record<string, unknown>[]> {
|
|
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<string, unknown> => Boolean(item && typeof item === "object"));
|
|
return Array.isArray(json.items) ? json.items.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === "object")) : [];
|
|
}
|
|
|
|
export async function getRawBillFlow(
|
|
client: KyInstance,
|
|
corpId: string,
|
|
target: string
|
|
): Promise<Record<string, unknown> | undefined> {
|
|
let match: Record<string, unknown> | 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<string, unknown>[] };
|
|
match = (lookupJson.items ?? []).find((item) => {
|
|
const flow = item.flowId && typeof item.flowId === "object" ? item.flowId as Record<string, unknown> : {};
|
|
const form = flow.form && typeof flow.form === "object" ? flow.form as Record<string, unknown> : {};
|
|
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.form.submitterId,submitterId,/v1/organization/staffs?join=defaultDepartment,defaultDepartment,/v1/organization/departments",
|
|
"flowId.form.ownerId,ownerId,/v1/organization/staffs?select=id,name,code",
|
|
"flowId.form.expenseDepartment,expenseDepartment,/v1/organization/departments",
|
|
"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<string, unknown>; items?: Record<string, unknown>[] };
|
|
return json.value ?? json.items?.[0];
|
|
}
|
|
|
|
export interface BillActionTarget {
|
|
backlogId: string;
|
|
flowId: string;
|
|
billId?: string;
|
|
billCode?: string;
|
|
nodeId?: string;
|
|
nodeName?: string;
|
|
raw: Record<string, unknown>;
|
|
}
|
|
|
|
export interface BillActionOptions {
|
|
currentStaffId?: string;
|
|
reminder?: boolean;
|
|
keepItSecret?: boolean;
|
|
comment?: string;
|
|
participants?: string[];
|
|
approverIds?: string[];
|
|
rejectTo?: string | null;
|
|
resubmitMethod?: string;
|
|
addNodeType?: "PRE_ADD_NODE" | "AFT_ADD_NODE";
|
|
}
|
|
|
|
async function readActionResponse(response: Response): Promise<unknown> {
|
|
if (response.status === 204) return undefined;
|
|
const text = await response.text();
|
|
if (!text) return undefined;
|
|
try {
|
|
return JSON.parse(text) as unknown;
|
|
} catch {
|
|
return text;
|
|
}
|
|
}
|
|
|
|
function htmlComment(comment: string | undefined): string {
|
|
const value = comment ?? "";
|
|
return `<p>${value
|
|
.replaceAll("&", "&")
|
|
.replaceAll("<", "<")
|
|
.replaceAll(">", ">")
|
|
.replaceAll('"', """)
|
|
.replaceAll("'", "'")}</p>`;
|
|
}
|
|
|
|
function backlogSearchParams(corpId: string): Record<string, string> {
|
|
return { messageCode: "debug", corpId };
|
|
}
|
|
|
|
export async function approveBillAction(
|
|
client: KyInstance,
|
|
corpId: string,
|
|
target: BillActionTarget,
|
|
options: BillActionOptions = {},
|
|
): Promise<unknown> {
|
|
const response = await client.post(`api/flow/v2/backlogs/$${target.backlogId}`, {
|
|
searchParams: backlogSearchParams(corpId),
|
|
json: {
|
|
node: {
|
|
flowId: target.flowId,
|
|
id: target.nodeId,
|
|
name: "freeflow.agree",
|
|
},
|
|
reminder: options.reminder ?? false,
|
|
keepItSecret: options.keepItSecret ?? false,
|
|
comment: options.comment ?? "",
|
|
participants: options.participants ?? [],
|
|
isSingle: true,
|
|
id: target.backlogId,
|
|
name: "freeflow.agree",
|
|
},
|
|
});
|
|
return readActionResponse(response);
|
|
}
|
|
|
|
export async function rejectBillAction(
|
|
client: KyInstance,
|
|
corpId: string,
|
|
target: BillActionTarget,
|
|
options: BillActionOptions = {},
|
|
): Promise<unknown> {
|
|
const response = await client.post("api/flow/v2/backlogs/approveListWithNode", {
|
|
searchParams: backlogSearchParams(corpId),
|
|
json: {
|
|
data: [{
|
|
id: target.backlogId,
|
|
resubmitMethod: options.resubmitMethod ?? "TO_REJECTOR",
|
|
reminder: options.reminder ?? false,
|
|
keepItSecret: options.keepItSecret ?? false,
|
|
rejectTo: options.rejectTo ?? null,
|
|
comment: htmlComment(options.comment),
|
|
participants: options.participants ?? [],
|
|
name: "freeflow.reject",
|
|
}],
|
|
},
|
|
});
|
|
return readActionResponse(response);
|
|
}
|
|
|
|
export async function transferBillAction(
|
|
client: KyInstance,
|
|
corpId: string,
|
|
target: BillActionTarget,
|
|
options: BillActionOptions = {},
|
|
): Promise<unknown> {
|
|
const response = await client.post(`api/flow/v2/backlogs/$${target.backlogId}`, {
|
|
searchParams: backlogSearchParams(corpId),
|
|
json: {
|
|
reminder: options.reminder ?? false,
|
|
keepItSecret: options.keepItSecret ?? false,
|
|
approverId: options.approverIds ?? [],
|
|
type: "SHIFT_NODE",
|
|
autographImageId: "",
|
|
comment: options.comment ? htmlComment(options.comment) : "",
|
|
participants: options.participants ?? [],
|
|
id: target.backlogId,
|
|
name: "freeflow.addnode",
|
|
},
|
|
});
|
|
return readActionResponse(response);
|
|
}
|
|
|
|
export async function addNodeBillAction(
|
|
client: KyInstance,
|
|
corpId: string,
|
|
target: BillActionTarget,
|
|
options: BillActionOptions = {},
|
|
): Promise<unknown> {
|
|
const response = await client.post(`api/flow/v2/backlogs/$${target.backlogId}`, {
|
|
searchParams: backlogSearchParams(corpId),
|
|
json: {
|
|
reminder: options.reminder ?? false,
|
|
keepItSecret: options.keepItSecret ?? false,
|
|
approverId: options.approverIds ?? [],
|
|
type: options.addNodeType ?? "PRE_ADD_NODE",
|
|
autographImageId: "",
|
|
comment: htmlComment(options.comment),
|
|
participants: options.participants ?? [],
|
|
id: target.backlogId,
|
|
name: "freeflow.addnode",
|
|
},
|
|
});
|
|
return readActionResponse(response);
|
|
}
|
|
|
|
export async function commentBillAction(
|
|
client: KyInstance,
|
|
corpId: string,
|
|
target: BillActionTarget,
|
|
options: BillActionOptions = {},
|
|
): Promise<unknown> {
|
|
const response = await client.post(`api/flow/v1/flows/comment/$${target.flowId}`, {
|
|
searchParams: { messageCode: "debug", corpId },
|
|
json: {
|
|
id: target.flowId,
|
|
params: {
|
|
comment: htmlComment(options.comment),
|
|
participants: options.participants ?? [],
|
|
attachments: [],
|
|
keepItSecret: options.keepItSecret ?? false,
|
|
},
|
|
name: "freeflow.comment",
|
|
},
|
|
});
|
|
return readActionResponse(response);
|
|
}
|
|
|
|
export async function getRawBillRisk(
|
|
client: KyInstance,
|
|
corpId: string,
|
|
flowId: string,
|
|
submitterId?: string
|
|
): Promise<Record<string, unknown>> {
|
|
const searchParams = (extra: Record<string, string> = {}) => ({ corpId, ...extra });
|
|
const requests: Array<Promise<unknown>> = [
|
|
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<string, unknown>,
|
|
rules: values[1] as Record<string, unknown>,
|
|
notes: values[2] as Record<string, unknown>,
|
|
coalition: values[3] as Record<string, unknown>,
|
|
invoice: values[4] as Record<string, unknown>,
|
|
budget: values[5] as Record<string, unknown>,
|
|
staff: (submitterId ? values[6] : {}) as Record<string, unknown>,
|
|
};
|
|
}
|
|
|
|
// ── 原始单据检索 API ──────────────────────────────────────────────────────────
|
|
|
|
export async function searchRawBills(
|
|
client: KyInstance,
|
|
corpId: string,
|
|
options: { start?: number; count?: number } = {}
|
|
): Promise<RawBillSearchResponse> {
|
|
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<RawBillItem[]> {
|
|
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 ──────────────────────────────────────────
|
|
|
|
const AttachmentFileSchema = z.object({
|
|
id: z.string(),
|
|
key: z.string().optional(),
|
|
name: z.string().optional(),
|
|
url: z.string().optional(),
|
|
thumbUrl: z.string().optional(),
|
|
});
|
|
|
|
export type AttachmentFile = z.infer<typeof AttachmentFileSchema>;
|
|
|
|
export async function resolveAttachmentFiles(
|
|
client: KyInstance,
|
|
corpId: string,
|
|
ids: string[],
|
|
): Promise<AttachmentFile[]> {
|
|
if (ids.length === 0) return [];
|
|
|
|
const response = await client.post("api/v1/attachment/attachments/ids", {
|
|
searchParams: { corpId },
|
|
json: { ids },
|
|
});
|
|
const json = (await response.json()) as { items?: unknown[] };
|
|
return z.array(AttachmentFileSchema).parse(json.items ?? []);
|
|
}
|
|
|
|
// ── 单据实体与字段元数据字典 API ───────────────────────────────────────────────
|
|
|
|
export async function listEntitySchemas(
|
|
client: KyInstance,
|
|
corpId: string,
|
|
options: { start?: number; count?: number } = {}
|
|
): Promise<EntityMeta[]> {
|
|
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;
|
|
}
|
|
|
|
// ── 发票票面查验详情与商品明细 API ──────────────────────────────────────────────
|
|
|
|
export async function getInvoiceValidationDetail(
|
|
client: KyInstance,
|
|
corpId: string,
|
|
invoiceId: string
|
|
): Promise<Record<string, unknown> | undefined> {
|
|
try {
|
|
const response = await client.get(`api/v2/invoice/validation/$${encodeURIComponent(invoiceId)}`, {
|
|
searchParams: { masterId: invoiceId, corpId }
|
|
});
|
|
return (await response.json()) as Record<string, unknown>;
|
|
} catch {
|
|
return undefined;
|
|
}
|
|
}
|
|
|
|
// ── 数据连接业务对象与卡片详情 API ──────────────────────────────────────────────
|
|
|
|
export async function getDatalinkCard(
|
|
client: KyInstance,
|
|
corpId: string,
|
|
entityId: string,
|
|
type = "CARD"
|
|
): Promise<Record<string, unknown> | undefined> {
|
|
try {
|
|
const response = await client.get(`api/v2/datalink/detail/$${encodeURIComponent(entityId)}/$${encodeURIComponent(type)}`, {
|
|
searchParams: {
|
|
entityId,
|
|
type,
|
|
join: "data.dataLink.entityId,entity,/v2/datalink/entity",
|
|
corpId,
|
|
}
|
|
});
|
|
const json = (await response.json()) as { value?: Record<string, unknown> };
|
|
return json?.value ?? undefined;
|
|
} catch {
|
|
return undefined;
|
|
}
|
|
}
|