fix: 整合本地单据校验与离线身份修复
从旧审查分支选择仍未进入主分支的单据修复,保留主分支较新的工作流与插件分发实现。 兼容费用类型包装树,统一创建预演与执行,修正核销净支付,并将真实规格校验接入复制及送审。 注册 whoami 离线参数,补充写入契约和完整入口回归,保留旧分支与工作区。 验证:bun test 876 pass / 0 fail;bun run check、check:version、git diff --check 通过。
This commit is contained in:
1 parent
c2d36733fb
commit
ebeec98f6d
12 files changed
+369
-54
No files matched your search
@@ -29,7 +29,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"env"
|
||||
],
|
||||
"commandAliases": {},
|
||||
flags: { }
|
||||
flags: { ...flagList("offline cached", "boolean") }
|
||||
},
|
||||
"aipro": {
|
||||
"summary": "AI PRO 确定性审批仲裁",
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import { handleCreate } from "./create.js";
|
||||
import { parseArgs } from "../../parser.js";
|
||||
|
||||
test("create dry-run resolves the same available fee as execution and never posts", async () => {
|
||||
const writes: any[] = [];
|
||||
const client = {
|
||||
get: (url: string) => ({ json: async () => url.includes("specifications/")
|
||||
? { items: [{ id: "spec", name: "模板", components: [{ field: "title" }] }] }
|
||||
: url.includes("staffs/me") ? { value: { staff: { id: "staff", defaultDepartment: "dept" } } }
|
||||
: { items: [{ feeType: { id: "travel", name: "差旅", expenseSpecificationId: "detail" }, children: [] }] } }),
|
||||
post: (_: string, payload: any) => { writes.push(payload.json); return { json: async () => ({ flow: { id: "new" } }) }; },
|
||||
};
|
||||
const base = ["bill", "create", "--template", `spec:${"a".repeat(32)}`, "--json"];
|
||||
const context = (args: string[]) => ({ parsed: parseArgs(args), runtime: { jsonMode: true }, corpId: "corp", getClient: async () => client, requireWriteConfirmation: async () => {} }) as any;
|
||||
const preview = await handleCreate(context([...base, "--dry-run"]));
|
||||
expect(JSON.parse(preview.stdout)).toMatchObject({ dryRun: true, feeType: "差旅" });
|
||||
expect(writes).toEqual([]);
|
||||
await handleCreate(context([...base, "--yes"]));
|
||||
expect(writes[0].form.details[0].feeTypeId).toBe("travel");
|
||||
await expect(handleCreate(context([...base, "--fee-type", "不存在", "--dry-run"]))).rejects.toThrow("费用类型");
|
||||
expect(writes).toHaveLength(1);
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { createBillDraft } from "../../../domains/bill/create.js";
|
||||
import { createBillDraft, prepareBillDraft } from "../../../domains/bill/create.js";
|
||||
import { isDryRun } from "../../mutation.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson } from "../../printer.js";
|
||||
@@ -22,7 +22,8 @@ export async function handleCreate(ctx: BillActionContext): Promise<CliResult> {
|
||||
const feeTypeName = stringOption(parsed.options, ["fee-type", "feeType"]);
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
const preview = { template: templateId, title: title ?? "(模板名称)", amount, reason: reason ?? "", feeType: feeTypeName ?? "简单费用" };
|
||||
const prepared = await prepareBillDraft(await ctx.getClient(), corpId, { templateId, title, amount, reason, feeTypeName });
|
||||
const preview = { template: templateId, title: prepared.title, amount: prepared.amount, reason: reason ?? "", feeType: prepared.feeType };
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ dryRun: true, ...preview }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { getRawBillFlow } from "../../../domains/bill/tools.js";
|
||||
import {
|
||||
formatValidationIssues,
|
||||
validateBillDraft,
|
||||
loadBillValidationOptions,
|
||||
type BillDraftForm,
|
||||
} from "../../../domains/bill/draft-validation.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
@@ -41,7 +42,7 @@ export async function handleValidate(ctx: BillActionContext): Promise<CliResult>
|
||||
};
|
||||
}
|
||||
|
||||
const issues = validateBillDraft(form);
|
||||
const issues = validateBillDraft(form, await loadBillValidationOptions(await ctx.getClient(), corpId, form));
|
||||
const errors = issues.filter((item) => item.severity === "error");
|
||||
const warnings = issues.filter((item) => item.severity === "warning");
|
||||
const billCode = typeof form.title === "string" ? form.title : target;
|
||||
|
||||
@@ -9,6 +9,13 @@ import { CLI_COMMAND_REGISTRY, findCommandByArea } from "./registry.js";
|
||||
import { runAiProCli } from "../aipro-cli.js";
|
||||
|
||||
describe("strict command options", () => {
|
||||
test("top-level whoami accepts offline flags without changing the command target", () => {
|
||||
for (const flag of ["offline", "cached"]) {
|
||||
const parsed = parseArgs(["whoami", `--${flag}`, "--json"]);
|
||||
expect(parsed.options[flag]).toBe(true);
|
||||
expect(parsed.args).toEqual([]);
|
||||
}
|
||||
});
|
||||
test("rejects misspellings and missing values instead of silently dropping filters", async () => {
|
||||
const typo = await runCli(["bill", "list", "--limitt", "5", "--json"]);
|
||||
expect(typo.exitCode).toBe(2);
|
||||
|
||||
@@ -84,6 +84,14 @@ src/domains/bill/
|
||||
- 未指派审批人的节点必须由 `--approver` 显式指定,绝不自动编造;
|
||||
- 再 `POST /api/flow/v1/flows/$<flowId>`(`name: freeflow.submit`,携带 `nodes`)。
|
||||
|
||||
### 草稿写入前校验
|
||||
|
||||
- 复制和提交会先加载单据及费用明细的真实规格,必填字段由 `components[].optional === false` 决定,字符串上限仅在规格明确提供 `maxLength` 时执行;不再假定所有模板均包含收款信息、法人实体或最晚付款日期。
|
||||
- 已存在的金额、币种、汇率及派生合计始终检查;规格未声明且表单未提供的可选汇总字段不按缺失报错。纯函数 `validateBillDraft` 可传入 `components` / `detailComponents`;CLI `bill validate` 自动加载实际规格。
|
||||
- 缺失规格 ID、规格读取失败或一致性错误会阻止写请求;校验失败不会创建新单或提交审批。
|
||||
- 复制保留核销金额及其原有关联,支付金额按“明细报销合计 − 核销金额”重算。
|
||||
- 创建兼容 `{feeType, children}` 树和既有平面节点格式;只有省略 `--fee-type` 时采用默认费用类型。显式名称不存在、停用或重名时均拒绝,`--dry-run` 与实际执行共用解析逻辑(预演会读取元数据,不发送创建请求)。
|
||||
|
||||
## 写接口契约(实测)
|
||||
|
||||
```text
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { NotFoundError } from "../../core/errors.js";
|
||||
import { getRawBillFlow } from "./api.js";
|
||||
import type { BillDraftForm, BillMoney } from "./draft-validation.js";
|
||||
import { assertBillDraftValid, loadBillValidationOptions, type BillDraftForm, type BillMoney } from "./draft-validation.js";
|
||||
|
||||
/**
|
||||
* 纯接口复制单据。
|
||||
@@ -93,7 +93,7 @@ export function buildBillCopyForm(
|
||||
|
||||
form.u_发票总金额 = zeroMoney(form.u_发票总金额);
|
||||
form.expenseMoney = { ...(form.expenseMoney ?? {}), standard: amountSum.toFixed(2) };
|
||||
form.payMoney = { ...(form.payMoney ?? {}), standard: amountSum.toFixed(2) };
|
||||
form.payMoney = { ...(form.payMoney ?? {}), standard: (amountSum - moneyNumber(form.writtenOffMoney)).toFixed(2) };
|
||||
if (!keepAttachments) {
|
||||
form.attachments = [];
|
||||
}
|
||||
@@ -123,6 +123,7 @@ export async function copyBillAsDraft(
|
||||
}
|
||||
|
||||
const form = buildBillCopyForm(sourceForm, options);
|
||||
assertBillDraftValid(form, await loadBillValidationOptions(client, corpId, form));
|
||||
const response = await client.post("api/flow/v1/flows", {
|
||||
searchParams: { corpId },
|
||||
json: { name: "freeflow.edit", form },
|
||||
|
||||
+21
-10
@@ -85,13 +85,14 @@ interface FeeTypeNode {
|
||||
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);
|
||||
out.push(node.feeType ?? node);
|
||||
if (Array.isArray(node.children)) walk(node.children);
|
||||
}
|
||||
};
|
||||
@@ -110,11 +111,11 @@ function zeroMoney(): Record<string, unknown> {
|
||||
};
|
||||
}
|
||||
|
||||
export async function createBillDraft(
|
||||
export async function prepareBillDraft(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
options: CreateBillOptions
|
||||
): Promise<CreateBillResult> {
|
||||
): Promise<{ form: Record<string, unknown>; title: string; amount: string; feeType: string }> {
|
||||
const templateId = options.templateId.trim();
|
||||
if (!templateId) throw new ValidationError("请通过 --template 指定单据模板 ID");
|
||||
|
||||
@@ -173,12 +174,13 @@ export async function createBillDraft(
|
||||
|
||||
const feeTypes = flattenFeeTypes((await getFeeTypeTree(client, corpId)) as FeeTypeNode[]);
|
||||
const preferred = options.feeTypeName?.trim();
|
||||
const feeType =
|
||||
(preferred
|
||||
? feeTypes.find((item) => item.name === preferred && item.expenseSpecificationId)
|
||||
: undefined) ||
|
||||
feeTypes.find((item) => item.name === "简单费用" && item.expenseSpecificationId) ||
|
||||
feeTypes.find((item) => item.active !== false && item.expenseSpecificationId);
|
||||
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)");
|
||||
}
|
||||
@@ -234,6 +236,15 @@ export async function createBillDraft(
|
||||
);
|
||||
}
|
||||
|
||||
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 response = await client.post("api/flow/v1/flows", {
|
||||
searchParams: { corpId },
|
||||
json: { name: "freeflow.edit", form },
|
||||
@@ -249,6 +260,6 @@ export async function createBillDraft(
|
||||
code: String(value?.form?.code ?? ""),
|
||||
title,
|
||||
amount,
|
||||
feeType: feeType.name ?? "",
|
||||
feeType,
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
import { ValidationError } from "../../core/errors.js";
|
||||
import type { KyInstance } from "ky";
|
||||
import { getFormSpecification } from "./api.js";
|
||||
import { NotFoundError, ValidationError } from "../../core/errors.js";
|
||||
|
||||
/**
|
||||
* 单据草稿的派生字段一致性校验。
|
||||
@@ -80,7 +82,17 @@ export interface ValidationIssue {
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface BillValidationComponent {
|
||||
field?: string;
|
||||
label?: string;
|
||||
optional?: boolean;
|
||||
maxLength?: number;
|
||||
}
|
||||
|
||||
export interface ValidateOptions {
|
||||
/** 实际模板字段;未提供时仅检查通用结构与已有金额。 */
|
||||
components?: BillValidationComponent[];
|
||||
detailComponents?: BillValidationComponent[][];
|
||||
/** 金额比较容差,默认 0.005(分位) */
|
||||
moneyTolerance?: number;
|
||||
/** 外币换算比较容差,默认 0.01 */
|
||||
@@ -89,7 +101,6 @@ export interface ValidateOptions {
|
||||
|
||||
const DEFAULT_MONEY_TOLERANCE = 0.005;
|
||||
const DEFAULT_RATE_TOLERANCE = 0.01;
|
||||
const MAX_DESCRIPTION_LENGTH = 800;
|
||||
|
||||
function toNumber(value: unknown): number | undefined {
|
||||
if (typeof value === "number" && Number.isFinite(value)) return value;
|
||||
@@ -134,34 +145,22 @@ export function validateBillDraft(
|
||||
}
|
||||
|
||||
// 1. 必填表头
|
||||
const requiredHeader: Array<[keyof BillDraftForm, string]> = [
|
||||
["title", "标题"],
|
||||
["specificationId", "单据模板"],
|
||||
["submitterId", "提交人"],
|
||||
["expenseDate", "提交日期"],
|
||||
["expenseDepartment", "费用承担部门"],
|
||||
["payeeId", "收款信息"],
|
||||
["法人实体", "公司(法人实体)"],
|
||||
["u_最晚付款日期", "最晚付款日期"],
|
||||
];
|
||||
for (const [key, label] of requiredHeader) {
|
||||
const value = form[key];
|
||||
if (value === undefined || value === null || value === "") {
|
||||
issues.push(issue("MISSING_FIELD", String(key), `缺少必填字段:${label}`));
|
||||
const checkComponents = (value: Record<string, unknown>, components: BillValidationComponent[], prefix = "") => {
|
||||
for (const component of components) {
|
||||
if (!component.field) continue;
|
||||
const content = value[component.field];
|
||||
const field = prefix + component.field;
|
||||
if (component.optional === false && (content == null || content === "" || (Array.isArray(content) && content.length === 0))) {
|
||||
issues.push(issue("MISSING_FIELD", field, `缺少必填字段:${component.label || component.field}`));
|
||||
}
|
||||
if (typeof content === "string" && typeof component.maxLength === "number" && content.length > component.maxLength) {
|
||||
issues.push(issue(component.field === "description" ? "DESCRIPTION_TOO_LONG" : "FIELD_TOO_LONG", field, `字段长度 ${content.length} 超过模板上限 ${component.maxLength}`));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
checkComponents(form, [{ field: "specificationId", optional: false }, ...(options.components ?? [])]);
|
||||
|
||||
// 2. 描述长度
|
||||
const description = typeof form.description === "string" ? form.description : "";
|
||||
if (description.length > MAX_DESCRIPTION_LENGTH) {
|
||||
issues.push(
|
||||
issue(
|
||||
"DESCRIPTION_TOO_LONG",
|
||||
"description",
|
||||
`描述长度 ${description.length} 超过模板上限 ${MAX_DESCRIPTION_LENGTH}`
|
||||
)
|
||||
);
|
||||
}
|
||||
// 2. 描述长度由实际模板的 maxLength 决定,不假设所有模板均为 800。
|
||||
|
||||
// 3. 明细数量
|
||||
const details = Array.isArray(form.details) ? form.details : [];
|
||||
@@ -171,7 +170,11 @@ export function validateBillDraft(
|
||||
}
|
||||
|
||||
// 4. 本位币(以表头报销金额为准)
|
||||
const billCurrency = form.expenseMoney?.standardStrCode || form.payMoney?.standardStrCode;
|
||||
const billCurrency = form.expenseMoney?.standardStrCode || form.payMoney?.standardStrCode
|
||||
|| details.find((detail) => detail.feeTypeForm?.amount?.standardStrCode)?.feeTypeForm?.amount?.standardStrCode;
|
||||
if (form.expenseMoney?.standardStrCode && form.payMoney?.standardStrCode && form.expenseMoney.standardStrCode !== form.payMoney.standardStrCode) {
|
||||
issues.push(issue("CURRENCY_MISMATCH", "payMoney.standardStrCode", "支付金额与报销金额本位币不一致"));
|
||||
}
|
||||
|
||||
// 5. 逐条明细
|
||||
const seenDetailNos = new Map<number, number>();
|
||||
@@ -183,6 +186,7 @@ export function validateBillDraft(
|
||||
|
||||
details.forEach((detail, index) => {
|
||||
const ft = detail.feeTypeForm ?? {};
|
||||
checkComponents(ft, options.detailComponents?.[index] ?? [], `details[${index}].feeTypeForm.`);
|
||||
const position = index + 1;
|
||||
const label = `明细 #${ft.detailNo ?? position}`;
|
||||
|
||||
@@ -297,7 +301,7 @@ export function validateBillDraft(
|
||||
|
||||
// 明细发票总额
|
||||
const detailInvoiceTotal = moneyStandard(ft.u_发票总金额);
|
||||
if (detailInvoiceTotal === undefined) {
|
||||
if (ft.u_发票总金额 !== undefined && detailInvoiceTotal === undefined) {
|
||||
issues.push(
|
||||
issue(
|
||||
"DETAIL_INVOICE_TOTAL_INVALID",
|
||||
@@ -306,7 +310,7 @@ export function validateBillDraft(
|
||||
)
|
||||
);
|
||||
} else {
|
||||
detailInvoiceSum += detailInvoiceTotal;
|
||||
detailInvoiceSum += detailInvoiceTotal ?? 0;
|
||||
if (billCurrency && ft.u_发票总金额?.standardStrCode && ft.u_发票总金额.standardStrCode !== billCurrency) {
|
||||
issues.push(
|
||||
issue(
|
||||
@@ -341,11 +345,11 @@ export function validateBillDraft(
|
||||
|
||||
// 6. 表头派生金额
|
||||
const expenseMoney = moneyStandard(form.expenseMoney);
|
||||
if (expenseMoney === undefined) {
|
||||
if (form.expenseMoney !== undefined && expenseMoney === undefined) {
|
||||
issues.push(
|
||||
issue("EXPENSE_MONEY_INVALID", "expenseMoney", "单据报销金额缺失或不是合法数字")
|
||||
);
|
||||
} else if (hasValidDetailAmounts && !nearlyEqual(expenseMoney, detailAmountSum, moneyTolerance)) {
|
||||
} else if (expenseMoney !== undefined && hasValidDetailAmounts && !nearlyEqual(expenseMoney, detailAmountSum, moneyTolerance)) {
|
||||
issues.push(
|
||||
issue(
|
||||
"EXPENSE_TOTAL_MISMATCH",
|
||||
@@ -356,9 +360,9 @@ export function validateBillDraft(
|
||||
}
|
||||
|
||||
const payMoney = moneyStandard(form.payMoney);
|
||||
if (payMoney === undefined) {
|
||||
if (form.payMoney !== undefined && payMoney === undefined) {
|
||||
issues.push(issue("PAY_MONEY_INVALID", "payMoney", "单据支付金额缺失或不是合法数字"));
|
||||
} else if (expenseMoney !== undefined) {
|
||||
} else if (payMoney !== undefined && expenseMoney !== undefined) {
|
||||
const writtenOff = moneyStandard(form.writtenOffMoney) ?? 0;
|
||||
const expectedPay = expenseMoney - writtenOff;
|
||||
if (!nearlyEqual(payMoney, expectedPay, moneyTolerance)) {
|
||||
@@ -373,11 +377,11 @@ export function validateBillDraft(
|
||||
}
|
||||
|
||||
const billInvoiceTotal = moneyStandard(form.u_发票总金额);
|
||||
if (billInvoiceTotal === undefined) {
|
||||
if (form.u_发票总金额 !== undefined && billInvoiceTotal === undefined) {
|
||||
issues.push(
|
||||
issue("BILL_INVOICE_TOTAL_INVALID", "u_发票总金额", "单据发票总金额缺失或不是合法数字")
|
||||
);
|
||||
} else if (!nearlyEqual(billInvoiceTotal, detailInvoiceSum, moneyTolerance)) {
|
||||
} else if (billInvoiceTotal !== undefined && !nearlyEqual(billInvoiceTotal, detailInvoiceSum, moneyTolerance)) {
|
||||
issues.push(
|
||||
issue(
|
||||
"INVOICE_TOTAL_MISMATCH",
|
||||
@@ -387,6 +391,10 @@ export function validateBillDraft(
|
||||
);
|
||||
}
|
||||
|
||||
if (form.writtenOffMoney !== undefined && moneyStandard(form.writtenOffMoney) === undefined) {
|
||||
issues.push(issue("WRITTEN_OFF_MONEY_INVALID", "writtenOffMoney", "核销借款金额不合法"));
|
||||
}
|
||||
|
||||
// 7. 日期
|
||||
const submitAt = toNumber(form.expenseDate);
|
||||
const payBy = toNumber(form.u_最晚付款日期);
|
||||
@@ -424,3 +432,35 @@ export function formatValidationIssues(issues: ValidationIssue[]): string {
|
||||
.map((item) => `${item.severity === "error" ? "❌" : "⚠️"} [${item.field}] ${item.message}`)
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
/** 读取真实表头与费用明细规格;失败时禁止退回猜测模板规则。 */
|
||||
export async function loadBillValidationOptions(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
form: BillDraftForm,
|
||||
specification?: { components: BillValidationComponent[] }
|
||||
): Promise<ValidateOptions> {
|
||||
const resolveId = (reference: unknown): string => {
|
||||
const value = typeof reference === "string"
|
||||
? reference
|
||||
: reference && typeof reference === "object" ? (reference as { id?: unknown }).id : undefined;
|
||||
if (typeof value !== "string" || !value.trim()) {
|
||||
throw new ValidationError("单据或费用明细缺少规格 ID,无法校验模板");
|
||||
}
|
||||
return value.trim();
|
||||
};
|
||||
const load = async (id: string): Promise<BillValidationComponent[]> => {
|
||||
const spec = await getFormSpecification(client, corpId, id);
|
||||
if (!spec) throw new NotFoundError(`未找到单据或费用类型规格: ${id}`);
|
||||
return spec.components as BillValidationComponent[];
|
||||
};
|
||||
const headerId = resolveId(form.specificationId);
|
||||
const components = specification?.components ?? await load(headerId);
|
||||
const cache = new Map<string, Promise<BillValidationComponent[]>>();
|
||||
const detailComponents = await Promise.all((form.details ?? []).map((detail) => {
|
||||
const id = resolveId(detail.specificationId);
|
||||
if (!cache.has(id)) cache.set(id, load(id));
|
||||
return cache.get(id)!;
|
||||
}));
|
||||
return { components, detailComponents };
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { NotFoundError, ValidationError } from "../../core/errors.js";
|
||||
import { getFormSpecification, getRawBillFlow } from "./api.js";
|
||||
import { assertBillDraftValid, loadBillValidationOptions } from "./draft-validation.js";
|
||||
|
||||
/**
|
||||
* 纯接口提交单据草稿。
|
||||
@@ -53,10 +54,12 @@ export async function submitBillDraft(
|
||||
throw new ValidationError(`单据当前状态为 ${String(flow.state)},仅 draft 可提交`);
|
||||
}
|
||||
|
||||
const specificationId = form.specificationId;
|
||||
const specificationId = typeof form.specificationId === "object" && form.specificationId
|
||||
? (form.specificationId as { id?: string }).id : form.specificationId;
|
||||
const spec = specificationId
|
||||
? await getFormSpecification(client, corpId, String(specificationId))
|
||||
: undefined;
|
||||
assertBillDraftValid(form, await loadBillValidationOptions(client, corpId, form, spec));
|
||||
const configs = (spec as { configs?: Array<{ ability?: string; flowPlanConfigId?: string }> } | undefined)?.configs;
|
||||
const flowPlanConfigId = configs?.find((config) => config.ability === "flow")?.flowPlanConfigId;
|
||||
if (!flowPlanConfigId) {
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import type { KyInstance } from "ky";
|
||||
import { createBillDraft, prepareBillDraft } from "./create.js";
|
||||
import { buildBillCopyForm, copyBillAsDraft } from "./copy.js";
|
||||
import { submitBillDraft } from "./submit.js";
|
||||
import { loadBillValidationOptions, validateBillDraft, type BillDraftForm } from "./draft-validation.js";
|
||||
import { AuthenticationError } from "../../core/errors.js";
|
||||
|
||||
const versionedId = `spec:${"a".repeat(32)}`;
|
||||
const fee = { id: "fee", name: "简单费用", active: true, expenseSpecificationId: "detail" };
|
||||
function form(): BillDraftForm {
|
||||
return { specificationId: versionedId, title: "草稿", expenseMoney: { standard: "100", standardStrCode: "CNY" },
|
||||
payMoney: { standard: "70", standardStrCode: "CNY" }, writtenOffMoney: { standard: "30" },
|
||||
details: [{ specificationId: "detail", feeTypeForm: { amount: { standard: "100", standardStrCode: "CNY" } } }] };
|
||||
}
|
||||
function fixture(options: {
|
||||
tree?: unknown[];
|
||||
source?: BillDraftForm;
|
||||
required?: string;
|
||||
detailRequired?: string;
|
||||
missingSpec?: boolean;
|
||||
missingDetailSpec?: boolean;
|
||||
specError?: Error;
|
||||
} = {}) {
|
||||
const writes: Array<{ url: string; json: any }> = [];
|
||||
const reads: string[] = [];
|
||||
const plans: unknown[] = [];
|
||||
const source = options.source ?? form();
|
||||
const client = {
|
||||
get: (url: string) => ({ json: async () => {
|
||||
reads.push(url);
|
||||
if (url.includes("specifications/")) {
|
||||
if (options.specError) throw options.specError;
|
||||
const detailSpec = url.endsWith("[detail]");
|
||||
const required = detailSpec ? options.detailRequired : options.required;
|
||||
return { items: options.missingSpec || (detailSpec && options.missingDetailSpec) ? [] : [{
|
||||
id: detailSpec ? "detail" : "spec", name: "测试模板",
|
||||
configs: [{ ability: "flow", flowPlanConfigId: "plan" }],
|
||||
components: [{ field: "title", optional: true }, ...(required ? [{ field: required, optional: false }] : [])],
|
||||
}] };
|
||||
}
|
||||
if (url.includes("feeTypes/")) return { items: options.tree ?? [{ feeType: { id: "folder" }, children: [{ feeType: fee, children: [] }] }] };
|
||||
if (url.includes("staffs/me")) return { value: { staff: { id: "staff", defaultDepartment: "dept" } } };
|
||||
throw new Error(`Unexpected GET ${url}`);
|
||||
} }),
|
||||
post: (url: string, payload: { json: any }) => ({ json: async () => {
|
||||
if (url.endsWith("/flows/my")) return { items: [{ flow: { id: "f", form: source } }] };
|
||||
if (url.includes("/flows/flowId/")) return { value: { id: "f", state: "draft", form: source } };
|
||||
if (url.endsWith("/plans/computed")) {
|
||||
plans.push(payload.json);
|
||||
return { value: { nodes: [{ id: "review", type: "approval", approverId: "staff" }] } };
|
||||
}
|
||||
writes.push({ url, json: payload.json });
|
||||
return { flow: { id: "new", form: { code: "B1" } } };
|
||||
} }),
|
||||
} as unknown as KyInstance;
|
||||
return { client, writes, reads, plans };
|
||||
}
|
||||
|
||||
describe("bill API write contracts", () => {
|
||||
test("creates with nested canonical feeType nodes and retains flat response compatibility", async () => {
|
||||
for (const tree of [undefined, [fee]]) {
|
||||
const { client, writes } = fixture({ tree });
|
||||
await createBillDraft(client, "corp", { templateId: versionedId, amount: "10" });
|
||||
expect(writes).toHaveLength(1);
|
||||
expect(writes[0].json.form.details[0].feeTypeId).toBe("fee");
|
||||
}
|
||||
});
|
||||
test("explicit missing, inactive or ambiguous fee types never fall back or write", async () => {
|
||||
for (const tree of [[fee], [{ ...fee, name: "差旅", active: false }, fee], [{ ...fee, name: "差旅" }, { ...fee, id: "other", name: "差旅" }]]) {
|
||||
const { client, writes } = fixture({ tree });
|
||||
await expect(createBillDraft(client, "corp", { templateId: versionedId, feeTypeName: "差旅" })).rejects.toThrow("费用类型");
|
||||
await expect(prepareBillDraft(client, "corp", { templateId: versionedId, feeTypeName: "差旅" })).rejects.toThrow("费用类型");
|
||||
expect(writes).toEqual([]);
|
||||
}
|
||||
});
|
||||
test("default ignores disabled simple fee and preview resolves the same fee without writing", async () => {
|
||||
const { client, writes } = fixture({ tree: [{ ...fee, active: false }, { ...fee, id: "travel", name: "差旅" }] });
|
||||
const preview = await prepareBillDraft(client, "corp", { templateId: versionedId, expenseDate: 1 });
|
||||
expect(preview.feeType).toBe("差旅");
|
||||
expect(writes).toHaveLength(0);
|
||||
await createBillDraft(client, "corp", { templateId: versionedId, expenseDate: 1 });
|
||||
expect(writes[0].json.form).toEqual(preview.form);
|
||||
});
|
||||
test.each([0, 30, 100])("copy retains offsets %d and computes net payment", (offset) => {
|
||||
const source = form(); source.writtenOffMoney!.standard = String(offset);
|
||||
const copy = buildBillCopyForm(source);
|
||||
expect(copy.writtenOffMoney).toEqual(source.writtenOffMoney);
|
||||
expect(copy.payMoney!.standard).toBe((100 - offset).toFixed(2));
|
||||
expect(validateBillDraft(copy)).toEqual([]);
|
||||
expect(source.payMoney!.standard).toBe("70");
|
||||
expect(source.writtenOffMoney!.standard).toBe(String(offset));
|
||||
});
|
||||
for (const action of [copyBillAsDraft, submitBillDraft]) {
|
||||
test(`${action.name}: mixed currencies are blocked before write`, async () => {
|
||||
const source = form(); source.details!.push({ specificationId: "detail", feeTypeForm: { amount: { standard: "10", standardStrCode: "USD" } } });
|
||||
const { client, writes } = fixture({ source });
|
||||
await expect(action(client, "corp", "f")).rejects.toThrow("本位币");
|
||||
expect(writes).toEqual([]);
|
||||
});
|
||||
test(`${action.name}: requires actual template fields and refuses unknown templates`, async () => {
|
||||
for (const opts of [{ required: "u_项目" }, { missingSpec: true }]) {
|
||||
const { client, writes } = fixture(opts);
|
||||
await expect(action(client, "corp", "f")).rejects.toThrow();
|
||||
expect(writes).toEqual([]);
|
||||
}
|
||||
});
|
||||
test(`${action.name}: generic template without tenant-specific fields writes valid form`, async () => {
|
||||
const { client, writes } = fixture();
|
||||
await action(client, "corp", "f");
|
||||
expect(writes).toHaveLength(1);
|
||||
expect(writes[0].json.form.payMoney.standard).toBe(action === copyBillAsDraft ? "70.00" : "70");
|
||||
});
|
||||
test(`${action.name}: required detail fields and missing detail specifications block all writes`, async () => {
|
||||
for (const options of [{ detailRequired: "u_项目" }, { missingDetailSpec: true }]) {
|
||||
const { client, writes, plans } = fixture(options);
|
||||
await expect(action(client, "corp", "f")).rejects.toThrow();
|
||||
expect(writes).toEqual([]);
|
||||
expect(plans).toEqual([]);
|
||||
}
|
||||
});
|
||||
test(`${action.name}: invalid specification references and read errors block all writes`, async () => {
|
||||
for (const reference of [undefined, " ", {}, { id: 123 }]) {
|
||||
for (const header of [true, false]) {
|
||||
const source = form();
|
||||
if (header) source.specificationId = reference;
|
||||
else source.details![0].specificationId = reference;
|
||||
const { client, writes, plans } = fixture({ source });
|
||||
await expect(action(client, "corp", "f")).rejects.toThrow();
|
||||
expect(writes).toEqual([]);
|
||||
expect(plans).toEqual([]);
|
||||
}
|
||||
}
|
||||
const error = new AuthenticationError("规格读取无权限");
|
||||
const { client, writes, plans } = fixture({ specError: error });
|
||||
await expect(action(client, "corp", "f")).rejects.toBe(error);
|
||||
expect(writes).toEqual([]);
|
||||
expect(plans).toEqual([]);
|
||||
});
|
||||
}
|
||||
test("specification references resolve object IDs and reuse identical detail specifications", async () => {
|
||||
const source = form();
|
||||
source.specificationId = { id: versionedId };
|
||||
source.details!.push(structuredClone(source.details![0]));
|
||||
source.details![0].specificationId = { id: "detail" };
|
||||
const { client, reads } = fixture({ source });
|
||||
const options = await loadBillValidationOptions(client, "corp", source);
|
||||
expect(options.detailComponents).toHaveLength(2);
|
||||
expect(reads.filter(url => url.includes("specifications/"))).toHaveLength(2);
|
||||
expect(reads.filter(url => url.endsWith("[detail]"))).toHaveLength(1);
|
||||
});
|
||||
test("submit reuses the header specification for validation and approval-plan lookup", async () => {
|
||||
const { client, reads } = fixture();
|
||||
await submitBillDraft(client, "corp", "f");
|
||||
expect(reads.filter(url => url.includes("specifications/"))).toHaveLength(2);
|
||||
});
|
||||
test("template optionality and length are authoritative; existing money values stay checked", () => {
|
||||
const source = form(); source.description = "x".repeat(900);
|
||||
expect(validateBillDraft(source)).toEqual([]);
|
||||
expect(validateBillDraft(source, { components: [{ field: "u_项目", optional: false }, { field: "description", maxLength: 1000 }] }).map(x => x.code)).toEqual(["MISSING_FIELD"]);
|
||||
expect(validateBillDraft(source, { components: [{ field: "description", maxLength: 800 }] }).map(x => x.code)).toEqual(["DESCRIPTION_TOO_LONG"]);
|
||||
source.payMoney!.standard = "100";
|
||||
expect(validateBillDraft(source).map(x => x.code)).toContain("PAY_TOTAL_MISMATCH");
|
||||
});
|
||||
test("optional summary fields may be absent, but malformed amounts and currencies remain invalid", () => {
|
||||
const source = form();
|
||||
delete source.expenseMoney;
|
||||
delete source.payMoney;
|
||||
expect(validateBillDraft(source)).toEqual([]);
|
||||
source.details!.push({ feeTypeForm: { amount: { standard: "10", standardStrCode: "USD" } } });
|
||||
expect(validateBillDraft(source).map(issue => issue.code)).toContain("CURRENCY_MISMATCH");
|
||||
source.expenseMoney = { standard: "invalid" };
|
||||
source.writtenOffMoney = { standard: "invalid" };
|
||||
expect(validateBillDraft(source).map(issue => issue.code)).toEqual(expect.arrayContaining([
|
||||
"EXPENSE_MONEY_INVALID", "WRITTEN_OFF_MONEY_INVALID",
|
||||
]));
|
||||
const headerMismatch = form();
|
||||
headerMismatch.payMoney!.standardStrCode = "USD";
|
||||
expect(validateBillDraft(headerMismatch).map(issue => issue.field)).toContain("payMoney.standardStrCode");
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user