feat: unify CLI dry-run and write confirmation

This commit is contained in:
gitea committed 2026-09-11 16:53:14 +08:00
1 parent 639aaa9271
commit 45eb83a609
19 files changed
+506 -71

No files matched your search

+41 -23
View File
@@ -20,6 +20,7 @@ import {
commentBill,
resolveBillStaffIds,
} from "../../domains/bill/tools.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
export async function handleBillCommand(
parsed: CliParsedArgs,
@@ -32,15 +33,24 @@ export async function handleBillCommand(
);
}
const client = await createEkbClient(corp);
const action = parsed.action?.toLowerCase();
const corpId = corp.corpId || corp.id;
let client: Awaited<ReturnType<typeof createEkbClient>> | undefined;
const getClient = async () => {
client ??= await createEkbClient(corp);
return client;
};
const actionTarget = () => parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
const requireWriteConfirmation = async () => {
if (booleanOption(parsed.options, ["yes", "y", "confirm", "force-write"])) return;
if (isDryRun(parsed, runtime) || booleanOption(parsed.options, ["yes", "y", "confirm", "force-write"])) return;
if (!process.stdin.isTTY || !process.stdout.isTTY) {
throw new Error("审批动作会改变单据状态。请显式添加 --yes(或 --confirm)后重试。");
requireMutationConfirmation(
parsed,
runtime,
"单据审批动作",
`hose-use bill ${action || "approve"} ${actionTarget() || "<单号|ID>"} --yes`
);
}
const { prompt } = await import("../helpers.js");
const answer = await prompt("该操作会改变单据状态,确认继续?输入 yes 继续: ");
@@ -68,7 +78,7 @@ export async function handleBillCommand(
});
const resolveApproverIds = async (values: string[] | undefined): Promise<string[]> => {
if (!values?.length) throw new Error("请通过 --approver-id、--staff 或 --to 指定员工 ID、工号或姓名");
return resolveBillStaffIds(client, corpId, values);
return resolveBillStaffIds(await getClient(), corpId, values);
};
switch (action) {
@@ -77,7 +87,8 @@ export async function handleBillCommand(
await requireWriteConfirmation();
const target = actionTarget();
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill approve <单号|ID> --yes");
const result = await approveBill(client, corpId, target, actionOptions());
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "同意单据审批", target, actionOptions());
const result = await approveBill(await getClient(), corpId, target, actionOptions());
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
return { stdout: `审批同意成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
}
@@ -89,7 +100,8 @@ export async function handleBillCommand(
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill reject <单号|ID> --comment <原因> --yes");
const options = actionOptions();
if (!options.comment?.trim()) throw new Error("驳回原因不能为空,请通过 --comment 提供原因");
const result = await rejectBill(client, corpId, target, options);
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "驳回单据审批", target, options);
const result = await rejectBill(await getClient(), corpId, target, options);
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
return { stdout: `驳回成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
}
@@ -99,8 +111,10 @@ export async function handleBillCommand(
await requireWriteConfirmation();
const target = actionTarget();
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill transfer <单号|ID> --approver-id <员工ID> --yes");
const options = { ...actionOptions(), approverIds: await resolveApproverIds(actionOptions().approverIds) };
const result = await transferBill(client, corpId, target, options);
const rawOptions = actionOptions();
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "转交单据审批", target, rawOptions);
const options = { ...rawOptions, approverIds: await resolveApproverIds(rawOptions.approverIds) };
const result = await transferBill(await getClient(), corpId, target, options);
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
return { stdout: `转交审批成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
}
@@ -112,8 +126,10 @@ export async function handleBillCommand(
await requireWriteConfirmation();
const target = actionTarget();
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill add-node <单号|ID> --approver-id <员工ID> --yes");
const options = { ...actionOptions(), approverIds: await resolveApproverIds(actionOptions().approverIds) };
const result = await addNodeBill(client, corpId, target, options);
const rawOptions = actionOptions();
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "单据加签", target, rawOptions);
const options = { ...rawOptions, approverIds: await resolveApproverIds(rawOptions.approverIds) };
const result = await addNodeBill(await getClient(), corpId, target, options);
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
return { stdout: `加签审批成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
}
@@ -123,7 +139,9 @@ export async function handleBillCommand(
await requireWriteConfirmation();
const target = actionTarget();
if (!target) throw new Error("请提供单号或单据 ID: hose-use bill comment <单号|ID> --comment <内容> --yes");
const result = await commentBill(client, corpId, target, actionOptions());
const options = actionOptions();
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "添加单据评论", target, options);
const result = await commentBill(await getClient(), corpId, target, options);
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
return { stdout: `单据评论成功\n单号: ${result.billCode || target}\n流程 ID: ${result.flowId}\n`, stderr: "", exitCode: 0 };
}
@@ -137,7 +155,7 @@ export async function handleBillCommand(
const state = stringOption(parsed.options, ["state", "s"]);
const count = numberOption(parsed.options, ["count", "limit", "n"], 20);
const result = await searchAndFormatBills(client, corpId, {
const result = await searchAndFormatBills(await getClient(), corpId, {
code,
keyword,
stage,
@@ -192,7 +210,7 @@ export async function handleBillCommand(
throw new Error("请提供要查询的单号或单据 ID: hose-use bill get <单号|ID>");
}
const bills = await getBillByCodeOrId(client, corpId, target);
const bills = await getBillByCodeOrId(await getClient(), corpId, target);
if (bills.length === 0) {
if (runtime.jsonMode) {
@@ -211,7 +229,7 @@ export async function handleBillCommand(
const withRisk = booleanOption(parsed.options, ["risk", "with-risk", "audit"]);
const riskReports = withRisk
? await Promise.all(bills.map((bill) => getBillRisk(client, corpId, bill.billId || bill.billCode)))
? await Promise.all(bills.map(async (bill) => getBillRisk(await getClient(), corpId, bill.billId || bill.billCode)))
: [];
if (runtime.jsonMode) {
@@ -287,7 +305,7 @@ export async function handleBillCommand(
case "schema":
case "schemas":
case "entities": {
const { entities } = await getFieldDictionary(client, corpId, true);
const { entities } = await getFieldDictionary(await getClient(), corpId, true);
if (runtime.jsonMode) {
return {
@@ -328,7 +346,7 @@ export async function handleBillCommand(
case "timeline": {
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) throw new Error("请提供要查询流程的单号或单据 ID: hose-use bill flow <单号|ID>");
const flow = await getBillFlow(client, corpId, target);
const flow = await getBillFlow(await getClient(), corpId, target);
if (!flow) {
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
return { stdout: "", stderr: `[NOT FOUND] 未找到单据流程: ${target}\n`, exitCode: 1 };
@@ -370,7 +388,7 @@ export async function handleBillCommand(
case "warnings": {
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) throw new Error("请提供要查询风控结果的单号或单据 ID: hose-use bill risk <单号|ID>");
const report = await getBillRisk(client, corpId, target);
const report = await getBillRisk(await getClient(), corpId, target);
if (!report) {
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
return { stdout: "", stderr: `[NOT FOUND] 未找到单据风控结果: ${target}\n`, exitCode: 1 };
@@ -400,7 +418,7 @@ export async function handleBillCommand(
case "budgets": {
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) throw new Error("请提供要查询预算状态的单号或单据 ID: hose-use bill budget <单号|ID>");
const report = await getBillRisk(client, corpId, target);
const report = await getBillRisk(await getClient(), corpId, target);
if (!report) {
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
return { stdout: "", stderr: `[NOT FOUND] 未找到单据预算状态: ${target}\n`, exitCode: 1 };
@@ -426,7 +444,7 @@ export async function handleBillCommand(
case "resolve": {
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) throw new Error("请提供要解析引用的单号或单据 ID: hose-use bill refs <单号|ID>");
const report = await getBillReferences(client, corpId, target);
const report = await getBillReferences(await getClient(), corpId, target);
if (!report) {
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
return { stdout: "", stderr: `[NOT FOUND] 未找到单据引用: ${target}\n`, exitCode: 1 };
@@ -455,7 +473,7 @@ export async function handleBillCommand(
case "links": {
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) throw new Error("请提供要查询关联关系的单号或单据 ID: hose-use bill relations <单号|ID>");
const report = await getBillRelations(client, corpId, target);
const report = await getBillRelations(await getClient(), corpId, target);
if (!report) {
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
return { stdout: "", stderr: `[NOT FOUND] 未找到单据关联关系: ${target}\n`, exitCode: 1 };
@@ -488,7 +506,7 @@ export async function handleBillCommand(
case "files": {
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) throw new Error("请提供要查询附件的单号或单据 ID: hose-use bill attachments <单号|ID>");
const report = await getBillAttachments(client, corpId, target);
const report = await getBillAttachments(await getClient(), corpId, target);
if (!report) {
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
return { stdout: "", stderr: `[NOT FOUND] 未找到单据附件: ${target}\n`, exitCode: 1 };
@@ -511,7 +529,7 @@ export async function handleBillCommand(
if (!target) throw new Error("请提供要下载附件的单号或单据 ID: hose-use bill download <单号|ID>");
const outputDir = stringOption(parsed.options, ["output-dir", "dir"]) || `${process.cwd()}/downloads`;
const fileId = stringOption(parsed.options, ["file-id", "file"]);
const result = await downloadBillAttachments(client, corpId, target, outputDir, fileId);
const result = await downloadBillAttachments(await getClient(), corpId, target, outputDir, fileId);
const summary = {
corpId,
corpName: corp.name,
@@ -546,7 +564,7 @@ export async function handleBillCommand(
};
}
const items = await getBillByCodeOrId(client, corpId, target);
const items = await getBillByCodeOrId(await getClient(), corpId, target);
if (!items || items.length === 0) {
return {
stdout: "",
+30 -7
View File
@@ -229,8 +229,9 @@ describe("CLI - feetype 费用类型管理命令", () => {
options: {
name: "酒店住宿",
parent: "差旅费用",
yes: true,
},
raw: ["feetype", "create", "--name=酒店住宿", "--parent=差旅费用"],
raw: ["feetype", "create", "--name=酒店住宿", "--parent=差旅费用", "--yes"],
},
dummyRuntimeWithCorp
);
@@ -266,8 +267,8 @@ describe("CLI - feetype 费用类型管理命令", () => {
area: "feetype",
action: "update",
args: ["酒店住宿"],
options: { desc: "新说明" },
raw: ["feetype", "update", "酒店住宿", "--desc=新说明"],
options: { desc: "新说明", yes: true },
raw: ["feetype", "update", "酒店住宿", "--desc=新说明", "--yes"],
},
dummyRuntimeWithCorp
);
@@ -324,8 +325,8 @@ describe("CLI - feetype 费用类型管理命令", () => {
area: "feetype",
action: "enable",
args: ["酒店住宿"],
options: {},
raw: ["feetype", "enable", "酒店住宿"],
options: { yes: true },
raw: ["feetype", "enable", "酒店住宿", "--yes"],
},
dummyRuntimeWithCorp
);
@@ -355,8 +356,8 @@ describe("CLI - feetype 费用类型管理命令", () => {
area: "feetype",
action: "move",
args: ["酒店住宿"],
options: { parent: "办公费" },
raw: ["feetype", "move", "酒店住宿", "--parent=办公费"],
options: { parent: "办公费", yes: true },
raw: ["feetype", "move", "酒店住宿", "--parent=办公费", "--yes"],
},
dummyRuntimeWithCorp
);
@@ -368,6 +369,28 @@ describe("CLI - feetype 费用类型管理命令", () => {
spy.mockRestore();
});
it("feetype create --dry-run 不创建费用类型", async () => {
const spy = spyOn(feetypeTools, "createFeeType").mockResolvedValue({} as any);
const res = await handleFeeTypeCommand(
{
area: "feetype",
action: "create",
args: [],
options: { name: "酒店住宿", parent: "差旅费用", "dry-run": true },
raw: ["feetype", "create", "--name=酒店住宿", "--parent=差旅费用", "--dry-run"],
},
dummyRuntimeWithCorp
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("DRY-RUN");
expect(res.stdout).toContain("新建费用类型");
expect(spy).not.toHaveBeenCalled();
spy.mockRestore();
});
it("feetype fields 打印报账与申请字段表格", async () => {
const spy = spyOn(feetypeTools, "getFeeTypeFieldsList").mockResolvedValue({
feeType: {
+88 -9
View File
@@ -16,6 +16,7 @@ import {
updateFeeTypeInfo,
} from "../../domains/feetype/tools.js";
import { FeeTypeNode } from "../../domains/feetype/types.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
/**
* 递归渲染树形层级格式
@@ -65,9 +66,13 @@ export async function handleFeeTypeCommand(
);
}
const client = await createEkbClient(corp);
const corpId = corp.corpId || corp.id;
const action = (parsed.action?.toLowerCase() || "list").trim();
let client: Awaited<ReturnType<typeof createEkbClient>> | undefined;
const getClient = async () => {
client ??= await createEkbClient(corp);
return client;
};
// ── 1. 列表 / 树形展示 (list / tree) ──────────────────────────────────────────
if (["list", "tree", "all", "search"].includes(action)) {
@@ -80,7 +85,7 @@ export async function handleFeeTypeCommand(
const keyword =
stringOption(parsed.options, ["keyword", "q", "query"]) || parsed.args[0];
const result = await listFeeTypes(client, corpId, {
const result = await listFeeTypes(await getClient(), corpId, {
all: includeAll,
flat: isFlat,
keyword,
@@ -142,7 +147,7 @@ export async function handleFeeTypeCommand(
}
const includeSpecs = booleanOption(parsed.options, ["specs", "spec", "fields"]);
const detail = await getFeeTypeDetail(client, corpId, target, { includeSpecs });
const detail = await getFeeTypeDetail(await getClient(), corpId, target, { includeSpecs });
if (runtime.jsonMode) {
return {
@@ -215,7 +220,26 @@ export async function handleFeeTypeCommand(
const color = stringOption(parsed.options, ["color"]);
const icon = stringOption(parsed.options, ["icon"]);
const created = await createFeeType(client, corpId, {
requireMutationConfirmation(
parsed,
runtime,
"新建费用类型",
`hose-use feetype create --name="${name.trim()}" --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "新建费用类型", name.trim(), {
corpId,
name: name.trim(),
code: code || null,
parentId: parent || null,
enName: enName || null,
description: description || null,
color: color || null,
icon: icon || null,
});
}
const created = await createFeeType(await getClient(), corpId, {
name: name.trim(),
code,
parentId: parent,
@@ -283,7 +307,25 @@ export async function handleFeeTypeCommand(
throw new Error("请至少提供一个待更新的属性参数 (例如 --name, --code, --desc, --color)");
}
const updated = await updateFeeTypeInfo(client, corpId, target, {
requireMutationConfirmation(
parsed,
runtime,
"修改费用类型",
`hose-use feetype update ${target} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "修改费用类型", target, {
corpId,
name: name ?? null,
code: code ?? null,
enName: enName ?? null,
description: description ?? null,
color: color ?? null,
icon: icon ?? null,
});
}
const updated = await updateFeeTypeInfo(await getClient(), corpId, target, {
name,
code,
enName,
@@ -329,7 +371,17 @@ export async function handleFeeTypeCommand(
throw new Error("请指定待停用的费用类型: hose-use feetype disable <ID|编码|名称>");
}
const res = await disableFeeTypeItem(client, corpId, target);
requireMutationConfirmation(
parsed,
runtime,
"停用费用类型",
`hose-use feetype disable ${target} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "停用费用类型", target, { corpId, active: false });
}
const res = await disableFeeTypeItem(await getClient(), corpId, target);
if (runtime.jsonMode) {
return {
@@ -365,7 +417,21 @@ export async function handleFeeTypeCommand(
const recursive =
booleanOption(parsed.options, ["recursive", "r"]) !== false;
const res = await enableFeeTypeItem(client, corpId, target, { recursive });
requireMutationConfirmation(
parsed,
runtime,
"启用费用类型",
`hose-use feetype enable ${target} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "启用费用类型", target, {
corpId,
active: true,
recursive,
});
}
const res = await enableFeeTypeItem(await getClient(), corpId, target, { recursive });
if (runtime.jsonMode) {
return {
@@ -404,7 +470,20 @@ export async function handleFeeTypeCommand(
throw new Error("请指定目标父级: --parent=<目标父级ID|编码|名称> 或 --parent=root (移至顶级)");
}
const res = await moveFeeTypeItem(client, corpId, target, parentTarget);
requireMutationConfirmation(
parsed,
runtime,
"移动费用类型",
`hose-use feetype move ${target} --parent=${parentTarget} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "移动费用类型", target, {
corpId,
parent: parentTarget,
});
}
const res = await moveFeeTypeItem(await getClient(), corpId, target, parentTarget);
if (runtime.jsonMode) {
return {
@@ -443,7 +522,7 @@ export async function handleFeeTypeCommand(
throw new Error("请指定费用类型: hose-use feetype fields <ID|编码|名称>");
}
const res = await getFeeTypeFieldsList(client, corpId, target);
const res = await getFeeTypeFieldsList(await getClient(), corpId, target);
if (runtime.jsonMode) {
return {
+4 -4
View File
@@ -140,7 +140,7 @@ describe("CLI - platform 命令与 record 动作", () => {
spies.push(toggleSpy);
const res = await handlePlatformCommand(
{ area: "platform", action: "record", args: ["toggle", "platform-1", "entity-1", "r-1"], options: {}, raw: [] },
{ area: "platform", action: "record", args: ["toggle", "platform-1", "entity-1", "r-1"], options: { yes: true }, raw: ["platform", "record", "toggle", "platform-1", "entity-1", "r-1", "--yes"] },
dummyRuntime
);
@@ -161,8 +161,8 @@ describe("CLI - platform 命令与 record 动作", () => {
area: "platform",
action: "record",
args: ["edit", "platform-1", "entity-1", "r-1"],
options: { data: '{"name":"更新后的名称"}' },
raw: [],
options: { data: '{"name":"更新后的名称"}', yes: true },
raw: ["platform", "record", "edit", "platform-1", "entity-1", "r-1", "--yes"],
},
dummyRuntime
);
@@ -188,7 +188,7 @@ describe("CLI - platform 命令与 record 动作", () => {
spies.push(recomputeSpy);
const res = await handlePlatformCommand(
{ area: "platform", action: "record", args: ["recompute", "platform-1", "entity-1", "r-1"], options: {}, raw: [] },
{ area: "platform", action: "record", args: ["recompute", "platform-1", "entity-1", "r-1"], options: { yes: true }, raw: ["platform", "record", "recompute", "platform-1", "entity-1", "r-1", "--yes"] },
dummyRuntime
);
+43
View File
@@ -4,6 +4,7 @@ import { createClientsForCorp } from "../helpers.js";
import { booleanOption, numberOption, stringOption } from "../parser.js";
import { printJson, printTable } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
function requiredTarget(parsed: CliParsedArgs, index: number, usage: string): string {
const target = parsed.args[index]?.trim();
@@ -251,6 +252,20 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P
: parsed.options.active !== undefined
? booleanOption(parsed.options, ["active"], true)
: undefined;
requireMutationConfirmation(
parsed,
runtime,
"切换业务对象记录状态",
`hose-use platform record toggle ${resolved.platform.id} ${resolved.entity.id} ${recordId} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "切换业务对象记录状态", recordId, {
corpId: resolved.corpId,
platformId: resolved.platform.id,
entityId: resolved.entity.id,
active: explicitState ?? "toggle",
});
}
const res = await api.toggleRecordState(resolved.clients.ekbClient, resolved.corpId, recordId, explicitState);
if (runtime.jsonMode) {
return {
@@ -278,6 +293,21 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P
}
}
const activeOpt = parsed.options.active !== undefined ? booleanOption(parsed.options, ["active"], true) : undefined;
const changes = {
dataLinkEntityId: resolved.entity.id,
dataLinkId: recordId,
form,
active: activeOpt ?? null,
};
requireMutationConfirmation(
parsed,
runtime,
"编辑业务对象记录",
`hose-use platform record edit ${resolved.platform.id} ${resolved.entity.id} ${recordId} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "编辑业务对象记录", recordId, changes);
}
const result = await api.editRecord(resolved.clients.ekbClient, resolved.corpId, {
dataLinkEntityId: resolved.entity.id,
dataLinkId: recordId,
@@ -293,6 +323,19 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P
}
case "recompute":
case "recalc": {
requireMutationConfirmation(
parsed,
runtime,
"触发业务对象记录台账重算",
`hose-use platform record recompute ${resolved.platform.id} ${resolved.entity.id} ${recordId} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "触发业务对象记录台账重算", recordId, {
corpId: resolved.corpId,
platformId: resolved.platform.id,
entityId: resolved.entity.id,
});
}
const result = await api.recomputeRecordLedger(resolved.clients.ekbClient, resolved.corpId, recordId);
if (runtime.jsonMode) return { stdout: printJson({ success: true, recordId, result }, runtime.outputOptions), stderr: "", exitCode: 0 };
return {
+37 -1
View File
@@ -87,7 +87,8 @@ describe("CLI - hose-use rule 规则与场景索引命令", () => {
"add",
"办公采购",
"单笔采购大于1万,[必须附采购合同]{硬性};[建议由采购员集中办理]{建议}。",
"--json"
"--json",
"--yes"
]);
expect(addRes.exitCode).toBe(0);
const addData = JSON.parse(addRes.stdout);
@@ -102,6 +103,41 @@ describe("CLI - hose-use rule 规则与场景索引命令", () => {
expect(scopesData.scopes[2].scope).toBe("办公采购");
});
test("hose-use rule add --dry-run 只预览且不写入数据库", async () => {
const res = await runCli([
"rule",
"add",
"办公采购",
"单笔采购大于1万,[必须附采购合同]{硬性}。",
"--json",
"--dry-run",
]);
expect(res.exitCode).toBe(0);
const data = JSON.parse(res.stdout);
expect(data.dryRun).toBe(true);
expect(data.operation).toBe("新增审批规则");
expect(data.changes.scope).toBe("办公采购");
const scopes = await runCli(["rule", "scopes", "--json"]);
expect(JSON.parse(scopes.stdout).count).toBe(2);
});
test("hose-use rule add 未确认时拒绝写入并给出下一步", async () => {
const res = await runCli([
"rule",
"add",
"办公采购",
"单笔采购大于1万,[必须附采购合同]{硬性}。",
]);
expect(res.exitCode).not.toBe(0);
expect(res.stderr).toContain("--dry-run");
expect(res.stderr).toContain("--yes");
const scopes = await runCli(["rule", "scopes", "--json"]);
expect(JSON.parse(scopes.stdout).count).toBe(2);
});
test("hose-use rule add 语法错误拦截并阻止入库", async () => {
const failRes = await runCli([
"rule",
+30
View File
@@ -2,6 +2,7 @@ import { ApprovalRepository, parseRuleBody } from "../../domains/approval/index.
import { booleanOption, stringOption } from "../parser.js";
import { printJson, printTable } from "../printer.js";
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
export async function handleRuleCommand(
parsed: CliParsedArgs,
@@ -205,6 +206,22 @@ export async function handleRuleCommand(
if (!scope) throw new Error("缺少适用场景/索引参数:请输入索引名称或使用 --scope 指定");
if (!body) throw new Error("缺少规约正文参数:请输入正文或使用 --body 指定,须包含 [动作句式]{硬性|弹性|建议|特殊}");
// 先做纯函数校验,让调用方在确认前就能修正格式错误。
parseRuleBody(body);
requireMutationConfirmation(
parsed,
runtime,
"新增审批规则",
`hose-use rule add --scope=${scope} --body='${body}' --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "新增审批规则", scope, {
scope,
body,
status: "active",
});
}
const rule = repo.createRule({
scope,
@@ -240,6 +257,19 @@ export async function handleRuleCommand(
ruleId = found.id;
}
requireMutationConfirmation(
parsed,
runtime,
"删除审批规则",
`hose-use rule delete ${ruleId} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "删除审批规则", ruleId, {
id: ruleId,
irreversible: true,
});
}
const deleted = repo.deleteRule(ruleId);
if (runtime.jsonMode) {
return {
+48 -1
View File
@@ -21,6 +21,7 @@ import {
applyWorkflowPathPatch,
} from "../../domains/platform/workflow-state.js";
import { WorkflowAlertStore } from "../../domains/platform/workflow-alert-store.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
const WORKFLOW_STATE_DIR = process.env.HOSE_STATE_DIR || join(homedir(), ".config", "hose-use");
@@ -118,6 +119,20 @@ async function handlePatch(parsed: CliParsedArgs, runtime: CliRuntime): Promise<
}
const patched = applyWorkflowPathPatch(sourceWorkflow, path, value);
const target = inPlace ? file : output!;
requireMutationConfirmation(
parsed,
runtime,
"写入工作流草稿文件",
`hose-use workflow patch ${pipelineId} --file=${file} --path=${path} --value='${rawValue}' ${inPlace ? "--in-place" : `--output=${target}`} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "写入工作流草稿文件", target, {
pipelineId,
path,
value,
tasksVersion: patched.tasksVersion,
});
}
writeFileSync(target, `${JSON.stringify(patched, null, 2)}\n`, "utf8");
const result = { success: true, pipelineId, path, output: target, tasksVersion: patched.tasksVersion };
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
@@ -147,6 +162,21 @@ async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
throw new Error(`工作流 ID 不匹配:参数为 [${pipelineId}],文件中为 [${parsedWorkflow.id}]`);
}
const forceWrite = booleanOption(parsed.options, ["force-write", "forceWrite"]);
requireMutationConfirmation(
parsed,
runtime,
"保存工作流草稿到远端",
`hose-use workflow save ${pipelineId} --file=${file} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "保存工作流草稿到远端", pipelineId, {
file,
tasksVersion: parsedWorkflow.tasksVersion,
forceWrite,
});
}
const clients = await createClientsForCorp(runtime.selectedCorp!);
const platformId = await resolveWorkflowPlatformId(parsed, clients, pipelineId);
const piperClient = await createPiperClientForCorp(runtime.selectedCorp!, platformId);
@@ -159,7 +189,6 @@ async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
dirtyPaths: ["*"],
};
const forceWrite = booleanOption(parsed.options, ["force-write", "forceWrite"]);
if (!forceWrite && hasWorkflowVersionConflict(state, remote)) {
throw new Error(
`工作流版本已变化,拒绝覆盖:远端 tasksVersion=${remote.tasksVersion}, 文件 tasksVersion=${parsedWorkflow.tasksVersion}。确认来源后使用 --force-write。`
@@ -300,6 +329,15 @@ async function handleCheck(parsed: CliParsedArgs, runtime: CliRuntime): Promise<
async function handlePublish(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow publish <pipelineId>\n", exitCode: 1 };
requireMutationConfirmation(
parsed,
runtime,
"发布并启用工作流",
`hose-use workflow publish ${pipelineId} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "发布并启用工作流", pipelineId, { state: 1 });
}
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
const result = await api.toggleWorkflow(client, pipelineId, 1);
const output = { success: result.success, pipelineId, published: result.success, state: 1 };
@@ -468,6 +506,15 @@ async function handleToggle(parsed: CliParsedArgs, runtime: CliRuntime): Promise
}
const state = (stateArg === "1" || stateArg === "true" ? 1 : 0) as 0 | 1;
requireMutationConfirmation(
parsed,
runtime,
"切换工作流状态",
`hose-use workflow toggle ${pipelineId} --state=${state} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "切换工作流状态", pipelineId, { state });
}
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
const result = await api.toggleWorkflow(client, pipelineId, state);
+4
View File
@@ -13,6 +13,8 @@ export function initCorpRuntime(
stateless?: boolean;
stateful?: boolean;
jsonMode?: boolean;
dryRun?: boolean;
confirmed?: boolean;
outputOptions?: OutputOptions;
appRoot?: string;
entryFile?: string;
@@ -48,6 +50,8 @@ export function initCorpRuntime(
corpContext,
selectedCorp,
jsonMode: options.jsonMode ?? false,
dryRun: options.dryRun ?? false,
confirmed: options.confirmed ?? false,
outputOptions: options.outputOptions,
appRoot: options.appRoot,
entryFile: options.entryFile,
+55
View File
@@ -0,0 +1,55 @@
import { describe, expect, test } from "bun:test";
import { handleBillCommand } from "./commands/bill.js";
import type { CliRuntime } from "./types.js";
const runtime: CliRuntime = {
corpContext: {} as any,
selectedCorp: {
id: "corp-test",
name: "测试企业",
source: "account",
baseUrl: "https://app.ekuaibao.com",
credentials: {
corpId: "corp-test",
staffId: "staff-test",
accessToken: "token-test",
},
},
jsonMode: true,
};
describe("CLI mutation protocol", () => {
test("bill --dry-run returns a preview without creating an API client", async () => {
const result = await handleBillCommand(
{
area: "bill",
action: "approve",
args: ["S26000001"],
options: { "dry-run": true },
raw: ["bill", "approve", "S26000001", "--dry-run"],
},
runtime
);
expect(result.exitCode).toBe(0);
const preview = JSON.parse(result.stdout);
expect(preview.dryRun).toBe(true);
expect(preview.operation).toBe("同意单据审批");
expect(preview.target).toBe("S26000001");
});
test("bill write without confirmation is rejected before the API call", async () => {
await expect(
handleBillCommand(
{
area: "bill",
action: "approve",
args: ["S26000001"],
options: {},
raw: ["bill", "approve", "S26000001"],
},
runtime
)
).rejects.toThrow("--yes");
});
});
+84
View File
@@ -0,0 +1,84 @@
import { booleanOption } from "./parser.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "./types.js";
/**
* All mutating CLI commands use the same two-step contract:
* 1. --dry-run only describes the intended change;
* 2. --yes/--confirm is required before the real operation runs.
*
* The parsed-argument fallback keeps command handlers easy to unit-test without
* requiring every hand-built CliRuntime to include the newer fields.
*/
export class MutationConfirmationRequired extends Error {
readonly operation: string;
readonly nextAction: string;
constructor(operation: string, nextAction: string) {
super(
`拒绝执行${operation}:该操作会改变数据。请先使用 --dry-run 预览,确认后追加 --yes(或 --confirm)。\n下一步:${nextAction}`
);
this.name = "MutationConfirmationRequired";
this.operation = operation;
this.nextAction = nextAction;
}
}
export function isDryRun(parsed: CliParsedArgs, runtime: CliRuntime): boolean {
return runtime.dryRun === true || booleanOption(parsed.options, ["dry-run", "dryRun", "dryrun"]);
}
export function isConfirmed(parsed: CliParsedArgs, runtime: CliRuntime): boolean {
return (
runtime.confirmed === true ||
booleanOption(parsed.options, ["yes", "y", "confirm", "force-write"])
);
}
export function requireMutationConfirmation(
parsed: CliParsedArgs,
runtime: CliRuntime,
operation: string,
nextAction: string
): void {
if (isDryRun(parsed, runtime) || isConfirmed(parsed, runtime)) return;
throw new MutationConfirmationRequired(operation, nextAction);
}
export function mutationPreview(
parsed: CliParsedArgs,
runtime: CliRuntime,
operation: string,
target: string,
changes: Record<string, unknown>
): CliResult {
const payload = {
dryRun: true,
operation,
target,
changes,
nextAction: `hose-use ${parsed.raw.join(" ")} --yes`,
};
if (runtime.jsonMode) {
return {
stdout: `${JSON.stringify(payload, null, 2)}\n`,
stderr: "",
exitCode: 0,
};
}
const lines = [
"[DRY-RUN] 未执行任何写操作。",
`操作: ${operation}`,
`目标: ${target}`,
"变更:",
...Object.entries(changes).map(([key, value]) => ` ${key}: ${formatPreviewValue(value)}`),
`下一步: hose-use ${parsed.raw.join(" ")} --yes`,
];
return { stdout: `${lines.join("\n")}\n`, stderr: "", exitCode: 0 };
}
function formatPreviewValue(value: unknown): string {
if (typeof value === "string") return value;
return JSON.stringify(value);
}
+3
View File
@@ -27,6 +27,9 @@ const KNOWN_BOOLEAN_FLAGS = new Set([
"yes",
"confirm",
"force-write",
"dry-run",
"dryRun",
"dryrun",
]);
export function parseArgs(rawArgs: string[]): CliParsedArgs {
+3 -1
View File
@@ -155,7 +155,9 @@ export function printHelp(): string {
--full 允许全量输出大体积 JSON (绕过 200KB 防爆拦截)
--stateless 单次强制以无状态模式执行
--stateful 单次强制以有状态模式执行
--yes, -y 确认执行会改变单据状态的审批动作
--dry-run 只预览写操作,不发起写请求或落盘
--yes, -y 确认执行会改变数据的写操作
--confirm --yes 的可读别名;写操作必须显式确认
--help, -h 查看帮助信息
常用示例:
+4
View File
@@ -135,12 +135,16 @@ async function dispatchCli(
const statelessOption = booleanOption(parsed.options, ["stateless"]);
const statefulOption = booleanOption(parsed.options, ["stateful"]);
const outputOpts = outputOptions(parsed.options);
const dryRun = booleanOption(parsed.options, ["dry-run", "dryRun", "dryrun"]);
const confirmed = booleanOption(parsed.options, ["yes", "y", "confirm", "force-write"]);
const runtime = initCorpRuntime({
corpId: corpIdOption,
stateless: statelessOption,
stateful: statefulOption,
jsonMode,
dryRun,
confirmed,
outputOptions: outputOpts,
appRoot: options.appRoot,
entryFile: options.entryFile,
+2
View File
@@ -34,6 +34,8 @@ export interface CliRuntime {
corpContext: CorpContext;
selectedCorp: CorpConfig | null;
jsonMode: boolean;
dryRun?: boolean;
confirmed?: boolean;
outputOptions?: OutputOptions;
appRoot?: string;
entryFile?: string;