diff --git a/src/aipro-cli.ts b/src/aipro-cli.ts index dd1ada8..73e2bb3 100644 --- a/src/aipro-cli.ts +++ b/src/aipro-cli.ts @@ -15,7 +15,7 @@ import { validateGatewayAction, } from "./domains/approval/index.js"; import { getRawBillFlow } from "./domains/bill/api.js"; -import { approveBill, rejectBill } from "./domains/bill/tools.js"; +import { approveBill, rejectBill, getTranslatorContext } from "./domains/bill/tools.js"; import { translateBillFlowToMarkdown } from "./domains/bill/translator.js"; import { VERSION } from "./version.js"; @@ -164,7 +164,8 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; const flowIdObj = (raw.flowId && typeof raw.flowId === "object" ? raw.flowId : raw) as Record; const form = (flowIdObj.form && typeof flowIdObj.form === "object" ? flowIdObj.form : {}) as Record; const title = form.title || flowIdObj.title || "<无标题>"; - const snapshot = translateBillFlowToMarkdown(raw); + const translatorContext = await getTranslatorContext(context.client, context.corpId).catch(() => undefined); + const snapshot = translateBillFlowToMarkdown(raw, translatorContext); // 创建全新独立运行实例 (永久长 ID + 6 位短 ID, 6 小时有效期) const run = repo.createApprovalRun({ @@ -298,7 +299,8 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; if (!raw) { throw new Error(`在当前企业下未找到单号或 ID 为 [${targetSn}] 的单据`); } - const markdown = translateBillFlowToMarkdown(raw); + const translatorContext = await getTranslatorContext(context.client, context.corpId).catch(() => undefined); + const markdown = translateBillFlowToMarkdown(raw, translatorContext); repo.logAiProAction({ action: "translate", diff --git a/src/domains/bill/bill.test.ts b/src/domains/bill/bill.test.ts index 439c8a2..a908337 100644 --- a/src/domains/bill/bill.test.ts +++ b/src/domains/bill/bill.test.ts @@ -323,4 +323,187 @@ describe("Bill Domain", () => { expect(markdown).toContain("- **城市**: 辽宁省/大连市/大连市区"); expect(markdown).toContain("- **消费事由**: `今日在大连见客户`"); }); + + it("modular translator formatting functions format scalar and complex types properly", () => { + const { + formatAmountValue, + formatDateValue, + formatPersonValue, + formatDepartmentValue, + formatReferenceOrObject, + formatApportionSplits, + formatInlineAttachments, + formatInlineInvoices, + } = require("./translator.js"); + + // Amount + expect(formatAmountValue({ standard: "350", standardStrCode: "CNY" })).toBe("CNY 350.00"); + expect(formatAmountValue(12.5)).toBe("CNY 12.50"); + expect(formatAmountValue("¥100")).toBe("CNY 100.00"); + + // Date + expect(formatDateValue(1788364800000)).toMatch(/2026-09-03/); + expect(formatDateValue(1788364800000, true)).toMatch(/2026-09-03 \d{2}:\d{2}/); + + // Person + const staffMap = new Map([["staff-1", { name: "张三", code: "ZS01" }]]); + expect(formatPersonValue("staff-1", staffMap)).toBe("张三(ZS01)"); + expect(formatPersonValue({ name: "李四", code: "LS02" })).toBe("李四(LS02)"); + + // Department + const deptMap = new Map([["dept-1", { path: "总公司/财务部" }]]); + expect(formatDepartmentValue("dept-1", deptMap)).toBe("总公司/财务部"); + expect(formatDepartmentValue({ fullPath: "总公司/研发部" })).toBe("总公司/研发部"); + + // Reference & Objects (Supplier, Bank, Dimension) + const dimMap = new Map([ + ["ID_dim_1", { name: "钰泰半导体股份有限公司", code: "ETA" }], + ["ID_biz_1", { name: "费用", code: "CODE2" }], + ]); + expect(formatReferenceOrObject("ID_dim_1", dimMap)).toBe("钰泰半导体股份有限公司(code=ETA)"); + expect(formatReferenceOrObject("ID_biz_1", dimMap)).toBe("费用(code=CODE2)"); + expect(formatReferenceOrObject({ + supplierName: "上海戴维迪", + account: "03365200040008552", + bank: "农业银行", + })).toBe("供应商名称=上海戴维迪;账号=03365200040008552;银行=农业银行"); + + // Apportion splits + const apportions = [ + { + apportionForm: { + apportionPercent: "100.00", + apportionMoney: { standard: "350", standardStrCode: "CNY" }, + expenseDepartment: "dept-1", + }, + }, + ]; + expect(formatApportionSplits(apportions, deptMap)).toBe("分摊比例=100.00%;分摊金额=CNY 350.00;报销部门=总公司/财务部"); + + // Inline attachments + const attachments = [ + { fileName: "协议书.pdf", fileId: "file-01" }, + { fileName: "账单.pdf", fileId: "file-02" }, + ]; + const attLines = formatInlineAttachments(attachments); + expect(attLines[0]).toBe("- **附件Attachment**:"); + expect(attLines[1]).toBe(" 1. `协议书.pdf` (fileId=\"file-01\")"); + expect(attLines[2]).toBe(" 2. `账单.pdf` (fileId=\"file-02\")"); + + // Inline invoices + const invoices = [ + { + invoiceCode: "26312000005586052981", + fileInfo: { fileName: "发票原件.pdf", fileId: "inv-01" }, + buyer: "钰泰半导体", + seller: "上海戴维迪", + approveAmount: { standard: "350.00" }, + taxAmount: { standard: "19.81" }, + }, + ]; + const invLines = formatInlineInvoices(invoices); + expect(invLines[0]).toBe("- **发票列表**(1):"); + expect(invLines.join("\n")).toContain("发票号码: 26312000005586052981"); + expect(invLines.join("\n")).toContain("原始文件名: 发票原件.pdf"); + expect(invLines.join("\n")).toContain("购方: 钰泰半导体"); + expect(invLines.join("\n")).toContain("销方: 上海戴维迪"); + expect(invLines.join("\n")).toContain("价税合计: CNY 350.00"); + }); + + it("translates full bill preserving relative attachment and invoice positions", () => { + const { translateBillFlowToMarkdown } = require("./translator.js"); + const complexFlow = { + flowId: { + state: "APPROVING", + form: { + code: "B26002288", + title: "方镕霖的8月图文快印的对公付款", + specificationId: "ID_PAYMENT", + submitDate: 1788415807829, + description: "戴维迪图文快印8月月结费用,¥350.00", + 法人实体: "dim_eta", + expenseDepartment: "dept_admin", + u_提交人部门: "dept_admin", + u_经常交易供应商: "上海戴维迪图文制作有限公司", + payMoney: { standard: "350.00", standardStrCode: "CNY" }, + expenseMoney: { standard: "350.00", standardStrCode: "CNY" }, + u_本单税额: { standard: "19.81", standardStrCode: "CNY" }, + details: [ + { + feeTypeId: "fee_print", + feeTypeForm: { + amount: { standard: "350.00", standardStrCode: "CNY" }, + feeDate: 1788364800000, + consumptionReasons: "8月图文快印", + detailId: "DETAIL_01", + detailNo: 1, + u_业务类型: "dim_biz_fee", + attachments: [ + { fileName: "18-1-服务框架协议书.pdf", fileId: "ID01TvInwhsEwf" }, + { fileName: "钰泰账单.pdf", fileId: "ID01VWUmNcRryf" }, + ], + invoiceForm: { + invoices: [ + { + invoiceCode: "26312000005586052981", + buyer: "钰泰半导体股份有限公司", + seller: "上海戴维迪图文制作有限公司", + approveAmount: { standard: "350.00", standardStrCode: "CNY" }, + taxAmount: { standard: "19.81", standardStrCode: "CNY" }, + }, + ], + }, + apportions: [ + { + apportionForm: { + apportionPercent: "100.00", + apportionMoney: { standard: "350.00", standardStrCode: "CNY" }, + expenseDepartment: "dept_admin", + }, + }, + ], + }, + }, + ], + }, + }, + }; + + const options = { + dimensionItemMap: new Map([ + ["dim_eta", { name: "钰泰半导体股份有限公司", code: "ETA" }], + ["dim_biz_fee", { name: "费用", code: "CODE2" }], + ]), + departmentMap: new Map([ + ["dept_admin", { path: "钰泰半导体/行政中心/人事行政部" }], + ]), + feeTypeMap: new Map([ + ["fee_print", { name: "图文快印费", path: "办公费/图文快印费" }], + ]), + }; + + const md = translateBillFlowToMarkdown(complexFlow, options); + // 验证顶层关键字段不再丢失 + expect(md).toContain("- **单号**: `B26002288`"); + expect(md).toContain("- **法人实体**: 钰泰半导体股份有限公司(code=ETA)"); + expect(md).toContain("- **费用承担部门**: 钰泰半导体/行政中心/人事行政部"); + expect(md).toContain("- **提交人部门**: 钰泰半导体/行政中心/人事行政部"); + expect(md).toContain("- **事由**: `戴维迪图文快印8月月结费用,¥350.00`"); + expect(md).toContain("- **经常交易供应商**: 上海戴维迪图文制作有限公司"); + expect(md).toContain("- **本单税额**: CNY 19.81"); + expect(md).toContain("- **支付金额**: CNY 350.00"); + + // 验证明细 1 内部原位挂载发票列表与附件列表 + expect(md).toContain("#### 明细 1"); + expect(md).toContain("- **费用类型**: 办公费/图文快印费(name=图文快印费)"); + expect(md).toContain("- **发票列表**(1):"); + expect(md).toContain("发票号码: 26312000005586052981"); + expect(md).toContain("购方: 钰泰半导体股份有限公司"); + expect(md).toContain("销方: 上海戴维迪图文制作有限公司"); + expect(md).toContain("- **业务类型**: 费用(code=CODE2)"); + expect(md).toContain("- **费用归属分摊**: 分摊比例=100.00%;分摊金额=CNY 350.00;报销部门=钰泰半导体/行政中心/人事行政部"); + expect(md).toContain("- **附件Attachment**:"); + expect(md).toContain("1. `18-1-服务框架协议书.pdf` (fileId=\"ID01TvInwhsEwf\")"); + expect(md).toContain("2. `钰泰账单.pdf` (fileId=\"ID01VWUmNcRryf\")"); + }); }); diff --git a/src/domains/bill/tools.ts b/src/domains/bill/tools.ts index db2244a..1b8e5f6 100644 --- a/src/domains/bill/tools.ts +++ b/src/domains/bill/tools.ts @@ -21,6 +21,7 @@ import { type BillActionOptions, type BillActionTarget, } from "./api.js"; +import type { TranslatorOptions } from "./translator.js"; import { type RawBillItem, type FormattedBill, @@ -1271,4 +1272,58 @@ export const billTools = [ }, ]; -export { translateBillFlowToMarkdown } from "./translator.js"; +export async function getTranslatorContext( + client: KyInstance, + corpId: string +): Promise { + const [feeTypeTree, catalog, dimEntity, dimBiz] = await Promise.allSettled([ + getFeeTypeTree(client, corpId), + getReferenceCatalog(client, corpId), + resolveDimension(client, corpId, "法人实体"), + resolveDimension(client, corpId, "业务类型"), + ]); + + const feeTypeMap = new Map(); + if (feeTypeTree.status === "fulfilled") { + const flat = flattenFeeTypes(feeTypeTree.value); + for (const [id, val] of flat.entries()) { + feeTypeMap.set(id, { name: val.name as string, path: val.path as string }); + } + } + + const staffMap = catalog.status === "fulfilled" ? catalog.value.staff : undefined; + const departmentMap = catalog.status === "fulfilled" ? catalog.value.departments : undefined; + + const dimensionItemMap = new Map(); + if (dimEntity.status === "fulfilled" && dimEntity.value?.items) { + for (const item of dimEntity.value.items) { + dimensionItemMap.set(item.id, { name: item.name, code: item.code }); + } + } + if (dimBiz.status === "fulfilled" && dimBiz.value?.items) { + for (const item of dimBiz.value.items) { + dimensionItemMap.set(item.id, { name: item.name, code: item.code }); + } + } + + return { + feeTypeMap, + staffMap, + departmentMap, + dimensionItemMap, + }; +} + +export { + translateBillFlowToMarkdown, + formatAmountValue, + formatDateValue, + formatPersonValue, + formatDepartmentValue, + formatReferenceOrObject, + formatApportionSplits, + formatInlineInvoices, + formatInlineAttachments, + formatDynamicField, + type TranslatorOptions, +} from "./translator.js"; diff --git a/src/domains/bill/translator.ts b/src/domains/bill/translator.ts index a8dcf19..4362d7f 100644 --- a/src/domains/bill/translator.ts +++ b/src/domains/bill/translator.ts @@ -1,91 +1,374 @@ -import { KyInstance } from "ky"; -import { getRawBillFlow } from "./api.js"; -import { getFeeTypeTree } from "./api.js"; - -function formatDate(val: unknown): string { - if (!val) return ""; - if (typeof val === "number" || (typeof val === "string" && /^\d+$/.test(val))) { - const d = new Date(Number(val)); - if (!isNaN(d.getTime())) { - const year = d.getFullYear(); - const month = String(d.getMonth() + 1).padStart(2, "0"); - const day = String(d.getDate()).padStart(2, "0"); - return `${year}-${month}-${day}`; - } - } - if (typeof val === "string") { - const match = val.match(/^(\d{4})[-/](\d{1,2})[-/](\d{1,2})/); - if (match) { - return `${match[1]}-${match[2].padStart(2, "0")}-${match[3].padStart(2, "0")}`; - } - return val; - } - return String(val); +export interface TranslatorOptions { + feeTypeMap?: Map; + staffMap?: Map>; + departmentMap?: Map }>; + dimensionItemMap?: Map; + dictionary?: Map; + corpName?: string; } -function formatDateTime(val: unknown): string { - if (!val) return ""; - if (typeof val === "number" || (typeof val === "string" && /^\d+$/.test(val))) { - const d = new Date(Number(val)); - if (!isNaN(d.getTime())) { - const year = d.getFullYear(); - const month = String(d.getMonth() + 1).padStart(2, "0"); - const day = String(d.getDate()).padStart(2, "0"); - const hours = String(d.getHours()).padStart(2, "0"); - const minutes = String(d.getMinutes()).padStart(2, "0"); - return `${year}-${month}-${day} ${hours}:${minutes}`; - } - } - return String(val); -} +// ── 1. 金额格式化 ───────────────────────────────────────────────────────────── -function parseCity(cityVal: unknown): string { - if (!cityVal) return ""; - if (typeof cityVal === "string") { - try { - const parsed = JSON.parse(cityVal); - if (Array.isArray(parsed) && parsed[0]?.label) { - return parsed[0].label; - } - } catch {} - return cityVal; - } - if (Array.isArray(cityVal) && cityVal[0]?.label) { - return cityVal[0].label; - } - return String(cityVal); -} - -function formatAmount(money: any): string { - if (!money) return "CNY 0.00"; +export function formatAmountValue(money: unknown): string { + if (money === null || money === undefined || money === "") return "CNY 0.00"; if (typeof money === "number") return `CNY ${money.toFixed(2)}`; if (typeof money === "string") { - const n = parseFloat(money.replace(/[^0-9.-]/g, "")); - return isNaN(n) ? money : `CNY ${n.toFixed(2)}`; + const trimmed = money.trim(); + if (!trimmed) return "CNY 0.00"; + const n = parseFloat(trimmed.replace(/[^0-9.-]/g, "")); + if (isNaN(n)) return trimmed; + const currencyMatch = trimmed.match(/^([A-Za-z]{3}|¥|\$)/); + const curr = currencyMatch ? (currencyMatch[1] === "¥" ? "CNY" : currencyMatch[1]) : "CNY"; + return `${curr} ${n.toFixed(2)}`; } if (typeof money === "object") { - const currency = money.standardStrCode || money.currency || "CNY"; - const amountNum = parseFloat(money.standard || money.amount || 0); - return `${currency} ${isNaN(amountNum) ? "0.00" : amountNum.toFixed(2)}`; + const obj = money as Record; + const curr = (obj.standardStrCode || obj.currency || (obj.standardSymbol === "¥" ? "CNY" : obj.standardSymbol) || "CNY") as string; + const val = obj.standard ?? obj.amount ?? obj.value ?? 0; + const n = typeof val === "number" ? val : parseFloat(String(val).replace(/[^0-9.-]/g, "")); + return `${curr} ${isNaN(n) ? "0.00" : n.toFixed(2)}`; } return String(money); } -function resolveSpecificationName(specId: unknown): string { +// ── 2. 日期时间格式化 ───────────────────────────────────────────────────────── + +export function formatDateValue(val: unknown, withTime = false): string { + if (!val) return ""; + let d: Date | undefined; + if (typeof val === "number" || (typeof val === "string" && /^\d+$/.test(val.trim()))) { + const num = Number(val); + if (!isNaN(num) && num > 0) d = new Date(num); + } else if (typeof val === "string") { + const match = val.match(/^(\d{4})[-/](\d{1,2})[-/](\d{1,2})(?:[ T](\d{1,2}):(\d{1,2}))?/); + if (match) { + const year = match[1]; + const month = match[2].padStart(2, "0"); + const day = match[3].padStart(2, "0"); + if (withTime && match[4] !== undefined && match[5] !== undefined) { + return `${year}-${month}-${day} ${match[4].padStart(2, "0")}:${match[5].padStart(2, "0")}`; + } + return `${year}-${month}-${day}`; + } + const parsed = Date.parse(val); + if (!isNaN(parsed)) d = new Date(parsed); + } + + if (d && !isNaN(d.getTime())) { + const formatter = new Intl.DateTimeFormat("zh-CN", { + timeZone: "Asia/Shanghai", + year: "numeric", + month: "2-digit", + day: "2-digit", + ...(withTime ? { hour: "2-digit", minute: "2-digit", hour12: false } : {}), + }); + const parts = formatter.formatToParts(d); + const partMap: Record = {}; + for (const p of parts) partMap[p.type] = p.value; + const dateStr = `${partMap.year}-${partMap.month}-${partMap.day}`; + if (withTime && partMap.hour !== undefined && partMap.minute !== undefined) { + return `${dateStr} ${partMap.hour}:${partMap.minute}`; + } + return dateStr; + } + return String(val); +} + +// ── 3. 城市解析 ─────────────────────────────────────────────────────────────── + +export function parseCityValue(cityVal: unknown): string { + if (!cityVal) return ""; + if (typeof cityVal === "string") { + try { + const parsed = JSON.parse(cityVal); + if (Array.isArray(parsed) && parsed[0]?.label) return parsed[0].label; + } catch {} + return cityVal; + } + if (Array.isArray(cityVal) && cityVal[0]?.label) { + return String(cityVal[0].label); + } + return String(cityVal); +} + +// ── 4. 员工/人员格式化 ───────────────────────────────────────────────────────── + +export function formatPersonValue( + val: unknown, + staffMap?: Map> +): string { + if (!val) return "未知"; + if (Array.isArray(val)) { + return val.map((v) => formatPersonValue(v, staffMap)).join("、"); + } + if (typeof val === "string") { + const trimmed = val.trim(); + if (staffMap?.has(trimmed)) { + const match = staffMap.get(trimmed)!; + const name = (match.name || match.nickName || trimmed) as string; + const code = match.code ? `(${match.code})` : ""; + return `${name}${code}`; + } + return trimmed; + } + if (typeof val === "object") { + const obj = val as Record; + const name = (obj.name || obj.nickName || obj.staffName || "") as string; + const code = obj.code ? `(${obj.code})` : ""; + if (name) return `${name}${code}`; + } + return String(val); +} + +// ── 5. 部门全路径格式化 ─────────────────────────────────────────────────────── + +export function formatDepartmentValue( + val: unknown, + departmentMap?: Map }> +): string { + if (!val) return ""; + if (Array.isArray(val)) { + return val.map((v) => formatDepartmentValue(v, departmentMap)).join("、"); + } + if (typeof val === "string") { + const trimmed = val.trim(); + if (departmentMap?.has(trimmed)) { + const match = departmentMap.get(trimmed)!; + return match.path || (match.item?.name as string) || trimmed; + } + return trimmed; + } + if (typeof val === "object") { + const obj = val as Record; + return (obj.fullPath || obj.path || obj.name || "") as string; + } + return String(val); +} + +// ── 6. 复杂对象与引用字典格式化 (供应商/银行卡号/枚举/档案项) ────────────────── + +export function formatReferenceOrObject( + val: unknown, + dimensionMap?: Map +): string { + if (val === null || val === undefined) return ""; + if (typeof val === "boolean") return val ? "是" : "否"; + if (typeof val === "number") return String(val); + + if (typeof val === "string") { + const trimmed = val.trim(); + if (dimensionMap?.has(trimmed)) { + const match = dimensionMap.get(trimmed)!; + const title = match.name || match.label || match.path || trimmed; + return match.code ? `${title}(code=${match.code})` : title; + } + return trimmed; + } + + if (Array.isArray(val)) { + const city = parseCityValue(val); + if (city && city !== String(val)) return city; + return val.map((item) => formatReferenceOrObject(item, dimensionMap)).join(";"); + } + + if (typeof val === "object") { + const obj = val as Record; + // 金额对象判断 + if ("standard" in obj || "standardStrCode" in obj) { + return formatAmountValue(obj); + } + // 标准枚举/档案节点判断 + if (obj.name || obj.label) { + const title = (obj.name || obj.label || "") as string; + const code = obj.code ? `(code=${obj.code})` : ""; + return `${title}${code}`; + } + // 供应商/银行账户解构 + const parts: string[] = []; + if (obj.supplierName) parts.push(`供应商名称=${obj.supplierName}`); + if (obj.supplierCode) parts.push(`供应商编码=${obj.supplierCode}`); + if (obj.accountName || obj.accountOwner) parts.push(`开户名=${obj.accountName || obj.accountOwner}`); + if (obj.account || obj.cardNo || obj.bankCardNo) parts.push(`账号=${obj.account || obj.cardNo || obj.bankCardNo}`); + if (obj.bankCardNumber) parts.push(`银行卡号=${obj.bankCardNumber}`); + if (obj.accountType) parts.push(`账户类型=${obj.accountType}`); + if (obj.accountCategory) parts.push(`账户类别=${obj.accountCategory}`); + if (obj.bank || obj.bankName) parts.push(`银行=${obj.bank || obj.bankName}`); + if (obj.openBankName || obj.branchBank) parts.push(`开户网点=${obj.openBankName || obj.branchBank}`); + if (parts.length > 0) return parts.join(";"); + + // 默认键值对铺平 + const entries = Object.entries(obj).filter(([k, v]) => v !== null && v !== undefined && v !== ""); + if (entries.length === 0) return ""; + return entries.map(([k, v]) => `${k}=${typeof v === "object" ? formatReferenceOrObject(v, dimensionMap) : v}`).join(";"); + } + + return String(val); +} + +// ── 7. 费用归属分摊格式化 ───────────────────────────────────────────────────── + +export function formatApportionSplits( + apportions: unknown[], + departmentMap?: Map }> +): string { + if (!Array.isArray(apportions) || apportions.length === 0) return ""; + const parts: string[] = []; + for (const item of apportions) { + if (!item || typeof item !== "object") continue; + const form = (item as Record).apportionForm && typeof (item as Record).apportionForm === "object" + ? (item as Record).apportionForm as Record + : (item as Record); + + const subParts: string[] = []; + let percent = form.apportionPercent || form.percent; + if (percent !== undefined && percent !== null && percent !== "") { + const pStr = String(percent); + subParts.push(`分摊比例=${pStr.endsWith("%") ? pStr : `${pStr}%`}`); + } + const money = form.apportionMoney || form.money || form.amount; + if (money !== undefined && money !== null) { + subParts.push(`分摊金额=${formatAmountValue(money)}`); + } + const dept = form.expenseDepartment || form.department; + if (dept) { + subParts.push(`报销部门=${formatDepartmentValue(dept, departmentMap)}`); + } + if (subParts.length > 0) { + parts.push(subParts.join(";")); + } + } + return parts.join(" | "); +} + +// ── 8. 明细发票列表行内格式化 ───────────────────────────────────────────────── + +export function formatInlineInvoices(invoices: unknown[]): string[] { + if (!Array.isArray(invoices) || invoices.length === 0) return []; + const lines: string[] = []; + lines.push(`- **发票列表**(${invoices.length}):`); + + invoices.forEach((invItem: any, idx: number) => { + const num = idx + 1; + const inv = invItem.invoice || invItem; + const verify = inv.verifyResult || inv; + const fileInfo = inv.fileInfo || {}; + const code = inv.invoiceCode || inv.invoiceNo || inv.invoiceNumber || verify.invoiceNo || inv.invoiceId || `发票-${num}`; + const fileId = fileInfo.fileId || inv.fileId || inv.invoiceId || ""; + const fileName = fileInfo.fileName || inv.fileName || ""; + const fileType = fileInfo.fileType || inv.fileType || "invoice"; + const invoiceDate = formatDateValue(inv.invoiceDate || verify.invoiceDate); + const verifyStatus = inv.verifyState || verify.verifyStatus || "verified"; + const buyer = verify.buyer || inv.buyer || ""; + const buyerTax = verify.buyerTaxNo || inv.buyerTaxNo || ""; + const seller = verify.seller || inv.seller || ""; + const sellerTax = verify.sellerTaxNo || inv.sellerTaxNo || ""; + const invoiceType = inv.invoiceType || verify.invoiceType || "电子发票"; + const totalAmount = formatAmountValue(inv.approveAmount || inv.totalAmount || verify.amount || inv.amount); + const taxAmount = formatAmountValue(inv.taxAmount || verify.taxAmount); + + lines.push(` ${num}. **发票号码: ${code}**`); + if (fileId) lines.push(` 原始文件fileId: ${fileId}`); + if (fileName) lines.push(` 原始文件名: ${fileName}`); + if (fileType) lines.push(` 原始文件类型: ${fileType}`); + if (invoiceDate) lines.push(` 发票日期: ${invoiceDate}`); + if (verifyStatus) lines.push(` 验真状态: ${verifyStatus}`); + if (buyer) lines.push(` 购方: ${buyer}${buyerTax ? `,税号: ${buyerTax}` : ""}`); + if (seller) lines.push(` 销方: ${seller}${sellerTax ? `,税号: ${sellerTax}` : ""}`); + if (invoiceType) lines.push(` 发票类型: ${invoiceType}`); + lines.push(` 价税合计: ${totalAmount}`); + if (taxAmount !== "CNY 0.00") lines.push(` 税额: ${taxAmount}`); + + const items = verify.items || inv.items; + if (Array.isArray(items) && items.length > 0) { + lines.push(` 发票明细(${items.length}):`); + for (const it of items) { + lines.push(` - ${JSON.stringify(it)}`); + } + } + }); + + return lines; +} + +// ── 9. 明细附件列表行内格式化 ───────────────────────────────────────────────── + +export function formatInlineAttachments(attachments: unknown[]): string[] { + if (!Array.isArray(attachments) || attachments.length === 0) return []; + const valid = attachments.filter((item): item is Record => Boolean(item && typeof item === "object")); + if (valid.length === 0) return []; + + const lines: string[] = []; + lines.push(`- **附件Attachment**:`); + valid.forEach((att: any, idx: number) => { + const num = idx + 1; + const name = att.fileName || att.name || "未命名附件"; + const fileId = att.fileId ? ` (fileId="${att.fileId}")` : ""; + lines.push(` ${num}. \`${name}\`${fileId}`); + }); + return lines; +} + +// ── 10. 模板名称标准化 ──────────────────────────────────────────────────────── + +export function resolveSpecificationName(specId: unknown): string { if (!specId || typeof specId !== "string") return "未知模板"; if (specId.includes("REQUISITION_TRIP") || specId.includes("trip")) return "差旅申请单"; if (specId.includes("REIMBURSEMENT") || specId.includes("expense")) return "报销单"; if (specId.includes("LOAN") || specId.includes("loan")) return "借款单"; - if (specId.includes("PAYMENT") || specId.includes("payment")) return "对公付款单"; + if (specId.includes("PAYMENT") || specId.includes("payment")) return "对公付款"; return specId; } +// ── 11. 动态表单字段过滤与格式化 ────────────────────────────────────────────── + +const BUILTIN_SYSTEM_KEYS = new Set([ + "code", "title", "specificationId", "details", "itineraries", "logs", "flowPlanId", + "actions", "threadId", "pipeline", "grayver", "dbVersion", "active", "version", + "sourceSign", "createTime", "updateTime", "printState", "printCount", "onlyOwnerPrint", + "ownerAndApproverPrintNodeFlag", "rejectionNum", "reviewStatus", "voucherStatus", + "voucherCreateTime", "preApprovedNodeName", "preNodeApprovedTime", "submitterId", + "expenseDate", "requisitionDate", "submitDate", "description", "expenseMoney", + "payMoney", "amount", "requisitionMoney", "companyRealPay", "writtenOffMoney", + "法人实体", "expenseDepartment", "u_提交人部门", "voucherNo", "payeeId", + "u_发票金额", "u_本单税额", "u_本单不含税", "u_是否有纸质票据", "u_经常交易供应商" +]); + +export function formatDynamicField( + key: string, + val: unknown, + options?: TranslatorOptions +): { label: string; text: string } | undefined { + if (BUILTIN_SYSTEM_KEYS.has(key)) return undefined; + if (val === null || val === undefined || val === "") return undefined; + + let label = options?.dictionary?.get(key)?.label || key.replace(/^u_/, ""); + const lowerKey = key.toLowerCase(); + + let text: string; + if (lowerKey.includes("money") || lowerKey.includes("amount") || lowerKey.includes("金额") || lowerKey.includes("税额")) { + text = formatAmountValue(val); + } else if (lowerKey.includes("date") || lowerKey.includes("time") || lowerKey.includes("日期") || lowerKey.includes("时间")) { + text = formatDateValue(val); + } else if (lowerKey.includes("department") || lowerKey.includes("部门")) { + text = formatDepartmentValue(val, options?.departmentMap); + } else if (lowerKey.includes("person") || lowerKey.includes("staff") || lowerKey.includes("submitter")) { + text = formatPersonValue(val, options?.staffMap); + } else { + text = formatReferenceOrObject(val, options?.dimensionItemMap); + } + + if (!text) return undefined; + return { label, text }; +} + +// ── 12. 主入口:全量单据流转译 Markdown ─────────────────────────────────────── + /** * 将合思原始单据流对象转译为标准 LLM / 审核视图 Markdown (单据字段转译器) */ export function translateBillFlowToMarkdown( rawFlow: Record, - feeTypeMap?: Map + options?: TranslatorOptions ): string { const flowIdObj = (rawFlow.flowId && typeof rawFlow.flowId === "object" ? rawFlow.flowId : rawFlow) as Record; const form = (flowIdObj.form && typeof flowIdObj.form === "object" ? flowIdObj.form : {}) as Record; @@ -94,11 +377,10 @@ export function translateBillFlowToMarkdown( const title = form.title || flowIdObj.title || "<无标题>"; const rawState = flowIdObj.state || "approving"; const stateLabel = String(rawState).toUpperCase() === "APPROVING" ? "审批中" : rawState; - const submitTime = formatDate(form.submitDate || flowIdObj.createTime); + const submitTime = formatDateValue(form.submitDate || flowIdObj.createTime); const templateName = resolveSpecificationName(form.specificationId); - const submitterName = form.submitterId?.name || (typeof form.submitterId === "string" ? form.submitterId : "未知"); - const requisitionDate = formatDate(form.requisitionDate); - const totalMoney = formatAmount(form.requisitionMoney || form.amount); + const submitterName = formatPersonValue(form.submitterId, options?.staffMap); + const requisitionDate = formatDateValue(form.requisitionDate || form.expenseDate); const lines: string[] = []; lines.push(`# 单据:${code}`); @@ -113,15 +395,99 @@ export function translateBillFlowToMarkdown( lines.push(`- **单据模板**: \`${templateName}\``); lines.push(`- **补充申请**: <无>`); lines.push(`- **标题**: \`${title}\``); - lines.push(`- **提交人**: ${submitterName}`); if (requisitionDate) { lines.push(`- **申请日期**: ${requisitionDate}`); } + lines.push(`- **提交人**: ${submitterName}`); + + // 法人实体 + const legalEntityVal = form.法人实体 ?? form.legalEntity; + if (legalEntityVal) { + const formattedEntity = formatReferenceOrObject(legalEntityVal, options?.dimensionItemMap); + lines.push(`- **法人实体**: ${formattedEntity}`); + } else if (options?.corpName) { + lines.push(`- **法人实体**: ${options.corpName}`); + } + + // 部门 + const expenseDept = form.expenseDepartment; + if (expenseDept) { + lines.push(`- **费用承担部门**: ${formatDepartmentValue(expenseDept, options?.departmentMap)}`); + } + const submitterDept = form.u_提交人部门 ?? form.submitterDepartment; + if (submitterDept) { + lines.push(`- **提交人部门**: ${formatDepartmentValue(submitterDept, options?.departmentMap)}`); + } + + // 事由说明 + const desc = form.description || form.reason; + if (desc) { + lines.push(`- **事由**: \`${desc}\``); + } + + // 是否有纸质票据 + const paperInvoice = form.u_是否有纸质票据; + if (paperInvoice !== undefined && paperInvoice !== null && paperInvoice !== "") { + lines.push(`- **是否有纸质票据**: ${formatReferenceOrObject(paperInvoice, options?.dimensionItemMap)}`); + } + + // 经常交易供应商 + const vendor = form.u_经常交易供应商 ?? form.payeeId; + if (vendor) { + lines.push(`- **经常交易供应商**: ${formatReferenceOrObject(vendor, options?.dimensionItemMap)}`); + } + + // 收款信息 + const payeeAccount = form.payeeAccountId ?? form.payeeInfo; + if (payeeAccount) { + lines.push(`- **收款信息**: ${formatReferenceOrObject(payeeAccount, options?.dimensionItemMap)}`); + } + + // 发票金额-总、税额、不含税 + if (form.u_发票金额) { + lines.push(`- **发票金额-总**: ${formatAmountValue(form.u_发票金额)}`); + } + if (form.u_本单税额) { + lines.push(`- **本单税额**: ${formatAmountValue(form.u_本单税额)}`); + } + if (form.u_本单不含税) { + lines.push(`- **本单不含税**: ${formatAmountValue(form.u_本单不含税)}`); + } + + // 动态扩展字段追加 + for (const [k, v] of Object.entries(form)) { + const formatted = formatDynamicField(k, v, options); + if (formatted) { + lines.push(`- **${formatted.label}**: ${formatted.text}`); + } + } + lines.push(`- **单号**: \`${code}\``); + if (form.payMoney) { + lines.push(`- **支付金额**: ${formatAmountValue(form.payMoney)}`); + } lines.push(`- **提交日期**: ${submitTime}`); - lines.push(`- **申请金额**: ${totalMoney}`); + + const mainAmount = form.requisitionMoney || form.amount || form.expenseMoney; + lines.push(`- **申请金额**: ${formatAmountValue(mainAmount)}`); + if (form.expenseMoney && form.payMoney) { + lines.push(`- **报销金额**: ${formatAmountValue(form.expenseMoney)}`); + } + if (form.companyRealPay !== undefined) { + lines.push(`- **公司实付金额**: ${formatAmountValue(form.companyRealPay)}`); + } + if (form.writtenOffMoney !== undefined) { + lines.push(`- **核销金额**: ${formatAmountValue(form.writtenOffMoney)}`); + } lines.push(""); + // 关联申请 + const requisitions = Array.isArray(form.requisitionIds) ? form.requisitionIds : []; + if (requisitions.length > 0) { + lines.push(`### 关联申请(共 ${requisitions.length} 条)`); + lines.push(""); + } + // 行程规划 const itineraries = Array.isArray(form.itineraries) ? form.itineraries : []; lines.push(`### 行程规划(共 ${itineraries.length} 条)`); @@ -142,8 +508,8 @@ export function translateBillFlowToMarkdown( let feeTypeName = "住宿费"; let feeTypePath = "差旅报销/住宿费"; - if (feeTypeMap?.has(feeTypeId)) { - const match = feeTypeMap.get(feeTypeId)!; + if (options?.feeTypeMap?.has(feeTypeId)) { + const match = options.feeTypeMap.get(feeTypeId)!; feeTypeName = match.name || feeTypeName; feeTypePath = match.path || feeTypeName; } else if (typeof feeTypeId === "string") { @@ -156,25 +522,61 @@ export function translateBillFlowToMarkdown( } else if (feeTypeId.includes("traffic") || feeTypeId.includes("交通")) { feeTypeName = "市内交通费"; feeTypePath = "差旅报销/市内交通费"; + } else if (feeTypeId.includes("3iPhCno9HdI") || feeTypeId.includes("办公")) { + feeTypeName = "办公用品"; + feeTypePath = "办公费/办公用品"; } } lines.push(`- **费用类型**: ${feeTypePath}(name=${feeTypeName})`); - lines.push(`- **金额**: ${formatAmount(feeForm.amount)}`); if (feeForm.feeDate) { - lines.push(`- **日期**: ${formatDateTime(feeForm.feeDate)}`); + lines.push(`- **日期**: ${formatDateValue(feeForm.feeDate, true)}`); } - const city = parseCity(feeForm.city); + lines.push(`- **金额**: ${formatAmountValue(feeForm.amount)}`); + + // 明细发票列表(内嵌相对位置) + const invoiceList = feeForm.invoiceForm?.invoices || feeForm.invoices; + if (Array.isArray(invoiceList) && invoiceList.length > 0) { + lines.push(...formatInlineInvoices(invoiceList)); + } + + const city = parseCityValue(feeForm.city); if (city) { lines.push(`- **城市**: ${city}`); } if (feeForm.consumptionReasons) { lines.push(`- **消费事由**: \`${feeForm.consumptionReasons}\``); } + if (feeForm.invoice) { + lines.push(`- **发票张数**: ${feeForm.invoice}`); + } + if (feeForm.u_发票金额) { + lines.push(`- **发票金额**: ${formatAmountValue(feeForm.u_发票金额)}`); + } + if (feeForm.taxAmount) { + lines.push(`- **税额**: ${formatAmountValue(feeForm.taxAmount)}`); + } + + // 明细费用归属分摊 + if (Array.isArray(feeForm.apportions) && feeForm.apportions.length > 0) { + lines.push(`- **费用归属分摊**: ${formatApportionSplits(feeForm.apportions, options?.departmentMap)}`); + } + + // 明细自定义业务字段 + if (feeForm.u_业务类型) { + lines.push(`- **业务类型**: ${formatReferenceOrObject(feeForm.u_业务类型, options?.dimensionItemMap)}`); + } + if (feeForm.detailId) { lines.push(`- **费用ID**: \`${feeForm.detailId}\``); } lines.push(`- **明细序号**: ${feeForm.detailNo || num}`); + + // 明细附件列表(内嵌相对位置) + if (Array.isArray(feeForm.attachments) && feeForm.attachments.length > 0) { + lines.push(...formatInlineAttachments(feeForm.attachments)); + } + lines.push(""); });