feat(bill): list templates grouped by specification group

- bill templates [--all] [--keyword]: 与页面快速新建同源,默认仅启用
- 服务端已按身份过滤可见性,--all 仅尝试带出停用项
- docs: README.bill.md 与 Skill 路由同步
This commit is contained in:
gitea committed 2026-10-23 16:59:06 +08:00
1 parent 5d1e3e5d8e
commit 9d7df10994
8 files changed
+463 -217

No files matched your search

+3 -2
View File
@@ -298,7 +298,8 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
"link": "生成单据详情链接",
"validate": "校验单据派生字段一致性(金额/币种/发票总额/草稿状态)",
"copy": "复制单据为新草稿(清空发票绑定,不提交)",
"delete": "删除草稿单据(仅 draft,需 --yes)"
"delete": "删除草稿单据(仅 draft,需 --yes)",
"templates": "查看单据模板(默认仅启用,--all 含停用)"
},
"options": [
"--dry-run 只预览审批动作",
@@ -342,7 +343,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
"url": "link",
"specification": "spec"
},
flags: { ...flagList("audit basic confirm distinct drop-attachments dropAttachments force-write keep-it-secret mine my no-invoice noInvoice private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target title to", "value") }
flags: { ...flagList("all audit basic confirm distinct drop-attachments dropAttachments force-write keep-it-secret mine my no-invoice noInvoice private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target title to", "value") }
},
"flow": {
"summary": "审批流全域透视与穿透诊断",
+8 -1
View File
@@ -8,6 +8,7 @@ import { handleSchema, handleLink, handleSpec } from "./meta.js";
import { handleValidate } from "./validate.js";
import { handleCopy } from "./copy.js";
import { handleDelete } from "./delete.js";
import { handleTemplates } from "./templates.js";
export async function handleBillCommand(
parsed: CliParsedArgs,
@@ -122,7 +123,13 @@ export async function handleBillCommand(
case "remove":
return handleDelete(ctx);
case "templates":
case "template":
case "specs":
case "spec-list":
return handleTemplates(ctx);
default:
throw new Error(`未知 bill 子命令: ${action}。支持: list, get <单号> [--risk], trace <单号|ID>, spec <specificationId>, refs <单号>, relations <单号>, attachments <单号>, download <单号>, flow <单号>, risk <单号>, budget <单号>, schema, link <单号>, validate <单号>, copy <单号> --yes, delete <单号> --yes`);
throw new Error(`未知 bill 子命令: ${action}。支持: list, get <单号> [--risk], trace <单号|ID>, spec <specificationId>, refs <单号>, relations <单号>, attachments <单号>, download <单号>, flow <单号>, risk <单号>, budget <单号>, schema, link <单号>, validate <单号>, copy <单号> --yes, delete <单号> --yes, templates [--all]`);
}
}
+64
View File
@@ -0,0 +1,64 @@
import { listBillTemplates } from "../../../domains/bill/templates.js";
import { booleanOption, stringOption } from "../../parser.js";
import { printJson } from "../../printer.js";
import type { CliResult } from "../../types.js";
import type { BillActionContext } from "./context.js";
/**
* `hose-use bill templates [--all] [--keyword=...]`
*
* 默认返回当前身份可见且启用中的模板(与页面「快速新建单据」同源、同分组);
* `--all` 才会带出停用模板。
*/
export async function handleTemplates(ctx: BillActionContext): Promise<CliResult> {
const { parsed, runtime, corp, corpId } = ctx;
const includeInactive = booleanOption(parsed.options, ["all"]);
const keyword = (stringOption(parsed.options, ["keyword", "k", "q", "query"]) ?? "").trim();
const result = await listBillTemplates(await ctx.getClient(), corpId, { includeInactive });
let groups = result.groups;
if (keyword) {
groups = groups
.map((group) => ({
...group,
specifications: group.specifications.filter((spec) => spec.name.includes(keyword)),
}))
.filter((group) => group.specifications.length > 0);
}
const total = groups.reduce((sum, group) => sum + group.specifications.length, 0);
if (runtime.jsonMode) {
return {
stdout: printJson(
{
corpId,
corpName: corp.name,
includeInactive,
total,
inactive: result.inactive,
groups,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const lines: string[] = [
`====== 单据模板(${corp.name} | ${groups.length} 组 / ${total} 个${includeInactive ? ",含停用" : ""})======`,
"",
];
for (const group of groups) {
lines.push(`${group.name || "未分组"}`);
for (const spec of group.specifications) {
const inactiveMark = spec.active ? "" : "(已停用)";
lines.push(` - ${spec.name}${inactiveMark} [${spec.type}]`);
}
lines.push("");
}
if (!includeInactive) {
lines.push("提示: 追加 --all 可查看包含停用模板的全量列表");
}
return { stdout: lines.join("\n") + "\n", stderr: "", exitCode: 0 };
}
+6
View File
@@ -11,6 +11,7 @@ src/domains/bill/
├── copy.ts # 草稿复制:服务端读取 → 本地转换 → 创建新草稿
├── write.ts # 草稿写动作:freeflow.delete 等(提交契约见下文)
├── draft-validation.ts # 草稿派生字段一致性校验(金额/币种/发票总额/草稿状态)
├── templates.ts # 单据模板列表(与页面「快速新建」同源,默认仅启用)
├── types.ts # 模型层:Zod Schema 与 TypeScript 类型定义
├── bill.test.ts # 单元测试
├── copy.test.ts # 复制转换单测
@@ -67,6 +68,11 @@ src/domains/bill/
- `POST /api/flow/v1/flows/$<flowId>`,`name: freeflow.delete`;
- CLI 仅允许删除 `draft` 状态单据,已提交/审批中/已支付一律拒绝。
12. **单据模板列表 (`listBillTemplates`)**:
- 与页面「快速新建单据」同源:`GET /api/form/v2/specificationGroups/withSpecificationVersioned`;
- 响应按「规格分组 → 规格」组织,且已由服务端按当前身份做可见性过滤;
- 默认只返回启用中的模板,`--all` 才会尝试带出停用项(服务端未返回停用项时两者一致)。
## 写接口契约(实测)
```text
+64
View File
@@ -0,0 +1,64 @@
import { describe, expect, it } from "bun:test";
import { normalizeTemplateGroups } from "./templates.js";
const raw = [
{
name: "报销单拆单",
active: true,
specifications: [
{ id: "a:1", name: "AI合同审批单", type: "custom", active: true },
{ id: "a:2", name: "报销单-汇总", type: "expense", active: true },
],
},
{
name: "历史模板",
active: true,
specifications: [
{ id: "b:1", name: "旧报销单", type: "expense", active: false },
],
},
{
name: "空分组",
active: true,
specifications: [],
},
{
name: "停用分组",
active: false,
specifications: [
{ id: "c:1", name: "隐藏模板", type: "expense", active: true },
],
},
];
describe("normalizeTemplateGroups", () => {
it("默认只返回启用模板,并跳过空分组/停用分组", () => {
const result = normalizeTemplateGroups(raw);
expect(result.total).toBe(2);
expect(result.inactive).toBe(1);
expect(result.groups.map((g) => g.name)).toEqual(["报销单拆单"]);
expect(result.groups[0].specifications.map((s) => s.name)).toEqual([
"AI合同审批单",
"报销单-汇总",
]);
});
it("includeInactive 返回停用模板与停用分组", () => {
const result = normalizeTemplateGroups(raw, { includeInactive: true });
expect(result.total).toBe(4);
expect(result.groups.map((g) => g.name)).toEqual(["报销单拆单", "历史模板", "停用分组"]);
const inactiveSpecs = result.groups.flatMap((g) => g.specifications).filter((s) => !s.active);
expect(inactiveSpecs.map((s) => s.name)).toEqual(["旧报销单"]);
});
it("保留分组名与模板类型", () => {
const result = normalizeTemplateGroups(raw);
expect(result.groups[0].specifications[0]).toMatchObject({
id: "a:1",
name: "AI合同审批单",
type: "custom",
group: "报销单拆单",
active: true,
});
});
});
+96
View File
@@ -0,0 +1,96 @@
import type { KyInstance } from "ky";
/**
* 单据模板(表单规格)列表。
*
* 页面「快速新建单据」读的是同一个接口:
* GET /api/form/v2/specificationGroups/withSpecificationVersioned?corpId=
* 响应按“规格分组 → 规格”组织,且已按当前身份做过可见性过滤。
*
* 默认只返回启用中的模板;`includeInactive` 用于排查/管理场景。
*/
export interface BillTemplateSpec {
id: string;
name: string;
type: string;
active: boolean;
group: string;
}
export interface BillTemplateGroup {
name: string;
specifications: BillTemplateSpec[];
}
export interface BillTemplateList {
groups: BillTemplateGroup[];
total: number;
inactive: number;
}
interface RawSpecification {
id?: string;
name?: string;
type?: string;
active?: boolean;
}
interface RawGroup {
name?: string;
active?: boolean;
specifications?: RawSpecification[];
}
export interface ListBillTemplatesOptions {
includeInactive?: boolean;
}
export function normalizeTemplateGroups(
items: RawGroup[],
options: ListBillTemplatesOptions = {}
): BillTemplateList {
const includeInactive = options.includeInactive === true;
const groups: BillTemplateGroup[] = [];
let total = 0;
let inactive = 0;
for (const item of items) {
if (!includeInactive && item.active === false) continue;
const specs: BillTemplateSpec[] = [];
for (const spec of item.specifications ?? []) {
if (!spec.id || !spec.name) continue;
const active = spec.active !== false;
if (!active) {
inactive += 1;
if (!includeInactive) continue;
}
specs.push({
id: spec.id,
name: spec.name,
type: spec.type ?? "unknown",
active,
group: item.name ?? "",
});
total += 1;
}
if (specs.length > 0) {
groups.push({ name: item.name ?? "", specifications: specs });
}
}
return { groups, total, inactive };
}
export async function listBillTemplates(
client: KyInstance,
corpId: string,
options: ListBillTemplatesOptions = {}
): Promise<BillTemplateList> {
const response = await client.get("api/form/v2/specificationGroups/withSpecificationVersioned", {
searchParams: { corpId },
});
const json = (await response.json()) as { items?: RawGroup[]; value?: { items?: RawGroup[] } };
const items = json.items ?? json.value?.items ?? [];
return normalizeTemplateGroups(items, options);
}