修复销售单据打印方向固定及跨页问题

打印遵循浏览器和驱动所选纸张与方向,将完整单据适配到一页,保留预览尺寸及套打偏移。新增打印时序和重复打印回归测试,并更新设置说明。

验证:251项测试通过;32种Chrome PDF组合均为单页,内容完整。
This commit is contained in:
summer committed 2026-10-22 12:32:44 +08:00
1 parent 020249d34b
commit b9154a752d
5 files changed
+120 -13

No files matched your search

+7 -5
View File
@@ -51,7 +51,9 @@ function receipt(order,rawSettings={},mode='full'){
const paper=String(order.paper_number||'未分配').replace(/^(\d{8})-(\d+)$/,'$1$2'); const paper=String(order.paper_number||'未分配').replace(/^(\d{8})-(\d+)$/,'$1$2');
const rounding=order.rounding_mode==='yuan'&&Number.isSafeInteger(order.rounding_adjustment)&&order.rounding_adjustment!==0?'<div>整单金额四舍五入到元</div>':''; const rounding=order.rounding_mode==='yuan'&&Number.isSafeInteger(order.rounding_adjustment)&&order.rounding_adjustment!==0?'<div>整单金额四舍五入到元</div>':'';
const totalText=order.rounding_mode==='yuan'&&order.total%100===0?String(order.total/100):yuan(order.total); const totalText=order.rounding_mode==='yuan'&&order.total%100===0?String(order.total/100):yuan(order.total);
const body=`<section class="sheet ${overlay?'overlay':''}"><div class="print-frame"><div class="content"> const frameWidth=s.width-Math.max(3,12+s.offsetX)-Math.max(3,12-s.offsetX);
const frameHeight=s.height-Math.max(3,s.contentTop+s.offsetY)-8;
const body=`<section class="sheet ${overlay?'overlay':''}"><div class="print-frame" data-layout-width-mm="${frameWidth}" data-layout-height-mm="${frameHeight}"><div class="content">
<header><h1 class="preprinted">${escape(s.store)}</h1><div class="preprinted subtitle">${escape(s.subtitle)}</div></header> <header><h1 class="preprinted">${escape(s.store)}</h1><div class="preprinted subtitle">${escape(s.subtitle)}</div></header>
<div class="meta"><span>客户:${escape(order.customer||'—')}</span><span>日期:${escape(order.date)}</span><strong>纸单号:${escape(paper)}</strong></div> <div class="meta"><span>客户:${escape(order.customer||'—')}</span><span>日期:${escape(order.date)}</span><strong>纸单号:${escape(paper)}</strong></div>
<div class="meta secondary">${STATUS_NOTICE[order.status]?`<span>${escape(STATUS_NOTICE[order.status])}</span>`:''}<span>收款方式:${escape(order.paymentMethods?.join('、')||'尚未登记')}</span></div> <div class="meta secondary">${STATUS_NOTICE[order.status]?`<span>${escape(STATUS_NOTICE[order.status])}</span>`:''}<span>收款方式:${escape(order.paymentMethods?.join('、')||'尚未登记')}</span></div>
@@ -60,10 +62,10 @@ function receipt(order,rawSettings={},mode='full'){
<section class="notices preprinted"><h2>注意事项</h2>${numbered(notices)}<h2>珠宝首饰保养须知</h2>${numbered(care)}<p class="promise"><strong>公司承诺:</strong>${escape(promise)}</p></section> <section class="notices preprinted"><h2>注意事项</h2>${numbered(notices)}<h2>珠宝首饰保养须知</h2>${numbered(care)}<p class="promise"><strong>公司承诺:</strong>${escape(promise)}</p></section>
<div class="note">备注:${escape(order.note||'—')}</div> <div class="note">备注:${escape(order.note||'—')}</div>
<div class="signatures">${s.contact?`<span>联系电话:${escape(s.contact)}</span>`:''}<span class="salesperson">经办人:${escape(order.salesperson||'')} ________________</span></div> <div class="signatures">${s.contact?`<span>联系电话:${escape(s.contact)}</span>`:''}<span class="salesperson">经办人:${escape(order.salesperson||'')} ________________</span></div>
</div></div></section>`; </div><svg class="print-canvas" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" aria-hidden="true"><foreignObject x="0" y="0"></foreignObject></svg></div></section>`;
return `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escape(paper)} · 客户单据</title><style> return `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escape(paper)} · 客户单据</title><style>
*{box-sizing:border-box}body{margin:0;background:#e8e7e4;color:#181818;font-family:"Microsoft YaHei","PingFang SC",sans-serif;font-size:12px}.toolbar{padding:12px 20px;background:white;position:sticky;top:0;z-index:2;display:flex;gap:12px;align-items:center;flex-wrap:wrap;box-shadow:0 1px 5px #aaa}.toolbar button,.toolbar a{padding:9px 16px;border:1px solid #444;border-radius:5px;background:white;color:#222;text-decoration:none;cursor:pointer}.toolbar button{background:#254d42;color:#fff}.toolbar button:disabled{opacity:.5}.toolbar small{color:#555}.sheet{width:${s.width}mm;height:${s.height}mm;background:white;margin:12px auto;position:relative;box-shadow:0 3px 16px #bbb}.print-frame{position:absolute;left:${Math.max(3,12+s.offsetX)}mm;right:${Math.max(3,12-s.offsetX)}mm;top:${Math.max(3,s.contentTop+s.offsetY)}mm;bottom:8mm}.content{width:100%;transform-origin:top left}header{text-align:center;padding:0 0 6mm}h1{font-size:25px;letter-spacing:5px;margin:0 0 5px;overflow-wrap:anywhere}.subtitle{letter-spacing:3px;font-size:16px;overflow-wrap:anywhere}.meta{display:flex;justify-content:space-between;gap:10px;margin:5px 0;overflow-wrap:anywhere}.meta span,.meta strong{max-width:65%}.secondary{font-size:11px;margin-bottom:8px}table{border-collapse:collapse;width:100%;table-layout:fixed}th,td{border:1px solid #333;padding:4px;overflow-wrap:anywhere;text-align:center}th{height:9mm;font-size:11px}td{height:${s.rowHeight}mm;font-size:12px}td:nth-child(2){text-align:left}.totals{display:flex;justify-content:space-between;gap:10px;padding:10px 6px;border:1px solid #333;border-top:0;line-height:1.6;overflow-wrap:anywhere}.amount{flex-shrink:0}.amount strong{font-size:16px}.notices{border:1px solid #333;border-top:0;padding:6px 8px;font-family:"SimSun","Songti SC",serif;font-size:12px;line-height:1.65}.notices h2{font-size:13px;margin:0;font-weight:700}.notices ol{padding-left:20px;margin:0 0 2px}.notices li{padding-left:0}.promise{margin:2px 0 0;font-weight:600}.note{padding:8px 0;white-space:pre-wrap;overflow-wrap:anywhere;line-height:1.6}.signatures{display:flex;justify-content:space-between;gap:12px;padding-top:8px;overflow-wrap:anywhere}.signatures .salesperson{margin-left:auto}.overlay .preprinted{visibility:hidden}.overlay th,.overlay td,.overlay .totals,.overlay .notices{border-color:transparent}.compact .blank-row{display:none}.compact td{height:7mm;padding:2px 3px}.compact header{padding-bottom:3mm}.compact .note,.compact .signatures{padding-top:4px;padding-bottom:4px} *{box-sizing:border-box}body{margin:0;background:#e8e7e4;color:#181818;font-family:"Microsoft YaHei","PingFang SC",sans-serif;font-size:12px}.toolbar{padding:12px 20px;background:white;position:sticky;top:0;z-index:2;display:flex;gap:12px;align-items:center;flex-wrap:wrap;box-shadow:0 1px 5px #aaa}.toolbar button,.toolbar a{padding:9px 16px;border:1px solid #444;border-radius:5px;background:white;color:#222;text-decoration:none;cursor:pointer}.toolbar button{background:#254d42;color:#fff}.toolbar button:disabled{opacity:.5}.toolbar small{color:#555}.sheet{width:${s.width}mm;height:${s.height}mm;background:white;margin:12px auto;position:relative;box-shadow:0 3px 16px #bbb}.print-frame{position:absolute;left:${Math.max(3,12+s.offsetX)}mm;right:${Math.max(3,12-s.offsetX)}mm;top:${Math.max(3,s.contentTop+s.offsetY)}mm;bottom:8mm}.content{width:100%;transform-origin:top left}.print-canvas{display:none}header{text-align:center;padding:0 0 6mm}h1{font-size:25px;letter-spacing:5px;margin:0 0 5px;overflow-wrap:anywhere}.subtitle{letter-spacing:3px;font-size:16px;overflow-wrap:anywhere}.meta{display:flex;justify-content:space-between;gap:10px;margin:5px 0;overflow-wrap:anywhere}.meta span,.meta strong{max-width:65%}.secondary{font-size:11px;margin-bottom:8px}table{border-collapse:collapse;width:100%;table-layout:fixed}th,td{border:1px solid #333;padding:4px;overflow-wrap:anywhere;text-align:center}th{height:9mm;font-size:11px}td{height:${s.rowHeight}mm;font-size:12px}td:nth-child(2){text-align:left}.totals{display:flex;justify-content:space-between;gap:10px;padding:10px 6px;border:1px solid #333;border-top:0;line-height:1.6;overflow-wrap:anywhere}.amount{flex-shrink:0}.amount strong{font-size:16px}.notices{border:1px solid #333;border-top:0;padding:6px 8px;font-family:"SimSun","Songti SC",serif;font-size:12px;line-height:1.65}.notices h2{font-size:13px;margin:0;font-weight:700}.notices ol{padding-left:20px;margin:0 0 2px}.notices li{padding-left:0}.promise{margin:2px 0 0;font-weight:600}.note{padding:8px 0;white-space:pre-wrap;overflow-wrap:anywhere;line-height:1.6}.signatures{display:flex;justify-content:space-between;gap:12px;padding-top:8px;overflow-wrap:anywhere}.signatures .salesperson{margin-left:auto}.overlay .preprinted{visibility:hidden}.overlay th,.overlay td,.overlay .totals,.overlay .notices{border-color:transparent}.compact .blank-row{display:none}.compact td{height:7mm;padding:2px 3px}.compact header{padding-bottom:3mm}.compact .note,.compact .signatures{padding-top:4px;padding-bottom:4px}
@page{size:${s.width}mm ${s.height}mm;margin:0}@media print{html,body{width:${s.width}mm;height:${s.height}mm;margin:0;padding:0;background:white}.toolbar{display:none}.sheet{box-shadow:none;margin:0;break-inside:avoid;page-break-inside:avoid}body.fit-error .sheet{visibility:hidden}} @page{size:auto;margin:0}@media print{html,body{width:auto;height:auto;margin:0;padding:0;background:white}.toolbar{display:none}.sheet{width:100%;height:calc(100vh - 1px);box-shadow:none;margin:0;break-inside:avoid;page-break-inside:avoid}.print-frame>.content{display:none}.print-canvas{display:block;width:100%;height:100%;position:absolute;inset:0}body.fit-error .sheet{visibility:hidden}}
</style></head><body><div class="toolbar"><button id="print" disabled>打印/保存 PDF</button><a href="?mode=${overlay?'full':'overlay'}">切换${overlay?'完整单据':'预印纸套打'}模板</a><small>${overlay?'套打位置是待校准初稿,尚未匹配实物纸样。':'打印比例选100%,关闭浏览器页眉页脚。'}</small><small id="fit-status" role="status">正在调整为一页…</small></div>${body}<script src="/print.js"></script></body></html>`; </style></head><body><div class="toolbar"><button id="print" disabled>打印/保存 PDF</button><a href="?mode=${overlay?'full':'overlay'}">切换${overlay?'完整单据':'预印纸套打'}模板</a><small>纸张尺寸和横向/纵向在打印窗口选择,关闭页眉页脚。${overlay?'套打位置仍需按实物纸样校准。':''}</small><small id="fit-status" role="status">正在调整为一页…</small></div>${body}<script src="/print.js"></script></body></html>`;
} }
module.exports={receipt,settings,defaults,escape,uppercaseMoney,notices,care,promise}; module.exports={receipt,settings,defaults,escape,uppercaseMoney,notices,care,promise};
+1 -1
View File
@@ -746,7 +746,7 @@ async function savePrintSettings(form,data){
finally{printSettingsSaving=false;if($('#print-settings')===form)fields.disabled=state.user.role!=='owner';syncPrintSettingsPreview();} finally{printSettingsSaving=false;if($('#print-settings')===form)fields.disabled=state.user.role!=='owner';syncPrintSettingsPreview();}
} }
function renderSettings(){const s=state.printing,canEdit=state.user.role==='owner'; function renderSettings(){const s=state.printing,canEdit=state.user.role==='owner';
$('#main').innerHTML=heading('PRINT & SETTINGS','打印与设置','先把单据做好,选好纸张和打印机后再校准位置。')+`<div class="split"><section class="panel"><div class="panel-title print-settings-title"><div><h2>客户打印模板</h2><p id="print-settings-status" class="small muted" aria-live="polite"></p></div>${canEdit?'<button type="submit" form="print-settings" class="primary">保存打印设置</button>':'<span class="small muted">由麦麦账号修改</span>'}</div><form id="print-settings"><fieldset class="print-settings-fields" ${canEdit?'':'disabled'}><div class="grid two">${field('店名','store',s.store,'text','maxlength="80" required')}${field('单据标题','subtitle',s.subtitle,'text','maxlength="80"')}${field('客户联系信息(选填)','contact',s.contact,'text','maxlength="80"')}${field('表格最少行数','rows',s.rows,'number','min="3" max="12" required')}${field('纸宽(mm)','width',s.width,'number','min="100" max="300" step="0.1" required')}${field('纸高(mm)','height',s.height,'number','min="140" max="400" step="0.1" required')}${field('左右偏移(mm,正数向右)','offsetX',s.offsetX,'number','min="-30" max="30" step="0.1" required')}${field('上下偏移(mm,正数向下)','offsetY',s.offsetY,'number','min="-30" max="30" step="0.1" required')}${field('内容距顶部(mm)','contentTop',s.contentTop,'number','min="5" max="40" step="0.1" required')}${field('商品行高(mm)','rowHeight',s.rowHeight,'number','min="7" max="16" step="0.1" required')}</div></fieldset><div class="form-actions">${state.orders[0]?button('打开最近一单预览','print','',`data-id="${state.orders[0].id}"`):''}</div><div id="print-settings-error" aria-live="polite"></div></form></section><section class="panel print-settings-preview"><p class="small muted">填写效果示意;保存后用于实际打印。</p><div class="print-preview-mini"><div class="paper-mini"><strong id="print-mini-store">${e(s.store)}</strong><p id="print-mini-subtitle">${e(s.subtitle)}</p><p id="print-mini-contact" ${s.contact?'':'hidden'}>${e(s.contact)}</p><table><tr><td>商品名称</td><td>克重</td><td>成交金额</td></tr><tr><td>足金手链</td><td>1.200g</td><td>1,200.00</td></tr><tr><td> </td><td></td><td></td></tr></table><p>合计金额 ¥1,200.00</p><p>大写:壹仟贰佰元整</p><p>注意事项 · 珠宝首饰保养须知</p><p>经办人 ______</p></div></div><div class="note">默认纸张241 × 279mm。所有内容自动排在一页,明细较多时自动缩小。表格最少行数只用于补空行,不再分页。完整模板可先打印成PDF;套打模板是可调初稿,尚未匹配实物预印格线。</div><p class="small muted">补打沿用同一订单号,不会重复出库或收入。客户预览接口不返回成本、垫资人、利润及内部操作日志。</p></section></div><div class="grid two"><section class="panel"><h2>数据库与备份</h2><p>${state.mode==='production'?'主账保存在部署服务器的独立SQLite数据库。':'现在运行在本机试用环境,云端正式数据库尚未部署。'}</p><p class="small muted">启动时和运行期间每6小时生成完整数据库备份。本机同盘备份不能防电脑损坏,正式部署还需异地备份。</p>${state.backup.last?`<p class="small">本次运行最近备份:${e(state.backup.last.time)}</p>`:''}${state.backup.error?`<p class="error">${e(state.backup.error)}</p>`:''}${state.user.role==='owner'?button('生成并下载完整备份','backup'):'<p class="muted">由麦麦账号下载备份。</p>'}</section><section class="panel"><h2>飞书查看副本</h2><p><span class="badge ${state.sync.enabled?'':'warn'}">${state.sync.enabled?'已配置':'尚未连接'}</span></p><p class="small muted">使用新账专用表单向同步。修改和复核在本系统完成;同步失败不重开订单、不影响本地账务保存。</p>${state.sync.enabled?`<p>待同步 ${state.sync.pending} 项 · 失败 ${state.sync.failed} 项</p>${state.sync.error?`<p class="error">${e(state.sync.error)}</p>`:''}${state.user.role==='owner'?button('立即重试同步','sync'):''}`:'<p class="note">已预留应用API同步通道。正式连接时再配置新表,未连接原销售表,未试写真实账务。</p>'}</section></div>${state.mode!=='demo'?`<section class="panel"><h2>更改当前账号密码</h2><form id="password-form"><div class="grid two">${field('原密码','current','','password','required autocomplete="current-password"')}${field('新密码(至少12个字符)','password','','password','required minlength="12" autocomplete="new-password"')}</div><div class="form-actions"><button>修改并重新登录</button></div></form></section>`:''}`; $('#main').innerHTML=heading('PRINT & SETTINGS','打印与设置','先把单据做好,选好纸张和打印机后再校准位置。')+`<div class="split"><section class="panel"><div class="panel-title print-settings-title"><div><h2>客户打印模板</h2><p id="print-settings-status" class="small muted" aria-live="polite"></p></div>${canEdit?'<button type="submit" form="print-settings" class="primary">保存打印设置</button>':'<span class="small muted">由麦麦账号修改</span>'}</div><form id="print-settings"><fieldset class="print-settings-fields" ${canEdit?'':'disabled'}><div class="grid two">${field('店名','store',s.store,'text','maxlength="80" required')}${field('单据标题','subtitle',s.subtitle,'text','maxlength="80"')}${field('客户联系信息(选填)','contact',s.contact,'text','maxlength="80"')}${field('表格最少行数','rows',s.rows,'number','min="3" max="12" required')}${field('预览纸宽(mm)','width',s.width,'number','min="100" max="300" step="0.1" required')}${field('预览纸高(mm)','height',s.height,'number','min="140" max="400" step="0.1" required')}${field('左右偏移(mm,正数向右)','offsetX',s.offsetX,'number','min="-30" max="30" step="0.1" required')}${field('上下偏移(mm,正数向下)','offsetY',s.offsetY,'number','min="-30" max="30" step="0.1" required')}${field('内容距顶部(mm)','contentTop',s.contentTop,'number','min="5" max="40" step="0.1" required')}${field('商品行高(mm)','rowHeight',s.rowHeight,'number','min="7" max="16" step="0.1" required')}</div></fieldset><div class="form-actions">${state.orders[0]?button('打开最近一单预览','print','',`data-id="${state.orders[0].id}"`):''}</div><div id="print-settings-error" aria-live="polite"></div></form></section><section class="panel print-settings-preview"><p class="small muted">填写效果示意;保存后用于实际打印。</p><div class="print-preview-mini"><div class="paper-mini"><strong id="print-mini-store">${e(s.store)}</strong><p id="print-mini-subtitle">${e(s.subtitle)}</p><p id="print-mini-contact" ${s.contact?'':'hidden'}>${e(s.contact)}</p><table><tr><td>商品名称</td><td>克重</td><td>成交金额</td></tr><tr><td>足金手链</td><td>1.200g</td><td>1,200.00</td></tr><tr><td> </td><td></td><td></td></tr></table><p>合计金额 ¥1,200.00</p><p>大写:壹仟贰佰元整</p><p>注意事项 · 珠宝首饰保养须知</p><p>经办人 ______</p></div></div><div class="note">实际纸张尺寸和横向/纵向在打印窗口或打印机驱动中选择,单据会按可用区域自动排为一页。这里的宽高只用于预览和内容排版,默认241 × 279mm。表格最少行数只用于补空行。完整模板可先保存PDF;套打模板仍需按实物预印格线校准偏移。</div><p class="small muted">补打沿用同一订单号,不会重复出库或收入。客户预览接口不返回成本、垫资人、利润及内部操作日志。</p></section></div><div class="grid two"><section class="panel"><h2>数据库与备份</h2><p>${state.mode==='production'?'主账保存在部署服务器的独立SQLite数据库。':'现在运行在本机试用环境,云端正式数据库尚未部署。'}</p><p class="small muted">启动时和运行期间每6小时生成完整数据库备份。本机同盘备份不能防电脑损坏,正式部署还需异地备份。</p>${state.backup.last?`<p class="small">本次运行最近备份:${e(state.backup.last.time)}</p>`:''}${state.backup.error?`<p class="error">${e(state.backup.error)}</p>`:''}${state.user.role==='owner'?button('生成并下载完整备份','backup'):'<p class="muted">由麦麦账号下载备份。</p>'}</section><section class="panel"><h2>飞书查看副本</h2><p><span class="badge ${state.sync.enabled?'':'warn'}">${state.sync.enabled?'已配置':'尚未连接'}</span></p><p class="small muted">使用新账专用表单向同步。修改和复核在本系统完成;同步失败不重开订单、不影响本地账务保存。</p>${state.sync.enabled?`<p>待同步 ${state.sync.pending} 项 · 失败 ${state.sync.failed} 项</p>${state.sync.error?`<p class="error">${e(state.sync.error)}</p>`:''}${state.user.role==='owner'?button('立即重试同步','sync'):''}`:'<p class="note">已预留应用API同步通道。正式连接时再配置新表,未连接原销售表,未试写真实账务。</p>'}</section></div>${state.mode!=='demo'?`<section class="panel"><h2>更改当前账号密码</h2><form id="password-form"><div class="grid two">${field('原密码','current','','password','required autocomplete="current-password"')}${field('新密码(至少12个字符)','password','','password','required minlength="12" autocomplete="new-password"')}</div><div class="form-actions"><button>修改并重新登录</button></div></form></section>`:''}`;
syncPrintSettingsPreview(); syncPrintSettingsPreview();
} }
function markFeeEdited(target){const row=target.closest('#fee-rows .fee-row');if(row)row.dataset.edited='true';} function markFeeEdited(target){const row=target.closest('#fee-rows .fee-row');if(row)row.dataset.edited='true';}
+31 -5
View File
@@ -1,8 +1,31 @@
'use strict'; 'use strict';
(()=>{ (()=>{
const button=document.getElementById('print'),frame=document.querySelector('.print-frame'),content=document.querySelector('.content'),status=document.getElementById('fit-status'); const button=document.getElementById('print'),frame=document.querySelector('.print-frame'),content=document.querySelector('.content'),status=document.getElementById('fit-status');
// 先压缩空行与行距,再根据真实排版尺寸缩放;保留每个商品及附加项,不裁掉尾部。 const canvas=document.querySelector('.print-canvas'),foreignObject=canvas.querySelector('foreignObject'),printMedia=window.matchMedia('print');
let printing=false;
// 打印副本保留原始文字与表格。SVG 根据最终纸张自动适配,不依赖 beforeprint 的屏幕尺寸或异步 resize 时序。
function preparePrint(){
const widthMm=Number(frame.dataset.layoutWidthMm),heightMm=Number(frame.dataset.layoutHeightMm);
if(!(widthMm>0&&heightMm>0))throw new Error('页面尺寸未就绪');
const measure=document.createElement('div'),copy=content.cloneNode(true);
Object.assign(measure.style,{position:'fixed',left:'0',top:'0',visibility:'hidden',pointerEvents:'none',width:widthMm+'mm',height:heightMm+'mm'});
copy.style.transform='none';copy.style.width='100%';copy.classList.remove('compact');copy.removeAttribute('data-scale');
measure.appendChild(copy);document.body.appendChild(measure);
try{
if(copy.scrollHeight>measure.clientHeight)copy.classList.add('compact');
const width=Math.max(measure.clientWidth,copy.scrollWidth,copy.offsetWidth);
copy.style.width=width+'px';
const height=Math.ceil(Math.max(copy.scrollHeight,copy.offsetHeight,copy.getBoundingClientRect().height))+1;
if(!(width>0&&height>1))throw new Error('页面尺寸未就绪');
canvas.setAttribute('viewBox',`0 0 ${width} ${height}`);
foreignObject.setAttribute('width',String(width));foreignObject.setAttribute('height',String(height));
foreignObject.replaceChildren(copy);
}finally{measure.remove();}
}
function failed(){document.body.classList.add('fit-error');button.disabled=true;status.textContent='页面暂未排好,请刷新后再打印。';return false;}
// 屏幕沿用已保存的纸张预览;明细较多时保留全部商品、附加项和尾部内容。
function fit(){ function fit(){
if(printing||printMedia.matches)return true;
try{ try{
content.style.transform='none';content.style.width='100%';content.classList.remove('compact'); content.style.transform='none';content.style.width='100%';content.classList.remove('compact');
if(content.scrollHeight>frame.clientHeight)content.classList.add('compact'); if(content.scrollHeight>frame.clientHeight)content.classList.add('compact');
@@ -20,12 +43,15 @@
scale=low;measure(scale); scale=low;measure(scale);
} }
content.style.transform='scale('+scale+')';content.dataset.scale=String(scale); content.style.transform='scale('+scale+')';content.dataset.scale=String(scale);
document.body.classList.remove('fit-error');button.disabled=false; preparePrint();document.body.classList.remove('fit-error');button.disabled=false;
status.textContent=scale<.65?'已排为一页;内容较多,字号已缩小,请先查看预览。':'已排为一页,全部明细与注意事项完整保留。'; status.textContent=scale<.65?'内容较多,字号已缩小,请先查看打印预览。':'打印时按所选纸张和方向自动排为一页。';
return true; return true;
}catch{document.body.classList.add('fit-error');button.disabled=true;status.textContent='页面暂未排好,请刷新后再打印。';return false;} }catch{return failed();}
} }
const ready=()=>document.fonts?.ready||Promise.resolve(); const ready=()=>document.fonts?.ready||Promise.resolve();
ready().then(fit);window.addEventListener('load',fit);window.addEventListener('resize',fit);window.addEventListener('beforeprint',fit); ready().then(fit);window.addEventListener('load',fit);window.addEventListener('resize',fit);
window.addEventListener('beforeprint',()=>{printing=true;try{preparePrint();document.body.classList.remove('fit-error');}catch{failed();}});
window.addEventListener('afterprint',()=>{printing=false;fit();});
printMedia.addEventListener('change',event=>{if(!event.matches){printing=false;fit();}});
button.addEventListener('click',async()=>{await ready();if(fit())window.print();}); button.addEventListener('click',async()=>{await ready();if(fit())window.print();});
})(); })();
+78
View File
@@ -0,0 +1,78 @@
'use strict';
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path'),vm=require('node:vm');
const {receipt,settings}=require('../printing');
const script=fs.readFileSync(path.join(__dirname,'../public/print.js'),'utf8');
const mm=value=>Number.parseFloat(value)*96/25.4;
function classList(initial=[]){const values=new Set(initial);return {add:value=>values.add(value),remove:value=>values.delete(value),contains:value=>values.has(value)};}
// 模拟 beforeprint 的两种浏览器时序:进入打印媒体之前,或屏幕 HTML 已被打印 CSS 隐藏之后。
function page({long=false,fontsReady=true}={}){
const events=new Map(),mediaEvents=new Map(),clicks=new Map(),media={matches:false,addEventListener:(name,fn)=>mediaEvents.set(name,fn)};
const body={classList:classList(),children:[],appendChild(node){this.children.push(node);node.parentNode=this;}};
const frame={dataset:{layoutWidthMm:'217',layoutHeightMm:'120'},get clientWidth(){return media.matches?640:Math.floor(mm('217'));},get clientHeight(){return media.matches?980:Math.floor(mm('120'));}};
const makeContent=original=>({
style:{},dataset:{},classList:classList(),textContent:'首行商品 尾行商品 注意事项 珠宝首饰保养须知 备注 经办人:麦麦',
get offsetWidth(){return Number.parseFloat(this.style.width?.endsWith('px')?this.style.width:this.parentNode.clientWidth);},
get scrollWidth(){return this.offsetWidth;},
get scrollHeight(){if(original&&media.matches)return 0;return Math.ceil((long?2800000:490000)/this.offsetWidth*(this.classList.contains('compact')?.8:1));},
get offsetHeight(){return this.scrollHeight;},getBoundingClientRect(){return {height:this.scrollHeight};},
cloneNode(){const copy=makeContent(false);copy.style={...this.style};copy.dataset={...this.dataset};return copy;},
removeAttribute(name){if(name==='data-scale')delete this.dataset.scale;}
});
const content=makeContent(true);content.parentNode=frame;
const foreignObject={attributes:{},children:[],setAttribute(name,value){this.attributes[name]=value;},replaceChildren(child){this.children=[child];child.parentNode=this;}};
const canvas={attributes:{},setAttribute(name,value){this.attributes[name]=value;},querySelector:()=>foreignObject};
const button={disabled:true,addEventListener:(name,fn)=>clicks.set(name,fn)},status={textContent:''};
const window={matchMedia:()=>media,addEventListener:(name,fn)=>events.set(name,fn),printCalls:0,print(){this.printCalls++;}};
const document={
body,fonts:{ready:fontsReady?Promise.resolve():new Promise(()=>{})},getElementById:id=>id==='print'?button:status,
querySelector:selector=>({'.print-frame':frame,'.content':content,'.print-canvas':canvas})[selector],
createElement:()=>({style:{},get clientWidth(){return Math.floor(mm(this.style.width));},get clientHeight(){return Math.floor(mm(this.style.height));},appendChild(child){this.child=child;child.parentNode=this;},remove(){body.children.splice(body.children.indexOf(this),1);}})
};
vm.runInNewContext(script,{window,document});
return {body,content,foreignObject,canvas,button,status,window,media,events,mediaEvents,click:()=>clicks.get('click')()};
}
test('打印纸型和方向由浏览器决定,旧宽高只保留为预览及来源排版尺寸',()=>{
const sample={lines:[],total:0,paper_number:'20261022001',status:'delivered'};
for(const raw of [{width:241,height:140},{width:241,height:279},{width:140,height:241}]){
const saved=settings(raw),html=receipt(sample,saved),print=html.slice(html.indexOf('@page'));
assert.equal(saved.width,raw.width);assert.equal(saved.height,raw.height);
assert.match(print,/@page\{size:auto;margin:0\}/);assert.match(print,/html,body\{width:auto;height:auto/);
assert.match(print,/\.sheet\{width:100%;height:calc\(100vh - 1px\)/);
assert.doesNotMatch(print,/@page\{size:\d|rotate\(|landscape|portrait/);
assert.match(html,new RegExp(`data-layout-width-mm="${raw.width-24}"`));
assert.match(html,/preserveAspectRatio="xMinYMin meet"/);
}
});
test('打印在媒体切换前后准备都不沿用屏幕缩放,且保留尾部所有文字',async()=>{
for(const mediaFirst of [false,true]){
const p=page({long:true});await Promise.resolve();
const screenScale=Number(p.content.dataset.scale),viewBox=p.canvas.attributes.viewBox;
assert.ok(screenScale>0&&screenScale<1);
if(mediaFirst)p.media.matches=true;
p.events.get('beforeprint')();p.media.matches=true;
assert.equal(p.canvas.attributes.viewBox,viewBox);
const copy=p.foreignObject.children[0];
assert.equal(copy.style.transform,'none');assert.equal(copy.dataset.scale,undefined);
assert.equal(copy.textContent,p.content.textContent);assert.ok(Number(p.foreignObject.attributes.height)>0);
assert.equal(p.body.classList.contains('fit-error'),false);
assert.equal(p.body.children.length,0,'测量节点在打印前清理,不产生额外打印页');
p.events.get('resize')();assert.equal(p.body.classList.contains('fit-error'),false);
assert.equal(Number(p.content.dataset.scale),screenScale);
p.media.matches=false;p.events.get('afterprint')();
assert.equal(Number(p.content.dataset.scale),screenScale);assert.equal(p.foreignObject.children.length,1);
}
});
test('快捷键在字体等待期间进入打印也能同步生成完整客户副本',()=>{
const p=page({fontsReady:false});p.media.matches=true;p.events.get('beforeprint')();
assert.ok(p.canvas.attributes.viewBox);assert.equal(p.foreignObject.children.length,1);
assert.match(p.foreignObject.children[0].textContent,/尾行商品.*注意事项.*经办人:麦麦/);
assert.equal(p.body.classList.contains('fit-error'),false);
});
test('打印按钮等待排版,关闭打印后恢复预览且再次打印不累积副本',async()=>{
const p=page();await Promise.resolve();assert.equal(p.button.disabled,false);
await p.click();assert.equal(p.window.printCalls,1);
p.events.get('beforeprint')();p.media.matches=true;p.events.get('resize')();
p.media.matches=false;p.mediaEvents.get('change')({matches:false});p.events.get('afterprint')();
await p.click();assert.equal(p.window.printCalls,2);assert.equal(p.foreignObject.children.length,1);
assert.equal(p.button.disabled,false);assert.equal(p.body.children.length,0);
});
+3 -2
View File
@@ -153,8 +153,9 @@
- 客户单据分列金价与销售工费,商品与附加项目统一按1、2、3、4连续编号;主商品行显示未含附加项目的基础金额,整单合计包含附加项目且不重复相加;金额大写按优惠后的最终成交金额生成。显示纸单号与收款方式:已有有效收款流水时按实际渠道,没有流水的旧单显示开单选择的微信/支付宝/现金。此显示不会补写收款流水;所有内部成本与直接费用不输出。 正常销售单不显示预订或交付状态;已取消、已退货仍保留提示。 - 客户单据分列金价与销售工费,商品与附加项目统一按1、2、3、4连续编号;主商品行显示未含附加项目的基础金额,整单合计包含附加项目且不重复相加;金额大写按优惠后的最终成交金额生成。显示纸单号与收款方式:已有有效收款流水时按实际渠道,没有流水的旧单显示开单选择的微信/支付宝/现金。此显示不会补写收款流水;所有内部成本与直接费用不输出。 正常销售单不显示预订或交付状态;已取消、已退货仍保留提示。
- 「完整单据」有店名、表格、金额大写、经办人栏和麦麦提供纸单中的注意事项、珠宝首饰保养须知及公司承诺;已按最新要求删除免费维修/清洗/抛光及人为损坏只收配件费的整条承诺。可用普通纸试印或在Chrome/Edge中保存PDF。 - 「完整单据」有店名、表格、金额大写、经办人栏和麦麦提供纸单中的注意事项、珠宝首饰保养须知及公司承诺;已按最新要求删除免费维修/清洗/抛光及人为损坏只收配件费的整条承诺。可用普通纸试印或在Chrome/Edge中保存PDF。
- 「预印纸套打」隐藏已印标题和表格线,保留填写内容。目前是可调初稿,没有纸样和机器,不能保证与旧单格线对齐。 - 「预印纸套打」隐藏已印标题和表格线,保留填写内容。目前是可调初稿,没有纸样和机器,不能保证与旧单格线对齐。
- 默认241×279mm,可调整纸宽高、上下左右偏移、行高、表格最少行数。所有内容统一排在一页:明细较多时先去掉空行、压缩行距,再自动缩放字号;不丢弃商品、附加项目、长备注或注意事项。表格最少行数只控制补空行,不再分页。 - 纸张尺寸和横向/纵向以浏览器打印窗口及打印机驱动的选择为准。系统不再强制纸型或方向,会把全部明细、长备注、注意事项和经办人完整适配到一页。表格最少行数只用于补空行,明细较多时会自动缩小。
- 打印比例100%,关闭浏览器页眉页脚。先保存PDF看排版,等纸样和打印机到位后连续多张校准。 - 设置中的「预览纸宽/高」默认241×279mm,用于屏幕预览和内容排版;旧设置继续保留。上下左右偏移、内容距顶部和行高仍可调整,套打按实物纸样校准。
- 在打印窗口选好实际纸张及横向/纵向,打印比例100%,关闭浏览器页眉页脚。先保存PDF核对完整性,再用店内纸张和打印机连续试打校准。
- 打印、取消打印或补打不会改变库存或收入。日志只记录“打开打印页”,不会冒充打印成功。 - 打印、取消打印或补打不会改变库存或收入。日志只记录“打开打印页”,不会冒充打印成功。
- Codex内置浏览器可能不提供PDF或实体打印功能;实际打单用店里电脑的Chrome或Edge。 - Codex内置浏览器可能不提供PDF或实体打印功能;实际打单用店里电脑的Chrome或Edge。
- 上一级「打印样张」文件夹有独立的完整模板、套打模板HTML,可直接双击查看。 - 上一级「打印样张」文件夹有独立的完整模板、套打模板HTML,可直接双击查看。