From b9154a752dc822c50725ea2be7ed22e8c23b6a37 Mon Sep 17 00:00:00 2001 From: summer Date: Thu, 22 Oct 2026 12:32:44 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E9=94=80=E5=94=AE=E5=8D=95?= =?UTF-8?q?=E6=8D=AE=E6=89=93=E5=8D=B0=E6=96=B9=E5=90=91=E5=9B=BA=E5=AE=9A?= =?UTF-8?q?=E5=8F=8A=E8=B7=A8=E9=A1=B5=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 打印遵循浏览器和驱动所选纸张与方向,将完整单据适配到一页,保留预览尺寸及套打偏移。新增打印时序和重复打印回归测试,并更新设置说明。 验证:251项测试通过;32种Chrome PDF组合均为单页,内容完整。 --- 新账系统/printing.js | 12 +++-- 新账系统/public/app.js | 2 +- 新账系统/public/print.js | 36 ++++++++++++-- 新账系统/test/print-layout.test.js | 78 ++++++++++++++++++++++++++++++ 新账系统/使用说明.md | 5 +- 5 files changed, 120 insertions(+), 13 deletions(-) create mode 100644 新账系统/test/print-layout.test.js diff --git a/新账系统/printing.js b/新账系统/printing.js index deaf436..9ca14d9 100644 --- a/新账系统/printing.js +++ b/新账系统/printing.js @@ -51,7 +51,9 @@ function receipt(order,rawSettings={},mode='full'){ 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?'
整单金额四舍五入到元
':''; const totalText=order.rounding_mode==='yuan'&&order.total%100===0?String(order.total/100):yuan(order.total); - const body=`
`; return `${escape(paper)} · 客户单据
切换${overlay?'完整单据':'预印纸套打'}模板${overlay?'套打位置是待校准初稿,尚未匹配实物纸样。':'打印比例选100%,关闭浏览器页眉页脚。'}正在调整为一页…
${body}`; + *{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: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}} +
切换${overlay?'完整单据':'预印纸套打'}模板纸张尺寸和横向/纵向在打印窗口选择,关闭页眉页脚。${overlay?'套打位置仍需按实物纸样校准。':''}正在调整为一页…
${body}`; } module.exports={receipt,settings,defaults,escape,uppercaseMoney,notices,care,promise}; diff --git a/新账系统/public/app.js b/新账系统/public/app.js index 1bf027f..c191c5a 100644 --- a/新账系统/public/app.js +++ b/新账系统/public/app.js @@ -746,7 +746,7 @@ async function savePrintSettings(form,data){ 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'; - $('#main').innerHTML=heading('PRINT & SETTINGS','打印与设置','先把单据做好,选好纸张和打印机后再校准位置。')+`

数据库与备份

${state.mode==='production'?'主账保存在部署服务器的独立SQLite数据库。':'现在运行在本机试用环境,云端正式数据库尚未部署。'}

启动时和运行期间每6小时生成完整数据库备份。本机同盘备份不能防电脑损坏,正式部署还需异地备份。

${state.backup.last?`

本次运行最近备份:${e(state.backup.last.time)}

`:''}${state.backup.error?`

${e(state.backup.error)}

`:''}${state.user.role==='owner'?button('生成并下载完整备份','backup'):'

由麦麦账号下载备份。

'}

飞书查看副本

${state.sync.enabled?'已配置':'尚未连接'}

使用新账专用表单向同步。修改和复核在本系统完成;同步失败不重开订单、不影响本地账务保存。

${state.sync.enabled?`

待同步 ${state.sync.pending} 项 · 失败 ${state.sync.failed} 项

${state.sync.error?`

${e(state.sync.error)}

`:''}${state.user.role==='owner'?button('立即重试同步','sync'):''}`:'

已预留应用API同步通道。正式连接时再配置新表,未连接原销售表,未试写真实账务。

'}
${state.mode!=='demo'?`

更改当前账号密码

${field('原密码','current','','password','required autocomplete="current-password"')}${field('新密码(至少12个字符)','password','','password','required minlength="12" autocomplete="new-password"')}
`:''}`; + $('#main').innerHTML=heading('PRINT & SETTINGS','打印与设置','先把单据做好,选好纸张和打印机后再校准位置。')+`

数据库与备份

${state.mode==='production'?'主账保存在部署服务器的独立SQLite数据库。':'现在运行在本机试用环境,云端正式数据库尚未部署。'}

启动时和运行期间每6小时生成完整数据库备份。本机同盘备份不能防电脑损坏,正式部署还需异地备份。

${state.backup.last?`

本次运行最近备份:${e(state.backup.last.time)}

`:''}${state.backup.error?`

${e(state.backup.error)}

`:''}${state.user.role==='owner'?button('生成并下载完整备份','backup'):'

由麦麦账号下载备份。

'}

飞书查看副本

${state.sync.enabled?'已配置':'尚未连接'}

使用新账专用表单向同步。修改和复核在本系统完成;同步失败不重开订单、不影响本地账务保存。

${state.sync.enabled?`

待同步 ${state.sync.pending} 项 · 失败 ${state.sync.failed} 项

${state.sync.error?`

${e(state.sync.error)}

`:''}${state.user.role==='owner'?button('立即重试同步','sync'):''}`:'

已预留应用API同步通道。正式连接时再配置新表,未连接原销售表,未试写真实账务。

'}
${state.mode!=='demo'?`

更改当前账号密码

${field('原密码','current','','password','required autocomplete="current-password"')}${field('新密码(至少12个字符)','password','','password','required minlength="12" autocomplete="new-password"')}
`:''}`; syncPrintSettingsPreview(); } function markFeeEdited(target){const row=target.closest('#fee-rows .fee-row');if(row)row.dataset.edited='true';} diff --git a/新账系统/public/print.js b/新账系统/public/print.js index ab8dec3..ce65ab6 100644 --- a/新账系统/public/print.js +++ b/新账系统/public/print.js @@ -1,8 +1,31 @@ 'use strict'; (()=>{ 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(){ + if(printing||printMedia.matches)return true; try{ content.style.transform='none';content.style.width='100%';content.classList.remove('compact'); if(content.scrollHeight>frame.clientHeight)content.classList.add('compact'); @@ -20,12 +43,15 @@ scale=low;measure(scale); } content.style.transform='scale('+scale+')';content.dataset.scale=String(scale); - document.body.classList.remove('fit-error');button.disabled=false; - status.textContent=scale<.65?'已排为一页;内容较多,字号已缩小,请先查看预览。':'已排为一页,全部明细与注意事项完整保留。'; + preparePrint();document.body.classList.remove('fit-error');button.disabled=false; + status.textContent=scale<.65?'内容较多,字号已缩小,请先查看打印预览。':'打印时按所选纸张和方向自动排为一页。'; 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(); - 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();}); })(); diff --git a/新账系统/test/print-layout.test.js b/新账系统/test/print-layout.test.js new file mode 100644 index 0000000..e0babcc --- /dev/null +++ b/新账系统/test/print-layout.test.js @@ -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); +}); diff --git a/新账系统/使用说明.md b/新账系统/使用说明.md index a1a7409..7f9e578 100644 --- a/新账系统/使用说明.md +++ b/新账系统/使用说明.md @@ -153,8 +153,9 @@ - 客户单据分列金价与销售工费,商品与附加项目统一按1、2、3、4连续编号;主商品行显示未含附加项目的基础金额,整单合计包含附加项目且不重复相加;金额大写按优惠后的最终成交金额生成。显示纸单号与收款方式:已有有效收款流水时按实际渠道,没有流水的旧单显示开单选择的微信/支付宝/现金。此显示不会补写收款流水;所有内部成本与直接费用不输出。 正常销售单不显示预订或交付状态;已取消、已退货仍保留提示。 - 「完整单据」有店名、表格、金额大写、经办人栏和麦麦提供纸单中的注意事项、珠宝首饰保养须知及公司承诺;已按最新要求删除免费维修/清洗/抛光及人为损坏只收配件费的整条承诺。可用普通纸试印或在Chrome/Edge中保存PDF。 - 「预印纸套打」隐藏已印标题和表格线,保留填写内容。目前是可调初稿,没有纸样和机器,不能保证与旧单格线对齐。 -- 默认241×279mm,可调整纸宽高、上下左右偏移、行高、表格最少行数。所有内容统一排在一页:明细较多时先去掉空行、压缩行距,再自动缩放字号;不丢弃商品、附加项目、长备注或注意事项。表格最少行数只控制补空行,不再分页。 -- 打印比例100%,关闭浏览器页眉页脚。先保存PDF看排版,等纸样和打印机到位后连续多张校准。 +- 纸张尺寸和横向/纵向以浏览器打印窗口及打印机驱动的选择为准。系统不再强制纸型或方向,会把全部明细、长备注、注意事项和经办人完整适配到一页。表格最少行数只用于补空行,明细较多时会自动缩小。 +- 设置中的「预览纸宽/高」默认241×279mm,用于屏幕预览和内容排版;旧设置继续保留。上下左右偏移、内容距顶部和行高仍可调整,套打按实物纸样校准。 +- 在打印窗口选好实际纸张及横向/纵向,打印比例100%,关闭浏览器页眉页脚。先保存PDF核对完整性,再用店内纸张和打印机连续试打校准。 - 打印、取消打印或补打不会改变库存或收入。日志只记录“打开打印页”,不会冒充打印成功。 - Codex内置浏览器可能不提供PDF或实体打印功能;实际打单用店里电脑的Chrome或Edge。 - 上一级「打印样张」文件夹有独立的完整模板、套打模板HTML,可直接双击查看。