import type { KyInstance } from "ky"; import { NotFoundError, ValidationError } from "../../core/errors.js"; import { createBillFlow, getBillCurrentStaff, getDepartmentTree, getFeeTypeTree, getFormSpecification } from "./api.js"; import { listBillTemplates } from "./templates.js"; import { assertBillDraftValid } from "./draft-validation.js"; /** * 纯接口创建单据草稿。 * * 模板决定必填字段;这里构造最小可用表单: * - 表头:specificationId / title / submitterId / expenseDate / expenseDepartment * - 明细:选中一个费用类型(默认「简单费用」或第一个可用类型),金额可配置 * * 创建后仍为 draft,不会提交。 */ export interface CreateBillOptions { /** 模板 ID(bill templates 输出的 id) */ templateId: string; title?: string; /** 本位币金额,默认 0.01 */ amount?: string; reason?: string; /** 指定费用类型名称,默认「简单费用」,找不到则取第一个可用类型 */ feeTypeName?: string; submitterId?: string; expenseDepartment?: string; expenseDate?: number; } export interface TemplateComponent { field?: string; optional?: boolean; type?: string; } /** * 按模板字段白名单过滤表单:只保留模板声明过的字段 + specificationId/details。 * 返回缺失的必填字段,供调用方明确报错(而不是让服务端 412)。 */ export function filterBillFormByTemplate( form: Record, components: TemplateComponent[] ): { form: Record; missingRequired: string[] } { const allowed = new Set(["specificationId", "details"]); for (const component of components) { if (component.field) allowed.add(component.field); } const filtered: Record = {}; for (const [key, value] of Object.entries(form)) { if (allowed.has(key)) filtered[key] = value; } const missingRequired = components .filter((component) => component.field && component.optional === false && !(component.field in filtered)) .map((component) => component.field as string); return { form: filtered, missingRequired }; } /** * 按费用类型 schema 过滤明细字段:费用类型没有声明的字段不发(如 feeDate)。 * 规格未声明字段(components 为空)时保留候选字段;调用方须先确认规格存在。 */ export function filterFeeTypeFormBySpec( candidate: Record, components: TemplateComponent[] ): Record { const allowed = new Set(); for (const component of components) { if (component.field) allowed.add(component.field); } if (allowed.size === 0) return candidate; return Object.fromEntries(Object.entries(candidate).filter(([key]) => allowed.has(key))); } export interface CreateBillResult { flowId: string; code: string; title: string; amount: string; feeType: string; } interface FeeTypeNode { id?: string; name?: string; active?: boolean; expenseSpecificationId?: string; children?: FeeTypeNode[]; feeType?: Omit; } function flattenFeeTypes(nodes: FeeTypeNode[]): FeeTypeNode[] { const out: FeeTypeNode[] = []; const walk = (list: FeeTypeNode[]) => { for (const node of list) { out.push(node.feeType ?? node); if (Array.isArray(node.children)) walk(node.children); } }; walk(nodes); return out; } function zeroMoney(): Record { return { standard: "0", standardUnit: "元", standardScale: 2, standardSymbol: "¥", standardNumCode: "156", standardStrCode: "CNY", }; } export async function prepareBillDraft( client: KyInstance, corpId: string, options: CreateBillOptions ): Promise<{ form: Record; title: string; amount: string; feeType: string }> { const templateId = options.templateId.trim(); if (!templateId) throw new ValidationError("请通过 --template 指定单据模板 ID"); const specification = await getFormSpecification(client, corpId, templateId); if (!specification) { throw new NotFoundError(`未找到单据模板: ${templateId}`); } // 创建接口要求版本化 specificationId(`:`); // 用户传入的通常是 bill templates 输出的原始 ID。 let versionedSpecificationId = templateId; if (!/:[0-9a-f]{32,64}$/i.test(templateId)) { const templates = await listBillTemplates(client, corpId); const hit = templates.groups .flatMap((group) => group.specifications) .find((item) => item.id === templateId || item.name === templateId); if (!hit) throw new NotFoundError(`未找到单据模板: ${templateId}`); versionedSpecificationId = hit.versionedId; } const staff = await getBillCurrentStaff(client, corpId); const submitterId = options.submitterId || staff.id; const corpDeptCandidate = (value: unknown): string | undefined => { if (typeof value === "string" && value && value !== corpId) return value; if (value && typeof value === "object" && typeof (value as any).id === "string") { const id = (value as any).id as string; return id === corpId ? undefined : id; } return undefined; }; let expenseDepartment = options.expenseDepartment || corpDeptCandidate(staff.defaultDepartment) || corpDeptCandidate(staff.defaultDepartmentId) || corpDeptCandidate(Array.isArray(staff.departments) ? staff.departments[0] : undefined); if (!expenseDepartment) { // OpenAPI/协助身份可能只返回企业 ID 作为部门;回退到部门树第一个有效节点。 const tree = (await getDepartmentTree(client, corpId)) as Array>; const flat: Array> = []; const walk = (nodes: Array>) => { for (const node of nodes) { flat.push(node); if (Array.isArray(node.children)) walk(node.children); } }; walk(tree); expenseDepartment = corpDeptCandidate(flat.find((node) => corpDeptCandidate(node.id))?.id); } if (!submitterId || !expenseDepartment) { throw new ValidationError("无法确定提交人或报销部门,请通过 --submitter / --department 指定"); } const feeTypes = flattenFeeTypes((await getFeeTypeTree(client, corpId)) as FeeTypeNode[]); const preferred = options.feeTypeName?.trim(); const available = feeTypes.filter((item) => item.active !== false && item.id && item.expenseSpecificationId); const matches = preferred ? available.filter((item) => item.name === preferred) : []; if (preferred && matches.length !== 1) { throw new ValidationError(`费用类型 [${preferred}] ${matches.length ? "存在重名,请使用唯一名称" : "不存在、已停用或无可用规格"}`); } const feeType = preferred ? matches[0] : available.find((item) => item.name === "简单费用") ?? available[0]; if (!feeType?.id || !feeType.expenseSpecificationId) { throw new NotFoundError("未找到可用的费用类型(缺少 expenseSpecificationId)"); } const amount = options.amount?.trim() || "0.01"; if (!Number.isFinite(Number(amount)) || Number(amount) <= 0) { throw new ValidationError(`金额不合法: ${amount}`); } const expenseDate = options.expenseDate ?? Date.now(); const title = options.title?.trim() || specification.name; const amountMoney = { standard: amount, standardUnit: "元", standardScale: 2, standardSymbol: "¥", standardNumCode: "156", standardStrCode: "CNY", }; const detailSpec = await getFormSpecification(client, corpId, feeType.expenseSpecificationId); if (!detailSpec) throw new NotFoundError(`未找到费用类型规格: ${feeType.expenseSpecificationId}`); const detailComponents = ((detailSpec as { components?: TemplateComponent[] } | undefined)?.components ?? []) as TemplateComponent[]; const feeTypeForm = filterFeeTypeFormBySpec( { amount: amountMoney, feeDate: expenseDate }, detailComponents ); // 金额是核心字段:即使 schema 未声明也必须保留。 if (!("amount" in feeTypeForm)) feeTypeForm.amount = amountMoney; const detail = { feeTypeId: feeType.id, specificationId: feeType.expenseSpecificationId, feeTypeForm, }; const candidate = { specificationId: versionedSpecificationId, title, submitterId, expenseDate, expenseDepartment, ...(options.reason?.trim() ? { description: options.reason.trim() } : {}), details: [detail], }; const { form, missingRequired } = filterBillFormByTemplate( candidate as Record, ((specification as { components?: TemplateComponent[] }).components ?? []) as TemplateComponent[] ); if (missingRequired.length > 0) { throw new ValidationError( `模板要求以下字段但 CLI 未提供:${missingRequired.join("、")}。` + `当前 create 仅自动填充标准表头与一条费用明细,请补充对应模板字段后再创建。` ); } assertBillDraftValid(form, { components: specification.components, detailComponents: [detailSpec.components] }); return { form, title, amount, feeType: feeType.name ?? "" }; } export async function createBillDraft( client: KyInstance, corpId: string, options: CreateBillOptions ): Promise { const { form, title, amount, feeType } = await prepareBillDraft(client, corpId, options); const value = await createBillFlow(client, corpId, form); return { flowId: String(value?.id ?? ""), code: String(value?.form?.code ?? ""), title, amount, feeType, }; }