Files
hose-use/src/domains/bill/create.ts
gitea 51fb54dfe8 fix: 统一单据写前校验与传输结果契约
将模板、当前员工、草稿创建/删除、审批计划和送审共七处 HTTP 调用收口到 bill/api.ts,业务层函数签名保持兼容。创建与预演复用实际规格校验,缺失明细规格、必填字段或超长文本均先于写入拒绝。
统一检查已知业务错误及有效流程 ID,保留 flow/value/裸对象成功包装与已有单号字段;补充业务拒绝、HTTP 失败、无效 ID、计划失败不送审及 CLI 非零退出回归,同步域文档。

验证:bun test 911 通过、0 失败;bun run check、git diff --check 通过。未调用真实企业接口。
2026-10-29 18:14:52 +08:00

258 lines
9.4 KiB
TypeScript
Raw Permalink 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 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<string, unknown>,
components: TemplateComponent[]
): { form: Record<string, unknown>; missingRequired: string[] } {
const allowed = new Set<string>(["specificationId", "details"]);
for (const component of components) {
if (component.field) allowed.add(component.field);
}
const filtered: Record<string, unknown> = {};
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<string, unknown>,
components: TemplateComponent[]
): Record<string, unknown> {
const allowed = new Set<string>();
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<FeeTypeNode, "children" | "feeType">;
}
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<string, unknown> {
return {
standard: "0",
standardUnit: "元",
standardScale: 2,
standardSymbol: "¥",
standardNumCode: "156",
standardStrCode: "CNY",
};
}
export async function prepareBillDraft(
client: KyInstance,
corpId: string,
options: CreateBillOptions
): Promise<{ form: Record<string, unknown>; 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(`<originalId>:<hash>`);
// 用户传入的通常是 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<Record<string, any>>;
const flat: Array<Record<string, any>> = [];
const walk = (nodes: Array<Record<string, any>>) => {
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<string, unknown>,
((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<CreateBillResult> {
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,
};
}