Files
weiguang-jewelry-ledger/新账系统/test/credit-card-fees-ui.test.js
T
summer a506fb1228 完善订单审批、每日对账与信用卡手续费
加入助理订单变更复核、收款人汇总、每日报销和应转金额;优化库存筛选、订单明细与连续浏览。开单身份必填,信用卡手续费按实收4‰自动计算并默认由麦麦承担,打印优惠显示在人民币大写旁。

验证:484项测试通过;独立HTTP与浏览器覆盖普通订单、锁价、修改审批、断线恢复和打印隔离。旧报表兼容,本机升级原29表295行数据保持一致。
2026-10-23 09:49:36 +08:00

110 lines
17 KiB
JavaScript

'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 {randomUUID}=require('node:crypto'),Calc=require('../public/calculations'),Fees=require('../public/fee-estimates'),Cards=require('../public/credit-card-fees'),Templates=require('../public/order-templates'),Copy=require('../public/order-copy');
const D='2026-10-23',PAYMENT='11111111-1111-4111-8111-111111111111',EXPENSE='22222222-2222-4222-8222-222222222222';
const accounts=['助理微信','助理支付宝','助理现金','助理信用卡','麦麦微信','麦麦支付宝','麦麦现金','麦麦信用卡'];
const autoFee=(extra={})=>({key:'card_fee:'+PAYMENT,system:'credit_card',source_kind:'payment',source_id:PAYMENT,expense_id:EXPENSE,date:D,note:'信用卡手续费(4‰)',amount:'4.00',payer:'owner',status:'recorded',...extra});
const shipping={key:'shipping',note:'快递费',amount:'6.00',payer:'assistant',edited:true};
function input(value='',extra={}){return {value,disabled:false,required:false,readOnly:false,checked:false,closest(){return this.label??=( {hidden:false} );},...extra};}
function fieldsForm(values={},extra={}){const fields=Object.fromEntries(Object.entries(values).map(([key,value])=>[key,typeof value==='object'?value:input(value)]));return {fields,dataset:{},querySelector:selector=>fields[selector.match(/\[name="([^"]+)"\]/)?.[1]]||null,querySelectorAll:()=>[],...extra};}
function preview(basis='客户付款金额',payer='owner'){
const fields={'[name="credit_card_fee_payer"]':input(payer),'[data-credit-card-amount]':input(''), '[data-credit-card-formula]':{textContent:''}};
return {hidden:true,dataset:{basis},fields,querySelector:selector=>fields[selector]||null};
}
function feeRow(item){const values=new Set(),fields={feeAmount:input(item.amount),feePayer:input(item.payer),feeDate:input(item.date||'')};return {dataset:{fee:item.key,expenseId:item.expense_id||'',feeDate:item.date||'',...(Cards.isFee(item)?{automaticFee:JSON.stringify(item)}:{source:item.sourceName||'',edited:String(!!item.edited),status:item.status||''})},fields,classList:{toggle(name,on){if(on)values.add(name);else values.delete(name);},contains:name=>values.has(name)},help:{textContent:''},querySelector(selector){if(selector==='.fee-help')return this.help;if(selector==='.fee-name')return {textContent:item.note};if(selector==='.fee-source')return {textContent:''};return fields[selector.match(/\[name="([^"]+)"\]/)?.[1]]||null;}};}
function harness(){
const nodes=new Map(),saved=new Map(),automaticRows=[],handlers={};
const context=vm.createContext({console,LedgerCalc:Calc,FeeEstimates:Fees,CreditCardFees:Cards,OrderTemplates:Templates,OrderCopy:Copy,crypto:{randomUUID},URLSearchParams,setInterval(){},setTimeout(){},clearTimeout(){},
document:{querySelector:selector=>nodes.get(selector)||null,querySelectorAll:selector=>selector==='#fee-rows .fee-automatic'?automaticRows:[],addEventListener(name,fn){(handlers[name]??=[]).push(fn);}},window:{scrollTo(){}},localStorage:{getItem:key=>saved.get(key)??null,setItem:(key,value)=>saved.set(key,String(value)),removeItem:key=>saved.delete(key)},sessionStorage:{getItem(){return null;},setItem(){}}});
const run=code=>vm.runInContext(code,context),json=code=>JSON.parse(JSON.stringify(run(code)));
for(const file of ['price-locks-ui.js','order-edit-ui.js','app.js'])run(fs.readFileSync(path.join(__dirname,'../public',file),'utf8').replace(/\ninit\(\);\s*$/,''));
run(`session={user:{id:'card-ui-owner',name:'麦麦',role:'owner'}};state={today:'${D}',user:session.user,accounts:${JSON.stringify(accounts)},pockets:['现货']};pending=function(){return null;};`);
return {context,nodes,saved,automaticRows,handlers,run,json};
}
test('卡费整数分4‰及半分舍入,浏览器与Node helper一致且不接受负额或浮点分',()=>{
const browser={};vm.runInNewContext(fs.readFileSync(path.join(__dirname,'../public/credit-card-fees.js'),'utf8'),browser);
for(const [cents,fee] of [[0,0],[1,0],[124,0],[125,1],[374,1],[375,2],[100000,400],[75264,301],[75300,301],[100000000000,400000000]]){assert.equal(Cards.amount(cents),fee);assert.equal(browser.CreditCardFees.amount(cents),fee);}
for(const invalid of [-1,1.1,'100',NaN,Infinity,100000000001,Number.MAX_SAFE_INTEGER])assert.throws(()=>Cards.amount(invalid));
assert.equal(Cards.isAccount('助理信用卡'),true);assert.equal(Cards.isAccount('麦麦信用卡'),true);assert.equal(Cards.isAccount('信用卡'),false);assert.equal(Cards.isFee({key:'card_fee:old'}),true);assert.equal(Cards.isFee({system:'credit_card'}),true);
});
test('旧6账户或helper未加载时不开放卡选项,正式支持后两个收款人都可选',()=>{
const h=harness();assert.match(h.run('accountFields("麦麦信用卡")'),/<option value="信用卡" selected>/);
h.run('state.accounts=state.accounts.filter(account=>!account.endsWith("信用卡"))');assert.doesNotMatch(h.run('accountFields()'),/信用卡/);
h.context.__accounts=accounts;h.run('state.accounts=__accounts;delete globalThis.CreditCardFees');assert.doesNotMatch(h.run('accountFields()'),/信用卡/);
h.context.__draft={customer:'客户',salesperson:'麦麦',payment_account:'麦麦信用卡'};assert.throws(()=>h.run('validateIssueDraft(__draft)'),/信用卡收款暂未准备好/);
const index=fs.readFileSync(path.join(__dirname,'../public/index.html'),'utf8');assert.equal((index.match(/src="\/credit-card-fees.js"/g)||[]).length,1);assert.ok(index.indexOf('/credit-card-fees.js')<index.indexOf('/app.js'));
});
test('新卡预览按最终成交额计算,付款人默认麦麦可改;0和切回非卡不留下自动费',()=>{
const h=harness(),root=preview('成交合计');h.context.__root=root;
assert.equal(h.run('syncCreditCardPreview(__root,"助理信用卡",100000)'),400);assert.equal(root.fields['[data-credit-card-amount]'].value,'4.00');assert.equal(root.fields['[name="credit_card_fee_payer"]'].value,'owner');assert.equal(root.hidden,false);assert.match(root.fields['[data-credit-card-formula]'].textContent,/成交合计.*1,000.00.*4‰.*4.00/);
root.fields['[name="credit_card_fee_payer"]'].value='assistant';assert.equal(h.run('syncCreditCardPreview(__root,"麦麦信用卡",200000)'),800);assert.equal(root.fields['[name="credit_card_fee_payer"]'].value,'assistant');
assert.equal(h.run('syncCreditCardPreview(__root,"助理信用卡",0)'),0);assert.equal(root.fields['[data-credit-card-amount]'].value,'0.00');assert.equal(h.run('syncCreditCardPreview(__root,"助理微信",200000)'),0);assert.equal(root.hidden,true);assert.equal(root.fields['[name="credit_card_fee_payer"]'].disabled,true);
const html=h.run('creditCardPreviewHTML("sample")');assert.match(html,/readonly data-credit-card-amount/);assert.doesNotMatch(html,/name="credit_card_fee_amount"/);assert.match(html,/默认|信用卡手续费/);
});
test('完整编辑保留未变的逐笔费,改日期不另加;改额或渠道只计替换后的费',()=>{
const h=harness(),root=preview('成交合计'),form={dataset:{orderEdit:'true'}},rows=[feeRow(autoFee({amount:'1.00'})),feeRow(autoFee({key:'card_fee:second',amount:'3.00',payer:'assistant'}))];
h.nodes.set('#order-form',form);h.nodes.set('#order-credit-card-fee',root);h.nodes.set('#fees-total',{textContent:''});h.automaticRows.push(...rows);
h.context.__fees=rows.map(row=>JSON.parse(row.dataset.automaticFee));h.run(`tab='order-edit';orderEditEntry={paymentAccount:'助理信用卡',order:{date:'${D}',netReceived:100000,payment_account:'助理信用卡'}};`);
h.context.__draft={date:D,payment_account:'助理信用卡',fee_items:[...h.context.__fees,shipping]};
assert.equal(h.run('syncOrderCreditCardFees(__draft,100000)'),400);assert.equal(root.hidden,true);assert.equal(rows[0].classList.contains('is-replaced'),false);assert.equal(rows[0].fields.feePayer.disabled,false);
h.context.__draft.date='2026-10-22';assert.equal(h.run('syncOrderCreditCardFees(__draft,100000)'),400);assert.match(rows[0].help.textContent,/仅调整日期/);
assert.equal(h.run('syncOrderCreditCardFees(__draft,200000)'),800);assert.equal(root.hidden,false);assert.equal(root.fields['[data-credit-card-amount]'].value,'8.00');assert.equal(rows[0].classList.contains('is-replaced'),true);assert.equal(rows[0].fields.feePayer.disabled,true);assert.equal(rows[0].fields.feeAmount.value,'1.00');
h.run('updateFeeTotal(__draft.fee_items.filter(item=>!isAutomaticCardFee(item)),800)');assert.match(h.nodes.get('#fees-total').textContent,/14.00/);
h.context.__draft.payment_account='麦麦微信';assert.equal(h.run('syncOrderCreditCardFees(__draft,200000)'),0);assert.equal(root.hidden,true);
});
test('多渠道原收款保持时仍保留原信用卡费,不把整单再当一笔卡收款',()=>{
const h=harness(),root=preview('成交合计');h.nodes.set('#order-form',{dataset:{orderEdit:'true'}});h.nodes.set('#order-credit-card-fee',root);h.context.__draft={date:D,payment_account:'助理微信',fee_items:[autoFee({amount:'2.00'})]};h.run(`orderEditEntry={paymentAccount:'助理微信',order:{date:'${D}',netReceived:100000,payment_account:'麦麦信用卡'}}`);
assert.equal(h.run('syncOrderCreditCardFees(__draft,100000)'),200);assert.equal(root.hidden,true);
});
test('旧自动卡费元数据、金额和日期原样回传,只允许付款人改变,不提供移除',()=>{
const h=harness(),source=autoFee(),row=feeRow(source),root={querySelectorAll:()=>[row]};row.fields.feePayer.value='assistant';h.context.__root=root;h.context.__fee=source;
assert.deepEqual(h.json('readFeeRows(__root)'),[{...source,payer:'assistant'}]);
h.run(`tab='order-edit';orderEditEntry={inputs:{fees_date:'${D}',date:'${D}'}}`);const html=h.run('feeRowHTML(__fee)');assert.match(html,/data-automatic-fee=/);assert.match(html,/name="feeAmount"[^>]*readonly/);assert.match(html,/name="feeDate"[^>]*readonly/);assert.doesNotMatch(html,/remove-fee|name="feeNote"/);assert.match(html,/name="feePayer"/);
});
test('普通新单提交保留人工费用与付款人,自动预览不写入fee_items',()=>{
const h=harness(),values={orderId:'',revision:'',rounding_mode:'yuan',date:D,customer:'客户',salesperson:'麦麦',payment_recipient:'助理',payment_method:'信用卡',fees_date:D,discount:'0',note:'',credit_card_fee_payer:'assistant'};
const form=fieldsForm(values,{querySelectorAll:()=>[]});h.nodes.set('#order-form',form);const rows=[feeRow(shipping),feeRow(autoFee())];h.nodes.set('#fee-rows',{querySelectorAll:()=>rows});
const result=h.json('collectDraft()');assert.equal(result.payment_account,'助理信用卡');assert.equal(result.credit_card_fee_payer,'assistant');assert.equal(result.fee_items.length,1);assert.equal(result.fee_items[0].key,'shipping');assert.equal(result.fee_items[0].amount,'6.00');assert.equal(JSON.stringify(result).includes('card_fee:'),false);
});
test('补收与正向收款更正展示4‰,退款和费用更正不新增卡费',()=>{
const h=harness(),root=preview(),form=fieldsForm({amount:'1000',payment_recipient:'助理',payment_method:'信用卡',account:'麦麦信用卡',entry:'payment:'+PAYMENT},{dataset:{kind:'receipt'}});h.nodes.set('#action-form',form);h.nodes.set('#action-credit-card-fee',root);h.run(`currentOrder={payments:[{id:'${PAYMENT}',kind:'receipt'},{id:'refund-id',kind:'refund'}]}`);
h.run('syncActionCreditCardFee()');assert.equal(root.fields['[data-credit-card-amount]'].value,'4.00');assert.equal(root.hidden,false);
form.dataset.kind='correct';form.fields.amount.value='1250';h.run('syncActionCreditCardFee()');assert.equal(root.fields['[data-credit-card-amount]'].value,'5.00');
for(const entry of ['payment:refund-id','expense:any']){form.fields.entry.value=entry;h.run('syncActionCreditCardFee()');assert.equal(root.hidden,true);}
form.dataset.kind='refund';h.run('syncActionCreditCardFee()');assert.equal(root.hidden,true);
});
test('锁价首收按实际付款预览而非预计报价,付款人进入payment,原卡费只读留存',()=>{
const h=harness(),root=preview(),form=fieldsForm({date:D,customer:'合成客户',salesperson:'麦麦',note:'',discount:'0',name:'足金999',quantity:'1.000',goldPrice:'1000',laborRate:'0',laborMode:'gram',pieces:'1',received_amount:'500',payment_recipient:'助理',payment_method:'信用卡',credit_card_fee_payer:'assistant',material_rate:'800',material_payer:'owner',payment_verified:input('on',{checked:true}),material_verified:input('on',{checked:true})});
h.nodes.set('#price-lock-create-form',form);h.nodes.set('#lock-create-card-fee',root);for(const id of ['#lock-create-total','#lock-sale-estimate','#lock-material-estimate'])h.nodes.set(id,{textContent:''});h.run('syncPriceLockCreate()');assert.equal(root.fields['[data-credit-card-amount]'].value,'2.00');assert.equal(h.json('collectPriceLockCreate().payment').credit_card_fee_payer,'assistant');assert.equal(h.nodes.get('#lock-create-total').textContent,'¥1,000');
h.context.__lock={credit_card_fees:[{date:'2026-10-21',amount:200,payer:'owner'},{date:D,amount:80,payer:'assistant'}],credit_card_fee_total:280};const html=h.run('priceLockCardFeesHTML(__lock)');for(const text of ['2.80','2.00','0.80','麦麦支付','助理支付','交付时沿用,不重复'])assert.ok(html.includes(text));assert.doesNotMatch(html,/<input|<select|remove-/);
});
test('交付仅正补收产生新费,已付卡费和其他费用始终留在已知合计',()=>{
const h=harness(),root=preview();h.context.__root=root;h.nodes.set('#fees-total',{textContent:''});h.context.__fees=[shipping];
assert.equal(h.run('syncCreditCardPreview(__root,"助理信用卡",20000,{enabled:true})'),80);h.run('updateFeeTotal(__fees,280)');assert.match(h.nodes.get('#fees-total').textContent,/8.80/);
assert.equal(h.run('syncCreditCardPreview(__root,"助理信用卡",-20000,{enabled:false})'),0);assert.equal(root.hidden,true);h.run('updateFeeTotal(__fees,200)');assert.match(h.nodes.get('#fees-total').textContent,/8.00/);
h.run('updateFeeTotal(__fees,null,{knownCardCost:200})');assert.match(h.nodes.get('#fees-total').textContent,/已知部分.*8.00.*手续费待计算/);
});
test('模板和复制保留信用卡渠道、剔除旧费,改额后仅按新金额重算',()=>{
const fee=autoFee({amount:'3.02'}),line={name:'定制珠宝',nameType:'其他',customName:'定制珠宝',unit:'件',quantity:'1',pocket:'',payer:'owner',pricingMode:'manual',baseSale:'753',sale:'753',charges:[],cost:'400'},draft={date:D,customer:'旧客户',salesperson:'麦麦',payment_account:'麦麦信用卡',credit_card_fee_payer:'assistant',discount:'0',lines:[line],fee_items:[fee,shipping]};
const preset=Templates.fromDraft(draft),applied=Templates.apply(preset,{today:D});assert.equal(applied.customer,'');assert.equal(applied.payment_account,'麦麦信用卡');assert.equal(applied.credit_card_fee_payer,'assistant');assert.equal(applied.fee_items.length,1);assert.equal(applied.fee_items[0].key,'shipping');assert.ok(!JSON.stringify(applied).includes(PAYMENT));applied.lines[0].baseSale='1000';const total=Calc.orderTotal([Calc.sale(applied.lines[0]).sale],0,'yuan').total;assert.equal(Cards.amount(total),400);
const source={...draft,discount:0,status:'delivered',pendingFees:[],corrections:[],fee_items:[{...fee,amount:302}],expenses:[{id:EXPENSE,date:D,note:fee.note,amount:302,payer:'owner'}],lines:[{...line,quantity:1,baseSale:75300,sale:75300,cost:40000}]};const copied=Copy.fromOrder(source,{today:D});assert.equal(copied.payment_account,'麦麦信用卡');assert.equal(copied.fee_items.length,0);assert.equal(copied.customer,'');copied.lines[0].baseSale='100';assert.equal(Cards.amount(Calc.orderTotal([Calc.sale(copied.lines[0]).sale],0,'yuan').total),40);
});
test('汇总显示信用卡渠道,自动费移动端取消最小横宽且屏幕样式不进入客户打印',()=>{
const h=harness();h.context.__receipts={receipt:100000,refund:0,channels:[{channel:'wechat',name:'微信',receipt:0,refund:0},{channel:'alipay',name:'支付宝',receipt:0,refund:0},{channel:'cash',name:'现金',receipt:0,refund:0},{channel:'credit_card',name:'信用卡',receipt:100000,refund:0}]};
for(const selector of ['#order-lock-activity','#order-book-people','#order-book-summary','#order-book-scope','#order-book-count','#order-list'])h.nodes.set(selector,{innerHTML:'',textContent:'',setAttribute(){}});
h.run('validateOrderBook=book=>book;peopleCountHTML=()=>"";orderBookScope=()=>"今日";orderBookFilters={q:"",status:""};renderOrderBook({rows:[],summaryWithoutCancelled:{orderCount:0,totalCost:0,profit:0,ownerCost:0,assistantCost:0,knownCounts:{}},receiptsWithoutCancelled:__receipts},{name:"今日"})');assert.match(h.nodes.get('#order-book-summary').innerHTML,/信用卡/);
const css=fs.readFileSync(path.join(__dirname,'../public/app.css'),'utf8');assert.match(css,/@media screen\{\.credit-card-preview/);assert.match(css,/#fee-rows \.fee-row\.fee-automatic\{min-width:0/);assert.match(css,/@media screen and \(max-width:650px\)\{\.credit-card-preview/);
});