来源仓库:jxc/ai-fresh-delivery 来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d 快照树: 09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件) 按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据 (生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、 deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
736 lines
40 KiB
TypeScript
736 lines
40 KiB
TypeScript
import type { DeliveryHtmlTemplate, DeliveryHtmlTemplateLayout } from './deliveryHtmlTemplates';
|
||
import { orderCodeDisplayLabel } from './orderCodeDisplay';
|
||
import { resolveTopCategory, sortLinesByCategory } from './deliveryNotePrint';
|
||
import { applyLayoutTargets } from './deliveryTemplateLayout';
|
||
import type { DeliveryNotePrintGroup, DeliveryPrintLine, DeliveryPrintOrderHeader } from './deliveryNotePrint';
|
||
|
||
const ALLOWED_TAGS = new Set(['DIV', 'SPAN', 'TABLE', 'THEAD', 'TBODY', 'TFOOT', 'TR', 'TH', 'TD', 'P', 'STRONG', 'BR', 'HR', 'H1', 'H2', 'H3']);
|
||
const ALLOWED_STYLE_PROPERTIES = new Set([
|
||
'width', 'min-width', 'max-width', 'height', 'min-height', 'max-height', 'margin', 'margin-top',
|
||
'margin-right', 'margin-bottom', 'margin-left', 'padding', 'padding-top', 'padding-right',
|
||
'padding-bottom', 'padding-left', 'font-family', 'font-size', 'font-weight', 'font-style',
|
||
'line-height', 'color', 'background-color', 'border', 'border-top', 'border-right', 'border-bottom',
|
||
'border-left', 'border-collapse', 'border-spacing', 'text-align', 'vertical-align', 'display',
|
||
'table-layout', 'white-space', 'box-sizing', 'page-break-before', 'page-break-after', 'break-before',
|
||
'break-after',
|
||
]);
|
||
|
||
function safeStyle(style: string): string {
|
||
if (/url\s*\(|expression\s*\(|javascript:|@import|\\/i.test(style)) return '';
|
||
return style.split(';').map((declaration) => {
|
||
const colon = declaration.indexOf(':');
|
||
if (colon < 1) return '';
|
||
const key = declaration.slice(0, colon).trim().toLowerCase();
|
||
const value = declaration.slice(colon + 1).trim();
|
||
if (!ALLOWED_STYLE_PROPERTIES.has(key) || !value || /[<>]/.test(value)) return '';
|
||
return `${key}:${value}`;
|
||
}).filter(Boolean).join(';');
|
||
}
|
||
|
||
export function sanitizeDeliveryTemplateHtml(html: string): string {
|
||
const document = new DOMParser().parseFromString(`<body>${html}</body>`, 'text/html');
|
||
const clean = (parent: ParentNode) => {
|
||
Array.from(parent.childNodes).forEach((node) => {
|
||
if (node.nodeType !== Node.ELEMENT_NODE) return;
|
||
const element = node as HTMLElement;
|
||
if (!ALLOWED_TAGS.has(element.tagName)) {
|
||
element.remove();
|
||
return;
|
||
}
|
||
Array.from(element.attributes).forEach((attribute) => {
|
||
const key = attribute.name.toLowerCase();
|
||
if (key === 'style') {
|
||
const value = safeStyle(attribute.value);
|
||
if (value) element.setAttribute('style', value);
|
||
else element.removeAttribute('style');
|
||
} else if (!['class', 'colspan', 'rowspan'].includes(key)) {
|
||
element.removeAttribute(attribute.name);
|
||
}
|
||
});
|
||
clean(element);
|
||
});
|
||
};
|
||
clean(document.body);
|
||
return document.body.innerHTML;
|
||
}
|
||
|
||
export function sanitizeDeliveryTemplateCss(css: string): string {
|
||
if (/url\s*\(|expression\s*\(|javascript:|@import|behavior\s*:|-moz-binding/i.test(css)) return '';
|
||
return css.replace(/<[^>]*>/g, '').replace(/<\/?style/gi, '').replace(/<\/?script/gi, '').slice(0, 30_000);
|
||
}
|
||
|
||
function scopeDeliveryTemplateCss(css: string): string {
|
||
return css.replace(/([^{}]+)\{([^{}]*)\}/g, (rule, selectorText: string, declarations: string) => {
|
||
const selectorSource = selectorText.trim();
|
||
if (!selectorSource || selectorSource.startsWith('@')) return rule;
|
||
const selectors = selectorSource.split(',')
|
||
.map((selector) => selector.trim())
|
||
.filter((selector) => selector && !/^(html|body|:root)(?:\b|$)/i.test(selector))
|
||
.map((selector) => `.delivery-html-template-root ${selector}`);
|
||
return selectors.length ? `${selectors.join(', ')} {${declarations}}` : '';
|
||
});
|
||
}
|
||
|
||
function escapeHtml(value: unknown): string {
|
||
return String(value ?? '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');
|
||
}
|
||
|
||
/**
|
||
* 编辑器里**可选中 / 可改文字**的标签集合。
|
||
*
|
||
* ⚠️ 全站只有这一份编号方案:`addEditorNodeClasses` 用它给元素编 `dht-edit-node-N`,
|
||
* 页面里的「文字内容」用 `replaceStaticNodeText` 按同一个编号反查源码位置。
|
||
* 两边一旦用了不同的集合,索引就会整体错位 —— 事故(2026-10-06):AI 模板常在最外层写
|
||
* `<body>`,本集合不含 body 所以编辑器跳过它,而反查那侧当时按「任意标签」数,
|
||
* 于是整份模板偏 1:点「应用文字」要么改到隔壁元素,要么落在有子节点的容器上直接没反应
|
||
* (用户看到的就是「文字内容无法修改」)。
|
||
*/
|
||
export const DELIVERY_TEMPLATE_EDITOR_TAG_PATTERN = 'div|span|table|thead|tbody|tfoot|tr|th|td|p|strong|br|hr|h1|h2|h3';
|
||
|
||
/** 判定为「标题/标签」的纯静态文字长度上限(超过就当成正文,不做标题处理) */
|
||
const TITLE_LIKE_TEXT_MAX = 10;
|
||
|
||
/**
|
||
* 这个可编辑元素是否算「标题/标签」类(2026-10-07 用户要求:表单里的标题只能互换位置、不许自由摆放)。
|
||
*
|
||
* 判定(满足任一):
|
||
* 1. 标签是 `th`(表头单元格);
|
||
* 2. class 含 `title` / `label`(AI 生成的模板通常这么命名,如 category-title / doc-title / total-label);
|
||
* 3. 没有 class 的**纯静态短文字叶子**(无子元素、不含 `{{`、不含数字、去空白 ≤ 10 字),
|
||
* 如 `<td>备注</td>`、`<span>收货商户:</span>`。
|
||
*
|
||
* 判定偏保守:判不准时按「非标题」处理(保持自由摆放),免得把本该自由摆放的数据元素锁成互换。
|
||
* 只影响**编辑器拖动行为**,与渲染/打印无关。
|
||
*/
|
||
export function isTitleLikeEditorNode(
|
||
element: Element,
|
||
options?: { sourceHtml?: string; nodeId?: string }
|
||
): boolean {
|
||
if (!element) return false;
|
||
// 只有**表格里**的标题才「只能互换」(表头 th、分类标题、小计标签)。
|
||
// 表格外的(页眉大标题、收货商户/配送时间/仓号等标签、签字栏)要能**自由摆放**
|
||
// —— 2026-10-07 用户明确区分这两类:页眉那块不能锁成互换。
|
||
if (!element.closest('table')) return false;
|
||
if (element.tagName.toLowerCase() === 'th') return true;
|
||
const className = String((element as HTMLElement).className || '').toLowerCase();
|
||
if (className.includes('title') || className.includes('label')) return true;
|
||
// 规则 3 只认**模板源码里就是纯静态文字**的叶子:DOM 里 `{{字段}}` 已经渲染成文字了,
|
||
// 光看 DOM 会把「绵阳邮政分公司」「豆制品」这种**字段值**误判成标题(实测踩到过)。
|
||
if (!options?.sourceHtml || options.nodeId == null) return false;
|
||
const id = Number(options.nodeId);
|
||
if (!Number.isFinite(id)) return false;
|
||
if (element.children.length > 0) return false;
|
||
if (replaceStaticNodeText(options.sourceHtml, id, 'probe') === null) return false; // 含 {{…}} 或子元素
|
||
const text = String(element.textContent || '').replace(/\s+/g, '');
|
||
if (!text || text.length > TITLE_LIKE_TEXT_MAX) return false;
|
||
return !text.includes('{{') && !/[0-9]/.test(text);
|
||
}
|
||
|
||
/** 从元素的 class 里取编辑器节点编号(dht-edit-node-N);不是可编辑节点返回 null */
|
||
export function editorNodeIdOf(element: Element): string | null {
|
||
for (const name of Array.from(element.classList)) {
|
||
if (name.startsWith('dht-edit-node-')) return name.slice('dht-edit-node-'.length);
|
||
}
|
||
return null;
|
||
}
|
||
|
||
function addEditorNodeClasses(html: string): string {
|
||
let index = 0;
|
||
return html.replace(new RegExp(`<(${DELIVERY_TEMPLATE_EDITOR_TAG_PATTERN})\\b([^>]*)>`, 'gi'), (tag, name: string, attributes: string) => {
|
||
const nodeClass = `dht-edit-node-${index++}`;
|
||
const classMatch = attributes.match(/\bclass\s*=\s*(["'])(.*?)\1/i);
|
||
const nextAttributes = classMatch
|
||
? attributes.replace(classMatch[0], `class=${classMatch[1]}${classMatch[2]} ${nodeClass}${classMatch[1]}`)
|
||
: `${attributes} class="${nodeClass}"`;
|
||
return `<${name}${nextAttributes}>`;
|
||
});
|
||
}
|
||
|
||
function layoutCss(
|
||
layout: DeliveryHtmlTemplateLayout | undefined,
|
||
paper: DeliveryHtmlTemplate['paper'],
|
||
repeatedNodeIds: Set<string>
|
||
): string {
|
||
if (!layout) return '';
|
||
const contentWidthMm = Math.max(1, paper.widthMm - paper.marginMm * 2);
|
||
const contentHeightMm = Math.max(1, paper.heightMm - paper.marginMm * 2);
|
||
const mm = (value: number) => Number(value.toFixed(4));
|
||
const rules: string[] = [];
|
||
Object.entries(layout.nodes || {}).forEach(([id, value]) => {
|
||
if (!/^\d+$/.test(id)) return;
|
||
const declarations: string[] = [];
|
||
const xMm = Number.isFinite(value.xPercent) ? contentWidthMm * Number(value.xPercent) / 100 : Number(value.x) / 3.779527559;
|
||
const yMm = Number.isFinite(value.yPercent) ? contentHeightMm * Number(value.yPercent) / 100 : Number(value.y) / 3.779527559;
|
||
if (xMm || yMm) {
|
||
const flowAnchored = layout.anchoring === 'flow';
|
||
if (repeatedNodeIds.has(id) || flowAnchored) {
|
||
// 相对平移:元素保持文档流,各自平移固定距离。
|
||
// · 重复节点(循环体/分类组内):同一节点出现多次,只能整体平移,否则会叠在一起;
|
||
// · flow 语义(2026-10-07 起默认):坐标本就是「相对自然位置的偏移」,
|
||
// 于是合计/签字这类元素**跟着内容走** —— 真实行数不会把它钉死在样例行数时的高度。
|
||
//
|
||
// ⚠️ 只对**块级**元素有效:行内元素(`<span>`,例如按参考图做了坐标复刻的页眉
|
||
// 「订单备注:/收货日期:」标签)上的 transform **不生效**,这类元素在编辑器里就是
|
||
// **移不动**的。2026-10-07 三方确认后的决定:**不为行内元素做特殊处理**
|
||
// (曾试过 applyLayoutTargets 里的 inline→inline-block 升级、以及在样式表里直接升级,
|
||
// 都撤掉了)——改由提示词在源头避免(`deliveryTemplateOcrService.ts` 的 PROMPT 要求
|
||
// 「每一段会被单独调整的文字都必须是块级或 inline-block」)。详见
|
||
// docs/design/20261007-delivery-template-editor-layout-consistency.md。
|
||
declarations.push(`transform:translate(${mm(xMm)}mm,${mm(yMm)}mm) !important`);
|
||
}
|
||
// 仍未标 flow 的历史布局:唯一节点走「绝对目标位置」——坐标以 data 属性注入,
|
||
// 布局完成后由 applyLayoutTargets() 量出自然位置、算出位移做平移。
|
||
}
|
||
if (Number.isFinite(value.widthPercent) && Number(value.widthPercent) > 0) declarations.push(`width:${mm(contentWidthMm * Number(value.widthPercent) / 100)}mm !important`);
|
||
else if (Number.isFinite(value.width) && Number(value.width) > 0) declarations.push(`width:${Number(value.width)}px !important`);
|
||
if (Number.isFinite(value.heightPercent) && Number(value.heightPercent) > 0) declarations.push(`height:${mm(contentHeightMm * Number(value.heightPercent) / 100)}mm !important`);
|
||
else if (Number.isFinite(value.height) && Number(value.height) > 0) declarations.push(`height:${Number(value.height)}px !important`);
|
||
if (Number.isFinite(value.fontSize) && Number(value.fontSize) > 0) declarations.push(`font-size:${Number(value.fontSize)}px !important`);
|
||
if (Number.isFinite(value.fontWeight) && Number(value.fontWeight) >= 100) declarations.push(`font-weight:${Number(value.fontWeight)} !important`);
|
||
if (value.textAlign && ['left', 'center', 'right'].includes(value.textAlign)) declarations.push(`text-align:${value.textAlign} !important`);
|
||
if (value.hidden) declarations.push('display:none !important');
|
||
if (declarations.length) rules.push(`.delivery-html-template-root .dht-edit-node-${id}{${declarations.join(';')}}`);
|
||
});
|
||
(layout.additions || []).forEach((item) => {
|
||
const id = String(item.id || '').replace(/[^a-zA-Z0-9_-]/g, '');
|
||
if (!id) return;
|
||
const x = mm(Number.isFinite(item.xPercent) ? contentWidthMm * Number(item.xPercent) / 100 : Number(item.x) / 3.779527559);
|
||
const y = mm(Number.isFinite(item.yPercent) ? contentHeightMm * Number(item.yPercent) / 100 : Number(item.y) / 3.779527559);
|
||
rules.push(`.delivery-html-template-root .dht-added-${id}{position:absolute;left:${x}mm;top:${y}mm}`);
|
||
});
|
||
return rules.join('\n');
|
||
}
|
||
|
||
/** 分类分组块:{{#categories}} … {{/categories}}(内层再套 {{#items}}…{{/items}}) */
|
||
const CATEGORY_LOOP = /{{\s*#categories\s*}}([\s\S]*?){{\s*\/\s*categories\s*}}/;
|
||
|
||
/** 明细行的 token 值(分组/未分组两条路径共用;seq_no 由调用方给,跨分类连续) */
|
||
function itemValues(line: DeliveryPrintLine, seqNo: number): Record<string, unknown> {
|
||
return {
|
||
'item.seq_no': seqNo,
|
||
'item.sku_name': line.sku_name,
|
||
'item.item_name': line.item_name,
|
||
'item.spec': line.spec,
|
||
'item.origin': line.origin,
|
||
'item.unit': line.unit,
|
||
'item.quantity': line.delivery_qty ?? line.quantity,
|
||
'item.price': line.price,
|
||
'item.amount': line.amount,
|
||
'item.actual_amount': line.actual_amount ?? line.amount,
|
||
'item.remark': line.remark,
|
||
'item.category_name': line.category_name,
|
||
};
|
||
}
|
||
|
||
function sum(lines: DeliveryPrintLine[], field: 'amount' | 'actual_amount'): number {
|
||
return lines.reduce((total, line) => total + Number(line[field] ?? (field === 'actual_amount' ? line.amount : 0) ?? 0), 0);
|
||
}
|
||
|
||
/** 金额类字段:统一保留两位小数(数量/序号不在此列,保持原样) */
|
||
const MONEY_PATHS = new Set([
|
||
'order.total_amount',
|
||
'group.total_amount',
|
||
'group.total_actual_amount',
|
||
'item.price',
|
||
'item.amount',
|
||
'item.actual_amount',
|
||
'category.total_amount',
|
||
'category.total_actual_amount',
|
||
]);
|
||
|
||
/**
|
||
* 可选块:`{{#字段}}…{{/字段}}`(mustache 的条件段)。
|
||
*
|
||
* AI 会用它表达「这个字段有值才输出」,例如 `{{item.item_name}}{{#item.spec}} {{item.spec}}{{/item.spec}}`。
|
||
* 渲染器原先只认 `{{#items}}` / `{{#categories}}` 两个循环,于是这标记被原样印到单据上
|
||
* (2026-10-06 事故:「五花肉{{#item.spec}}」直接印出来了)。
|
||
* 现在按 mustache 语义处理:字段有值 → 输出块内内容;没有值 → 整块不输出(含块内的文字)。
|
||
* 明细/分类两个循环不归这里管(负向先行断言排除),它们由 renderGroup 先展开。
|
||
*/
|
||
const OPTIONAL_SECTION = /\{\{\s*#\s*(?!items\b|categories\b)([a-z_.]+)\s*\}\}([\s\S]*?)\{\{\s*\/\s*\1\s*\}\}/i;
|
||
|
||
function expandOptionalSections(source: string, values: Record<string, unknown>): string {
|
||
let out = source;
|
||
// 非贪婪 + 反向引用先配到最内层,逐轮向外展开;上限只是防御死循环
|
||
for (let guard = 0; guard < 20; guard += 1) {
|
||
const match = out.match(OPTIONAL_SECTION);
|
||
if (!match) break;
|
||
const [whole, path, inner] = match;
|
||
const raw = values[path];
|
||
const present = raw !== undefined && raw !== null && String(raw).trim() !== '';
|
||
out = out.replace(whole, present ? inner : '');
|
||
}
|
||
return out;
|
||
}
|
||
|
||
function renderTokens(source: string, values: Record<string, unknown>): string {
|
||
return expandOptionalSections(source, values).replace(/{{\s*([a-z_.]+)\s*}}/g, (_match, path: string) => {
|
||
const raw = values[path];
|
||
if (!MONEY_PATHS.has(path)) return escapeHtml(raw);
|
||
// 缺值仍渲染成空白(不要变成 0.00):只有真取到数才格式化
|
||
if (raw === null || raw === undefined || raw === '') return '';
|
||
return escapeHtml(formatAmount(Number(raw)));
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 金额一律保留两位小数。
|
||
*
|
||
* ⚠️ 不要用 `toFixed(2).replace(/\.00$/, '')` 去省略 `.00`:那会让同一张单上出现
|
||
* 「25」与「1319.80」两种写法。而且行金额累加是 JS 浮点,必须靠 toFixed 收敛 ——
|
||
* 实测 `1099.9 + 219.9 = 1319.8000000000002`、`3574.8999999999996`。
|
||
*/
|
||
function formatAmount(value: number): string {
|
||
return Number.isFinite(value) ? value.toFixed(2) : '';
|
||
}
|
||
|
||
/**
|
||
* 兜底补合计:**仅当标签之后到块级闭合标签之间没有任何取值**时才补。
|
||
*
|
||
* ⚠️ 不能把 `</span>` / `</strong>` 当成「空的值单元格」:AI 模板常写成
|
||
* `<span class="total-label">每页合计:</span> {{group.total_amount}}</td>`
|
||
* 那样会把补的值插进 label 的 span **内部**,而模板 token 渲染出的原值仍留在外面,
|
||
* 一个合计就显示两次(实测:`每页合计: 1319.80</span> 1319.8000000000002`)。
|
||
* 因此这里把行内闭合标签单独捕获(补值时放到它**之后**),并要求它到块级闭合标签
|
||
* 之间只剩空白 —— 只要后面已有取值,整个正则就不匹配,一个数字都不会多出来。
|
||
*
|
||
* ⚠️ 还有第二种漏判(2026-10-07 实测,四川天府绿洲物业配送单):
|
||
* `<td class="page-total-label">每页合计:</td><td class="page-total-value">{{group.total_amount}}</td>`
|
||
* 标签**独占一格、值在相邻格**,于是「标签到 </td> 之间只剩空白」成立 → 补一个值进标签格,
|
||
* 而下一格又由 token 渲染出同一个合计 ⇒ **合计印两遍**(实测 `每页合计: 36.00` + 右侧 `36.00`)。
|
||
* 故追加负向先行断言:**标签闭合之后若还紧跟兄弟元素(td/th/div/p/span/strong),说明值有地方放,
|
||
* 一个都不补**;只有标签格本身是该行最后一个元素时(如 `<td colspan="3">每页合计:</td></tr>`)才兜底。
|
||
*/
|
||
function fillTotalFallback(html: string, label: string, value: string): string {
|
||
const pattern = new RegExp(
|
||
`(${label}\\s*[::]?)(\\s*(?:<\\/(?:span|strong)>)?)\\s*(<\\/(?:td|th|div|p)>)` +
|
||
`(?!(?:\\s*<(?:t[hd]|div|p|span|strong)\\b))`,
|
||
'i'
|
||
);
|
||
return html.replace(
|
||
pattern,
|
||
(_match, labelText: string, inlineClose: string, blockClose: string) =>
|
||
`${labelText}${inlineClose} ${escapeHtml(value)}${blockClose}`
|
||
);
|
||
}
|
||
|
||
/**
|
||
* 把 `YYYY-MM-DD` 拆成「年 / 月 / 日」,供按格填写的单据使用(2026-10-07 用户反馈)。
|
||
*
|
||
* 起因:像「送(销)货单」这种老式单据,日期是印成一格一格的 —— `__年__月__日`,
|
||
* 数字写在 年 / 月 / 日 的前面。而 AI 手上只有 `order.delivery_date` **一整个字符串**
|
||
* (后端 `to_char(…,'YYYY-MM-DD')` = `2026-10-07`),模板语法又只允许四种写法、**没有过滤器**,
|
||
* 于是它只能把整串塞进中间,印出来是「年 2026-10-07 月日」(用户实测截图)。
|
||
*
|
||
* 处理:在渲染值里补出拆分字段(仍然只用原来那四种语法,不新增过滤器/函数)。
|
||
* 拆不出来(空值、格式不认识)时全部给空串 —— 宁可留白,也不能印出 `NaN`/`undefined`。
|
||
*/
|
||
function deliveryDateParts(value: unknown): { year: string; month: string; day: string; monthPad: string; dayPad: string; text: string } {
|
||
const match = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(value ?? '').trim());
|
||
if (!match) return { year: '', month: '', day: '', monthPad: '', dayPad: '', text: '' };
|
||
const [, year, monthPad, dayPad] = match;
|
||
const month = String(Number(monthPad));
|
||
const day = String(Number(dayPad));
|
||
return { year, month, day, monthPad, dayPad, text: `${year}年${month}月${day}日` };
|
||
}
|
||
|
||
function renderGroup(template: DeliveryHtmlTemplate, group: DeliveryNotePrintGroup): string {
|
||
const primary: DeliveryPrintOrderHeader = group.orders[0] || ({} as DeliveryPrintOrderHeader);
|
||
const total = sum(group.lines, 'amount');
|
||
const dateParts = deliveryDateParts(primary.delivery_date);
|
||
const orderValues: Record<string, unknown> = {
|
||
// 票据上只显示去掉来源前缀的单号(ORD_WEB_… → 20260923_BR002_0001)
|
||
'order.order_code': group.orders.map((order) => orderCodeDisplayLabel(order.order_code)).join(', '),
|
||
'order.customer_name': group.customer_name,
|
||
'order.branch_name': primary.branch_name,
|
||
'order.delivery_date': primary.delivery_date,
|
||
// 日期拆分字段:`__年__月__日` 这类版式直接引用,不必自己拼字符串
|
||
'order.delivery_year': dateParts.year,
|
||
'order.delivery_month': dateParts.month,
|
||
'order.delivery_day': dateParts.day,
|
||
'order.delivery_month_pad': dateParts.monthPad,
|
||
'order.delivery_day_pad': dateParts.dayPad,
|
||
'order.delivery_date_cn': dateParts.text,
|
||
'order.delivery_address': primary.delivery_address,
|
||
'order.remark': primary.remark,
|
||
'order.delivery_person': primary.delivery_person,
|
||
'order.delivery_person_phone': primary.delivery_person_phone,
|
||
'order.total_amount': Number(primary.total_amount || 0) || total,
|
||
'order.item_count': group.lines.length,
|
||
'group.total_amount': total,
|
||
'group.total_quantity': group.lines.reduce((value, line) => value + Number(line.delivery_qty ?? line.quantity ?? 0), 0),
|
||
'group.total_actual_amount': sum(group.lines, 'actual_amount'),
|
||
'group.item_count': group.lines.length,
|
||
'group.order_count': group.orders.length,
|
||
};
|
||
// Expand the item loop before parsing the fragment. HTML parsers may move or
|
||
// discard text nodes inside table sections, which would otherwise hide the
|
||
// {{#items}} markers and leave an empty table body.
|
||
const rawHtml = normalizeLoopMarkers(template.layout ? addEditorNodeClasses(String(template.html || '')) : String(template.html || ''));
|
||
const itemLoop = /{{\s*#items\s*}}([\s\S]*?){{\s*\/items\s*}}/;
|
||
let body = rawHtml;
|
||
// ① 先展开「按分类分组」块:{{#categories}} 组标题/组内明细/组小计 {{/categories}}
|
||
// (顺序/兜底分类名与旧版模板共用 resolveTopCategory / sortLinesByCategory,保证两种模板一致)
|
||
const categoryMatch = body.match(CATEGORY_LOOP);
|
||
if (categoryMatch) {
|
||
const inner = categoryMatch[1];
|
||
const innerItem = inner.match(itemLoop);
|
||
const buckets: Array<{ name: string; lines: DeliveryPrintLine[] }> = [];
|
||
for (const line of sortLinesByCategory(group.lines)) {
|
||
const name = resolveTopCategory(line.category_name);
|
||
const last = buckets[buckets.length - 1];
|
||
if (last && last.name === name) last.lines.push(line);
|
||
else buckets.push({ name, lines: [line] });
|
||
}
|
||
let seqNo = 0;
|
||
const grouped = buckets.map((bucket, index) => {
|
||
const rows = innerItem
|
||
? bucket.lines.map((line) => renderTokens(innerItem[1], itemValues(line, ++seqNo))).join('')
|
||
: '';
|
||
const block = innerItem ? inner.replace(itemLoop, rows) : inner;
|
||
return renderTokens(block, {
|
||
'category.seq_no': index + 1,
|
||
'category.name': bucket.name,
|
||
'category.count': bucket.lines.length,
|
||
'category.total_quantity': bucket.lines.reduce(
|
||
(value, line) => value + Number(line.delivery_qty ?? line.quantity ?? 0),
|
||
0
|
||
),
|
||
'category.total_amount': sum(bucket.lines, 'amount'),
|
||
'category.total_actual_amount': sum(bucket.lines, 'actual_amount'),
|
||
});
|
||
}).join('');
|
||
body = body.replace(CATEGORY_LOOP, grouped);
|
||
}
|
||
// ② 再展开顶层(未分组)明细循环 —— 分组块里的内层循环上面已经展开掉,不会再被这里匹配
|
||
const match = body.match(itemLoop);
|
||
if (match) {
|
||
const rows = group.lines.map((line, index) => renderTokens(match[1], itemValues(line, index + 1))).join('');
|
||
body = body.replace(itemLoop, rows);
|
||
}
|
||
let rendered = renderTokens(sanitizeDeliveryTemplateHtml(body), orderValues)
|
||
// 兜底:**任何**没被解析的 mustache 标记都不得留在单据上。
|
||
// AI 可能写出渲染器不支持的写法({{^字段}} 反向块、{{!注释}}、{{>片段}}、{{&字段}}、
|
||
// 名字拼错、闭合标记配不上……),原样印出来就是「五花肉{{#item.spec}}」这种事故。
|
||
// 交付单上不存在「本来就该显示 {{…}}」的场景,所以一律抹掉。
|
||
.replace(/\{\{[^{}]*\}\}/g, '');
|
||
// Some source images contain these labels without a visible value cell. Fill
|
||
// the conventional totals so the generated form remains useful even when
|
||
// the vision model omitted the binding.
|
||
const totalText = formatAmount(total);
|
||
const grandTotalText = formatAmount(Number(primary.total_amount || 0) || total);
|
||
rendered = fillTotalFallback(rendered, '每页合计', totalText);
|
||
rendered = fillTotalFallback(rendered, '整单合计', grandTotalText);
|
||
const additions = (template.layout?.additions || []).map((item) =>
|
||
`<span class="dht-added-${escapeHtml(item.id)}">${escapeHtml(item.text)}</span>`
|
||
).join('');
|
||
return `${rendered}${additions}`;
|
||
}
|
||
|
||
function normalizeLoopMarkers(source: string): string {
|
||
return source
|
||
.replace(/&#(123|125);|&#x(7b|7d);/gi, (_match, decimal: string, hex: string) =>
|
||
decimal ? (decimal === '123' ? '{' : '}') : (hex.toLowerCase() === '7b' ? '{' : '}')
|
||
)
|
||
.replace(/{|{|{/gi, '{')
|
||
.replace(/}|}|}/gi, '}')
|
||
.replace(/\{\s*\{\s*#\s*items\s*\}\s*\}/gi, '{{#items}}')
|
||
.replace(/\{\s*\{\s*\/\s*items\s*\}\s*\}/gi, '{{/items}}')
|
||
.replace(/\{\s*\{\s*#\s*categories\s*\}\s*\}/gi, '{{#categories}}')
|
||
.replace(/\{\s*\{\s*\/\s*categories\s*\}\s*\}/gi, '{{/categories}}');
|
||
}
|
||
|
||
/**
|
||
* 给**唯一节点**注入目标坐标(data 属性,单位 mm)。
|
||
* 只在渲染结果里恰好出现一次的元素上注入;重复节点(循环体/分类组内)走相对偏移,不注入。
|
||
* 用 data 属性而不是 CSS 变量:自定义属性会向下继承,子节点会误读父节点的目标坐标。
|
||
*/
|
||
function injectLayoutTargets(
|
||
html: string,
|
||
layout: DeliveryHtmlTemplateLayout | undefined,
|
||
contentWidthMm: number,
|
||
contentHeightMm: number
|
||
): string {
|
||
if (!layout?.nodes) return html;
|
||
// flow 语义的坐标是「相对偏移」,由 layoutCss 直接出 transform,不注入绝对目标
|
||
if (layout.anchoring === 'flow') return html;
|
||
const mm = (value: number) => Number(value.toFixed(4));
|
||
let out = html;
|
||
Object.entries(layout.nodes).forEach(([id, value]) => {
|
||
if (!/^\d+$/.test(id) || !value) return;
|
||
const xMm = Number.isFinite(value.xPercent) ? contentWidthMm * Number(value.xPercent) / 100 : Number(value.x) / 3.779527559;
|
||
const yMm = Number.isFinite(value.yPercent) ? contentHeightMm * Number(value.yPercent) / 100 : Number(value.y) / 3.779527559;
|
||
if (!xMm && !yMm) return;
|
||
const token = `dht-edit-node-${id}`;
|
||
const occurrences = out.match(new RegExp(`${token}(?![0-9])`, 'g'))?.length || 0;
|
||
if (occurrences !== 1) return; // 重复节点不注入
|
||
const pattern = new RegExp(`(<[a-z][a-z0-9]*\\b[^>]*\\bclass=)(["'])([^"']*\\b${token}\\b[^"']*)\\2`, 'i');
|
||
out = out.replace(pattern, (_match, head: string, quote: string, classes: string) =>
|
||
`${head}${quote}${classes}${quote} data-dht-x="${mm(xMm)}" data-dht-y="${mm(yMm)}"`
|
||
);
|
||
});
|
||
return out;
|
||
}
|
||
|
||
/** 「文字内容」不能改的原因:dynamic 动态字段 / container 容器(内层还有子元素)/ missing 找不到或本来就没文字 */
|
||
export type StaticTextBlockReason = 'dynamic' | 'container' | 'missing';
|
||
|
||
/** 定位第 targetIndex 个可编辑元素的内层文字区间;找不到(或自闭合)返回 null */
|
||
function locateEditorNodeText(source: string, targetIndex: number): { start: number; end: number } | null {
|
||
const tags = new RegExp(`</?(${DELIVERY_TEMPLATE_EDITOR_TAG_PATTERN})\\b[^>]*>`, 'gi');
|
||
const stack: Array<{ name: string; index: number; innerStart: number }> = [];
|
||
let index = 0;
|
||
let replacement: { start: number; end: number } | null = null;
|
||
let match: RegExpExecArray | null;
|
||
while ((match = tags.exec(source))) {
|
||
const name = match[1].toLowerCase();
|
||
const isClosing = /^<\//.test(match[0]);
|
||
if (isClosing) {
|
||
const stackIndex = stack.map((entry) => entry.name).lastIndexOf(name);
|
||
if (stackIndex < 0) continue;
|
||
const [entry] = stack.splice(stackIndex, 1);
|
||
if (entry.index === targetIndex) replacement = { start: entry.innerStart, end: match.index };
|
||
continue;
|
||
}
|
||
const nodeIndex = index++;
|
||
const selfClosing = /\/>$/.test(match[0]) || ['br', 'hr'].includes(name);
|
||
if (nodeIndex === targetIndex && selfClosing) return null;
|
||
if (!selfClosing) stack.push({ name, index: nodeIndex, innerStart: tags.lastIndex });
|
||
}
|
||
return replacement;
|
||
}
|
||
|
||
/**
|
||
* 能不能改这个元素的文字;能改返回 null,不能改返回原因(页面据此显示对应的说明小字)。
|
||
* 不可改的两种情况:内含 `{{字段}}`(动态值,文字由订单数据决定)与内含子标签(容器,要选中里面的文字)。
|
||
*/
|
||
export function staticTextBlockReason(source: string, targetIndex: number): StaticTextBlockReason | null {
|
||
const located = locateEditorNodeText(source, targetIndex);
|
||
if (!located) return 'missing';
|
||
const contents = source.slice(located.start, located.end);
|
||
if (contents.includes('{{')) return 'dynamic';
|
||
if (contents.includes('<')) return 'container';
|
||
return null;
|
||
}
|
||
|
||
/**
|
||
* 把第 `targetIndex` 个可编辑元素(编号见 DELIVERY_TEMPLATE_EDITOR_TAG_PATTERN)的内层文字换成 `text`。
|
||
* 只处理「内层是纯文字」的叶子节点:内含子标签或 `{{字段}}` 的节点返回 null
|
||
* (动态值由数据决定,模板里改文字没有意义;容器节点的文字则要连子结构一起改,不能整段替换)。
|
||
* 返回 null 时页面不显示「文字内容」输入框、而是显示 staticTextBlockReason 给出的原因。
|
||
*/
|
||
export function replaceStaticNodeText(source: string, targetIndex: number, text: string): string | null {
|
||
const located = locateEditorNodeText(source, targetIndex);
|
||
if (!located) return null;
|
||
const contents = source.slice(located.start, located.end);
|
||
if (/<|{{/.test(contents)) return null;
|
||
return `${source.slice(0, located.start)}${escapeHtml(text)}${source.slice(located.end)}`;
|
||
}
|
||
|
||
/**
|
||
* 把布局**就地**同步进一份已加载的文档(编辑器用)。
|
||
*
|
||
* 为什么需要它:编辑器原先每改一次布局就把 srcDoc 重新生成一遍,iframe 因此整份重新导航 ——
|
||
* 视觉上就是预览「闪一下」(用户 2026-10-06 反馈:调一个元素的位置就快速闪动;控制台每次导航都会打
|
||
* 一条 `Blocked script execution in 'about:srcdoc' …`,可用它数导航次数)。
|
||
*
|
||
* 布局对文档只有两处影响,这里就和整份重建一样地改这两处,再调 applyLayoutTargets 应用位移:
|
||
* ① `<style id="dht-template-layout">` 里的规则(字号/对齐/隐藏/宽高/重复节点的相对平移);
|
||
* ② 唯一节点的 data-dht-x / data-dht-y 目标坐标(mm)。
|
||
* 判「重复节点」的口径与 buildDeliveryHtmlTemplateDocument 里的 collectRepeatedNodeIds 一致,
|
||
* 只是一个数文档字符串、一个数已加载的 DOM。
|
||
*/
|
||
export function syncTemplateLayoutInDocument(
|
||
doc: Document,
|
||
template: DeliveryHtmlTemplate,
|
||
layout: DeliveryHtmlTemplateLayout | undefined
|
||
): void {
|
||
const root = doc.querySelector('.delivery-html-template-root');
|
||
if (!root) return;
|
||
const paper = template.paper;
|
||
const contentWidthMm = Math.max(1, paper.widthMm - paper.marginMm * 2);
|
||
const contentHeightMm = Math.max(1, paper.heightMm - paper.marginMm * 2);
|
||
|
||
const counts = new Map<string, number>();
|
||
doc.querySelectorAll<HTMLElement>('[class*="dht-edit-node-"]').forEach((element) => {
|
||
const id = editorNodeIdOf(element);
|
||
if (id) counts.set(id, (counts.get(id) || 0) + 1);
|
||
});
|
||
const repeated = new Set<string>();
|
||
counts.forEach((count, id) => { if (count > 1) repeated.add(id); });
|
||
|
||
// ① 布局规则。文档里那块 style 由 buildDeliveryHtmlTemplateDocument 生成(同一个 layoutCss)。
|
||
const style = doc.getElementById('dht-template-layout');
|
||
if (style) style.textContent = layoutCss(layout, paper, repeated);
|
||
|
||
// ② 唯一节点的绝对目标坐标:先全部清掉,再按当前布局重设(否则被取消的坐标会留在元素上)。
|
||
// ⚠️ 同时清掉行内 transform:老语义的位移是 applyLayoutTargets 写在行内的,行内 !important 会盖住
|
||
// 新的样式表偏移(flow 语义),不清就会「换算完看起来没变、其实还钉在旧位置」。
|
||
doc.querySelectorAll<HTMLElement>('[data-dht-x], [data-dht-y]').forEach((element) => {
|
||
element.removeAttribute('data-dht-x');
|
||
element.removeAttribute('data-dht-y');
|
||
element.style.removeProperty('transform');
|
||
});
|
||
// flow 语义:坐标已由上面那块 style 出 transform,不再有绝对目标(清掉后 applyLayoutTargets 自然空转)
|
||
Object.entries(layout?.anchoring === 'flow' ? {} : layout?.nodes || {}).forEach(([id, value]) => {
|
||
if (!/^\d+$/.test(id) || !value || repeated.has(id)) return;
|
||
const xMm = Number.isFinite(value.xPercent) ? contentWidthMm * Number(value.xPercent) / 100 : Number(value.x) / 3.779527559;
|
||
const yMm = Number.isFinite(value.yPercent) ? contentHeightMm * Number(value.yPercent) / 100 : Number(value.y) / 3.779527559;
|
||
if (!xMm && !yMm) return;
|
||
const element = doc.querySelector<HTMLElement>(`.dht-edit-node-${id}`);
|
||
if (!element) return;
|
||
element.dataset.dhtX = String(Number(xMm.toFixed(4)));
|
||
element.dataset.dhtY = String(Number(yMm.toFixed(4)));
|
||
});
|
||
|
||
// ③ 量出位移并写 transform(全文档唯一应用点,编辑器与打印共用)
|
||
applyLayoutTargets(doc);
|
||
}
|
||
|
||
/**
|
||
* 「交换两列」:把同一张表里第 colA 列与第 colB 列**整列换掉**(表头 + 明细行 + 其它行一起换),
|
||
* 而不是只挪两个格子的显示位置(2026-10-07 用户要求:换位置后下方数据也要跟着换、宽度重排)。
|
||
*
|
||
* 做法:在**模板源码**上按行交换两列单元格的 outerHTML —— 明细行是循环体(源码里只有一份),
|
||
* 换掉后所有渲染出来的行都跟着换;宽度由浏览器按新内容自动重排(无需手工算)。
|
||
* 跨列合并(colspan)覆盖到这两列的行**跳过**(例如「金额小计」行是 colspan=8 + 一个值列),
|
||
* 避免拆坏合并单元格。
|
||
*
|
||
* 返回新的模板 HTML;无法安全交换时返回 null(调用方退回「按坐标互换」)。
|
||
*/
|
||
export function swapTableColumns(source: string, idA: string, idB: string): string | null {
|
||
if (!source || idA === idB) return null;
|
||
const cellPattern = new RegExp(`<(t[hd])\\b([^>]*)>([\\s\\S]*?)</\\1>`, 'gi');
|
||
const rowPattern = /<tr\b[^>]*>[\s\S]*?<\/tr>/gi;
|
||
const openTagPattern = new RegExp(`<(${DELIVERY_TEMPLATE_EDITOR_TAG_PATTERN})\\b[^>]*>`, 'gi');
|
||
|
||
/** 统计 [0, offset) 之间有多少个可编辑开标签 —— 就是该处第一个标签的编号 */
|
||
const nodeIndexAt = (offset: number) => {
|
||
openTagPattern.lastIndex = 0;
|
||
let count = 0;
|
||
let m: RegExpExecArray | null;
|
||
while ((m = openTagPattern.exec(source)) && m.index < offset) count += 1;
|
||
return count;
|
||
};
|
||
const colspanOf = (attributes: string) => {
|
||
const m = /\bcolspan\s*=\s*["']?(\d+)/i.exec(attributes);
|
||
return m ? Math.max(1, Number(m[1])) : 1;
|
||
};
|
||
|
||
let rowMatch: RegExpExecArray | null;
|
||
let colA = -1;
|
||
let colB = -1;
|
||
const edits: Array<{ start: number; end: number; text: string }> = [];
|
||
while ((rowMatch = rowPattern.exec(source))) {
|
||
const rowStart = rowMatch.index;
|
||
const row = rowMatch[0];
|
||
cellPattern.lastIndex = 0;
|
||
let cellMatch: RegExpExecArray | null;
|
||
let column = 0;
|
||
const cells: Array<{ start: number; end: number; column: number; colspan: number; nodeIndex: number }> = [];
|
||
while ((cellMatch = cellPattern.exec(row))) {
|
||
const cellStart = rowStart + cellMatch.index;
|
||
cells.push({
|
||
start: cellStart,
|
||
end: cellStart + cellMatch[0].length,
|
||
column,
|
||
colspan: colspanOf(cellMatch[2] || ''),
|
||
nodeIndex: nodeIndexAt(cellStart),
|
||
});
|
||
column += colspanOf(cellMatch[2] || '');
|
||
}
|
||
if (!cells.length) continue;
|
||
// 第一次遇到含 A/B 的行时确定列号
|
||
for (const cell of cells) {
|
||
if (cell.nodeIndex === Number(idA)) colA = cell.column;
|
||
if (cell.nodeIndex === Number(idB)) colB = cell.column;
|
||
}
|
||
if (colA < 0 || colB < 0 || colA === colB) continue;
|
||
const cellA = cells.find((c) => c.column === colA && c.colspan === 1);
|
||
const cellB = cells.find((c) => c.column === colB && c.colspan === 1);
|
||
if (!cellA || !cellB) continue; // 跨列合并覆盖到 → 这一行跳过
|
||
edits.push({ start: cellA.start, end: cellA.end, text: source.slice(cellB.start, cellB.end) });
|
||
edits.push({ start: cellB.start, end: cellB.end, text: source.slice(cellA.start, cellA.end) });
|
||
}
|
||
if (!edits.length || colA < 0 || colB < 0 || colA === colB) return null;
|
||
edits.sort((a, b) => b.start - a.start); // 从后往前替换,偏移不受影响
|
||
let out = source;
|
||
for (const edit of edits) {
|
||
out = out.slice(0, edit.start) + edit.text + out.slice(edit.end);
|
||
}
|
||
return out === source ? null : out;
|
||
}
|
||
|
||
/** 统计最终文档里每个 dht-edit-node-N 出现几次;出现 >1 次的就是重复节点(循环体/分类组内) */
|
||
function collectRepeatedNodeIds(html: string): Set<string> {
|
||
const counts = new Map<string, number>();
|
||
for (const match of html.matchAll(/dht-edit-node-(\d+)/g)) {
|
||
const id = match[1];
|
||
counts.set(id, (counts.get(id) || 0) + 1);
|
||
}
|
||
const repeated = new Set<string>();
|
||
counts.forEach((count, id) => {
|
||
if (count > 1) repeated.add(id);
|
||
});
|
||
return repeated;
|
||
}
|
||
|
||
export function buildDeliveryHtmlTemplateDocument(
|
||
template: DeliveryHtmlTemplate,
|
||
groups: DeliveryNotePrintGroup[]
|
||
): string {
|
||
const paper = template.paper;
|
||
const contentWidthMm = Math.max(1, paper.widthMm - paper.marginMm * 2);
|
||
const contentHeightMm = Math.max(1, paper.heightMm - paper.marginMm * 2);
|
||
const pages = injectLayoutTargets(
|
||
groups.map((group) => `<section class="delivery-template-page"><div class="delivery-html-template-root">${renderGroup(template, group)}</div></section>`).join(''),
|
||
template.layout,
|
||
contentWidthMm,
|
||
contentHeightMm
|
||
);
|
||
const css = scopeDeliveryTemplateCss(sanitizeDeliveryTemplateCss(template.css));
|
||
// 布局规则单独放一个可寻址的 <style>:编辑器改布局时只就地替换这一块(见 syncTemplateLayoutInDocument),
|
||
// 不必整份重建文档 —— 重建会让 iframe 重新导航,肉眼就是「闪一下」。
|
||
const layoutStyle = layoutCss(template.layout, paper, collectRepeatedNodeIds(pages));
|
||
return `<!doctype html><html><head><meta charset="utf-8"><style>
|
||
@page { size: ${paper.widthMm}mm ${paper.heightMm}mm; margin: ${paper.marginMm}mm; }
|
||
html, body { margin: 0; padding: 0; }
|
||
.delivery-template-page { width: ${contentWidthMm}mm; min-height: ${contentHeightMm}mm; margin: 0 auto; page-break-after: always; break-after: page; }
|
||
.delivery-template-page:last-child { page-break-after: auto; break-after: auto; }
|
||
.delivery-html-template-root, .delivery-html-template-root * { box-sizing: border-box; }
|
||
.delivery-html-template-root { position: relative; width: 100%; max-width: ${contentWidthMm}mm; margin: 0 auto; overflow: hidden; }
|
||
${css}
|
||
</style><style id="dht-template-layout">${layoutStyle}</style></head><body>${pages}</body></html>`;
|
||
}
|
||
|
||
export function buildDeliveryHtmlTemplatePreview(template: DeliveryHtmlTemplate): string {
|
||
const sampleOrder: DeliveryPrintOrderHeader = {
|
||
order_code: 'XS-202610060019', customer_code: 'C001', company_name: '绵阳邮政分公司',
|
||
merchant_name: '绵阳邮政分公司', delivery_date: '2026-10-06', total_amount: 136.5,
|
||
remark: '请按时配送', branch_name: '四川天府绿洲物业管理有限责任公司', delivery_person: '',
|
||
};
|
||
const sampleItems = [
|
||
['猪肉', '五花肉', 14, 13], ['猪肉', '肉颗粒', 6, 12], ['豆制品', '老豆腐', 15, 2.8],
|
||
['蔬菜', '大红椒', 7, 6], ['蔬菜', '洋葱', 5, 4], ['干杂', '青花椒', 2, 38],
|
||
['蔬菜', '园萝卜', 13, 2], ['蔬菜', '蒜苗', 2, 6],
|
||
];
|
||
const lines: DeliveryPrintLine[] = sampleItems.map(([category_name, sku_name, quantity, price], index) => ({
|
||
order_code: sampleOrder.order_code,
|
||
sku_code: `SKU00${index + 1}`,
|
||
sku_name: String(sku_name),
|
||
item_name: String(sku_name),
|
||
category_name: String(category_name),
|
||
quantity: Number(quantity),
|
||
delivery_qty: Number(quantity),
|
||
unit: '斤',
|
||
price: Number(price),
|
||
amount: Number(quantity) * Number(price),
|
||
remark: '',
|
||
}));
|
||
const group: DeliveryNotePrintGroup = {
|
||
groupKey: sampleOrder.order_code, customer_code: 'C001', customer_name: '绵阳邮政分公司',
|
||
orders: [sampleOrder], lines,
|
||
};
|
||
return buildDeliveryHtmlTemplateDocument(template, [group]);
|
||
}
|