/** * 分拣标签打印(Web · 浏览器打印)。 * 设计:docs/design/20261013-分拣标签打印改蓝牙与浏览器直连.md * 版式与旧安卓称重终端 PrintManager.buildPickingLabelBitmap 一致(50×30mm @8dot/mm): * 「分拣标签 / 客户:… / 品名:… / 重量:X.XX 斤(或数量)/ 日期:…」+ 右上角二维码及其下码文;**不印订单号**。 * 复用配送单浏览器打印通道(当前页宿主 + window.print()),**不改**该通道本身。 */ import { printHtmlViaHiddenIframe } from './deliveryNotePrint'; import { isPickingWeightUnit } from './picking'; import qrcode from 'qrcode-generator'; export interface PickingLabel { companyName?: string | null; itemName: string; /** 结算量(重量单位时按同口径换算为「斤」展示) */ qty: number; unit?: string | null; date?: string | null; /** 二维码内容与二维码下方码文(旧秤端即商品条码) */ barcode?: string | null; /** 商品所在区域(`picking_items.storage_zone`)——2026-10-14 开发者要求可打到标签上 */ zone?: string | null; } /** 标签纸张尺寸(mm)——**不写死**,由打印弹窗传入并记住;默认 80×60(实物签尺寸,2026-10-14 开发者指定) */ export interface PickingLabelPaper { widthMm: number; heightMm: number; } /** 默认纸型=实物签 80×60(GP-3120TUB,2026-10-14 开发者:「80×60 先设置为这个」) */ const DEFAULT_PAPER: PickingLabelPaper = { widthMm: 80, heightMm: 60 }; /** 夹在合理区间内,非法值回落默认(防 0/负数/NaN 把版面弄崩) */ function normalizePaper(paper?: Partial | null): PickingLabelPaper { const pick = (value: unknown, fallback: number, min: number) => { const n = Number(value); return Number.isFinite(n) && n >= min && n <= 300 ? n : fallback; }; return { widthMm: pick(paper?.widthMm, DEFAULT_PAPER.widthMm, 20), heightMm: pick(paper?.heightMm, DEFAULT_PAPER.heightMm, 10), }; } /** 批量打印时的排队维度 */ export type PickingLabelGroupBy = 'order' | 'category' | 'sku' | 'zone'; /** 可参与排队的商品行最小字段集 */ export interface LabelSortableItem { order_code?: string | null; category_name?: string | null; storage_zone?: string | null; item_name?: string | null; sku_code?: string | null; sort_order?: number | null; } function groupValueOf(item: LabelSortableItem, groupBy: PickingLabelGroupBy): string { if (groupBy === 'order') return String(item.order_code || '').trim(); if (groupBy === 'category') return String(item.category_name || '').trim(); if (groupBy === 'zone') return String(item.storage_zone || '').trim(); return String(item.sku_code || item.item_name || '').trim(); } /** 某商品行在指定排队维度下的分组值(弹窗分组标题用) */ export function labelGroupKey(item: LabelSortableItem, groupBy: PickingLabelGroupBy): string { return groupValueOf(item, groupBy); } /** * 批量打印标签前的排队:主键=所选维度,同键再按 sort_order、最后按品名。 * 区域可传入分公司区域顺序(`zoneOrder`):已列入的按顺序,未列入的排最后(再按名称)。 */ export function sortItemsForLabelPrint( items: T[], groupBy: PickingLabelGroupBy, options?: { zoneOrder?: string[] } ): T[] { const zoneRank = groupBy === 'zone' && Array.isArray(options?.zoneOrder) ? new Map(options!.zoneOrder.map((z, i) => [String(z).trim(), i])) : null; const compareGroup = (a: string, b: string) => { if (zoneRank) { const ra = zoneRank.has(a) ? zoneRank.get(a)! : Number.MAX_SAFE_INTEGER; const rb = zoneRank.has(b) ? zoneRank.get(b)! : Number.MAX_SAFE_INTEGER; if (ra !== rb) return ra - rb; } return a.localeCompare(b, 'zh-CN'); }; return [...items].sort((a, b) => { const ga = groupValueOf(a, groupBy); const gb = groupValueOf(b, groupBy); if (ga !== gb) return compareGroup(ga, gb); const sa = Number(a.sort_order) || 0; const sb = Number(b.sort_order) || 0; if (sa !== sb) return sa - sb; return String(a.item_name || '').localeCompare(String(b.item_name || ''), 'zh-CN'); }); } /** 与秤端 203dpi(8 dot/mm)一致;下面是**内容偏移**的基准(旧秤端 50×30mm 版面)。 纸宽/纸高本身不写死,由打印弹窗传入(见 PickingLabelPaper)。 */ const DOT_MM = 1 / 8; const QR_DOTS = 110; const LINE_DOTS = 28; function mm(dots: number): string { return `${(dots * DOT_MM).toFixed(3)}mm`; } /** 当天本地日期(旧秤端 date 缺失时用当天) */ function todayIso(): string { const d = new Date(); const pad = (n: number) => String(n).padStart(2, '0'); return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`; } function esc(value: unknown): string { return String(value == null ? '' : value) .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"'); } /** 市斤/斤(不含「公斤」,与秤端 WeighStationMatcher.isJinUnit 一致) */ function isJinUnit(unit?: string | null): boolean { const u = String(unit || '').trim().toLowerCase(); if (!u) return false; if (u.includes('公斤') || u.includes('千克') || u === 'kg' || u === 'g' || u === '克') return false; return u.includes('斤'); } /** 克(与秤端 WeighStationMatcher.isGramUnit 一致) */ function isGramUnit(unit?: string | null): boolean { const u = String(unit || '').trim().toLowerCase(); return u === 'g' || u === '克'; } /** 展示用单位;空则默认斤(与秤端 displayUnit 一致) */ function displayUnit(unit?: string | null): string { const u = String(unit || '').trim(); return u || '斤'; } /** 标签重量/数量行(与旧秤端 formatLabelWeightLine 逐字一致):重量单位统一展示「斤」,计数单位展示数量。 */ export function formatLabelWeightLine(qty: number, unit?: string | null): string { const value = Number(qty) || 0; if (!isPickingWeightUnit(unit)) { return `数量:${value.toFixed(2)} ${displayUnit(unit)}`; } let kg = value; if (isJinUnit(unit)) kg = value / 2.0; else if (isGramUnit(unit)) kg = value / 1000.0; return `重量:${(kg * 2.0).toFixed(2)} 斤`; } /** 生成二维码 SVG(内联,不依赖外部服务);内容为空或编码失败时返回空串。 */ function qrSvg(text: unknown): string { const content = String(text == null ? '' : text).trim(); if (!content) return ''; try { const qr = qrcode(0, 'M'); qr.addData(content); qr.make(); return qr.createSvgTag({ cellSize: 4, margin: 1, scalable: true }); } catch { return ''; } } /** 打印旋转(补偿打印机驱动把页面转 90°/180° 的情况;默认不旋转) */ export type PickingLabelRotation = 0 | 90 | 180 | 270; function normalizeRotation(value: unknown): PickingLabelRotation { const n = Number(value); return n === 90 || n === 180 || n === 270 ? n : 0; } /** 把「若干个标签块 + 内部 CSS」拼成完整打印文档(页面尺寸/旋转两模式共用) */ function assembleLabelDocument(params: { title: string; sections: string[]; innerRules: string; paper: PickingLabelPaper; rotation: PickingLabelRotation; /** 标签块高(mm,仅不旋转时生效):不传 = 纸高 − 0.5(整页,标尺页/旋转模式用) */ blockHeightMm?: number; /** 是否**强制**一签一页(见 buildPickingLabelHtml:块只包住内容时,必须靠强制分页保证一签一页) */ pageBreakPerLabel?: boolean; }): string { const { title, sections, innerRules, paper, rotation } = params; const transposed = rotation === 90 || rotation === 270; // 旋转 90/270 时页面尺寸转置(标签块转过来才装得下) const pageW = transposed ? paper.heightMm : paper.widthMm; const pageH = transposed ? paper.widthMm : paper.heightMm; const maxLabelH = paper.heightMm - 0.5; // 略小于纸高,防四舍五入把满高挤出页外 // 旋转模式仍用整页高(180° 以中心为原点旋转,改块高会把内容挪位) const wantedH = rotation === 0 ? Number(params.blockHeightMm) : Number.NaN; // 取 3 位小数再拼进 CSS,避免浮点噪声(如 23.839999999999996mm) const labelH = wantedH > 0 && wantedH < maxLabelH ? Math.round(wantedH * 1000) / 1000 : maxLabelH; /** 块级样式:不旋转 = 相对定位(留在文档流里,靠分页控制一签一页);旋转 = 绝对定位在页面框内 + transform */ const blockBase = `box-sizing: border-box; overflow: hidden; color: #000; font-family: -apple-system, "PingFang SC", "Microsoft YaHei", Arial, sans-serif;`; if (rotation === 0) { // 一签一页:块只包住内容(blockHeightMm)+ **强制分页**。 // 为什么不能再靠「自然平铺」:平铺要求块高恰好等于**可用高度**,而打印对话框的「边距」 // 会盖掉 `@page{margin:0}`(默认约 10mm,机头还有死区)⇒ 块高 = 纸高 就溢出被拆到下一页, // 实测「打两张耗三张、中间夹一张空白」。块只包住内容后,边距怎么选都不会溢出。 // 末张复位分页,防尾部多出一张空白(历史同类问题勿回退)。 const breakRules = params.pageBreakPerLabel ? ` .pick-label { page-break-after: always; break-after: page; } .pick-label:last-child { page-break-after: auto; break-after: auto; }` : ''; return `${title}${sections.join('')}`; } // 旋转模式:一页一签(页面框 = 纸型),标签块绝对定位 + 旋转 const transform = rotation === 90 ? ' transform-origin: top left; transform: rotate(90deg) translateY(-100%);' : rotation === 180 ? ' transform-origin: center center; transform: rotate(180deg);' : ' transform-origin: top left; transform: rotate(-90deg) translateX(-100%);'; const pages = sections.map((section) => `
${section}
`).join(''); return `${title}${pages}`; } /** 生成标签页(纸张尺寸 + 旋转 + 客户/区域开关可配);旋转 0° 时**一签一页**(块只包住内容 + 强制分页)。 */ export function buildPickingLabelHtml( labels: PickingLabel[], options?: { paper?: Partial | null; /** 旋转角度:0(默认)| 90 | 180 | 270 —— 用于抵消打印机驱动自身的旋转 */ rotation?: PickingLabelRotation | number | null; /** 是否打「客户:…」行(默认 true;false 时该行不输出、后面的行上移) */ showCustomer?: boolean | null; /** 是否打「区域:…」行(默认 true,2026-10-14 开发者要求) */ showZone?: boolean | null; } ): string { const paper = normalizePaper(options?.paper); const rotation = normalizeRotation(options?.rotation); const showCustomer = options?.showCustomer !== false; const showZone = options?.showZone !== false; /** 版面行(自上而下):标题 / 客户? / 区域? / 品名 / 重量 / 日期 —— 关掉的行不占位,后面的行上移 */ const lineSpecs: Array<{ cls: string; fontDots: number; bold?: boolean }> = [ { cls: 't-title', fontDots: 24, bold: true }, ]; if (showCustomer) lineSpecs.push({ cls: 't-cust', fontDots: 20 }); if (showZone) lineSpecs.push({ cls: 't-zone', fontDots: 20 }); lineSpecs.push({ cls: 't-name', fontDots: 20 }); lineSpecs.push({ cls: 't-weight', fontDots: 26, bold: true }); lineSpecs.push({ cls: 't-date', fontDots: 18 }); const sections = (labels || []).map((label) => { const qr = qrSvg(label.barcode); const codeText = String(label.barcode || '').trim(); const lines: string[] = ['
分拣标签
']; if (showCustomer) { lines.push(`
${esc(`客户:${String(label.companyName || '').trim() || '客户'}`)}
`); } if (showZone) { lines.push(`
${esc(`区域:${String(label.zone || '').trim() || '—'}`)}
`); } lines.push(`
${esc(`品名:${String(label.itemName || '').trim() || '商品'}`)}
`); lines.push(`
${esc(formatLabelWeightLine(label.qty, label.unit))}
`); lines.push(`
${esc(`日期:${String(label.date || '').trim() || todayIso()}`)}
`); return `
${lines.join('\n')} ${qr ? `
${qr}
` : ''} ${codeText ? `
${esc(codeText)}
` : ''}
`; }); /** * 四周安全边距(2026-10-14,开发者要求“无论纸张大小四周都留足够比例的位置”): * · **比例**:取页面尺寸的 6%(至少 1mm); * · **再加一条硬约束**:80mm 卷的热敏/标签机打印头可打印宽度只有 ~70mm * ⇒ 内容宽度不得超过 `SAFE_PRINT_WIDTH_MM`,**左右各让出 `纸宽 − 上限`**(取"居中铺"与"左对齐铺"两种映射的**安全交集**)。 * 两者取大值 ⇒ 无论驱动把页面居中还是左对齐,内容都不会被裁。 * 窄纸(如 50×30)比例边距很小,与老版式接近。 */ const SAFE_MARGIN_RATIO = 0.06; const SAFE_PRINT_WIDTH_MM = 70; const labelH = paper.heightMm - 0.5; // 整页高:只用于算比例边距(块高另见 blockHeightMm) const printLimitInsetMm = Math.max(0, paper.widthMm - SAFE_PRINT_WIDTH_MM); const insetXMm = Math.max(1, paper.widthMm * SAFE_MARGIN_RATIO, printLimitInsetMm); const insetYMm = Math.max(1, labelH * SAFE_MARGIN_RATIO); const qrSizeMm = QR_DOTS * DOT_MM; // 13.75mm const lineStepMm = LINE_DOTS * DOT_MM; // 3.5mm const mmf = (value: number) => `${value.toFixed(3)}mm`; /** * 标签块高(2026-10-14 二次修正):**只包住内容**,不再等于纸高。 * 原因:`@page { margin: 0 }` 会被打印对话框的「边距」设置盖掉(默认约 10mm,机头还有死区), * 可用高度因此小于纸高;块高若等于纸高就溢出、被浏览器拆到下一页 ⇒ 实测「打两张耗三张、中间夹空白」。 * 块只包住内容 ⇒ 无论对话框边距选「默认」还是「无」都不会溢出(前提:可用高 ≥ 块高)。 * 一签一页改由**强制分页**保证(见 assembleLabelDocument 的 pageBreakPerLabel)。 * 取「文字行下沿」与「二维码 + 编号列下沿」两者的较大值,再加下边距 insetY(行高按字号 ×1.2 估)。 */ const lineBottomMm = Math.max( ...lineSpecs.map( (line, index) => insetYMm + index * lineStepMm + line.fontDots * DOT_MM * 1.2 ) ); const qrBottomMm = insetYMm + qrSizeMm + 0.75 + 14 * DOT_MM * 1.2; const blockHeightMm = Math.min( paper.heightMm - 0.5, Math.max(lineBottomMm, qrBottomMm) + insetYMm ); const lineTop = (index: number) => mmf(insetYMm + index * lineStepMm); /** 标签内部的文字/二维码规则(两种模式共用;四周留比例安全边距;行位置按**实际显示的行**排) */ const lineRules = lineSpecs .map( (line, index) => `.pick-label .${line.cls} { top: ${lineTop(index)}; font-size: ${mm(line.fontDots)};${ line.bold ? ' font-weight: 700;' : '' } }` ) .join('\n'); const innerRules = `.pick-label > div { position: absolute; left: ${mmf(insetXMm)}; right: ${mmf(insetXMm + qrSizeMm + 1)}; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } ${lineRules} .pick-label .t-qr { left: auto; right: ${mmf(insetXMm)}; top: ${mmf(insetYMm)}; width: ${mmf(qrSizeMm)}; height: ${mmf(qrSizeMm)}; } .pick-label .t-qr svg { width: 100%; height: 100%; } .pick-label .t-code { left: auto; right: ${mmf(insetXMm)}; top: ${mmf(insetYMm + qrSizeMm + 0.75)}; width: ${mmf(qrSizeMm)}; text-align: center; font-size: ${mm(14)}; }`; return assembleLabelDocument({ title: '分拣标签', sections, innerRules, paper, rotation, blockHeightMm, pageBreakPerLabel: true, }); } /** * **测试打印(标尺页)**:在整页上画边框 + 毫米刻度,用来量出打印机的**可打印区与原点**。 * 用途:现场出现“二维码/文字被裁”时,打一张拍给开发,就能看出到底从第几毫米开始/结束能打。 * 刻度:每 5mm 一个短刻度,每 10mm 一个长刻度 + 数字(左上起算)。 */ export function buildPickingLabelRulerHtml(options?: { paper?: Partial | null; rotation?: PickingLabelRotation | number | null; /** 打几张(默认 2,便于观察跨页) */ pages?: number; }): string { const paper = normalizePaper(options?.paper); const rotation = normalizeRotation(options?.rotation); const labelH = paper.heightMm - 0.5; const tik = (pos: number, axis: 'x' | 'y'): string => { const major = pos % 10 === 0; const cls = axis === 'x' ? `tk-v${major ? ' major' : ''}` : `tk-h${major ? ' major' : ''}`; const style = axis === 'x' ? `left:${pos}mm` : `top:${pos}mm`; const tick = `
`; if (!major) return tick; const lblStyle = axis === 'x' ? `left:${pos}mm` : `top:${pos}mm`; return `${tick}
${pos}
`; }; const ticks: string[] = []; for (let x = 0; x <= Math.floor(paper.widthMm); x += 5) ticks.push(tik(x, 'x')); for (let y = 0; y <= Math.floor(labelH); y += 5) ticks.push(tik(y, 'y')); const ruler = `
${ticks.join('')}
${paper.widthMm} × ${paper.heightMm} mm 旋转 ${rotation}°
↑ 顶边 / ← 左边(刻度单位 mm)
`; const count = Math.min(Math.max(Number(options?.pages) || 2, 1), 5); const sections = Array.from({ length: count }, () => ruler); const innerRules = `.pick-label .rl-frame { position: absolute; left: 1mm; top: 1mm; right: 1mm; bottom: 1mm; border: 0.4mm solid #000; } .pick-label .tk-v { position: absolute; top: 0; width: 0.3mm; height: 2mm; background: #000; } .pick-label .tk-v.major { height: 4mm; } .pick-label .tk-h { position: absolute; left: 0; height: 0.3mm; width: 2mm; background: #000; } .pick-label .tk-h.major { width: 4mm; } .pick-label .tk-lbl { position: absolute; font-size: 2.2mm; line-height: 2.2mm; color: #000; } .pick-label .tk-lbl-x { top: 4.2mm; transform: translateX(-50%); } .pick-label .tk-lbl-y { left: 4.4mm; transform: translateY(-50%); } .pick-label .rl-mid { position: absolute; left: 50%; top: 45%; transform: translate(-50%, -50%); font-size: 3.2mm; font-weight: 700; white-space: nowrap; } .pick-label .rl-mid2 { position: absolute; left: 50%; top: 58%; transform: translateX(-50%); font-size: 2.4mm; white-space: nowrap; }`; return assembleLabelDocument({ title: '打印测试(标尺)', sections, innerRules, paper, rotation }); } export async function printPickingLabels( labels: PickingLabel[], options?: { paper?: Partial | null; rotation?: PickingLabelRotation | number | null; /** 是否打「客户:…」行(默认 true) */ showCustomer?: boolean | null; /** 是否打「区域:…」行(默认 true) */ showZone?: boolean | null; } ): Promise { const list = (labels || []).filter(Boolean); if (!list.length) return; await printHtmlViaHiddenIframe(buildPickingLabelHtml(list, options)); } /** 测试打印(标尺页):量可打印区/原点用 */ export async function printPickingLabelRuler(options?: { paper?: Partial | null; rotation?: PickingLabelRotation | number | null; pages?: number; }): Promise { await printHtmlViaHiddenIframe(buildPickingLabelRulerHtml(options)); }