Files
SupplierSystem/src/utils/deliveryNotePrint.ts
T
Ubuntu deb3e72750
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
chore: 以 AI 生鲜配送系统 当前版本作为 SupplierSystem 起点
来源仓库: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 经哈希比对与线上同值),
整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。
供应商系统后续开发自本提交开始。
2026-10-08 17:35:43 +08:00

1360 lines
48 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { formatOrderAmount } from './currency';
import { formatChinaDate, formatChinaDateTime } from './datetime';
import { buildExportMatrix, type ExportColumnDef } from './documentExport';
import { formatCycleCode } from './cycleDisplay';
import { orderCodeDisplayLabel } from './orderCodeDisplay';
import { applyLayoutTargets } from './deliveryTemplateLayout';
import { formatOrderStatusLabel } from './orderStatusLabels';
import {
DELIVERY_NOTE_META_FIELDS,
type DeliveryNoteLayoutOptions,
renderTitleTemplate,
} from './printTemplates';
import { tWebUi, tWebUiOr } from '../i18n/printT';
function formatTimeSlot(slot?: string | null) {
if (!slot) return tWebUi('orders.print.allDay');
if (slot === 'morning') return tWebUi('orders.morning');
if (slot === 'afternoon') return tWebUi('orders.afternoon');
if (slot === 'evening') return tWebUi('orders.print.evening');
return slot;
}
export interface DeliveryPrintOrderHeader {
order_code: string;
customer_code?: string | null;
company_name?: string | null;
merchant_name?: string | null;
merchant_code?: string | null;
account_code?: string | null;
account_name?: string | null;
customer_role?: string | null;
parent_customer_code?: string | null;
delivery_address?: string | null;
delivery_date?: string | null;
delivery_time_slot?: string | null;
total_amount?: number | null;
remark?: string | null;
cycle_code?: string | null;
order_status?: number;
branch_code?: string | null;
branch_name?: string | null;
task_code?: string | null;
delivery_person?: string | null;
delivery_person_phone?: string | null;
}
export interface DeliveryPrintLine {
order_code: string;
order_item_id?: string;
sku_code: string;
sku_name: string;
item_name?: string | null;
customer_alias?: string | null;
category_name?: string | null;
spec?: string | null;
origin?: string | null;
quantity: number;
unit: string;
price?: number;
amount?: number;
processing_method?: string | null;
remark?: string | null;
supplier_name?: string | null;
picked_qty?: number | null;
loaded_qty?: number | null;
inspection_actual_qty?: number | null;
weigh_qty?: number | null;
weigh_unit?: string | null;
base_unit?: string | null;
weigh_qty_base?: number | null;
delivery_qty?: number | null;
actual_amount?: number | null;
box_no?: string | null;
box_count?: number | null;
sort_order?: number;
merchant_code?: string | null;
merchant_name?: string | null;
seq_no?: number;
is_extra_dish?: boolean;
is_returned?: boolean;
is_category_row?: boolean;
is_merchant_row?: boolean;
is_subtotal_row?: boolean;
is_grand_total_row?: boolean;
subtotal_label?: string;
}
export interface DeliveryNotePrintGroup {
groupKey: string;
customer_code: string;
customer_name: string;
account_code?: string;
account_name?: string;
merchant_codes?: string[];
orders: DeliveryPrintOrderHeader[];
lines: DeliveryPrintLine[];
}
export interface DeliveryNotePrintPayload {
title: string;
groups: DeliveryNotePrintGroup[];
columns: ExportColumnDef<DeliveryPrintLine>[];
selectedColumnIds: string[];
metaFields: string[];
layout: DeliveryNoteLayoutOptions;
/** 标题是否居中,默认 true */
titleCentered?: boolean;
}
function escapeHtml(value: unknown): string {
return String(value ?? '')
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
function fmtQty(value: number | null | undefined): string {
if (value == null || Number.isNaN(value)) return '';
const n = Number(value);
return Number.isInteger(n) ? String(n) : n.toFixed(2).replace(/\.?0+$/, '');
}
function mergeSkuKey(line: DeliveryPrintLine): string {
return [
line.sku_code,
line.unit,
line.price ?? '',
line.processing_method ?? '',
line.is_extra_dish ? '1' : '0',
line.is_returned ? '1' : '0',
].join('|');
}
function mergeLines(lines: DeliveryPrintLine[], mergeSameSku: boolean): DeliveryPrintLine[] {
if (!mergeSameSku) return lines.map((line) => ({ ...line }));
const map = new Map<string, DeliveryPrintLine>();
for (const line of lines) {
const key = mergeSkuKey(line);
const existing = map.get(key);
if (!existing) {
map.set(key, { ...line });
continue;
}
existing.quantity = Number(existing.quantity || 0) + Number(line.quantity || 0);
existing.amount = Number(existing.amount || 0) + Number(line.amount || 0);
existing.picked_qty = sumNullable(existing.picked_qty, line.picked_qty);
existing.loaded_qty = sumNullable(existing.loaded_qty, line.loaded_qty);
existing.inspection_actual_qty = sumNullable(existing.inspection_actual_qty, line.inspection_actual_qty);
existing.weigh_qty = sumNullable(existing.weigh_qty, line.weigh_qty);
existing.weigh_qty_base = sumNullable(existing.weigh_qty_base, line.weigh_qty_base);
existing.delivery_qty = sumNullable(existing.delivery_qty, line.delivery_qty);
existing.actual_amount = sumNullable(existing.actual_amount, line.actual_amount);
existing.box_count = sumNullable(existing.box_count, line.box_count);
}
return Array.from(map.values());
}
function sumNullable(a?: number | null, b?: number | null): number | null {
if (a == null && b == null) return null;
return Number(a || 0) + Number(b || 0);
}
function assignSeqNumbers(lines: DeliveryPrintLine[]): DeliveryPrintLine[] {
let seq = 0;
return lines.map((line) => {
if (line.is_category_row || line.is_subtotal_row || line.is_merchant_row || line.is_grand_total_row) {
return line;
}
seq += 1;
return { ...line, seq_no: seq };
});
}
/** 归到顶层分类:`蔬菜类/叶菜` → `蔬菜类`;空值 → 「未分类」。AI 模板分组复用同一口径。 */
export function resolveTopCategory(category?: string | null): string {
const raw = String(category || '').trim();
if (!raw) return tWebUi('orders.print.uncat');
const top = raw.split(/\s*[//]\s*/)[0]?.trim();
return top || raw;
}
/** 按(顶层分类 → 商品名)排序,使同分类连续。AI 模板的 `{{#categories}}` 分组复用同一口径。 */
export function sortLinesByCategory(lines: DeliveryPrintLine[]): DeliveryPrintLine[] {
const result: DeliveryPrintLine[] = [];
let bucket: DeliveryPrintLine[] = [];
const flushBucket = () => {
if (!bucket.length) return;
const items = bucket.filter((l) => !l.is_merchant_row);
const headers = bucket.filter((l) => l.is_merchant_row);
items.sort((a, b) => {
const cat = resolveTopCategory(a.category_name).localeCompare(
resolveTopCategory(b.category_name),
'zh-CN'
);
if (cat !== 0) return cat;
return String(a.sku_name || '').localeCompare(String(b.sku_name || ''), 'zh-CN');
});
result.push(...headers, ...items);
bucket = [];
};
for (const line of lines) {
if (line.is_merchant_row) {
flushBucket();
bucket.push(line);
continue;
}
bucket.push(line);
}
flushBucket();
return result;
}
function injectGuanmaiSubtotals(lines: DeliveryPrintLine[]): DeliveryPrintLine[] {
const result: DeliveryPrintLine[] = [];
let currentCategory = '';
let bucket: DeliveryPrintLine[] = [];
const flush = () => {
if (!bucket.length) return;
result.push(...bucket);
const subtotalAmount = bucket.reduce((sum, line) => sum + Number(line.amount || 0), 0);
result.push({
order_code: bucket[0].order_code,
sku_code: '',
sku_name: '',
quantity: 0,
unit: '',
is_subtotal_row: true,
subtotal_label: tWebUi('orders.print.subtotalNamed', {
category: currentCategory || tWebUi('orders.print.uncat'),
}),
amount: subtotalAmount,
});
bucket = [];
};
for (const line of lines) {
if (line.is_merchant_row) {
flush();
currentCategory = '';
result.push(line);
continue;
}
const category = resolveTopCategory(line.category_name);
if (category !== currentCategory && bucket.length) flush();
currentCategory = category;
bucket.push(line);
}
flush();
return result;
}
function buildCategorySummary(lines: DeliveryPrintLine[]): Array<{ name: string; count: number }> {
const map = new Map<string, number>();
for (const line of lines) {
if (line.is_merchant_row || line.is_subtotal_row || line.is_category_row || line.is_grand_total_row) {
continue;
}
const cat = resolveTopCategory(line.category_name);
map.set(cat, (map.get(cat) || 0) + 1);
}
return Array.from(map.entries())
.map(([name, count]) => ({ name, count }))
.sort((a, b) => a.name.localeCompare(b.name, 'zh-CN'));
}
function appendGrandTotalRow(
lines: DeliveryPrintLine[],
layout: DeliveryNoteLayoutOptions
): DeliveryPrintLine[] {
const items = lines.filter(
(l) => !l.is_subtotal_row && !l.is_merchant_row && !l.is_category_row && !l.is_grand_total_row
);
if (!items.length) return lines;
const totalQty = items.reduce((sum, line) => sum + Number(line.quantity || 0), 0);
const totalAmount = items.reduce((sum, line) => {
const amt =
layout.totalAmountType === 'actual' ? line.actual_amount ?? line.amount : line.amount;
return sum + Number(amt || 0);
}, 0);
return [
...lines,
{
order_code: items[0].order_code,
sku_code: '',
sku_name: tWebUi('orders.print.total'),
quantity: totalQty,
unit: '',
amount: totalAmount,
is_grand_total_row: true,
},
];
}
function prepareGuanmaiLines(
group: DeliveryNotePrintGroup,
layout: DeliveryNoteLayoutOptions
): DeliveryPrintLine[] {
let lines = group.lines.filter((l) => !l.is_category_row && !l.is_subtotal_row && !l.is_grand_total_row);
if (layout.printAudience === 'account' && layout.showMerchantSections) {
lines = injectMerchantSections(lines, true);
}
lines = sortLinesByCategory(lines);
if (layout.showCategorySubtotals) {
lines = injectGuanmaiSubtotals(lines);
}
if (layout.showSeqNo) {
lines = assignSeqNumbers(lines);
}
lines = appendGrandTotalRow(lines, layout);
return lines;
}
const ROWS_PER_PAGE_A4 = 22;
const ROWS_PER_PAGE_THERMAL = 16;
function isDataPrintLine(line: DeliveryPrintLine): boolean {
return !line.is_category_row && !line.is_subtotal_row && !line.is_merchant_row && !line.is_grand_total_row;
}
/** 按数据行数分页,小计/商户行跟随本页;合计仅在末页 */
function chunkPrintLines(lines: DeliveryPrintLine[], rowsPerPage: number): DeliveryPrintLine[][] {
if (rowsPerPage <= 0 || lines.length <= rowsPerPage) {
return lines.length ? [lines] : [];
}
const grandTotal = lines.find((l) => l.is_grand_total_row);
const bodyLines = lines.filter((l) => !l.is_grand_total_row);
const chunks: DeliveryPrintLine[][] = [];
let current: DeliveryPrintLine[] = [];
let dataRowCount = 0;
const flush = () => {
if (!current.length) return;
chunks.push(current);
current = [];
dataRowCount = 0;
};
for (const line of bodyLines) {
if (isDataPrintLine(line) && dataRowCount >= rowsPerPage) {
flush();
}
current.push(line);
if (isDataPrintLine(line)) dataRowCount += 1;
}
flush();
if (!chunks.length) {
return grandTotal ? [[grandTotal]] : [];
}
if (grandTotal) {
chunks[chunks.length - 1].push(grandTotal);
}
return chunks;
}
function renderGuanmaiCategorySummary(summary: Array<{ name: string; count: number }>): string {
if (!summary.length) return '';
const head = summary.map((item) => `<th>${escapeHtml(item.name)}</th>`).join('');
const body = summary.map((item) => `<td>${escapeHtml(item.count)}</td>`).join('');
return `<table class="category-summary"><thead><tr>${head}</tr></thead><tbody><tr>${body}</tr></tbody></table>`;
}
function renderGuanmaiHeader(
title: string,
group: DeliveryNotePrintGroup,
layout: DeliveryNoteLayoutOptions,
titleCentered = true
): string {
const primary = group.orders[0];
const docDate = primary?.delivery_date ? formatChinaDate(primary.delivery_date) : '-';
const docNo = group.orders.map((o) => orderCodeDisplayLabel(o.order_code)).join('、') || '-';
const customerLabel =
layout.printAudience === 'account'
? group.account_name || group.customer_name
: group.customer_name;
const customerCode =
layout.printAudience === 'account'
? group.account_code || group.customer_code
: group.customer_code;
const customerText = customerCode ? `${customerLabel}(${customerCode})` : customerLabel;
return `<div class="guanmai-header">
<h1 class="doc-title" style="text-align:${titleCentered === false ? 'left' : 'center'}">${escapeHtml(title)}</h1>
<div class="doc-head-row">
<span>${tWebUi('orders.print.docDate')}${escapeHtml(docDate)}</span>
<span>${tWebUi('orders.print.docNo')}${escapeHtml(docNo)}</span>
</div>
<div class="doc-customer">${tWebUi('orders.print.partner')}${escapeHtml(customerText)}</div>
</div>`;
}
function renderGuanmaiTableRows(
selectedColumnIds: string[],
matrix: (string | number)[][],
lines: DeliveryPrintLine[]
): string {
const colCount = selectedColumnIds.length;
let qtyIdx = selectedColumnIds.indexOf('planned_qty');
if (qtyIdx < 0) qtyIdx = selectedColumnIds.indexOf('quantity');
const amountIdx = selectedColumnIds.indexOf('amount');
const numIds = new Set(['planned_qty', 'quantity', 'price', 'amount', 'received_qty', 'actual_amount']);
return matrix
.map((row, idx) => {
const line = lines[idx];
if (line?.is_merchant_row) {
return `<tr class="merchant-row"><td colspan="${colCount}">${escapeHtml(line.merchant_name || line.sku_name)}</td></tr>`;
}
if (line?.is_subtotal_row) {
const label = `${line.subtotal_label || tWebUi('orders.print.subtotal')}: ${formatOrderAmount(line.amount || 0)}`;
return `<tr class="subtotal-row"><td colspan="${colCount}">${escapeHtml(label)}</td></tr>`;
}
if (line?.is_grand_total_row) {
const qtyCell = qtyIdx >= 0 ? `<td class="num">${escapeHtml(fmtQty(line.quantity))}</td>` : '';
const amountCell =
amountIdx >= 0 ? `<td class="num">${escapeHtml(formatOrderAmount(line.amount || 0))}</td>` : '';
const beforeQty = Math.max(1, qtyIdx >= 0 ? qtyIdx : colCount - 2);
const between = qtyIdx >= 0 && amountIdx > qtyIdx ? amountIdx - qtyIdx - 1 : 0;
const afterAmount = colCount - beforeQty - (qtyIdx >= 0 ? 1 : 0) - (amountIdx >= 0 ? 1 : 0) - between;
return `<tr class="grand-total-row">
<td colspan="${beforeQty}">${tWebUi('orders.print.total')}</td>
${qtyCell}
${between > 0 ? `<td colspan="${between}"></td>` : ''}
${amountCell}
${afterAmount > 0 ? `<td colspan="${afterAmount}"></td>` : ''}
</tr>`;
}
return `<tr>${row
.map((cell, cellIdx) => {
const cls = numIds.has(selectedColumnIds[cellIdx] || '') ? 'num' : '';
return `<td${cls ? ` class="${cls}"` : ''}>${escapeHtml(cell)}</td>`;
})
.join('')}</tr>`;
})
.join('');
}
function renderGuanmaiPage(
payload: DeliveryNotePrintPayload,
group: DeliveryNotePrintGroup,
options?: { rowsPerPage?: number }
): string[] {
const rowsPerPage = options?.rowsPerPage ?? ROWS_PER_PAGE_A4;
const rawItems = group.lines.filter(
(l) => !l.is_category_row && !l.is_subtotal_row && !l.is_merchant_row && !l.is_grand_total_row
);
const summary = payload.layout.showCategorySummary ? buildCategorySummary(rawItems) : [];
const lines = prepareGuanmaiLines(group, payload.layout);
const lineChunks = chunkPrintLines(lines, rowsPerPage);
const headerHtml = renderGuanmaiHeader(
payload.title,
group,
payload.layout,
payload.titleCentered !== false
);
const summaryHtml = renderGuanmaiCategorySummary(summary);
const totalSheets = lineChunks.length;
return lineChunks.map((chunkLines, sheetIndex) => {
const { headers, matrix } = buildExportMatrix(payload.columns, payload.selectedColumnIds, chunkLines);
const tableHtml = `<table class="guanmai-table">
<thead><tr>${headers.map((h) => `<th>${escapeHtml(h)}</th>`).join('')}</tr></thead>
<tbody>${renderGuanmaiTableRows(payload.selectedColumnIds, matrix, chunkLines)}</tbody>
</table>`;
const pageNoHtml =
totalSheets > 1
? `<div class="sheet-page-no">${tWebUi('orders.print.pageOf', {
page: sheetIndex + 1,
total: totalSheets,
})}</div>`
: '';
const signature =
sheetIndex === totalSheets - 1 ? renderSignatureFooter(payload.layout.showSignatureFooter) : '';
return `<div class="print-sheet guanmai-page">
${headerHtml}
${summaryHtml}
${pageNoHtml}
${tableHtml}
${signature}
</div>`;
});
}
function renderStandardSheets(
payload: DeliveryNotePrintPayload,
group: DeliveryNotePrintGroup,
options?: { rowsPerPage?: number }
): string[] {
let lines = group.lines.filter((l) => !l.is_category_row && !l.is_subtotal_row && !l.is_grand_total_row);
if (payload.layout.printAudience === 'account' && payload.layout.showMerchantSections) {
lines = injectMerchantSections(lines, true);
}
if (payload.layout.showCategorySubtotals) {
lines = injectCategorySubtotals(lines, true);
}
if (payload.layout.showSeqNo) {
lines = assignSeqNumbers(lines);
}
const meta = buildGroupMeta(group, payload.layout);
const metaHtml = Object.entries(meta)
.map(([key, value]) => `<div class="meta-row"><span class="meta-key">${escapeHtml(key)}</span><span>${escapeHtml(value)}</span></div>`)
.join('');
const titleHtml = `<h1 style="text-align:${payload.titleCentered === false ? 'left' : 'center'}">${escapeHtml(payload.title)}</h1>`;
if (payload.layout.dualColumn) {
const { headers, matrix } = buildExportMatrix(payload.columns, payload.selectedColumnIds, lines);
const tableHtml = renderDualColumnTable(headers, matrix, lines);
return [`<div class="print-sheet">
${titleHtml}
${metaHtml ? `<div class="meta">${metaHtml}</div>` : ''}
${tableHtml}
${renderSignatureFooter(payload.layout.showSignatureFooter)}
</div>`];
}
const rowsPerPage = options?.rowsPerPage ?? ROWS_PER_PAGE_A4;
const lineChunks = chunkPrintLines(lines, rowsPerPage);
const totalSheets = lineChunks.length;
return lineChunks.map((chunkLines, sheetIndex) => {
const { headers, matrix } = buildExportMatrix(payload.columns, payload.selectedColumnIds, chunkLines);
const tableHtml = `<table class="data-table">
<thead><tr>${headers.map((h) => `<th>${escapeHtml(h)}</th>`).join('')}</tr></thead>
<tbody>${renderTableRows(headers, matrix, chunkLines)}</tbody>
</table>`;
const pageNoHtml =
totalSheets > 1
? `<div class="sheet-page-no">${tWebUi('orders.print.pageOf', {
page: sheetIndex + 1,
total: totalSheets,
})}</div>`
: '';
const signature =
sheetIndex === totalSheets - 1 ? renderSignatureFooter(payload.layout.showSignatureFooter) : '';
return `<div class="print-sheet">
${titleHtml}
${metaHtml ? `<div class="meta">${metaHtml}</div>` : ''}
${pageNoHtml}
${tableHtml}
${signature}
</div>`;
});
}
function injectCategorySubtotals(lines: DeliveryPrintLine[], showSubtotals: boolean): DeliveryPrintLine[] {
if (!showSubtotals) return lines;
const result: DeliveryPrintLine[] = [];
let currentCategory = '';
let bucket: DeliveryPrintLine[] = [];
const flush = () => {
if (!bucket.length) return;
result.push(...bucket);
const subtotalAmount = bucket.reduce((sum, line) => sum + Number(line.amount || 0), 0);
const subtotalActual = bucket.reduce((sum, line) => sum + Number(line.actual_amount || line.amount || 0), 0);
result.push({
order_code: bucket[0].order_code,
sku_code: '',
sku_name: '',
quantity: 0,
unit: '',
is_subtotal_row: true,
subtotal_label: tWebUi('orders.print.subtotalNamed', {
category: currentCategory || tWebUi('orders.print.uncat'),
}),
amount: subtotalAmount,
actual_amount: subtotalActual,
});
bucket = [];
};
for (const line of lines) {
const category = line.category_name || tWebUi('orders.print.uncat');
if (category !== currentCategory && bucket.length) {
flush();
}
currentCategory = category;
if (bucket.length === 0) {
result.push({
order_code: line.order_code,
sku_code: '',
sku_name: category,
quantity: 0,
unit: '',
category_name: category,
is_category_row: true,
});
}
bucket.push(line);
}
flush();
return result;
}
function enrichLinesWithMerchant(
lines: DeliveryPrintLine[],
orderMap: Map<string, DeliveryPrintOrderHeader>
): DeliveryPrintLine[] {
return lines.map((line) => {
const order = orderMap.get(line.order_code);
return {
...line,
merchant_code: order?.customer_code || null,
merchant_name: order?.merchant_name || order?.company_name || null,
};
});
}
function injectMerchantSections(lines: DeliveryPrintLine[], enabled: boolean): DeliveryPrintLine[] {
if (!enabled) return lines;
const result: DeliveryPrintLine[] = [];
let currentMerchant = '';
for (const line of lines) {
const merchant = line.merchant_name || line.merchant_code || tWebUi('orders.print.unnamedMerchant');
if (merchant !== currentMerchant) {
currentMerchant = merchant;
result.push({
order_code: line.order_code,
sku_code: '',
sku_name: merchant,
quantity: 0,
unit: '',
merchant_name: merchant,
is_merchant_row: true,
});
}
result.push(line);
}
return result;
}
function resolveAccountKey(order: DeliveryPrintOrderHeader): string {
return order.account_code || order.customer_code || order.order_code;
}
export function buildDeliveryNoteGroups(input: {
orders: DeliveryPrintOrderHeader[];
lines: DeliveryPrintLine[];
printAudience: 'account' | 'merchant';
mergeSameCustomerOrders: boolean;
mergeSameSkuInOrder: boolean;
sortByCustomer: boolean;
sortByMerchant?: boolean;
}): DeliveryNotePrintGroup[] {
const {
orders,
lines,
printAudience,
mergeSameCustomerOrders,
mergeSameSkuInOrder,
sortByCustomer,
sortByMerchant = true,
} = input;
const orderMap = new Map(orders.map((o) => [o.order_code, o]));
const linesByOrder = new Map<string, DeliveryPrintLine[]>();
for (const line of lines) {
const list = linesByOrder.get(line.order_code) || [];
list.push(line);
linesByOrder.set(line.order_code, list);
}
if (printAudience === 'account') {
const accountBuckets = new Map<string, { orders: DeliveryPrintOrderHeader[]; lines: DeliveryPrintLine[] }>();
for (const order of orders) {
const accountKey = resolveAccountKey(order);
const bucket = accountBuckets.get(accountKey) || { orders: [], lines: [] };
bucket.orders.push(order);
const orderLines = enrichLinesWithMerchant(
mergeLines(linesByOrder.get(order.order_code) || [], mergeSameSkuInOrder),
orderMap
);
bucket.lines.push(...orderLines);
accountBuckets.set(accountKey, bucket);
}
const groups = Array.from(accountBuckets.entries()).map(([accountKey, bucket]) => {
const primary = bucket.orders[0];
const merchantCodes = [...new Set(bucket.orders.map((o) => o.customer_code).filter(Boolean))] as string[];
let mergedLines = mergeLines(bucket.lines, mergeSameSkuInOrder);
if (sortByMerchant) {
mergedLines = [...mergedLines].sort((a, b) =>
String(a.merchant_name || '').localeCompare(String(b.merchant_name || ''), 'zh-CN')
);
}
return {
groupKey: accountKey,
customer_code: accountKey,
customer_name: primary?.account_name || primary?.company_name || accountKey,
account_code: accountKey,
account_name: primary?.account_name || primary?.company_name || accountKey,
merchant_codes: merchantCodes,
orders: bucket.orders,
lines: mergedLines,
};
});
if (sortByCustomer) {
groups.sort((a, b) => a.customer_name.localeCompare(b.customer_name, 'zh-CN'));
}
return groups;
}
const customerBuckets = new Map<string, { orders: DeliveryPrintOrderHeader[]; lines: DeliveryPrintLine[] }>();
for (const order of orders) {
const customerCode = order.customer_code || order.company_name || order.order_code;
const bucket = customerBuckets.get(customerCode) || { orders: [], lines: [] };
bucket.orders.push(order);
const orderLines = enrichLinesWithMerchant(
mergeLines(linesByOrder.get(order.order_code) || [], mergeSameSkuInOrder),
orderMap
);
bucket.lines.push(...orderLines);
customerBuckets.set(customerCode, bucket);
}
if (!mergeSameCustomerOrders) {
const groups: DeliveryNotePrintGroup[] = [];
for (const order of orders) {
const customerCode = order.customer_code || order.company_name || order.order_code;
const orderLines = enrichLinesWithMerchant(
mergeLines(linesByOrder.get(order.order_code) || [], mergeSameSkuInOrder),
orderMap
);
groups.push({
groupKey: order.order_code,
customer_code: customerCode,
customer_name: order.merchant_name || order.company_name || customerCode,
account_code: order.account_code || undefined,
account_name: order.account_name || undefined,
orders: [order],
lines: orderLines,
});
}
return groups;
}
const groups = Array.from(customerBuckets.entries()).map(([customerCode, bucket]) => ({
groupKey: customerCode,
customer_code: customerCode,
customer_name: bucket.orders[0]?.merchant_name || bucket.orders[0]?.company_name || customerCode,
account_code: bucket.orders[0]?.account_code || undefined,
account_name: bucket.orders[0]?.account_name || undefined,
orders: bucket.orders,
lines: mergeLines(bucket.lines, mergeSameSkuInOrder),
}));
if (sortByCustomer) {
groups.sort((a, b) => a.customer_name.localeCompare(b.customer_name, 'zh-CN'));
}
return groups;
}
function buildGroupMeta(
group: DeliveryNotePrintGroup,
layout: DeliveryNoteLayoutOptions
): Record<string, string> {
const primary = group.orders[0];
const orderCodes = group.orders.map((o) => orderCodeDisplayLabel(o.order_code)).join('、');
const totalOrderAmount = group.lines.reduce((sum, line) => {
if (line.is_category_row || line.is_subtotal_row || line.is_merchant_row) return sum;
return sum + Number(line.amount || 0);
}, 0);
const totalActualAmount = group.lines.reduce((sum, line) => {
if (line.is_category_row || line.is_subtotal_row || line.is_merchant_row) return sum;
return sum + Number(line.actual_amount ?? line.amount ?? 0);
}, 0);
const values: Record<string, string> = {
order_code: orderCodes,
account: group.account_name || group.customer_name,
merchant: group.customer_name,
merchant_count: String(group.merchant_codes?.length || 1),
customer: group.customer_name,
branch_name: primary?.branch_name || primary?.branch_code || '-',
order_status:
primary?.order_status != null
? tWebUiOr(`orders.list.status.${primary.order_status}`, formatOrderStatusLabel(primary.order_status))
: '-',
delivery_date: primary?.delivery_date ? formatChinaDate(primary.delivery_date) : '-',
delivery_time_slot: formatTimeSlot(primary?.delivery_time_slot),
delivery_address: primary?.delivery_address || '-',
cycle_code: primary?.cycle_code ? formatCycleCode(primary.cycle_code) : '-',
created_at: '-',
total_amount: `¥${formatOrderAmount(
layout.totalAmountType === 'actual' ? totalActualAmount : totalOrderAmount
)}`,
order_total_amount: `¥${formatOrderAmount(totalOrderAmount)}`,
actual_total_amount: `¥${formatOrderAmount(totalActualAmount)}`,
item_count: String(
group.lines.filter((l) => !l.is_category_row && !l.is_subtotal_row && !l.is_merchant_row).length
),
remark: group.orders.map((o) => o.remark).filter(Boolean).join(';') || '-',
delivery_person: primary?.delivery_person || '-',
delivery_person_phone: primary?.delivery_person_phone || '-',
task_code: group.orders.map((o) => o.task_code).filter(Boolean).join('、') || '-',
};
const meta: Record<string, string> = {};
const fieldLabels = Object.fromEntries(
DELIVERY_NOTE_META_FIELDS.map((f) => [
f.id,
tWebUiOr(`orders.print.meta.${f.id}`, f.label),
])
);
for (const fieldId of layout.selectedMetaFields) {
meta[fieldLabels[fieldId] || fieldId] = values[fieldId] || '-';
}
return meta;
}
function renderTableRows(
headers: string[],
matrix: (string | number)[][],
lines: DeliveryPrintLine[]
): string {
return matrix
.map((row, idx) => {
const line = lines[idx];
if (line?.is_category_row) {
return `<tr class="category-row"><td colspan="${headers.length}"><span class="category-label">${escapeHtml(line.sku_name || line.category_name)}</span></td></tr>`;
}
if (line?.is_merchant_row) {
return `<tr class="merchant-row"><td colspan="${headers.length}">${escapeHtml(line.merchant_name || line.sku_name)}</td></tr>`;
}
if (line?.is_subtotal_row) {
return `<tr class="subtotal-row"><td colspan="${Math.max(1, headers.length - 2)}">${escapeHtml(line.subtotal_label || tWebUi('orders.print.subtotal'))}</td><td>${escapeHtml(formatOrderAmount(line.amount || 0))}</td><td>${escapeHtml(formatOrderAmount(line.actual_amount || line.amount || 0))}</td></tr>`;
}
return `<tr>${row.map((cell) => `<td>${escapeHtml(cell)}</td>`).join('')}</tr>`;
})
.join('');
}
function renderDualColumnTable(
headers: string[],
matrix: (string | number)[][],
lines: DeliveryPrintLine[]
): string {
const half = Math.ceil(matrix.length / 2);
const leftHead = headers.map((h) => `<th>${escapeHtml(h)}</th>`).join('');
const renderHalf = (start: number, end: number) =>
matrix
.slice(start, end)
.map((row, offset) => {
const line = lines[start + offset];
if (line?.is_category_row) {
return `<tr class="category-row"><td colspan="${headers.length}"><span class="category-label">${escapeHtml(line.sku_name || line.category_name)}</span></td></tr>`;
}
if (line?.is_subtotal_row) {
return `<tr class="subtotal-row"><td colspan="${headers.length}">${escapeHtml(line.subtotal_label || tWebUi('orders.print.subtotal'))}: ¥${escapeHtml(formatOrderAmount(line.amount || 0))}</td></tr>`;
}
return `<tr>${row.map((cell) => `<td>${escapeHtml(cell)}</td>`).join('')}</tr>`;
})
.join('');
return `<div class="dual-column">
<table class="half-table"><thead><tr>${leftHead}</tr></thead><tbody>${renderHalf(0, half)}</tbody></table>
<table class="half-table"><thead><tr>${leftHead}</tr></thead><tbody>${renderHalf(half, matrix.length)}</tbody></table>
</div>`;
}
function renderSignatureFooter(show: boolean): string {
if (!show) return '';
return `<div class="signature-row">
<div class="signature-box"><div class="signature-label">${tWebUi('orders.print.signDriver')}</div><div class="signature-line"></div></div>
<div class="signature-box"><div class="signature-label">${tWebUi('orders.print.signReceiver')}</div><div class="signature-line"></div></div>
<div class="signature-box"><div class="signature-label">${tWebUi('orders.print.signDate')}</div><div class="signature-line"></div></div>
</div>`;
}
function buildDeliveryNotePages(
payload: DeliveryNotePrintPayload,
options?: { rowsPerPage?: number }
): {
pages: string[];
documentStyle: 'guanmai' | 'standard';
} {
const pages: string[] = [];
const useGuanmai = payload.layout.documentStyle === 'guanmai';
for (const group of payload.groups) {
if (useGuanmai) {
pages.push(...renderGuanmaiPage(payload, group, options));
continue;
}
pages.push(...renderStandardSheets(payload, group, options));
}
if (!pages.length) throw new Error(tWebUi('orders.print.noSheets'));
return { pages, documentStyle: useGuanmai ? 'guanmai' : 'standard' };
}
export function buildDeliveryNoteDocumentHtml(
pages: string[],
documentStyle: 'guanmai' | 'standard' = 'standard',
options?: {
forThermal?: boolean;
paperWidthMm?: 58 | 80;
/** 浏览器打印纸张宽高(mm),默认 A4 */
pageWidthMm?: number;
pageHeightMm?: number;
pageMarginMm?: number;
autoPrint?: boolean;
}
): string {
const forThermal = options?.forThermal === true;
const paperWidthMm = options?.paperWidthMm ?? 80;
const pageWidthMm = Math.max(50, Number(options?.pageWidthMm) || 210);
const pageHeightMm = Math.max(50, Number(options?.pageHeightMm) || 297);
const pageMarginMm = Math.max(0, Math.min(30, Number(options?.pageMarginMm) || 10));
const guanmaiCss =
documentStyle === 'guanmai'
? `
.guanmai-page { font-size: ${forThermal ? '11px' : '13px'}; }
.doc-title { font-size: ${forThermal ? '16px' : '22px'}; font-weight: 700; text-align: center; margin: 0 0 8px; letter-spacing: 1px; }
.doc-head-row { display: flex; justify-content: space-between; margin-bottom: 4px; font-size: ${forThermal ? '11px' : '13px'}; }
.doc-customer { margin-bottom: 8px; font-size: ${forThermal ? '11px' : '13px'}; word-break: break-all; }
table.category-summary { width: auto; max-width: 100%; margin-bottom: 8px; border-collapse: collapse; font-size: ${forThermal ? '10px' : '12px'}; }
table.category-summary th, table.category-summary td { border: 1px solid #333; padding: 2px 4px; text-align: center; white-space: nowrap; }
table.guanmai-table { border: 1px solid #333; width: 100%; }
table.guanmai-table th, table.guanmai-table td { border: 1px solid #333; padding: ${forThermal ? '2px 3px' : '4px 6px'}; font-size: ${forThermal ? '10px' : '12px'}; }
table.guanmai-table th { background: #fff; font-weight: 600; text-align: center; }
table.guanmai-table td.num { text-align: right; }
tr.subtotal-row td { font-weight: 700; text-align: left; }
tr.grand-total-row td { font-weight: 700; }
tr.merchant-row td { font-weight: 600; }
.sheet-page-no { text-align: right; font-size: ${forThermal ? '10px' : '11px'}; color: #666; margin: 4px 0 6px; }
.print-sheet { page-break-after: always; break-after: page; }
.print-sheet:last-child { page-break-after: auto; break-after: auto; }
`
: `
.sheet-page-no { text-align: right; font-size: 11px; color: #666; margin: 4px 0 8px; }
.print-sheet { page-break-after: always; break-after: page; }
.print-sheet:last-child { page-break-after: auto; break-after: auto; }
table.data-table { width: 100%; }
`;
const thermalCss = forThermal
? `
@page { margin: 0; size: ${paperWidthMm}mm auto; }
html, body {
width: ${paperWidthMm}mm;
max-width: ${paperWidthMm}mm;
margin: 0;
padding: 2mm;
box-sizing: border-box;
}
body { font-size: 11px; }
table { width: 100%; max-width: 100%; font-size: 10px; word-break: break-word; table-layout: fixed; }
th, td { padding: 2px 3px; overflow-wrap: anywhere; }
.page { page-break-after: always; margin-bottom: 8px; width: 100%; box-sizing: border-box; }
.print-sheet { width: 100%; max-width: 100%; box-sizing: border-box; }
`
: `
/* 打印:页边距交给 @page,正文占满可印区域 */
@page { size: ${pageWidthMm}mm ${pageHeightMm}mm; margin: ${pageMarginMm}mm; }
html, body {
width: auto;
max-width: none;
margin: 0;
padding: 0;
box-sizing: border-box;
}
.print-sheet {
width: 100%;
max-width: 100%;
box-sizing: border-box;
padding: 0;
}
table { width: 100%; max-width: 100%; table-layout: auto; }
`;
const screenPreviewCss = forThermal
? `
@media screen {
body {
background: #fff !important;
padding: 2mm !important;
margin: 0 !important;
box-sizing: border-box;
}
.print-sheet, .page {
background: #fff;
box-shadow: none;
margin: 0 0 12px !important;
outline: none;
width: 100%;
box-sizing: border-box;
}
.print-sheet:last-child, .page:last-child { margin-bottom: 0 !important; }
}
`
: `
@media screen {
/* 预览按所选纸张 mm;内边距等同打印页边距 */
body {
background: #fff !important;
padding: 0 !important;
margin: 0 !important;
box-sizing: border-box;
}
.print-sheet {
width: ${pageWidthMm}mm;
min-height: ${pageHeightMm}mm;
margin: 0 auto 16px !important;
padding: ${pageMarginMm}mm;
box-sizing: border-box;
background: #fff;
box-shadow: 0 1px 4px rgba(0,0,0,.12);
outline: 1px solid #d1d5db;
}
.print-sheet:last-child { margin-bottom: 0 !important; }
.page {
background: #fff;
box-shadow: 0 1px 4px rgba(0,0,0,.12);
margin: 0 auto 16px !important;
outline: 1px solid #d1d5db;
}
}
`;
const autoPrintScript = options?.autoPrint === true && !forThermal
? '<script>window.onload=function(){window.print();}</script>'
: '';
return `<!DOCTYPE html><html><head><meta charset="utf-8"/><title></title>
<style>
body { font-family: "Microsoft YaHei", "SimSun", sans-serif; color: #111; }
.print-sheet { page-break-after: always; break-after: page; margin-bottom: 0; }
.print-sheet:last-child { page-break-after: auto; break-after: auto; }
.page { page-break-after: always; margin-bottom: 24px; }
.page:last-child { page-break-after: auto; }
h1 { font-size: 20px; margin: 0 0 12px; text-align: center; }
.meta { display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 6px 16px; margin-bottom: 12px; font-size: 13px; }
.meta-key { color: #666; margin-right: 6px; }
table { width: 100%; max-width: 100%; border-collapse: collapse; font-size: 12px; }
th, td { border: 1px solid #ddd; padding: 5px 6px; text-align: left; word-break: break-word; }
th { background: #f5f5f5; }
tr.category-row td { background: transparent; font-weight: 600; border-left-color: transparent; border-right-color: transparent; padding-left: 0; }
.category-label { display: inline-block; width: auto; background: #fafafa; border: 1px solid #ddd; padding: 3px 6px; white-space: nowrap; }
tr.merchant-row td { background: #f0f7ff; font-weight: 600; color: #1e40af; }
tr.subtotal-row td { background: #f9f9f9; font-weight: 600; }
.dual-column { display: flex; gap: 8px; width: 100%; box-sizing: border-box; }
.half-table { width: 50%; max-width: 50%; box-sizing: border-box; }
.signature-row { display: flex; gap: 24px; margin-top: 24px; }
.signature-box { flex: 1; min-width: 0; }
.signature-label { font-size: 13px; margin-bottom: 28px; }
.signature-line { border-bottom: 1px solid #333; height: 1px; }
${guanmaiCss}
${thermalCss}
${screenPreviewCss}
@media print {
html, body {
width: auto !important;
max-width: none !important;
margin: 0 !important;
padding: 0 !important;
background: #fff !important;
}
.print-sheet, .page {
width: 100% !important;
max-width: 100% !important;
min-height: auto !important;
padding: 0 !important;
margin: 0 !important;
box-shadow: none !important;
outline: none !important;
}
.print-sheet { page-break-after: always; break-after: page; }
.print-sheet:last-child { page-break-after: auto; break-after: auto; }
}
</style></head><body>
${pages.join('')}
${autoPrintScript}
</body></html>`;
}
/** 组装可预览/可打印的完整 HTML(默认不自动调起系统打印) */
export function buildDeliveryNotePrintHtml(
payload: DeliveryNotePrintPayload,
options?: {
forThermal?: boolean;
paperWidthMm?: 58 | 80;
pageWidthMm?: number;
pageHeightMm?: number;
pageMarginMm?: number;
autoPrint?: boolean;
rowsPerPage?: number;
}
): { html: string; documentStyle: 'guanmai' | 'standard' } {
const extraPrefix = tWebUi('orders.print.extraDish');
const localized: DeliveryNotePrintPayload = {
...payload,
columns: payload.columns.map((col) => ({
...col,
label: tWebUiOr(`orders.print.col.${col.id}`, col.label),
getValue: (row: DeliveryPrintLine) => {
const value = col.getValue(row);
if (typeof value !== 'string' || !row.is_extra_dish) return value;
return value.replace(/^【加菜】/, extraPrefix);
},
})),
};
const { pages, documentStyle } = buildDeliveryNotePages(localized, {
rowsPerPage: options?.rowsPerPage,
});
return {
html: buildDeliveryNoteDocumentHtml(pages, documentStyle, {
forThermal: options?.forThermal,
paperWidthMm: options?.paperWidthMm,
pageWidthMm: options?.pageWidthMm,
pageHeightMm: options?.pageHeightMm,
pageMarginMm: options?.pageMarginMm,
autoPrint: options?.autoPrint === true,
}),
documentStyle,
};
}
/** 将完整 HTML 单据挂到当前页后调系统打印(不用 iframe / blob)。
*
* 冻结:改打印通道前须用户明确许可(见 `.cursor/rules/delivery-note-print.mdc`、
* `docs/design/20260904-delivery-note-print-blank-fix.md`)。
*
* 为何不用 iframe:
* - Blob URL 被 CSP `default-src 'self'` 拦截 → 空框 → 预览 1 张白纸
* - 屏外 / 极小 / opacity iframe:Chrome 常跳过渲染 → 同样白纸
*
* 做法:解析 HTML,注入样式 + 打印宿主节点;@media print 隐藏其余页面,只打宿主。
*/
/** 标题自动缩放的字号下限(再小就影响可读性,改为换行兜底) */
const PRINT_HEADING_MIN_FONT_PX = 9;
/**
* 标题过长时自动缩小字号(**只作用于 AI 模板**,即 .delivery-html-template-root 内)。
*
* 为什么在这里做:AI 照参考图生成的标题常常是「一行且不换行」(或写死了固定字号),
* 真实单据的标题(公司名/客户名)比参考图长时就顶出纸张、挤掉版式。纯 CSS 无法按文字
* 长度定量地缩字号,而本函数运行时 HTML 已经挂在当前文档里、布局已完成,可以真实测量
* 后再调 print()。
*
* 语义:**只在真的横向溢出时缩小**(能正常换行的模板原样不动,避免偏离参考版式);
* 逐级缩到下限仍放不下,才改成允许换行,至少不溢出纸张。
*/
export function fitOverflowingPrintHeadings(host: HTMLElement): void {
const root = host.querySelector<HTMLElement>('.delivery-html-template-root');
if (!root) return;
const headings = Array.from(root.querySelectorAll<HTMLElement>('h1, h2, h3'));
for (const el of headings) {
if (!el.textContent?.trim()) continue;
const available = el.clientWidth || root.clientWidth;
if (available <= 0) continue;
if (el.scrollWidth <= available + 1) continue;
const base = Number.parseFloat(window.getComputedStyle(el).fontSize) || 0;
if (!(base > 0)) continue;
const floor = Math.max(PRINT_HEADING_MIN_FONT_PX, base * 0.5);
let size = base;
while (size > floor && el.scrollWidth > available + 1) {
size = Math.max(floor, size - 1);
el.style.setProperty('font-size', `${size}px`, 'important');
}
if (el.scrollWidth > available + 1) {
el.style.setProperty('white-space', 'normal', 'important');
el.style.setProperty('word-break', 'break-word', 'important');
el.style.setProperty('overflow-wrap', 'anywhere', 'important');
}
}
}
export function printHtmlViaHiddenIframe(html: string): Promise<void> {
return new Promise((resolve, reject) => {
let parsed: Document;
try {
parsed = new DOMParser().parseFromString(html, 'text/html');
} catch (err) {
reject(err instanceof Error ? err : new Error(tWebUi('orders.print.parseFail')));
return;
}
const bodyHtml = parsed.body?.innerHTML?.trim() || '';
if (!bodyHtml) {
reject(new Error(tWebUi('orders.print.emptyBody')));
return;
}
const HOST_ID = 'canteen-delivery-print-host';
const STYLE_ID = 'canteen-delivery-print-style';
// 清掉上一次残留
document.getElementById(HOST_ID)?.remove();
document.getElementById(STYLE_ID)?.remove();
const docStyles = Array.from(parsed.querySelectorAll('style'))
.map((el) => el.textContent || '')
.join('\n');
const hasIsolatedHtmlTemplate = parsed.querySelector('.delivery-html-template-root') !== null;
const isolatedTemplateReset = hasIsolatedHtmlTemplate ? `
#${HOST_ID} .delivery-template-page { width: 100%; margin: 0 auto; }
#${HOST_ID} .delivery-html-template-root { box-sizing: border-box !important; margin-left: auto !important; margin-right: auto !important; }
#${HOST_ID} .delivery-html-template-root,
#${HOST_ID} .delivery-html-template-root * ,
#${HOST_ID} .delivery-html-template-root *::before,
#${HOST_ID} .delivery-html-template-root *::after { box-sizing: border-box; }
` : '';
const styleEl = document.createElement('style');
styleEl.id = STYLE_ID;
styleEl.textContent = `
${docStyles}
${isolatedTemplateReset}
@media screen {
#${HOST_ID} {
position: fixed;
left: 0;
top: 0;
width: 100vw;
height: 100vh;
overflow: hidden;
z-index: 2147483646;
visibility: hidden;
pointer-events: none;
}
}
@media print {
html, body {
background: #fff !important;
color: #111 !important;
height: auto !important;
overflow: visible !important;
}
body > *:not(#${HOST_ID}) {
display: none !important;
}
#${HOST_ID} {
display: block !important;
position: static !important;
inset: auto !important;
width: auto !important;
height: auto !important;
max-width: none !important;
overflow: visible !important;
background: #fff !important;
color: #111 !important;
visibility: visible !important;
z-index: auto !important;
}
}
`;
const host = document.createElement('div');
host.id = HOST_ID;
host.setAttribute('data-print-host', 'delivery-note');
host.innerHTML = bodyHtml;
let fallbackTimer: number | null = null;
let afterPrintTimer: number | null = null;
let cleaned = false;
let resolved = false;
const cleanup = () => {
if (cleaned) return;
cleaned = true;
if (fallbackTimer) window.clearTimeout(fallbackTimer);
if (afterPrintTimer) window.clearTimeout(afterPrintTimer);
fallbackTimer = null;
afterPrintTimer = null;
window.removeEventListener('afterprint', onAfterPrint);
try {
host.remove();
} catch {
/* ignore */
}
try {
styleEl.remove();
} catch {
/* ignore */
}
};
const onAfterPrint = () => {
if (afterPrintTimer) window.clearTimeout(afterPrintTimer);
// 对话框打开期间也可能触发;多留一会再卸,避免预览源被拆
afterPrintTimer = window.setTimeout(cleanup, 15000);
};
try {
document.head.appendChild(styleEl);
document.body.appendChild(host);
window.addEventListener('afterprint', onAfterPrint);
// 等宿主挂上并完成一帧布局
window.requestAnimationFrame(() => {
window.requestAnimationFrame(() => {
try {
// 布局已完成:①先把过长标题缩到不溢出(会改变高度,必须排在位移测量之前)
// ②再把「目标坐标」换算成位移(方案 B:元素保持文档流,只平移)
fitOverflowingPrintHeadings(host);
applyLayoutTargets(host);
window.focus();
window.print();
if (!resolved) {
resolved = true;
resolve();
}
fallbackTimer = window.setTimeout(cleanup, 300000);
} catch (err) {
cleanup();
if (!resolved) {
resolved = true;
reject(err);
}
}
});
});
} catch (err) {
cleanup();
reject(err instanceof Error ? err : new Error(tWebUi('orders.print.openFail')));
}
});
}
function printDeliveryNoteHtml(pages: string[], documentStyle: 'guanmai' | 'standard' = 'standard') {
const html = buildDeliveryNoteDocumentHtml(pages, documentStyle, { autoPrint: false });
void printHtmlViaHiddenIframe(html);
}
export async function printDeliveryNotesToThermal(
payload: DeliveryNotePrintPayload,
printerName: string,
paperWidthMm: 58 | 80 = 80
): Promise<void> {
const { html } = buildDeliveryNotePrintHtml(payload, {
forThermal: true,
paperWidthMm,
autoPrint: false,
rowsPerPage: ROWS_PER_PAGE_THERMAL,
});
const { printHtmlToThermalPrinter } = await import('./thermalPrintService');
await printHtmlToThermalPrinter({
printerName,
html,
paperWidthMm,
title: payload.title,
});
}
export function printDeliveryNotes(payload: DeliveryNotePrintPayload) {
const { html } = buildDeliveryNotePrintHtml(payload, { autoPrint: false });
void printHtmlViaHiddenIframe(html);
}
export { fmtQty };