735 lines
32 KiB
TypeScript
735 lines
32 KiB
TypeScript
export interface TranslatorOptions {
|
||
feeTypeMap?: Map<string, { name?: string; path?: string }>;
|
||
staffMap?: Map<string, Record<string, unknown>>;
|
||
departmentMap?: Map<string, { path?: string; item?: Record<string, unknown> }>;
|
||
dimensionItemMap?: Map<string, { name?: string; code?: string; label?: string; path?: string }>;
|
||
dictionary?: Map<string, { label: string; type?: string }>;
|
||
corpName?: string;
|
||
}
|
||
|
||
// ── 1. 金额格式化 ─────────────────────────────────────────────────────────────
|
||
|
||
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 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 obj = money as Record<string, unknown>;
|
||
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);
|
||
}
|
||
|
||
// ── 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<string, string> = {};
|
||
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, Record<string, unknown>>
|
||
): 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<string, unknown>;
|
||
const name = (obj.name || obj.nickName || obj.staffName || "") as string;
|
||
const code = obj.code ? `(${obj.code})` : "";
|
||
if (name) return `${name}${code}`;
|
||
}
|
||
return String(val);
|
||
}
|
||
|
||
export interface TranslatorOptions {
|
||
corpName?: string;
|
||
feeTypeMap?: Map<string, { name?: string; path?: string }>;
|
||
staffMap?: Map<string, Record<string, unknown>>;
|
||
departmentMap?: Map<string, { path?: string; item?: Record<string, unknown> }>;
|
||
dimensionItemMap?: Map<string, { name?: string; code?: string; label?: string; path?: string }>;
|
||
invoiceDetailMap?: Map<string, Record<string, unknown>>;
|
||
datalinkCardMap?: Map<string, string>;
|
||
}
|
||
|
||
const BILL_FLOW_ACTION_LABELS: Record<string, string> = {
|
||
"freeflow.submit": "提交送审",
|
||
"freeflow.agree": "审批同意",
|
||
"freeflow.autoAgree": "自动同意",
|
||
"freeflow.reject": "审批驳回",
|
||
"freeflow.print": "打印单据",
|
||
"freeflow.retract": "单据撤回",
|
||
"freeflow.addnode": "加签/转交",
|
||
"freeflow.comment": "发表评论",
|
||
};
|
||
|
||
const BILL_FLOW_STATE_LABELS: Record<string, string> = {
|
||
APPROVING: "审批中",
|
||
APPROVED: "审批通过",
|
||
REJECTED: "审批驳回",
|
||
REVOKED: "已撤回",
|
||
CANCELED: "已取消",
|
||
CANCELLED: "已取消",
|
||
SKIPPED: "已跳过",
|
||
SUBMITTED: "已提交",
|
||
PENDING: "待审批",
|
||
WAITING: "待处理",
|
||
COMPLETED: "已完成",
|
||
DRAFT: "草稿",
|
||
};
|
||
|
||
export function translateBillFlowAction(action?: string): string | undefined {
|
||
if (!action) return undefined;
|
||
return BILL_FLOW_ACTION_LABELS[action] || action;
|
||
}
|
||
|
||
export function translateBillFlowState(state?: string): string | undefined {
|
||
if (!state) return undefined;
|
||
return BILL_FLOW_STATE_LABELS[state.toUpperCase()] || state;
|
||
}
|
||
|
||
export function formatBillFlowOperator(
|
||
operator?: { id?: string; name?: string },
|
||
automatic = false,
|
||
isEbot = false
|
||
): string {
|
||
const raw = `${operator?.id || ""} ${operator?.name || ""}`.toLowerCase();
|
||
if (isEbot || raw.includes("ebot")) return "Ebot (智能审批)";
|
||
return operator?.name || (automatic ? "系统" : "-");
|
||
}
|
||
|
||
// ── 5. 部门全路径格式化 ───────────────────────────────────────────────────────
|
||
|
||
export function formatDepartmentValue(
|
||
val: unknown,
|
||
departmentMap?: Map<string, { path?: string; item?: Record<string, unknown> }>
|
||
): 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<string, unknown>;
|
||
const id = (obj.id || obj.deptId || obj.departmentId || "") as string;
|
||
if (id) {
|
||
const match = departmentMap?.get(id) ?? departmentMap?.get(id.split(":").at(-1) ?? id);
|
||
if (match?.path) return match.path;
|
||
if (match?.item?.name) return match.item.name as string;
|
||
}
|
||
return (obj.fullPath || obj.path || obj.name || "") as string;
|
||
}
|
||
return String(val);
|
||
}
|
||
|
||
// ── 6. 复杂对象与引用字典格式化 (供应商/银行卡号/枚举/档案项) ──────────────────
|
||
|
||
export function formatReferenceOrObject(
|
||
val: unknown,
|
||
dimensionMap?: Map<string, { name?: string; code?: string; label?: string; path?: string }>,
|
||
datalinkCardMap?: Map<string, string>
|
||
): 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 (datalinkCardMap?.has(trimmed)) {
|
||
return datalinkCardMap.get(trimmed)!;
|
||
}
|
||
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, datalinkCardMap)).join(";");
|
||
}
|
||
|
||
if (typeof val === "object") {
|
||
const obj = val as Record<string, unknown>;
|
||
// 金额对象判断
|
||
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, { path?: string; item?: Record<string, unknown> }>
|
||
): 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<string, unknown>).apportionForm && typeof (item as Record<string, unknown>).apportionForm === "object"
|
||
? (item as Record<string, unknown>).apportionForm as Record<string, unknown>
|
||
: (item as Record<string, unknown>);
|
||
|
||
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[],
|
||
invoiceDetailMap?: Map<string, Record<string, 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 rawInvoiceId = String(inv.invoiceId || inv.id || "");
|
||
const detailFromMap = (rawInvoiceId && invoiceDetailMap?.get(rawInvoiceId)) || undefined;
|
||
const master = detailFromMap?.master as Record<string, unknown> | undefined;
|
||
const masterForm = (master?.form as Record<string, unknown>) || {};
|
||
const goodsDetails = Array.isArray(detailFromMap?.details) ? detailFromMap.details : [];
|
||
|
||
const verify = inv.verifyResult || inv;
|
||
const fileInfo = inv.fileInfo || {};
|
||
let code = inv.invoiceCode || inv.invoiceNo || inv.invoiceNumber || verify.invoiceNo || (masterForm["E_system_发票主体_发票号码"] as string) || inv.invoiceId || `发票-${num}`;
|
||
if (typeof code === "string" && code.includes("::")) {
|
||
code = code.split("::").at(-1) || code;
|
||
}
|
||
|
||
const fileId = fileInfo.fileId || inv.fileId || inv.invoiceId || "";
|
||
let fileName = fileInfo.fileName || inv.fileName || "";
|
||
if (!fileName && masterForm["E_system_发票主体_图片"]) {
|
||
try {
|
||
fileName = decodeURIComponent(String(masterForm["E_system_发票主体_图片"]));
|
||
} catch {
|
||
fileName = String(masterForm["E_system_发票主体_图片"]);
|
||
}
|
||
}
|
||
const fileType = fileInfo.fileType || inv.fileType || "invoice";
|
||
const rawDate = inv.invoiceDate || verify.invoiceDate || masterForm["E_system_发票主体_发票日期"];
|
||
const invoiceDate = formatDateValue(rawDate);
|
||
const verifyStatus = inv.verifyState || verify.verifyStatus || (masterForm["E_system_发票主体_验真"] ? "verified" : undefined) || "verified";
|
||
const buyer = verify.buyer || inv.buyer || masterForm["E_system_发票主体_购买方名称"] || "";
|
||
const buyerTax = verify.buyerTaxNo || inv.buyerTaxNo || masterForm["E_system_发票主体_购买方纳税人识别号"] || "";
|
||
const seller = verify.seller || inv.seller || masterForm["E_system_发票主体_销售方名称"] || "";
|
||
const sellerTax = verify.sellerTaxNo || inv.sellerTaxNo || masterForm["E_system_发票主体_销售方纳税人识别号"] || "";
|
||
|
||
let invoiceType = inv.invoiceType || verify.invoiceType;
|
||
if (!invoiceType && masterForm["E_system_发票主体_发票类别"]) {
|
||
const cat = String(masterForm["E_system_发票主体_发票类别"]);
|
||
if (cat.includes("SPECIAL") || cat.includes("专票")) {
|
||
invoiceType = "电子发票(增值税专用发票)";
|
||
} else {
|
||
invoiceType = "电子发票";
|
||
}
|
||
}
|
||
invoiceType = invoiceType || "电子发票";
|
||
|
||
const remark = (masterForm["E_system_发票主体_备注"] as string) || inv.remark || "";
|
||
const totalAmount = formatAmountValue(inv.approveAmount || inv.totalAmount || verify.amount || inv.amount || masterForm["E_system_发票主体_价税合计"]);
|
||
const taxAmount = formatAmountValue(inv.taxAmount || verify.taxAmount || masterForm["E_system_发票主体_税额"]);
|
||
|
||
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}`);
|
||
if (remark) lines.push(` 备注: ${remark}`);
|
||
lines.push(` 价税合计: ${totalAmount}`);
|
||
if (taxAmount && taxAmount !== "CNY 0.00") lines.push(` 税额: ${taxAmount}`);
|
||
|
||
const items = verify.items || inv.items || (goodsDetails.length > 0 ? goodsDetails.map((gd: any) => {
|
||
const f = gd.form || {};
|
||
return {
|
||
名称: gd.name || f["E_system_发票明细_name"] || "",
|
||
单位: f["E_system_发票明细_单位"] || "",
|
||
数量: String(f["E_system_发票明细_数量"] || ""),
|
||
单价: formatAmountValue(f["E_system_发票明细_单价"]),
|
||
金额: formatAmountValue(f["E_system_发票明细_金额"]),
|
||
税率: f["E_system_发票明细_税率"] || "",
|
||
税额: formatAmountValue(f["E_system_发票明细_税额"]),
|
||
};
|
||
}) : undefined);
|
||
|
||
if (Array.isArray(items) && items.length > 0) {
|
||
lines.push(` 发票明细(${items.length}):`);
|
||
for (const it of items) {
|
||
lines.push(` - ${JSON.stringify(it)}`);
|
||
}
|
||
}
|
||
|
||
if (master && Object.keys(masterForm).length > 0) {
|
||
const invInfoObj = {
|
||
销售方地址电话: masterForm["E_system_发票主体_销售方地址电话"] || "",
|
||
是否有发票原件: masterForm["E_system_发票主体_是否有发票原件"] ? "是" : "否",
|
||
收票状态: masterForm["E_system_收票状态"] || "NORECEIVE",
|
||
可抵扣税额: formatAmountValue(masterForm["E_税额"] || masterForm["E_system_发票主体_税额"]),
|
||
名称: masterForm["E_system_发票主体_name"] || code,
|
||
发票号码: code,
|
||
发票日期: invoiceDate,
|
||
购买方名称: buyer,
|
||
购买方纳税人识别号: buyerTax,
|
||
发票金额: formatAmountValue(masterForm["E_不计税金额"] || masterForm["E_system_发票主体_发票金额"]),
|
||
税额: taxAmount,
|
||
价税合计: totalAmount,
|
||
销售方名称: seller,
|
||
销售方纳税人识别号: sellerTax,
|
||
销售方开户行及账号: masterForm["E_system_发票主体_销售方开户行及账号"] || "",
|
||
备注: remark,
|
||
发票类别: invoiceType,
|
||
不计税金额: formatAmountValue(masterForm["E_不计税金额"] || masterForm["E_system_发票主体_发票金额"]),
|
||
发票状态: masterForm["E_system_发票主体_发票状态"] || "NORMAL_BLUE",
|
||
是否电子票: masterForm["E_system_发票主体_是否电子票"] ? "是" : "否",
|
||
};
|
||
lines.push(` 发票信息: ${JSON.stringify(invInfoObj)}`);
|
||
}
|
||
});
|
||
|
||
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<string, unknown> => 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) return "未知模板";
|
||
if (typeof specId === "object") {
|
||
const obj = specId as Record<string, unknown>;
|
||
if (typeof obj.name === "string" && obj.name) return obj.name;
|
||
if (typeof obj.id === "string") return resolveSpecificationName(obj.id);
|
||
}
|
||
if (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 "对公付款";
|
||
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 as any)?.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, options?.datalinkCardMap);
|
||
}
|
||
|
||
if (!text) return undefined;
|
||
return { label, text };
|
||
}
|
||
|
||
// ── 12. 主入口:全量单据流转译 Markdown ───────────────────────────────────────
|
||
|
||
/**
|
||
* 将合思原始单据流对象转译为标准 LLM / 审核视图 Markdown (单据字段转译器)
|
||
*/
|
||
export function translateBillFlowToMarkdown(
|
||
rawFlow: Record<string, unknown>,
|
||
options?: TranslatorOptions
|
||
): string {
|
||
const flowIdObj = (rawFlow.flowId && typeof rawFlow.flowId === "object" ? rawFlow.flowId : rawFlow) as Record<string, any>;
|
||
const form = (flowIdObj.form && typeof flowIdObj.form === "object" ? flowIdObj.form : {}) as Record<string, any>;
|
||
|
||
const code = form.code || flowIdObj.code || "未知单号";
|
||
const title = form.title || flowIdObj.title || "<无标题>";
|
||
const rawState = flowIdObj.state || "approving";
|
||
const stateLabel = String(rawState).toUpperCase() === "APPROVING" ? "审批中" : rawState;
|
||
const submitTime = formatDateValue(form.submitDate || flowIdObj.createTime);
|
||
const templateName = resolveSpecificationName(form.specificationId);
|
||
const submitterName = formatPersonValue(form.submitterId, options?.staffMap);
|
||
const requisitionDate = formatDateValue(form.requisitionDate || form.expenseDate);
|
||
|
||
const lines: string[] = [];
|
||
lines.push(`# 单据:${code}`);
|
||
lines.push("");
|
||
lines.push("## 基本信息");
|
||
lines.push("");
|
||
lines.push(`- **状态**: ${stateLabel} (${String(rawState).toLowerCase()})`);
|
||
lines.push(`- **提交时间**: ${submitTime}`);
|
||
lines.push("");
|
||
lines.push(`### 单据信息(${code})`);
|
||
lines.push("");
|
||
lines.push(`- **单据模板**: \`${templateName}\``);
|
||
lines.push(`- **补充申请**: <无>`);
|
||
lines.push(`- **标题**: \`${title}\``);
|
||
if (requisitionDate) {
|
||
lines.push(`- **申请日期**: ${requisitionDate}`);
|
||
}
|
||
lines.push(`- **提交人**: ${submitterName}`);
|
||
|
||
// 法人实体
|
||
const legalEntityVal = form.法人实体 ?? form.legalEntity;
|
||
if (legalEntityVal) {
|
||
const formattedEntity = formatReferenceOrObject(legalEntityVal, options?.dimensionItemMap, options?.datalinkCardMap);
|
||
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, options?.datalinkCardMap)}`);
|
||
}
|
||
|
||
// 经常交易供应商
|
||
const vendor = form.u_经常交易供应商 ?? form.payeeId;
|
||
if (vendor) {
|
||
lines.push(`- **经常交易供应商**: ${formatReferenceOrObject(vendor, options?.dimensionItemMap, options?.datalinkCardMap)}`);
|
||
}
|
||
|
||
// 收款信息
|
||
const payeeAccount = form.payeeAccountId ?? form.payeeInfo;
|
||
if (payeeAccount) {
|
||
lines.push(`- **收款信息**: ${formatReferenceOrObject(payeeAccount, options?.dimensionItemMap, options?.datalinkCardMap)}`);
|
||
} else if (vendor && typeof vendor === "string" && options?.datalinkCardMap?.has(`payeeInfo:${vendor}`)) {
|
||
lines.push(`- **收款信息**: ${options.datalinkCardMap.get(`payeeInfo:${vendor}`)}`);
|
||
}
|
||
|
||
// 发票金额-总、税额、不含税
|
||
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}`);
|
||
|
||
if (form.requisitionMoney) {
|
||
lines.push(`- **申请金额**: ${formatAmountValue(form.requisitionMoney)}`);
|
||
}
|
||
if (form.expenseMoney) {
|
||
lines.push(`- **报销金额**: ${formatAmountValue(form.expenseMoney)}`);
|
||
} else if (!form.requisitionMoney && (form.amount || form.payMoney)) {
|
||
lines.push(`- **申请金额**: ${formatAmountValue(form.amount || form.payMoney)}`);
|
||
}
|
||
|
||
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 : [];
|
||
lines.push(`### 关联申请(共 ${requisitions.length} 条)`);
|
||
lines.push("");
|
||
|
||
// 行程规划 (仅在有行程时输出)
|
||
const itineraries = Array.isArray(form.itineraries) ? form.itineraries : [];
|
||
if (itineraries.length > 0) {
|
||
lines.push(`### 行程规划(共 ${itineraries.length} 条)`);
|
||
lines.push("");
|
||
}
|
||
|
||
// 费用明细
|
||
const details = Array.isArray(form.details) ? form.details : [];
|
||
lines.push(`### 费用明细(共 ${details.length} 条)`);
|
||
lines.push("");
|
||
|
||
details.forEach((item: any, idx: number) => {
|
||
const num = idx + 1;
|
||
lines.push(`#### 明细 ${num}`);
|
||
lines.push("");
|
||
|
||
const feeForm = item.feeTypeForm || item;
|
||
const feeTypeId = item.feeTypeId || feeForm.feeTypeId || "";
|
||
let feeTypeName = "住宿费";
|
||
let feeTypePath = "差旅报销/住宿费";
|
||
|
||
if (options?.feeTypeMap?.has(feeTypeId)) {
|
||
const match = options.feeTypeMap.get(feeTypeId)!;
|
||
feeTypeName = match.name || feeTypeName;
|
||
feeTypePath = match.path || feeTypeName;
|
||
} else if (typeof feeTypeId === "string") {
|
||
if (feeTypeId.includes("hotel") || feeTypeId.includes("住宿")) {
|
||
feeTypeName = "住宿费";
|
||
feeTypePath = "差旅报销/住宿费";
|
||
} else if (feeTypeId.includes("meal") || feeTypeId.includes("餐")) {
|
||
feeTypeName = "餐饮费";
|
||
feeTypePath = "业务招待/餐饮费";
|
||
} else if (feeTypeId.includes("traffic") || feeTypeId.includes("交通")) {
|
||
feeTypeName = "市内交通费";
|
||
feeTypePath = "差旅报销/市内交通费";
|
||
} else if (feeTypeId.includes("3iPhCno9HdI") || feeTypeId.includes("办公")) {
|
||
feeTypeName = "办公用品";
|
||
feeTypePath = "办公费/办公用品";
|
||
}
|
||
}
|
||
|
||
lines.push(`- **费用类型**: ${feeTypePath}(name=${feeTypeName})`);
|
||
if (feeForm.feeDate) {
|
||
lines.push(`- **日期**: ${formatDateValue(feeForm.feeDate, true)}`);
|
||
}
|
||
lines.push(`- **金额**: ${formatAmountValue(feeForm.amount)}`);
|
||
|
||
// 明细发票列表(内嵌相对位置)
|
||
const invoiceList = feeForm.invoiceForm?.invoices || feeForm.invoices;
|
||
if (Array.isArray(invoiceList) && invoiceList.length > 0) {
|
||
lines.push(...formatInlineInvoices(invoiceList, options?.invoiceDetailMap));
|
||
}
|
||
|
||
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("");
|
||
});
|
||
|
||
return lines.join("\n");
|
||
}
|