'use strict';
const test=require('node:test'),assert=require('node:assert/strict');
const {randomUUID}=require('node:crypto');const fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {Ledger,today,money,weight}=require('../ledger');const {receipt}=require('../printing');
const actor={id:'owner-test',name:'测试麦麦',role:'owner'},assistant={id:'assistant-test',name:'测试助理',role:'assistant'};
const D='2026-09-30',D2='2026-10-01';
function fixture(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'maimai-ledger-test-'));const l=new Ledger(path.join(dir,'ledger.sqlite'));t.after(()=>{try{l.close();}catch{}fs.rmSync(dir,{recursive:true,force:true});});const run=(payload,fn,a=actor,key=randomUUID())=>l.transact(key,a,payload,fn);const stock=(p={},a=actor)=>run(p,()=>l.stock({kind:'opening',date:D,pocket:'现货',grams:'10.000',note:'合成测试',...p},a),a);const save=(p={})=>run(p,()=>l.saveOrder({date:D,customer:'测试客户',discount:'0',lines:[{name:'测试黄金',unit:'g',quantity:'1.200',pocket:'现货',payer:'owner',cost:'1000',sale:'1200',priceNote:'销售单价'}],...p},actor)).id;const act=(id,a,p={},who=actor)=>run({id,a,...p},()=>l.action(id,a,{date:D,...p},who),who);const fulfill=id=>{act(id,'confirm');act(id,'receipt',{amount:'1200',account:'助理微信',verified:true});act(id,'deliver',{verified:true});};return {l,dir,run,stock,save,act,fulfill};}
test('金额与克重整数化,拒绝空值、指数、超精度、NaN',()=>{assert.equal(money('0.29'),29);assert.equal(weight('0.001'),1);for(const v of ['',null,'NaN','1e2','-1','1.005'])assert.throws(()=>money(v));assert.throws(()=>weight('0.0001'));});
test('定金、跨天尾款、交付是三个独立事实',t=>{const {l,stock,save,act}=fixture(t);stock();const id=save();act(id,'confirm');act(id,'receipt',{amount:'300',account:'助理微信',verified:true});assert.equal(l.detail(id).settlementDue,0);assert.equal(l.detail(id).profit,0);assert.equal(l.inventory()[0].mg,10000);assert.equal(l.inventory()[0].reserved,1200);assert.throws(()=>act(id,'deliver',{verified:true}),/未收齐/);act(id,'receipt',{date:D2,amount:'900',account:'助理支付宝',verified:true});act(id,'deliver',{date:D2,verified:true});assert.equal(l.inventory()[0].mg,8800);assert.equal(l.detail(id).profit,20000);assert.equal(l.detail(id).costDue,100000);assert.equal(l.report(D).sales,0);assert.equal(l.report(D2).accounts.find(a=>a.account==='助理支付宝').receipt,90000);assert.equal(l.report(D2).sales,120000);});
test('同一操作号重试不多记款,内容改变报冲突',t=>{const {l,stock,save,act}=fixture(t);stock();const id=save();act(id,'confirm');const key=randomUUID(),payload={amount:'300',account:'助理微信',verified:true,date:D};const run=()=>l.transact(key,actor,payload,()=>l.action(id,'receipt',payload,actor));run();run();assert.equal(l.detail(id).received,30000);assert.equal(l.detail(id).payments.length,1);assert.throws(()=>l.transact(key,actor,{different:true},()=>({})),/其他内容/);});
test('同一次交付、补打及重新补打不重复扣库存',t=>{const {l,stock,save,act,fulfill}=fixture(t);stock();const id=save();fulfill(id);assert.throws(()=>act(id,'deliver',{verified:true}),/待交付/);for(let i=0;i<3;i++)act(id,'print');assert.equal(l.inventory()[0].mg,8800);assert.equal(l.detail(id).received,120000);assert.equal(l.report(D).sales,120000);});
test('三位克重、混合货盘、调拨守恒',t=>{const {l,stock,save,act}=fixture(t);stock({grams:'0.003'});stock({kind:'transfer',grams:'0.001',to:'金料'});assert.equal(l.inventory()[0].mg,2);assert.equal(l.inventory()[1].mg,1);assert.equal(l.inventory().reduce((s,r)=>s+r.mg,0),3);const id=save({lines:[{name:'测试',unit:'g',quantity:'0.001',pocket:'金料',payer:'owner',cost:'1',sale:'2'}]});act(id,'confirm');act(id,'receipt',{amount:'2',account:'助理微信',verified:true});act(id,'deliver',{verified:true});assert.equal(l.inventory()[1].mg,0);});
test('库存被订单占用后,调拨不能消耗占用;失败事务不留下半笔',t=>{const {l,stock,save,act}=fixture(t);stock({grams:'1.200'});const id=save();act(id,'confirm');assert.throws(()=>stock({kind:'transfer',grams:'0.001',to:'金料'}),/可用库存不足/);assert.equal(l.inventory()[0].mg,1200);assert.equal(l.inventory()[1].mg,0);assert.equal(l.rows('SELECT * FROM movements').length,1);});
test('历史回填不能制造过去负库存',t=>{const {l,stock}=fixture(t);stock({date:D2});assert.throws(()=>stock({kind:'adjustment',date:D,grams:'-1.000'}),/库存不足/);assert.equal(l.inventory()[0].mg,10000);});
test('空白成本不是0,交付前须补齐',t=>{const {l,stock,save,act}=fixture(t);stock();const id=save({lines:[{name:'测试',unit:'g',quantity:'1',pocket:'现货',payer:'owner',cost:'',sale:'1200'}]});act(id,'confirm');act(id,'receipt',{amount:'1200',account:'助理微信',verified:true});assert.equal(l.detail(id).estimatedProfit,null);assert.throws(()=>act(id,'deliver',{verified:true}),/补齐/);act(id,'cost',{costs:['1000']});act(id,'deliver',{verified:true});assert.throws(()=>act(id,'cost',{costs:['900']}),/锁定/);assert.equal(l.detail(id).profit,20000);});
test('外配助理垫资只交利润,整单费用只扣一次',t=>{const {l,save,act}=fixture(t);const id=save({lines:[{name:'外配',unit:'g',quantity:'1.2',pocket:'',payer:'assistant',cost:'1000',sale:'1200'}]});act(id,'confirm');act(id,'expense',{amount:'8',payer:'assistant',note:'实际邮费'});act(id,'receipt',{amount:'1200',account:'助理微信',verified:true});act(id,'deliver',{verified:true});assert.equal(l.inventory()[0].mg,0);assert.equal(l.detail(id).ownerCost,0);assert.equal(l.detail(id).profit,19200);assert.equal(l.detail(id).settlementDue,19200);});
test('混合垫资订单分清货款与利润',t=>{const {l,stock,save,act}=fixture(t);stock();const id=save({lines:[{name:'自有料',unit:'g',quantity:'0.5',pocket:'现货',payer:'owner',cost:'500',sale:'600'},{name:'外配',unit:'件',quantity:'1',pocket:'',payer:'assistant',cost:'400',sale:'600'}]});act(id,'confirm');act(id,'expense',{amount:'10',payer:'assistant',note:'快递'});act(id,'expense',{amount:'20',payer:'owner',note:'证书'});act(id,'receipt',{amount:'1200',account:'助理支付宝',verified:true});act(id,'deliver',{verified:true});assert.equal(l.detail(id).ownerCost,52000);assert.equal(l.detail(id).profit,27000);assert.equal(l.detail(id).settlementDue,79000);});
test('跨月全额退货按原成本,客户退款和老板返款不重复扣利润',t=>{const {l,stock,save,act,fulfill}=fixture(t);stock();const id=save();fulfill(id);for(const [bucket,amount] of [['cost','1000'],['profit','200']])act(id,'settlement',{bucket,amount,direction:'toOwner',note:'实际转款',verified:true});assert.equal(l.detail(id).settlementDue,0);act(id,'return',{date:D2,reason:'整单退回',verified:true});assert.equal(l.inventory()[0].mg,10000);assert.equal(l.detail(id).costDue,-100000);assert.equal(l.detail(id).profitDue,-20000);assert.equal(l.report(D).profit,20000);assert.equal(l.report(D2).profit,-20000);act(id,'refund',{date:D2,amount:'1200',account:'助理微信',verified:true});for(const [bucket,amount] of [['cost','1000'],['profit','200']])act(id,'settlement',{date:D2,bucket,amount,direction:'toAssistant',note:'原单返款',verified:true});assert.equal(l.detail(id).profit,0);assert.equal(l.detail(id).netReceived,0);assert.equal(l.detail(id).settlementDue,0);assert.throws(()=>act(id,'return',{date:D2,reason:'重复',verified:true}),/已交付/);});
test('退货保留已经发生的运费,不反复扣除',t=>{const {l,stock,save,act,fulfill}=fixture(t);stock();const id=save();fulfill(id);act(id,'expense',{amount:'8',payer:'assistant',note:'已付运费'});act(id,'return',{date:D2,reason:'测试',verified:true});assert.equal(l.detail(id).profit,-800);assert.equal(l.report(D2).profit,-20000);});
test('取消定金单释放占用、不造入库,退款从原账户',t=>{const {l,stock,save,act}=fixture(t);stock();const id=save();act(id,'confirm');act(id,'receipt',{amount:'300',account:'助理微信',verified:true});act(id,'cancel',{reason:'客户取消'});assert.equal(l.inventory()[0].mg,10000);assert.equal(l.inventory()[0].reserved,0);assert.throws(()=>act(id,'refund',{amount:'300',account:'麦麦微信',verified:true}),/原收款账户/);act(id,'refund',{amount:'300',account:'助理微信',verified:true});assert.equal(l.detail(id).balance,0);});
test('转款超过余额、重复开账、未来业务、旧版草稿冲突均阻止',t=>{const {stock,save,act,fulfill,l}=fixture(t);stock();assert.throws(()=>stock(),/重复登记/);const id=save();assert.throws(()=>l.saveOrder({...l.rawOrder(id),revision:0,lines:[{name:'x',unit:'g',quantity:'1',pocket:'现货',payer:'owner',cost:'1',sale:'2'}]},actor),/已被更新/);fulfill(id);assert.throws(()=>act(id,'settlement',{amount:'1201',bucket:'cost',direction:'toOwner',note:'超额',verified:true}),/超过/);assert.throws(()=>act(id,'expense',{date:'2099-01-01',amount:'1',payer:'owner',note:'未来'}),/业务日期/);});
test('客户投影和HTML中没有成本、利润、垫资和日志字段,文本转义',t=>{const {l,stock,save}=fixture(t);stock();const id=save({customer:'',note:'
',lines:[{name:'足金