Files
hose-use/src/domains/bill/api.ts
T
giteaandClaude 4b4a7049a0 feat(bill): 支持未提交草稿查询与 flowId 直读
- bill list --state=draft/草稿 改走 flows/my 草稿列表,修复草稿不在
  invoice/search 台账索引中导致 --state=draft 返回空的问题
- 新增 --template/--title/--staff/--page 过滤与分页;服务端 RQL 结合
  客户端兜底匹配,模板版本化 ID 自动剥离哈希
- bill get 新增 flowId 直读通道,工作流/他人创建的草稿无需 flows/my 可见
- 补充域层与 CLI 单测、bill 文档、Skill 与 OpenAPI 参数说明

Fixes #153

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-18 16:06:34 +08:00

822 lines
31 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { KyInstance } from "ky";
import { z } from "zod";
import { AuthenticationError, EkbApiError, PermissionError } from "../../core/errors.js";
import {
RawBillSearchResponseSchema,
RawBillBatchGetResponseSchema,
EntityListResponseSchema,
FormSpecificationSchema,
type RawBillSearchResponse,
type RawBillItem,
type EntityMeta,
type FormSpecification,
type BillTemplateRawGroup,
type BillPlanNode,
type BillFlowWriteResult,
} 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> {
const cleanTarget = target.trim();
let match: Record<string, unknown> | undefined;
// 通道 0: flows/my & flows/approved 服务端按单号/ID 精确过滤
// 覆盖已支付/已归档等不在 backlogs 中的单据,避免回退到「最近 N 条」本地匹配。
try {
const endpoints = ["api/flow/v1/flows/my", "api/flow/v1/flows/approved"];
let flowId: string | undefined;
for (const ep of endpoints) {
let items: Record<string, unknown>[] = [];
try {
const res = await client.post(ep, {
searchParams: { corpId, type: "home5" },
json: {
limit: { start: 0, count: 10 },
filterBy: `(form.code.in(${quoted(cleanTarget)}))||(id==${quoted(cleanTarget)})`,
},
});
const body = (await res.json()) as { items?: Record<string, unknown>[] };
items = body.items ?? [];
} catch {
continue;
}
const item = items.find((it) => {
const flow = (it.flow && typeof it.flow === "object" ? it.flow : {}) as Record<string, unknown>;
const form = (it.form && typeof it.form === "object"
? it.form
: (flow.form && typeof flow.form === "object" ? flow.form : {})) as Record<string, unknown>;
return flow.id === cleanTarget || form.code === cleanTarget;
});
const flow = item && item.flow && typeof item.flow === "object" ? item.flow as Record<string, unknown> : undefined;
if (flow && typeof flow.id === "string") {
flowId = flow.id;
break;
}
}
if (flowId) {
const detail = await client.post(`api/flow/v1/flows/flowId/$${flowId}`, {
searchParams: { id: flowId, corpId },
json: {
filterBy: `(id==${quoted(flowId)})`,
select: "id,state,form,logs",
},
});
const json = (await detail.json()) as { value?: Record<string, unknown> };
if (json.value) {
return { flowId: json.value };
}
}
} catch {
// 通道 0 失败时继续走既有回溯通道
}
// 通道 0.2: 已知 flowId 时直接读取流程详情。
// 工作流或其他身份创建的草稿可能不在当前身份的 flows/my 中,但 Job 输出/页面链接会给出 flowId;
// 该通道不依赖列表可见性,也避免回退到「最近 N 条」本地匹配。
if (/^ID01/i.test(cleanTarget)) {
try {
const detail = await client.post(`api/flow/v1/flows/flowId/$${cleanTarget}`, {
searchParams: { id: cleanTarget, corpId },
json: {
filterBy: `(id==${quoted(cleanTarget)})`,
select: "id,state,form,logs",
},
});
const json = (await detail.json()) as { value?: Record<string, unknown> };
if (json.value) return { flowId: json.value };
} catch {
// 非流程 ID 或不可见时继续走既有回溯通道
}
}
// 通道 1: api/flow/v2/backlogs/search 精准单号与 ID 匹配
const searchFilters = [
`(id==${quoted(cleanTarget)})||((flowId.id==${quoted(cleanTarget)})||(flowId.form.code==${quoted(cleanTarget)}))`,
`(flowId.form.code==${quoted(cleanTarget)})`,
`(state.in("APPROVING","PROCESSED","REJECTED","DRAFT"))`,
];
for (const filterBy of searchFilters) {
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 === cleanTarget || flow.id === cleanTarget || form.code === cleanTarget;
});
if (match) break;
} catch {
// 继续尝试其他检索
}
}
// 通道 2: 尝试从我发起的流程与已审批单据中检索 (flows/my & flows/approved)
if (!match) {
const endpoints = ["api/flow/v1/flows/my", "api/flow/v1/flows/approved", "api/flow/v2/carbonCopy/search"];
for (const ep of endpoints) {
try {
const res = await client.post(ep, {
searchParams: { corpId },
json: {
limit: { start: 0, count: 50 },
filterBy: `(form.code==${quoted(cleanTarget)})||(flowId.form.code==${quoted(cleanTarget)})`,
},
});
const json = (await res.json()) as { items?: Record<string, unknown>[] };
const found = (json.items ?? []).find((item) => {
const flow = item.flowId && typeof item.flowId === "object" ? item.flowId as Record<string, unknown> : {};
const form = (flow.form ?? item.form) as Record<string, unknown> | undefined;
return item.id === cleanTarget || flow.id === cleanTarget || form?.code === cleanTarget;
});
if (found) {
match = found;
break;
}
} catch {
// 忽略通道异常
}
}
}
// 通道 0.5: 企业级按单号索引(跨身份,不依赖 flows/my 的“我发起”范围)
// 部分单据由系统或其他员工创建,当前凭证身份在 flows/my 中不可见,但 searchByCode 可查。
try {
const res = await client.post("api/flow/v2/flows/searchByCode", {
searchParams: { corpId },
json: {},
});
const json = (await res.json()) as { items?: Record<string, unknown>[] };
const item = (json.items ?? []).find((it) => {
const form = (it.form && typeof it.form === "object" ? it.form : {}) as Record<string, unknown>;
return it.id === cleanTarget || form.code === cleanTarget;
});
if (item) {
const flowId = typeof item.id === "string" ? item.id : undefined;
// searchByCode 返回的是精简表单(可能缺收款信息/部门等表头字段),
// 命中后统一再拉一次完整详情,保证 bill get / bill validate 拿到的字段齐全。
if (flowId) {
const detail = await client.post(`api/flow/v1/flows/flowId/$${flowId}`, {
searchParams: { id: flowId, corpId },
json: { filterBy: `(id==${quoted(flowId)})`, select: "id,state,form,logs" },
});
const detailJson = (await detail.json()) as { value?: Record<string, unknown> };
if (detailJson.value) return { flowId: detailJson.value };
}
return { flowId: item };
}
} catch {
// 通道 0.5 失败时继续走既有回溯通道
}
const backlogId = typeof match?.id === "string" ? match.id : cleanTarget;
const flowIdFromMatch = match?.flowId && typeof match.flowId === "object" && typeof (match.flowId as any).id === "string"
? (match.flowId as any).id
: undefined;
// 通道 3: 调用 api/flow/v2/backlogs/id 获取完整结构化详情
try {
const filterByCond = flowIdFromMatch
? `(id==${quoted(backlogId)})||(flowId.id==${quoted(flowIdFromMatch)})`
: `(id==${quoted(backlogId)})||((flowId.id==${quoted(cleanTarget)})||(flowId.form.code==${quoted(cleanTarget)}))`;
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: filterByCond,
select: flowDetailSelect(),
},
});
const json = (await detail.json()) as { value?: Record<string, unknown>; items?: Record<string, unknown>[] };
return json.value ?? json.items?.[0] ?? match;
} catch (err) {
if (match) return match;
throw err;
}
}
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("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;")
.replaceAll("'", "&#39;")}</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 interface RawBillSearchOptions {
start?: number;
count?: number;
timeout?: number | false;
filterBy?: string;
orderBy?: Array<{ value: string; order: "ASC" | "DESC" }>;
select?: string;
distinct?: boolean;
join?: string | string[];
}
export async function searchRawBills(
client: KyInstance,
corpId: string,
options: RawBillSearchOptions = {}
): Promise<RawBillSearchResponse> {
const jsonBody: Record<string, unknown> = {
limit: {
start: options.start ?? 0,
count: options.count ?? 50,
},
};
if (options.filterBy) {
jsonBody.filterBy = options.filterBy;
}
if (options.orderBy && options.orderBy.length > 0) {
jsonBody.orderBy = options.orderBy;
}
if (options.select) {
jsonBody.select = options.select;
}
if (options.distinct !== undefined) {
jsonBody.distinct = options.distinct;
}
const searchParams: Record<string, string> = {
corporationId: corpId,
corpId,
};
if (options.join) {
searchParams.join = Array.isArray(options.join) ? options.join.join(";") : options.join;
}
const response = await client.post("api/v2/invoice/search", {
searchParams,
timeout: options.timeout ?? 30000,
json: jsonBody,
});
const json = await response.json();
return RawBillSearchResponseSchema.parse(json);
}
export interface RawDraftFlowSearchOptions {
start?: number;
count?: number;
code?: string;
keyword?: string;
title?: string;
templateId?: string;
submitterIds?: string[];
from?: number;
to?: number;
order?: "ASC" | "DESC";
}
/**
* 查询「我发起」的未提交草稿流程。
*
* 草稿尚未进入单据台账索引(`api/v2/invoice/search`),因此列表必须走
* `api/flow/v1/flows/my`。服务端过滤字段与 task 域提交列表保持一致:
* state 使用小写 `draft`,模板/标题用 `INSTR(form.*, ...)`,时间用流程 `createTime`。
*/
export async function searchMyDraftFlows(
client: KyInstance,
corpId: string,
options: RawDraftFlowSearchOptions = {}
): Promise<{ count: number; items: Record<string, unknown>[] }> {
const filters: string[] = [
'(state.in("draft"))',
// 与 task submitted 一致:对账单流程不是费控单据草稿,避免混入列表。
`(INSTR(form.specificationId, ${quoted(`${corpId}:system:对账单`)})==0)`,
];
const code = options.code?.trim();
if (code) filters.push(`(form.code.in(${quoted(code)}))`);
const title = options.title?.trim();
if (title) filters.push(`(INSTR(form.title, ${quoted(title)}) > 0)`);
const templateId = options.templateId?.trim();
if (templateId) filters.push(`(INSTR(form.specificationId, ${quoted(templateId)}) > 0)`);
const submitterIds = (options.submitterIds ?? []).map((id) => id.trim()).filter(Boolean);
if (submitterIds.length > 0) {
const submitterFilters = submitterIds.map((id) => `(INSTR(form.submitterId, ${quoted(id)}) > 0)`);
filters.push(submitterFilters.length === 1 ? submitterFilters[0]! : `(${submitterFilters.join(" || ")})`);
}
const keyword = options.keyword?.trim();
if (keyword) {
filters.push(
`((INSTR(form.title, ${quoted(keyword)}) > 0) || (INSTR(form.code, ${quoted(keyword)}) > 0))`
);
}
if (options.from !== undefined) filters.push(`(createTime > ${options.from})`);
if (options.to !== undefined) filters.push(`(createTime < ${options.to})`);
const response = await client.post("api/flow/v1/flows/my", {
searchParams: {
type: "home5",
delegatedFilter: "DELEGATE_TO_ME",
corpId,
},
json: {
filterBy: filters.join("&&"),
limit: { start: options.start ?? 0, count: options.count ?? 20 },
orderBy: [{ value: "createTime", order: options.order ?? "DESC" }],
},
});
const json = (await response.json()) as { count?: number; items?: unknown[] };
const items = Array.isArray(json.items)
? json.items.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === "object"))
: [];
return { count: json.count ?? items.length, items };
}
// ── 按 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,
options: { signal?: AbortSignal } = {}
): Promise<Record<string, unknown> | undefined> {
try {
const response = await client.get(`api/v2/invoice/validation/$${encodeURIComponent(invoiceId)}`, {
searchParams: { masterId: invoiceId, corpId },
signal: options.signal,
retry: 0,
});
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;
}
}
// ── 单据模板规格定义 API(GET api/form/v2/specifications/[{specificationId}])──
export async function getFormSpecification(
client: KyInstance,
corpId: string,
specificationId: string
): Promise<FormSpecification | undefined> {
const rawId = specificationId.replace(/^\[|\]$/g, "").trim();
if (!rawId) return undefined;
// 服务端用于查询的是「原始规格 ID」,版本化 ID 形如 `<originalId>:<hash>`;
// 仅剥离末尾的 hash(originalId 本身可能包含冒号,如 `<corpId>:system:<name>`)。
const cleanId = rawId.replace(/:[0-9a-f]{32,64}$/i, "");
const response = await client.get(
`api/form/v2/specifications/[${encodeURIComponent(cleanId)}]`,
{
searchParams: { corpId, _t: String(Date.now()) },
headers: { "cache-control": "no-cache", pragma: "no-cache" },
}
);
const json = (await response.json()) as {
items?: unknown[];
value?: unknown;
id?: string;
};
assertBillResponse(json);
const raw = Array.isArray(json.items)
? json.items[0]
: json.value ?? (typeof json.id === "string" ? json : undefined);
if (!raw || typeof raw !== "object") return undefined;
return FormSpecificationSchema.parse(raw);
}
/** 检查已知业务错误包装;单据的 code(如 B26000001)不是状态码。 */
function assertBillResponse(value: unknown): asserts value is Record<string, unknown> {
if (!value || typeof value !== "object" || Array.isArray(value)) {
throw new EkbApiError("单据接口返回的响应格式无效", "BILL_RESPONSE_INVALID", 502);
}
const record = value as Record<string, unknown>;
const errorCode = record.errorCode;
const hasErrorCode = errorCode != null && ![0, "0", "", "SUCCESS", false].includes(errorCode as string | number | boolean);
if (!hasErrorCode && record.success !== false && record.error !== true && !(typeof record.code === "number" && record.code !== 0 && record.code !== 200)) return;
const message = [record.errorMessage, record.message, record.msg].find((item): item is string => typeof item === "string" && item.length > 0) || "单据接口拒绝了操作";
const status = Number(errorCode ?? record.code);
if (status === 401) throw new AuthenticationError(message);
if (status === 403) throw new PermissionError(message);
throw new EkbApiError(message, "BILL_API_ERROR", 400);
}
function billFlowResult(json: unknown): BillFlowWriteResult {
assertBillResponse(json);
const flow = json.flow ?? json.value ?? json;
assertBillResponse(flow);
if (typeof flow.id !== "string" || !flow.id.trim() || (flow.form !== undefined && (!flow.form || typeof flow.form !== "object" || Array.isArray(flow.form)))) {
throw new EkbApiError("单据写入响应缺少有效流程 ID 或表单结构", "BILL_WRITE_RESPONSE_INVALID", 502);
}
return flow as BillFlowWriteResult;
}
export async function getBillCurrentStaff(client: KyInstance, corpId: string): Promise<Record<string, unknown>> {
const response = await client.get("api/v1/organization/staffs/me", { searchParams: { corpId } });
const json: unknown = await response.json();
assertBillResponse(json);
const value = json.value;
const staff = value && typeof value === "object" ? (value as Record<string, unknown>).staff ?? json : json;
assertBillResponse(staff);
return staff;
}
export async function getBillTemplateGroups(client: KyInstance, corpId: string): Promise<BillTemplateRawGroup[]> {
// 服务端/CDN 会缓存该 GET 响应,改名后可能读到旧名称;带时间戳强制回源。
const response = await client.get("api/form/v2/specificationGroups/withSpecificationVersioned", {
searchParams: { corpId, _t: String(Date.now()) },
headers: { "cache-control": "no-cache", pragma: "no-cache" },
});
const json: unknown = await response.json();
assertBillResponse(json);
const value = json.value as { items?: unknown } | undefined;
return z.array(z.object({
name: z.string().optional(), active: z.boolean().optional(),
specifications: z.array(z.object({ id: z.string().optional(), originalId: z.string().optional(), name: z.string().optional(), type: z.string().optional(), active: z.boolean().optional() })).optional(),
})).parse(json.items ?? value?.items ?? []);
}
export async function createBillFlow(client: KyInstance, corpId: string, form: Record<string, unknown>): Promise<BillFlowWriteResult> {
const response = await client.post("api/flow/v1/flows", { searchParams: { corpId }, json: { name: "freeflow.edit", form } });
return billFlowResult(await response.json());
}
export async function computeBillApprovalPlan(client: KyInstance, corpId: string, flowId: string, flowPlanConfigId: string, form: Record<string, unknown>, formType: string): Promise<BillPlanNode[]> {
const response = await client.post("api/v1/flow/plans/computed", {
searchParams: { corpId }, json: { flowId, flowPlanConfigId, form, formType, params: {} },
});
const json: unknown = await response.json();
assertBillResponse(json);
const value = json.value as { nodes?: unknown } | undefined;
const parsed = z.array(z.object({ id: z.string().optional(), name: z.string().optional(), type: z.string().optional(), approverId: z.unknown().optional(), approverIds: z.array(z.unknown()).optional() }).passthrough()).safeParse(value?.nodes ?? []);
if (!parsed.success) throw new EkbApiError("审批计划节点格式无效", "BILL_PLAN_RESPONSE_INVALID", 502);
return parsed.data;
}
export async function submitBillFlow(client: KyInstance, corpId: string, flowId: string, form: Record<string, unknown>, formType: string, nodes: BillPlanNode[]): Promise<unknown> {
const response = await client.post(`api/flow/v1/flows/$${flowId}`, {
searchParams: { corpId, pushMessageCode: "debug" }, json: { id: flowId, name: "freeflow.submit", formType, form, nodes },
});
const json: unknown = await response.json();
billFlowResult(json);
return json;
}
export async function deleteBillFlow(client: KyInstance, corpId: string, flowId: string): Promise<void> {
const response = await client.post(`api/flow/v1/flows/$${flowId}`, { searchParams: { corpId }, json: { id: flowId, name: "freeflow.delete" } });
const text = await response.text();
if (!text) throw new EkbApiError("删除单据失败:服务端未返回流程对象", "BILL_DELETE_FAILED", 500);
billFlowResult(JSON.parse(text));
}