import { getRawBillFlow } from "../../../domains/bill/tools.js"; import { buildBillCopyForm, copyBillAsDraft } from "../../../domains/bill/copy.js"; import type { BillDraftForm } from "../../../domains/bill/draft-validation.js"; import { isDryRun } from "../../mutation.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 copy <单号|ID> [--title=...] [--drop-attachments] [--dry-run] --yes` * * 纯接口复制:读取服务端最新表单 → 清空发票绑定/重算金额 → 创建新草稿。 * 只创建草稿,不提交。 */ export async function handleCopy(ctx: BillActionContext): Promise { const { parsed, runtime, corpId } = ctx; const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]); if (!target) { throw new Error("请提供要复制的单号或 ID: hose-use bill copy <单号|ID> [--title=...] --yes"); } const title = stringOption(parsed.options, ["title"]); const keepAttachments = !booleanOption(parsed.options, ["drop-attachments", "dropAttachments"]); const client = await ctx.getClient(); if (isDryRun(parsed, runtime)) { const raw = await getRawBillFlow(client, corpId, target); const flow = raw && typeof raw.flowId === "object" ? (raw.flowId as Record) : undefined; const form = flow && typeof flow.form === "object" ? (flow.form as BillDraftForm) : undefined; if (!form) { return { stdout: "", stderr: `[NOT FOUND] 在企业下未找到单号或 ID 为 [${target}] 的单据,无法复制\n`, exitCode: 1, }; } const copy = buildBillCopyForm(form, { title, keepAttachments }); if (runtime.jsonMode) { return { stdout: printJson( { dryRun: true, source: target, sourceTitle: form.title, title: copy.title, detailCount: copy.details?.length ?? 0, expenseMoney: copy.expenseMoney?.standard, keepAttachments, invoicesCleared: true, }, runtime.outputOptions ), stderr: "", exitCode: 0, }; } return { stdout: `====== 复制单据(dry-run,未创建) ======\n` + ` 源单 : ${target}(${form.title ?? "-"})\n` + ` 新标题 : ${copy.title ?? "-"}\n` + ` 明细 : ${copy.details?.length ?? 0} 条\n` + ` 金额 : ${copy.expenseMoney?.standard ?? "0"} CNY\n` + ` 附件 : ${keepAttachments ? "保留" : "清空"}\n` + ` 发票 : 清空绑定,发票总额归零\n` + `\n提示: 确认无误后追加 --yes 执行创建(仍为草稿,不会提交)\n`, stderr: "", exitCode: 0, }; } await ctx.requireWriteConfirmation(); const result = await copyBillAsDraft(client, corpId, target, { title, keepAttachments }); if (runtime.jsonMode) { return { stdout: printJson( { source: target, flowId: result.flowId, code: result.code, title: result.title, detailCount: result.detailCount, expenseMoney: result.expenseMoney, submitted: false, }, runtime.outputOptions ), stderr: "", exitCode: 0, }; } return { stdout: `复制成功(已创建草稿,未提交)\n` + ` 新单号 : ${result.code}\n` + ` 单据 ID : ${result.flowId}\n` + ` 标题 : ${result.title}\n` + ` 明细 : ${result.detailCount} 条 / ${result.expenseMoney} CNY\n`, stderr: "", exitCode: 0, }; }