初始化珠宝台账系统:保存新旧程序与使用文档
This commit is contained in:
commit
93528a879b
51 files changed
+6078
No files matched your search
@@ -0,0 +1,147 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict');
|
||||
const {randomUUID}=require('node:crypto'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
|
||||
const {Ledger,today}=require('../ledger'),{createApp}=require('../server');
|
||||
const owner={id:'after-owner',name:'测试麦麦',role:'owner'},assistant={id:'after-assistant',name:'测试助理',role:'assistant'};
|
||||
const D='2026-09-30',D2='2026-10-01',D3='2026-10-02';
|
||||
const line=(extra={})=>({name:'合成商品',unit:'g',quantity:'1.200',pocket:'',payer:'owner',sale:'1200',costParts:{material:'980',labor:'20',accessories:'0',other:'0'},...extra});
|
||||
const input=(extra={})=>({date:D,project:'合成改圈支出',customer:'合成客户',amount:'8.50',payer:'assistant',...extra});
|
||||
function fixture(t){
|
||||
const ledger=new Ledger(':memory:');t.after(()=>ledger.close());
|
||||
const run=(payload,fn,actor=owner,key=randomUUID())=>ledger.transact(key,actor,payload,fn);
|
||||
const after=(extra={},actor=owner,key=randomUUID())=>{const value=input(extra);return run(value,()=>ledger.saveAfterSale(value,actor),actor,key);};
|
||||
const save=(extra={},issue=false)=>{
|
||||
const value={date:D,customer:'合成销售客户',payment_account:'助理微信',lines:[line()],fee_items:[],...extra};
|
||||
return run(value,()=>issue?ledger.issueOrder(value,owner):ledger.saveOrder(value,owner)).id;
|
||||
};
|
||||
const action=(id,kind,extra={})=>{const value={date:D,...extra};return run({id,kind,value},()=>ledger.action(id,kind,value,owner));};
|
||||
const book=(query={})=>ledger.orderBook({date:D,...query});
|
||||
const report=(date=D,from=date)=>ledger.reportByOrderDate(date,from);
|
||||
const close=(date=D)=>run({date},()=>ledger.closeDay(date,owner,'orderDate'));
|
||||
return {ledger,run,after,save,action,book,report,close};
|
||||
}
|
||||
function contents(ledger,tables){return JSON.stringify(tables.map(table=>[table,ledger.rows('SELECT * FROM "'+table+'"')]));}
|
||||
function allContents(ledger){return contents(ledger,ledger.rows("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").map(row=>row.name));}
|
||||
|
||||
test('售后独立保存整数分和实际付款人,双方均可登记,不造销售单、收款、库存或纸单号',t=>{
|
||||
const f=fixture(t);f.save({},true);
|
||||
const tables=['orders','payments','expenses','settlements','movements','journal','meta','sync','inventory_snapshots'];
|
||||
const before=contents(f.ledger,tables),paper=f.ledger.paperNumber(D),audit=f.ledger.rows('SELECT * FROM audit').length;
|
||||
const result=f.after({project:' 合成改圈 ',customer:' 合成客户 '},assistant);
|
||||
assert.equal(result.kind,'afterSale');assert.ok(result.after_sale_id);assert.ok(!('id' in result));
|
||||
const record=f.ledger.one('SELECT * FROM after_sales WHERE id=?',result.after_sale_id);
|
||||
assert.equal(record.amount,850);assert.equal(record.date,D);assert.equal(record.project,'合成改圈');assert.equal(record.customer,'合成客户');assert.equal(record.payer,'assistant');assert.equal(record.actor,assistant.name);
|
||||
const zero=f.after({amount:'0',payer:'owner'},owner);assert.equal(f.ledger.one('SELECT amount FROM after_sales WHERE id=?',zero.after_sale_id).amount,0);
|
||||
assert.equal(contents(f.ledger,tables),before);assert.equal(f.ledger.paperNumber(D),paper);
|
||||
const audits=f.ledger.rows("SELECT * FROM audit WHERE entity LIKE 'after-sale:%'");assert.equal(audits.length,2);assert.equal(f.ledger.rows('SELECT * FROM audit').length,audit+2);
|
||||
assert.equal(audits[0].action,'登记售后');assert.equal(JSON.parse(audits[0].detail).amount,850);
|
||||
});
|
||||
|
||||
test('售后五字段须完整,0元合法;负数、空白、未来日期和超精度失败且不留下半笔',t=>{
|
||||
const f=fixture(t),before=allContents(f.ledger);
|
||||
const invalid=[];
|
||||
for(const key of ['date','project','customer','amount','payer'])for(const value of [undefined,null,''])invalid.push({[key]:value});
|
||||
invalid.push({project:' '.repeat(3)},{customer:' '},{project:'字'.repeat(101)},{customer:'字'.repeat(61)},{project:{}},{customer:[]},
|
||||
{date:'2099-01-01'},{date:'2026-02-30'},{date:'2026-9-30'},{date:'1999-12-31'},{payer:'other'});
|
||||
for(const amount of ['-1','-0','1.234','1e2','NaN','Infinity','1000000000.01',true,{},[]])invalid.push({amount});
|
||||
for(const value of invalid)assert.throws(()=>f.after(value),JSON.stringify(value));
|
||||
assert.throws(()=>f.ledger.saveAfterSale(null,owner));assert.throws(()=>f.ledger.saveAfterSale([],owner));
|
||||
assert.throws(()=>f.after({}, {...assistant,role:'customer'}),/麦麦或助理账号/);
|
||||
assert.equal(allContents(f.ledger),before);
|
||||
const record=f.after({date:today(),amount:'0.01'});assert.equal(f.ledger.one('SELECT amount FROM after_sales WHERE id=?',record.after_sale_id).amount,1);
|
||||
});
|
||||
|
||||
test('订单列表合并售后,真实销售单数量和状态保持独立,日期客户项目及售后状态均可筛选',t=>{
|
||||
const f=fixture(t),sale=f.save({},true);f.save({customer:'草稿客户'});const confirmed=f.save({customer:'旧单客户'});f.action(confirmed,'confirm');
|
||||
const after=f.after(),later=f.after({date:D2,project:'合成维修',customer:'另一客户',amount:'6',payer:'owner'});
|
||||
const b=f.book(),row=b.rows.find(row=>row.after_sale_id===after.after_sale_id);
|
||||
assert.equal(row.kind,'afterSale');assert.equal(row.status,'after_sale');assert.equal(row.project,'合成改圈支出');assert.equal(row.customer,'合成客户');assert.equal(row.paper_number,'');assert.deepEqual(row.types,['售后']);
|
||||
assert.equal(row.sale,0);assert.equal(row.material,0);assert.equal(row.unallocated,0);assert.equal(row.laborAndFees,850);assert.equal(row.totalCost,850);assert.equal(row.profit,-850);
|
||||
assert.equal(row.ownerCost,0);assert.equal(row.assistantCost,850);assert.equal(row.balance,0);assert.equal(row.mg,0);assert.equal(row.pieces,0);
|
||||
assert.equal(row.incomplete,false);assert.equal(row.missingCosts,0);assert.equal(row.pendingCosts,0);assert.deepEqual(row.pendingCostItems,[]);assert.equal(row.costItems.length,1);assert.equal(row.costItems[0].kind,'afterSale');
|
||||
assert.equal(b.summary.orderCount,3);assert.equal(b.summary.completedCount,1);assert.equal(b.summary.draftCount,1);assert.equal(b.summary.confirmedCount,1);assert.equal(b.summary.afterSaleCount,1);assert.equal(b.summary.recordCount,4);
|
||||
assert.equal(b.summary.knownCounts.profit,1);assert.equal(b.summary.unknownCounts.profit,1);assert.equal(b.summary.profit,19150);assert.equal(b.receiptsByOrderDate.receipt,120000);
|
||||
const only=f.book({status:'after_sale'});assert.deepEqual(only.rows.map(row=>row.after_sale_id),[after.after_sale_id]);assert.equal(only.summary.orderCount,0);assert.equal(only.summary.afterSaleCount,1);assert.equal(only.summary.profit,-850);assert.equal(only.receiptsByOrderDate.receipt,0);
|
||||
assert.deepEqual(f.book({status:'delivered'}).rows.map(row=>row.id),[sale]);assert.equal(f.book({status:'draft'}).summary.afterSaleCount,0);
|
||||
for(const q of ['改圈','合成客户','售后'])assert.deepEqual(f.book({q,status:'after_sale'}).rows.map(row=>row.after_sale_id),[after.after_sale_id]);
|
||||
assert.deepEqual(f.book({date:D2,q:'另一客户'}).rows.map(row=>row.after_sale_id),[later.after_sale_id]);
|
||||
assert.equal(f.book({from:D,date:D2,status:'after_sale'}).summary.afterSaleCount,2);assert.deepEqual(f.book({q:'不存在'}).rows,[]);
|
||||
});
|
||||
|
||||
test('售后只扣所选日期和月份利润,订单后补费用仍归原开单日,各口径不重复计费',t=>{
|
||||
const f=fixture(t),id=f.save({},true);f.action(id,'expense',{date:D3,amount:'5',payer:'assistant',note:'原单后补费用'});
|
||||
f.after({date:D2,amount:'20',payer:'owner'});
|
||||
const original=f.report(),after=f.report(D2),empty=f.report(D3),september=f.report(D,'2026-09-01'),october=f.report(D3,D2),combined=f.report(D3,D);
|
||||
assert.equal(original.profit,19500);assert.equal(original.expense,500);assert.equal(original.summary.afterSaleCount,0);
|
||||
assert.equal(after.profit,-2000);assert.equal(after.expense,2000);assert.equal(after.goods,0);assert.equal(after.sales,0);assert.equal(after.summary.orderCount,0);assert.equal(after.summary.afterSaleCount,1);
|
||||
assert.equal(empty.profit,0);assert.equal(empty.expense,0);assert.equal(september.profit,19500);assert.equal(october.profit,-2000);assert.equal(combined.profit,17500);assert.equal(combined.expense,2500);
|
||||
assert.equal(f.ledger.report(D2).profit,-2000);assert.equal(f.ledger.report(D2).expense,2000);assert.equal(f.ledger.report(D3).profit,-500);
|
||||
for(const r of [original,after,empty,september,october,combined]){
|
||||
const b=f.ledger.orderBook({from:r.from,date:r.date});assert.equal(r.profit,b.summary.profit);assert.equal(r.goods+r.expense,b.summary.totalCost);assert.equal(r.payerCosts.owner.total+r.payerCosts.assistant.total,b.summary.totalCost);
|
||||
}
|
||||
});
|
||||
|
||||
test('售后明细按付款人计已付费用,无订单链接标识,0元记录和客户项目日期完整保留',t=>{
|
||||
const f=fixture(t);f.save({},true);f.after({amount:'20.05',payer:'owner'});f.after({amount:'1.30',payer:'assistant'});f.after({amount:'0',payer:'assistant'});
|
||||
const r=f.report(),ownerCosts=r.payerCosts.owner,helperCosts=r.payerCosts.assistant;
|
||||
assert.equal(r.goods,100000);assert.equal(r.expense,2135);assert.equal(r.profit,17865);assert.equal(ownerCosts.goods,100000);assert.equal(ownerCosts.paidFees,2005);assert.equal(helperCosts.paidFees,130);
|
||||
const items=[...ownerCosts.items,...helperCosts.items].filter(item=>item.kind==='afterSale');assert.equal(items.length,3);assert.equal(items.filter(item=>item.amount===0).length,1);
|
||||
for(const item of items){assert.ok(item.after_sale_id);assert.ok(!('order_id' in item));assert.equal(item.date,D);assert.equal(item.customer,'合成客户');assert.equal(item.project,'合成改圈支出');assert.equal(item.name,item.project);assert.equal(item.component,'fee');assert.equal(item.calculation,null);assert.equal(item.status,'recorded');}
|
||||
assert.equal(ownerCosts.missingCount+helperCosts.missingCount,0);assert.equal(ownerCosts.pendingCount+helperCosts.pendingCount,0);
|
||||
});
|
||||
|
||||
test('未补齐旧单和售后混合时保留已知负利润及成本,销售单与已知贡献计数不混算',t=>{
|
||||
const f=fixture(t),id=f.save({lines:[line({costParts:{material:'',labor:'0',accessories:'5',other:'0'}})]});f.action(id,'confirm');
|
||||
f.after({amount:'20',payer:'owner'});f.after({amount:'0',payer:'assistant'});
|
||||
const b=f.book(),r=f.report();assert.equal(b.summary.orderCount,1);assert.equal(b.summary.afterSaleCount,2);assert.equal(b.summary.recordCount,3);
|
||||
assert.equal(b.summary.knownCounts.profit,0);assert.equal(b.summary.unknownCounts.profit,1);assert.equal(b.summary.unknownProfitCount,1);
|
||||
assert.equal(b.summary.profit,-2000);assert.equal(r.profit,-2000);assert.equal(r.totalCost,2500);assert.equal(b.summary.unknownCostCount,1);assert.equal(b.summary.partial,true);
|
||||
assert.equal(r.payerCosts.owner.total,2500);assert.equal(r.payerCosts.owner.missingCount,1);assert.equal(r.payerCosts.assistant.items[0].amount,0);
|
||||
assert.equal(r.orderRows.find(row=>row.id===id).profit,null);assert.equal(r.orderRows.filter(row=>row.kind==='afterSale').reduce((sum,row)=>sum+row.profit,0),-2000);
|
||||
});
|
||||
|
||||
test('售后只使对应日期财务快照过期,其他日期、库存快照、库存版本与同步均不受影响',t=>{
|
||||
const f=fixture(t);f.save({},true);f.close(D);f.close(D2);
|
||||
const inventory=contents(f.ledger,['inventory_snapshots','movements','sync']),version=f.ledger.inventoryRevision(D);
|
||||
const next=f.report(D2).reportRevision;assert.equal(f.report().close.stale,false);assert.equal(f.report(D2).close.stale,false);
|
||||
f.after();assert.equal(f.report().close.stale,true);assert.equal(f.report(D2).close.stale,false);assert.equal(f.report(D2).reportRevision,next);
|
||||
assert.equal(f.ledger.one('SELECT stale FROM closes WHERE date=?',D).stale,1);assert.equal(f.ledger.one('SELECT stale FROM closes WHERE date=?',D2).stale,0);
|
||||
assert.equal(contents(f.ledger,['inventory_snapshots','movements','sync']),inventory);assert.equal(f.ledger.inventoryRevision(D),version);assert.equal(f.ledger.inventorySnapshot(D).stale,false);
|
||||
f.close(D);assert.equal(f.report().close.stale,false);f.after({amount:'0'});assert.equal(f.report().close.stale,true,'0元售后也是新增的核对记录');
|
||||
});
|
||||
|
||||
test('旧数据库增量建立售后表且可重启保留,读取与筛选不改账本或核对快照',t=>{
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'maimai-after-upgrade-')),filename=path.join(dir,'ledger.sqlite');
|
||||
let ledger=new Ledger(filename);t.after(()=>{try{ledger.close();}catch{}fs.rmSync(dir,{recursive:true,force:true});});
|
||||
const value={date:D,customer:'原销售客户',lines:[line()],fee_items:[]};const id=ledger.transact(randomUUID(),owner,value,()=>ledger.issueOrder(value,owner)).id;
|
||||
const original=ledger.detail(id),paper=ledger.paperNumber(D);ledger.db.exec('DROP TABLE after_sales');ledger.close();
|
||||
ledger=new Ledger(filename);assert.deepEqual(ledger.detail(id),original);assert.equal(ledger.paperNumber(D),paper);assert.equal(ledger.rows('SELECT * FROM after_sales').length,0);
|
||||
const after=ledger.transact(randomUUID(),assistant,input(),()=>ledger.saveAfterSale(input(),assistant));ledger.close();
|
||||
ledger=new Ledger(filename);assert.equal(ledger.one('SELECT amount FROM after_sales WHERE id=?',after.after_sale_id).amount,850);assert.deepEqual(ledger.detail(id),original);
|
||||
const before=allContents(ledger),changes=ledger.one('SELECT total_changes() AS count').count;
|
||||
const report=ledger.reportByOrderDate(D);assert.deepEqual(ledger.reportByOrderDate(D),report);ledger.orderBook({date:D,status:'after_sale',q:'改圈'});ledger.reportByOrderDate(D2,D);ledger.report(D);
|
||||
assert.equal(allContents(ledger),before);assert.equal(ledger.one('SELECT total_changes() AS count').count,changes);
|
||||
});
|
||||
|
||||
test('HTTP售后沿用登录、CSRF与双方权限,并发重试只记一次,失败及未知编辑入口不写账',async t=>{
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'maimai-after-http-')),app=createApp({mode:'demo',dataDir:dir,ledger:new Ledger(':memory:'),feishuConfig:{enabled:false}});
|
||||
await new Promise(resolve=>app.server.listen(0,'127.0.0.1',resolve));
|
||||
t.after(async()=>{await new Promise(resolve=>app.server.close(resolve));app.ledger.close();fs.rmSync(dir,{recursive:true,force:true});});
|
||||
const base='http://127.0.0.1:'+app.server.address().port;let cookie='';
|
||||
const call=(route,data,key=randomUUID(),origin=base)=>fetch(base+route,{method:data?'POST':'GET',headers:{...(cookie?{Cookie:cookie}:{}),...(data?{'Content-Type':'application/json',Origin:origin,'X-Requested-With':'maimai-ledger','Idempotency-Key':key}:{} )},...(data?{body:JSON.stringify(data)}:{})});
|
||||
assert.equal((await call('/api/after-sales',input())).status,401);
|
||||
let login=await call('/api/demo-login',{role:'assistant'});cookie=login.headers.get('set-cookie').split(';')[0];
|
||||
const protectedTables=['orders','payments','expenses','settlements','movements','journal','meta','sync','inventory_snapshots'],protectedBefore=contents(app.ledger,protectedTables);
|
||||
assert.equal((await call('/api/after-sales',input(),randomUUID(),'https://invalid.example')).status,403);
|
||||
for(const value of [input({amount:'-1'}),input({amount:'1.234'}),input({customer:''}),input({date:'2099-01-01'})])assert.equal((await call('/api/after-sales',value)).status,400);
|
||||
assert.equal(app.ledger.rows('SELECT * FROM after_sales').length,0);
|
||||
const key=randomUUID(),results=await Promise.all([call('/api/after-sales',input(),key),call('/api/after-sales',input(),key)]);assert.deepEqual(results.map(result=>result.status),[200,200]);
|
||||
const first=await results[0].json();assert.deepEqual(await results[1].json(),first);assert.equal(app.ledger.rows('SELECT * FROM after_sales').length,1);
|
||||
assert.equal(app.ledger.rows("SELECT * FROM audit WHERE action='登记售后'").length,1);assert.equal(app.ledger.rows('SELECT * FROM operations WHERE id=?',key).length,1);
|
||||
assert.equal((await call('/api/after-sales',input({amount:'9'}),key)).status,409);
|
||||
assert.equal((await call('/api/after-sales/'+first.after_sale_id,input())).status,404);assert.equal((await call('/api/orders/'+first.after_sale_id)).status,404);assert.equal((await call('/print/'+first.after_sale_id)).status,404);
|
||||
const b=await (await call('/api/order-book?date='+D+'&status=after_sale')).json();assert.equal(b.summary.afterSaleCount,1);assert.equal(b.summary.orderCount,0);assert.equal(b.rows[0].profit,-850);
|
||||
const r=await (await call('/api/report?date='+D+'&basis=orderDate')).json();assert.equal(r.profit,-850);assert.equal(r.payerCosts.assistant.paidFees,850);assert.equal(r.receiptsByOrderDate.receipt,0);
|
||||
login=await call('/api/demo-login',{role:'owner'});cookie=login.headers.get('set-cookie').split(';')[0];assert.equal((await call('/api/after-sales',input({amount:'0',payer:'owner'}))).status,200);
|
||||
assert.equal(app.ledger.rows('SELECT * FROM after_sales').length,2);assert.equal(contents(app.ledger,protectedTables),protectedBefore);
|
||||
});
|
||||
@@ -0,0 +1,124 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict');
|
||||
const {randomUUID}=require('node:crypto'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
|
||||
const {Ledger}=require('../ledger'),Calc=require('../public/calculations'),{createApp}=require('../server'),{FeishuSync}=require('../sync');
|
||||
const owner={id:'component-owner',name:'测试麦麦',role:'owner'},D='2026-09-30',D2='2026-10-01';
|
||||
const line=(extra={})=>({name:'合成商品',unit:'g',quantity:'2.200',pocket:'现货',payer:'owner',sale:'2300',
|
||||
costParts:{material:'9999',labor:'999',accessories:'5',other:'1'},costMaterial:{mode:'gram',rate:'900'},costLabor:{mode:'gram',rate:'20'},...extra});
|
||||
const payload=(extra={})=>({date:D,customer:'合成客户',payment_account:'助理微信',lines:[line()],
|
||||
fee_items:[{key:'shipping',note:'快递费',amount:'6',payer:'assistant'},{key:'box',note:'包装',amount:'3',payer:'owner'}],...extra});
|
||||
function fixture(t){
|
||||
const ledger=new Ledger(':memory:');t.after(()=>ledger.close());
|
||||
const run=(input,fn,key=randomUUID())=>ledger.transact(key,owner,input,fn);
|
||||
run({stock:true},()=>ledger.stock({kind:'opening',date:D,pocket:'现货',grams:'20',note:'合成库存'},owner));
|
||||
const save=(input=payload(),issue=false)=>run(input,()=>issue?ledger.issueOrder(input,owner):ledger.saveOrder(input,owner)).id;
|
||||
const action=(id,kind,extra={})=>{const input={date:D,...extra};return run({id,kind,input},()=>ledger.action(id,kind,input,owner));};
|
||||
return {ledger,run,save,action};
|
||||
}
|
||||
const snapshot=ledger=>JSON.stringify(ledger.rows("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").map(({name})=>[name,ledger.rows('SELECT * FROM "'+name+'"')]));
|
||||
|
||||
test('料费和克工费可相反或同人支付,配件其他仍按共享付款人,成本利润与库存不变',t=>{
|
||||
const f=fixture(t),cases=[
|
||||
{payer:'owner',costPayers:{material:'assistant',labor:'owner'},ownerGoods:5000,assistantGoods:198000},
|
||||
{payer:'assistant',costPayers:{material:'owner',labor:'assistant'},ownerGoods:198000,assistantGoods:5000},
|
||||
{payer:'assistant',costPayers:{material:'owner',labor:'owner'},ownerGoods:202400,assistantGoods:600},
|
||||
{payer:'owner',costPayers:{material:'assistant',labor:'assistant'},ownerGoods:600,assistantGoods:202400}
|
||||
];
|
||||
for(const entry of cases){
|
||||
const id=f.save(payload({lines:[line(entry)]}),true),o=f.ledger.detail(id),costs=Calc.orderCosts(o),row=f.ledger.orderBook({date:D}).rows.find(row=>row.id===id);
|
||||
assert.deepEqual(o.lines[0].costPayers,entry.costPayers);assert.equal(costs.byPayer.owner.goods,entry.ownerGoods);assert.equal(costs.byPayer.assistant.goods,entry.assistantGoods);
|
||||
assert.equal(o.goodsCost,203000);assert.equal(o.profit,26100);assert.equal(o.total,230000);assert.equal(o.ownerCost,entry.ownerGoods+300);assert.equal(o.costDue,o.ownerCost);assert.equal(o.settlementDue,o.ownerCost+26100);
|
||||
assert.equal(costs.rows.find(row=>row.name==='料费成本').payer,entry.costPayers.material);assert.equal(costs.rows.find(row=>row.name==='进货工费').payer,entry.costPayers.labor);
|
||||
assert.ok(costs.rows.filter(row=>['配件成本','其他货品成本'].includes(row.name)).every(row=>row.payer===entry.payer));
|
||||
assert.equal(row.ownerCost,entry.ownerGoods+300);assert.equal(row.assistantCost,entry.assistantGoods+600);assert.equal(row.totalCost,203900);
|
||||
}
|
||||
const book=f.ledger.orderBook({date:D}),r=f.ledger.reportByOrderDate(D);
|
||||
assert.equal(book.summary.totalCost,815600);assert.equal(book.summary.profit,104400);assert.deepEqual(r.summary,book.summary);
|
||||
assert.equal(r.payerCosts.owner.total,book.summary.ownerCost);assert.equal(r.payerCosts.assistant.total,book.summary.assistantCost);assert.equal(r.goods,812000);assert.equal(r.expense,3600);
|
||||
assert.equal(f.ledger.inventory().find(row=>row.pocket==='现货').mg,11200);
|
||||
});
|
||||
|
||||
test('每克料价和总工费各按一次金额分账,实际结算仅回收麦麦支付的分项',t=>{
|
||||
const f=fixture(t),id=f.save(payload({lines:[line({costPayers:{material:'assistant',labor:'owner'},costMaterial:{mode:'gram',rate:'900.01'},costLabor:{mode:'total'},costParts:{material:'0',labor:'17.34',accessories:'5',other:'1'}})]}),true);
|
||||
const o=f.ledger.detail(id),costs=Calc.orderCosts(o);assert.equal(o.lines[0].costParts.material,198002);assert.equal(o.lines[0].costParts.labor,1734);assert.equal(o.goodsCost,200336);assert.equal(o.profit,28764);
|
||||
assert.equal(o.ownerCost,2634);assert.equal(o.costDue,2634);assert.equal(o.settlementDue,31398);assert.equal(costs.byPayer.assistant.total,198602);
|
||||
assert.deepEqual(costs.rows.find(row=>row.name==='料费成本').calculation,{rate:90001,quantity:2200});assert.equal(costs.rows.find(row=>row.name==='进货工费').calculation,null);
|
||||
assert.throws(()=>f.action(id,'settlement',{amount:'26.35',bucket:'cost',direction:'toOwner',note:'超过分项垫资',verified:true}),/超过/);
|
||||
f.action(id,'settlement',{amount:'26.34',bucket:'cost',direction:'toOwner',note:'已转实际货款',verified:true});assert.equal(f.ledger.detail(id).costDue,0);assert.equal(f.ledger.detail(id).settlementDue,28764);
|
||||
f.action(id,'settlement',{amount:'287.64',bucket:'profit',direction:'toOwner',note:'已转利润',verified:true});assert.equal(f.ledger.detail(id).settlementDue,0);
|
||||
});
|
||||
|
||||
test('麦麦直接收款时按分项垫资算净待返助理金额,同步副本使用相同结算和内部明细',t=>{
|
||||
const f=fixture(t),id=f.save(payload({payment_account:'麦麦微信',lines:[line({costPayers:{material:'assistant',labor:'owner'}})]}),true),o=f.ledger.detail(id);
|
||||
assert.equal(o.ownerCost,5300);assert.equal(o.ownerDirect,230000);assert.equal(o.settlementDue,-198600);
|
||||
const sync=new FeishuSync(f.ledger,{enabled:false},()=>{throw new Error('禁止网络');}),fields=sync.fields('order:'+id,o.revision),details=JSON.parse(fields['明细']);
|
||||
assert.equal(fields['待结算'],-1986);assert.equal(details.ownerCost,5300);assert.deepEqual(details.lines[0].costPayers,{material:'assistant',labor:'owner'});
|
||||
});
|
||||
|
||||
test('旧分项和未分项记录按原payer回退,读取不补写;相同归属的显式元数据不改变财务哈希',t=>{
|
||||
const f=fixture(t),id=f.save(payload(),true),legacy=f.save(payload({lines:[line({unit:'件',quantity:'1',pocket:'',payer:'assistant',costParts:undefined,costMaterial:undefined,costLabor:undefined,cost:'12.34',sale:'50'})],fee_items:[]}),true);
|
||||
const before=snapshot(f.ledger),report=f.ledger.reportByOrderDate(D);
|
||||
assert.ok(!Object.hasOwn(f.ledger.detail(id).lines[0],'costPayers'));assert.ok(!Object.hasOwn(f.ledger.detail(legacy).lines[0],'costPayers'));
|
||||
const originalCosts=Calc.orderCosts(f.ledger.detail(id));assert.equal(originalCosts.byPayer.owner.goods,203000);assert.equal(originalCosts.byPayer.assistant.goods,0);
|
||||
const legacyCosts=Calc.orderCosts(f.ledger.detail(legacy));assert.equal(legacyCosts.rows[0].name,'货品成本(原单未分项)');assert.equal(legacyCosts.byPayer.assistant.goods,1234);
|
||||
f.ledger.orderBook({date:D});f.ledger.reportByOrderDate(D);assert.equal(snapshot(f.ledger),before);
|
||||
// 只在内存模拟等价的新格式,确认新增字段不会迫使未变动的旧财务快照过期。
|
||||
const raw=f.ledger.rawOrder(id);raw.lines[0].costPayers={material:'owner',labor:'owner'};f.ledger.run('UPDATE orders SET lines=? WHERE id=?',JSON.stringify(raw.lines),id);
|
||||
assert.deepEqual(Calc.orderCosts(f.ledger.detail(id)),originalCosts);assert.equal(f.ledger.reportByOrderDate(D).reportRevision,report.reportRevision);
|
||||
});
|
||||
|
||||
test('草稿保存再编辑及旧客户端缺省字段均保留已有分项付款人,显式修改才更新',t=>{
|
||||
const f=fixture(t),first=payload({lines:[line({costPayers:{material:'assistant',labor:'owner'}})],fee_items:[]}),id=f.save(first),paper=f.ledger.detail(id).paper_number;
|
||||
const edit={...first,id,revision:f.ledger.detail(id).revision,lines:[{...first.lines[0],quantity:'3.000'}]};f.save(edit);
|
||||
let row=f.ledger.detail(id).lines[0];assert.equal(row.costParts.material,270000);assert.equal(row.costParts.labor,6000);assert.deepEqual(row.costPayers,{material:'assistant',labor:'owner'});
|
||||
const {costPayers,...oldClientLine}=edit.lines[0];f.save({...edit,revision:f.ledger.detail(id).revision,lines:[{...oldClientLine,payer:'assistant'}]});
|
||||
row=f.ledger.detail(id).lines[0];assert.deepEqual(row.costPayers,{material:'assistant',labor:'owner'});assert.equal(row.payer,'assistant');assert.equal(f.ledger.detail(id).paper_number,paper);
|
||||
f.save({...edit,revision:f.ledger.detail(id).revision,lines:[{...oldClientLine,costPayers:{material:'owner',labor:'assistant'}}]});assert.deepEqual(f.ledger.detail(id).lines[0].costPayers,{material:'owner',labor:'assistant'});
|
||||
});
|
||||
|
||||
test('旧单后补成本保留缺省分项付款人,可分别更新分项和配件其他付款人,交付后锁定',t=>{
|
||||
const f=fixture(t),id=f.save(payload({lines:[line({costParts:{material:'',labor:'0',accessories:'5',other:'1'},costMaterial:{mode:'total'},costPayers:{material:'assistant',labor:'owner'}})],fee_items:[]}));f.action(id,'confirm');
|
||||
const parts={material:'1980',labor:'44',accessories:'5',other:'1'};f.action(id,'cost',{costs:[{parts,payer:'assistant'}]});
|
||||
let row=f.ledger.detail(id).lines[0];assert.deepEqual(row.costPayers,{material:'assistant',labor:'owner'});assert.equal(row.payer,'assistant');assert.equal(Calc.orderCosts(f.ledger.detail(id)).byPayer.owner.goods,4400);
|
||||
f.action(id,'cost',{costs:[{parts,costPayers:{material:'owner',labor:'assistant'}}]});row=f.ledger.detail(id).lines[0];assert.equal(row.payer,'assistant');assert.deepEqual(row.costPayers,{material:'owner',labor:'assistant'});
|
||||
f.action(id,'receipt',{amount:'2300',account:'助理微信',verified:true});f.action(id,'deliver',{verified:true});assert.equal(f.ledger.detail(id).ownerCost,198000);assert.equal(f.ledger.detail(id).settlementDue,225000);
|
||||
assert.throws(()=>f.action(id,'cost',{costs:[{parts,costPayers:{material:'assistant',labor:'owner'}}]}),/交付前/);
|
||||
const old=f.save(payload({lines:[line({costParts:{material:'',labor:'0',accessories:'0',other:'0'},costMaterial:{mode:'total'}})],fee_items:[]}));f.action(old,'confirm');f.action(old,'cost',{costs:[parts]});
|
||||
assert.ok(!Object.hasOwn(f.ledger.detail(old).lines[0],'costPayers'));assert.equal(Calc.orderCosts(f.ledger.detail(old)).byPayer.owner.goods,203000);
|
||||
});
|
||||
|
||||
test('显式无效分项付款人一律拒绝,新建编辑后补均完整回滚,不能擦掉已有值',t=>{
|
||||
const f=fixture(t),invalid=[null,'',[],{},'owner',{material:'owner'},{labor:'assistant'},{material:'owner',labor:''},{material:null,labor:'owner'},{material:'invalid',labor:'assistant'},{material:'owner',labor:'assistant',accessories:'owner'}];
|
||||
const first=payload({lines:[line({costPayers:{material:'assistant',labor:'owner'}})],fee_items:[]}),id=f.save(first);
|
||||
for(const value of invalid){
|
||||
let before=snapshot(f.ledger);assert.throws(()=>f.save(payload({lines:[line({costPayers:value})]})),/付款人/);assert.equal(snapshot(f.ledger),before);
|
||||
assert.throws(()=>f.save({...first,id,revision:f.ledger.detail(id).revision,lines:[line({costPayers:value})]}),/付款人/);assert.equal(snapshot(f.ledger),before);
|
||||
}
|
||||
f.action(id,'confirm');const before=snapshot(f.ledger),parts={material:'1980',labor:'44',accessories:'5',other:'1'};
|
||||
for(const costPayers of invalid){assert.throws(()=>f.action(id,'cost',{costs:[{parts,costPayers}]}),/付款人/);assert.equal(snapshot(f.ledger),before);}
|
||||
assert.throws(()=>f.action(id,'cost',{costs:[{parts,payer:'invalid'}]}),/垫资人/);assert.equal(snapshot(f.ledger),before);
|
||||
assert.throws(()=>Calc.costPayers({material:'owner',labor:null}),/付款人/);assert.deepEqual(f.ledger.detail(id).lines[0].costPayers,{material:'assistant',labor:'owner'});
|
||||
});
|
||||
|
||||
test('退货和取消不计货品分项垫资,原实际费用保留,货款返还只冲原麦麦货品成本',t=>{
|
||||
const f=fixture(t),p=payload({lines:[line({costPayers:{material:'assistant',labor:'owner'}})]}),id=f.save(p,true);
|
||||
f.action(id,'settlement',{amount:'53',bucket:'cost',direction:'toOwner',note:'原货款已交',verified:true});f.action(id,'return',{date:D2,reason:'合成退货',verified:true});
|
||||
let o=f.ledger.detail(id),costs=Calc.orderCosts(o);assert.equal(o.ownerCost,300);assert.equal(o.costDue,-5000);assert.equal(o.profit,-900);assert.equal(costs.byPayer.owner.goods,0);assert.equal(costs.byPayer.assistant.goods,0);assert.ok(costs.rows.filter(row=>row.kind==='goods').every(row=>row.excluded));
|
||||
assert.equal(costs.byPayer.owner.paidFees,300);assert.equal(costs.byPayer.assistant.paidFees,600);
|
||||
const cancelled=f.save(p);f.action(cancelled,'confirm',{feesVerified:true});f.action(cancelled,'cancel',{date:D2,reason:'合成取消'});o=f.ledger.detail(cancelled);costs=Calc.orderCosts(o);
|
||||
assert.equal(o.ownerCost,300);assert.equal(o.costDue,300);assert.equal(o.profit,-900);assert.equal(o.settlementDue,-600);assert.equal(costs.total.goods,0);
|
||||
const report=f.ledger.reportByOrderDate(D);assert.equal(report.goods,0);assert.equal(report.expense,1800);assert.equal(report.payerCosts.owner.goods,0);assert.equal(report.payerCosts.assistant.goods,0);
|
||||
});
|
||||
|
||||
test('HTTP保存分项付款人并正确分账,客户接口与打印隔离,显式无效请求不写入',async t=>{
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'maimai-cost-payers-http-')),app=createApp({mode:'demo',dataDir:dir,ledger:new Ledger(':memory:'),feishuConfig:{enabled:false}});
|
||||
await new Promise(resolve=>app.server.listen(0,'127.0.0.1',resolve));t.after(async()=>{await new Promise(resolve=>app.server.close(resolve));app.ledger.close();fs.rmSync(dir,{recursive:true,force:true});});
|
||||
const base='http://127.0.0.1:'+app.server.address().port;let cookie='';
|
||||
const call=(route,data)=>fetch(base+route,{method:data?'POST':'GET',headers:{...(cookie?{Cookie:cookie}:{}),...(data?{'Content-Type':'application/json',Origin:base,'X-Requested-With':'maimai-ledger','Idempotency-Key':randomUUID()}:{} )},...(data?{body:JSON.stringify(data)}:{})});
|
||||
const login=await call('/api/demo-login',{role:'assistant'});cookie=login.headers.get('set-cookie').split(';')[0];
|
||||
const p=payload({lines:[line({pocket:'',costPayers:{material:'assistant',labor:'owner'}})]}),issue=await call('/api/orders/issue',p);assert.equal(issue.status,200);const {id}=await issue.json();
|
||||
const detail=await (await call('/api/orders/'+id)).json();assert.deepEqual(detail.lines[0].costPayers,p.lines[0].costPayers);assert.equal(detail.ownerCost,5300);assert.equal(detail.settlementDue,31400);
|
||||
const book=await (await call('/api/order-book?date='+D)).json(),report=await (await call('/api/report?date='+D+'&basis=orderDate')).json();assert.equal(book.summary.ownerCost,5300);assert.equal(report.payerCosts.owner.total,5300);assert.equal(report.payerCosts.assistant.total,198600);
|
||||
const customer=JSON.stringify(await (await call('/api/orders/'+id+'/public')).json()),html=await (await call('/print/'+id)).text();for(const key of ['costPayers','costParts','costMaterial','costLabor','payer','ownerCost']){assert.ok(!customer.includes('"'+key+'"'));assert.ok(!html.includes(key));}
|
||||
const before=snapshot(app.ledger);assert.equal((await call('/api/orders/issue',{...p,lines:[{...p.lines[0],costPayers:{material:'owner',labor:'invalid'}}]})).status,400);assert.equal(snapshot(app.ledger),before);
|
||||
});
|
||||
@@ -0,0 +1,192 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict');
|
||||
const {randomUUID}=require('node:crypto'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
|
||||
const {Ledger,today}=require('../ledger'),{createApp}=require('../server');
|
||||
const actor={id:'daily-owner',name:'测试麦麦',role:'owner'},assistant={id:'daily-assistant',name:'测试助理',role:'assistant'};
|
||||
const D='2026-09-30',D2='2026-10-01',D3='2026-10-02';
|
||||
const line=(extra={})=>({name:'合成商品',unit:'g',quantity:'1.200',pocket:'',payer:'owner',sale:'1200',costParts:{material:'980',labor:'20',accessories:'0',other:'0'},...extra});
|
||||
function fixture(t){
|
||||
const ledger=new Ledger(':memory:');t.after(()=>ledger.close());
|
||||
const run=(payload,fn,key=randomUUID())=>ledger.transact(key,actor,payload,fn);
|
||||
const save=(extra={},issue=false)=>{
|
||||
const input={date:D,customer:'合成客户',note:'仅用于测试',payment_account:'助理微信',lines:[line()],fee_items:[],...extra};
|
||||
return run(input,()=>issue?ledger.issueOrder(input,actor):ledger.saveOrder(input,actor)).id;
|
||||
};
|
||||
const action=(id,kind,extra={},key=randomUUID())=>{
|
||||
const input={date:D,...extra};return run({id,kind,input},()=>ledger.action(id,kind,input,actor),key);
|
||||
};
|
||||
const report=(date=D,from=date)=>ledger.reportByOrderDate(date,from);
|
||||
const close=(date=D,basis='orderDate')=>run({date,basis},()=>ledger.closeDay(date,actor,basis));
|
||||
return {ledger,run,save,action,report,close};
|
||||
}
|
||||
function sameBook(f,date=D,from=date){
|
||||
const report=f.report(date,from),book=f.ledger.orderBook({date,from,status:'all'});
|
||||
assert.equal(report.basis,'orderDate');assert.deepEqual(report.summary,book.summary);assert.deepEqual(report.orderRows,book.rows);
|
||||
assert.deepEqual(report.accounts,book.receiptsByOrderDate.accounts);assert.deepEqual(report.receiptsByOrderDate,book.receiptsByOrderDate);
|
||||
assert.equal(report.sales,book.summary.sale);assert.equal(report.profit,book.summary.profit);
|
||||
assert.equal(report.goods+report.expense,book.summary.totalCost);assert.equal(report.totalCost,book.summary.totalCost);
|
||||
for(const payer of ['owner','assistant'])assert.equal(report.payerCosts[payer].total,book.summary[payer+'Cost']);
|
||||
return report;
|
||||
}
|
||||
function databaseContents(ledger){return JSON.stringify(ledger.rows("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").map(({name})=>[name,ledger.rows('SELECT * FROM "'+name+'"')]));}
|
||||
|
||||
test('开单日对账与订单簿一致,双方货品及实际费用分开,按克结果和计算式保留',t=>{
|
||||
const f=fixture(t),id=f.save({lines:[line({quantity:'2.200',sale:'2300',costMaterial:{mode:'gram',rate:'900.01'},costLabor:{mode:'gram',rate:'20'},costParts:{material:'0',labor:'0',accessories:'5',other:'0'}}),
|
||||
line({name:'合成银饰',unit:'件',quantity:'2',payer:'assistant',sale:'200',costParts:{material:'80',labor:'10',accessories:'0',other:'0'}})],
|
||||
fee_items:[{key:'shipping',note:'快递费',amount:'6',payer:'assistant'},{key:'certificate',note:'证书',amount:'4',payer:'owner'}]},true);
|
||||
const r=sameBook(f),owner=r.payerCosts.owner,helper=r.payerCosts.assistant;
|
||||
assert.equal(r.sales,250000);assert.equal(r.goods,211902);assert.equal(r.expense,1000);assert.equal(r.profit,37098);
|
||||
assert.equal(owner.goods,202902);assert.equal(owner.paidFees,400);assert.equal(owner.total,203302);
|
||||
assert.equal(helper.goods,9000);assert.equal(helper.paidFees,600);assert.equal(helper.total,9600);
|
||||
assert.equal(owner.missingCount,0);assert.equal(helper.pendingCount,0);
|
||||
const material=owner.items.find(item=>item.component==='material');
|
||||
assert.equal(material.amount,198002);assert.deepEqual(material.calculation,{rate:90001,quantity:2200});
|
||||
const labor=owner.items.find(item=>item.component==='labor');assert.equal(labor.amount,4400);assert.deepEqual(labor.calculation,{rate:2000,quantity:2200});
|
||||
for(const item of [...owner.items,...helper.items]){assert.equal(item.order_id,id);assert.equal(item.date,D);assert.equal(item.paper_number,f.ledger.detail(id).paper_number);assert.equal(item.status,'recorded');}
|
||||
assert.equal(r.profit,f.ledger.detail(id).profit);assert.equal(r.profit,r.sales-owner.total-helper.total);
|
||||
});
|
||||
|
||||
test('实际费用的商品关联仅在原项目唯一匹配时保留,未知来源按整单费用展示',t=>{
|
||||
const f=fixture(t),charge=randomUUID(),id=f.save({lines:[line({charges:[{id:charge,name:'特殊包装',amount:'10'}]})],
|
||||
fee_items:[{key:'charge:'+charge,note:'特殊包装',amount:'3',payer:'assistant'},{key:'box',note:'包装',amount:'0',payer:'owner'}]},true);
|
||||
f.action(id,'expense',{date:D2,amount:'2',payer:'owner',note:'额外实付'});
|
||||
const r=sameBook(f),item=r.payerCosts.assistant.items.find(item=>item.kind==='paid');
|
||||
assert.equal(item.source,`商品 1 · 合成商品 · 实付 ${D}`);assert.equal(item.paidDate,D);assert.equal(item.date,D);
|
||||
const extra=r.payerCosts.owner.items.find(item=>item.name==='额外实付');assert.equal(extra.source,`整单费用 · 实付 ${D2}`);assert.equal(extra.paidDate,D2);assert.equal(extra.date,D);
|
||||
const zero=r.payerCosts.owner.items.find(item=>item.name==='包装');assert.equal(zero.kind,'zero');assert.equal(zero.amount,0);assert.equal(zero.status,'recorded');
|
||||
assert.equal(r.expense,500);assert.equal(r.payerCosts.owner.paidFees,200);
|
||||
});
|
||||
|
||||
test('旧单未分项货品总成本仍归原付款人,分币不变,不伪造分项',t=>{
|
||||
const f=fixture(t);f.save({lines:[line({unit:'件',quantity:'1',costParts:undefined,cost:'12.34',sale:'50',payer:'assistant'})],
|
||||
fee_items:[{key:'box',note:'包装',amount:'0.01',payer:'owner'}]},true);
|
||||
const r=sameBook(f),item=r.payerCosts.assistant.items[0];
|
||||
assert.equal(item.component,'unallocated');assert.equal(item.amount,1234);assert.equal(item.calculation,null);
|
||||
assert.equal(r.payerCosts.assistant.goods,1234);assert.equal(r.payerCosts.owner.total,1);assert.equal(r.totalCost,1235);assert.equal(r.profit,3765);
|
||||
assert.equal(r.summary.legacyUnallocatedCount,1);assert.equal(r.orderRows[0].material,null);assert.equal(r.summary.partial,true);
|
||||
});
|
||||
|
||||
test('缺项保留null,草稿和预估费用不算实际支出,按付款人显示待补与未入账数量',t=>{
|
||||
const f=fixture(t),old=f.save({lines:[line({costParts:{material:'',labor:'0',accessories:'5',other:'0'}})],
|
||||
fee_items:[{key:'shipping',note:'待核快递',amount:'6',payer:'assistant',status:'estimated'},{key:'box',note:'待补包装',amount:'',payer:'owner',status:'estimated'}]});
|
||||
f.action(old,'confirm');f.action(old,'expense',{amount:'24',payer:'assistant',note:'实际证书费'});
|
||||
const draft=f.save({customer:'草稿不算支出',lines:[line({payer:'assistant',sale:'9999'})],fee_items:[{key:'shipping',amount:'30',payer:'assistant',status:'estimated'}]});
|
||||
const r=sameBook(f),owner=r.payerCosts.owner,helper=r.payerCosts.assistant;
|
||||
assert.equal(r.goods,500);assert.equal(r.expense,2400);assert.equal(r.totalCost,2900);assert.equal(r.profit,0);assert.equal(r.sales,120000);
|
||||
assert.equal(owner.total,500);assert.equal(owner.missingCount,1);assert.equal(owner.pendingCount,1);assert.equal(helper.total,2400);assert.equal(helper.missingCount,0);assert.equal(helper.pendingCount,1);
|
||||
assert.equal(owner.items.find(item=>item.component==='material').amount,null);assert.equal(owner.items.find(item=>item.component==='material').status,'missing');
|
||||
assert.equal(helper.items.find(item=>item.kind==='pending').amount,600);assert.equal(helper.items.find(item=>item.kind==='pending').status,'pending');
|
||||
assert.ok([...owner.items,...helper.items].every(item=>item.order_id!==draft));
|
||||
assert.equal(r.summary.unknownCosts,3);assert.equal(r.summary.unknownProfitCount,1);assert.equal(r.orderRows.find(row=>row.id===old).totalCost,null);
|
||||
});
|
||||
|
||||
test('跨天及跨月尾款和费用归开单日,日月空日合计一致,旧流水日期接口保持原状',t=>{
|
||||
const f=fixture(t),id=f.save({lines:[line({sale:'100',costParts:{material:'50',labor:'0',accessories:'0',other:'0'}})]});
|
||||
f.action(id,'confirm');f.action(id,'receipt',{amount:'40',account:'助理微信',verified:true});
|
||||
f.action(id,'receipt',{date:D2,amount:'60',account:'麦麦支付宝',verified:true});
|
||||
f.action(id,'expense',{date:D2,amount:'8',payer:'assistant',note:'跨月快递'});f.action(id,'deliver',{date:D2,verified:true});
|
||||
f.action(id,'expense',{date:D3,amount:'2',payer:'owner',note:'跨月包装'});
|
||||
const cash=f.save({date:D2,customer:'次日开单',payment_account:'助理现金',lines:[line({sale:'30',costParts:{material:'10',labor:'0',accessories:'0',other:'0'}})]},true);
|
||||
const r=sameBook(f);assert.equal(r.sales,10000);assert.equal(r.profit,4000);assert.equal(r.expense,1000);assert.equal(r.receiptsByOrderDate.receipt,10000);
|
||||
assert.equal(r.payments.length,2);assert.ok(r.payments.every(payment=>payment.order_id===id&&payment.order_date===D));
|
||||
assert.ok(r.payerCosts.owner.items.some(item=>item.paidDate===D3));
|
||||
const next=sameBook(f,D2);assert.deepEqual(next.orderRows.map(row=>row.id),[cash]);assert.equal(next.receiptsByOrderDate.receipt,3000);assert.equal(next.expense,0);
|
||||
const september=sameBook(f,D,'2026-09-01');assert.equal(september.sales,r.sales);assert.equal(september.receiptsByOrderDate.receipt,10000);assert.equal(september.expense,1000);
|
||||
const october=sameBook(f,D3,D2);assert.equal(october.sales,3000);assert.equal(october.receiptsByOrderDate.receipt,3000);assert.equal(october.expense,0);
|
||||
const combined=sameBook(f,D3,D);for(const key of ['sales','goods','expense','profit'])assert.equal(combined[key],r[key]+next[key]);
|
||||
const empty=sameBook(f,D3);assert.equal(empty.sales,0);assert.equal(empty.expense,0);assert.equal(empty.profit,0);assert.deepEqual(empty.orderRows,[]);assert.equal(empty.receiptsByOrderDate.receipt,0);
|
||||
assert.equal(f.ledger.report(D).sales,0);assert.equal(f.ledger.report(D).accounts.find(item=>item.account==='助理微信').receipt,4000);
|
||||
assert.equal(f.ledger.report(D2).sales,13000);assert.equal(f.ledger.report(D3).expense,200);
|
||||
});
|
||||
|
||||
test('退货取消归原开单日冲回货品及销售,实际费用保留,客户退款不再扣一次利润',t=>{
|
||||
const f=fixture(t),returned=f.save({fee_items:[{key:'shipping',note:'已付运费',amount:'8',payer:'assistant'}]},true);
|
||||
f.action(returned,'return',{date:D2,reason:'合成退货',verified:true});f.action(returned,'refund',{date:D2,amount:'1200',account:'助理微信',verified:true});
|
||||
const cancelled=f.save({lines:[line({payer:'assistant'})]});f.action(cancelled,'confirm');f.action(cancelled,'expense',{amount:'2',payer:'owner',note:'已付打样'});
|
||||
f.action(cancelled,'receipt',{amount:'100',account:'麦麦现金',verified:true});f.action(cancelled,'cancel',{date:D2,reason:'合成取消'});f.action(cancelled,'refund',{date:D2,amount:'100',account:'麦麦现金',verified:true});
|
||||
const r=sameBook(f);assert.equal(r.sales,0);assert.equal(r.goods,0);assert.equal(r.expense,1000);assert.equal(r.profit,-1000);
|
||||
assert.equal(r.payerCosts.owner.total,200);assert.equal(r.payerCosts.assistant.total,800);assert.ok(Object.values(r.payerCosts).every(payer=>payer.items.every(item=>item.kind!=='goods')));
|
||||
assert.equal(r.receiptsByOrderDate.receipt,130000);assert.equal(r.receiptsByOrderDate.refund,130000);assert.equal(r.receiptsByOrderDate.net,0);
|
||||
assert.equal(sameBook(f,D2).profit,0);assert.equal(sameBook(f,D2).receiptsByOrderDate.refund,0);
|
||||
assert.equal(r.returns,1);assert.equal(r.summary.cancelledCount,1);
|
||||
});
|
||||
|
||||
test('跨日连续更正费用及付款人只计最新有效项,撤销后原项与冲回项不重复',t=>{
|
||||
const f=fixture(t),id=f.save({fee_items:[{key:'shipping',note:'快递',amount:'6',payer:'assistant'}]},true);
|
||||
let target=f.ledger.detail(id).expenses[0].id;
|
||||
for(const [amount,payer,ownerFees,assistantFees] of [['8','owner',800,0],['5','assistant',0,500],['0','assistant',0,0]]){
|
||||
f.action(id,'correct',{date:D2,type:'expense',target,amount,payer,reason:'合成更正',verified:true});
|
||||
const r=sameBook(f);assert.equal(r.payerCosts.owner.paidFees,ownerFees);assert.equal(r.payerCosts.assistant.paidFees,assistantFees);
|
||||
assert.equal(r.profit,120000-100000-ownerFees-assistantFees);assert.equal(r.profit,f.ledger.detail(id).profit);
|
||||
assert.equal(Object.values(r.payerCosts).flatMap(p=>p.items).filter(item=>item.kind==='paid').length,amount==='0'?0:1);
|
||||
if(amount!=='0')target=f.ledger.detail(id).expenses.find(item=>item.amount===Number(amount)*100).id;
|
||||
}
|
||||
assert.equal(sameBook(f,D2).expense,0);assert.equal(f.ledger.detail(id).expenses.length,6);
|
||||
});
|
||||
|
||||
test('读取对账和快照状态不改订单、审计、同步、操作号或快照,日期验证保持一致',t=>{
|
||||
const f=fixture(t);f.save({},true);f.close();
|
||||
const before=databaseContents(f.ledger),changes=f.ledger.one('SELECT total_changes() AS count').count;
|
||||
const first=f.report();assert.deepEqual(f.report(),first);sameBook(f);f.report(D,'2026-09-01');f.report(D2);
|
||||
for(const [date,from] of [['2026-02-30',undefined],['2099-01-01',undefined],[D,D2],['',undefined]])assert.throws(()=>f.ledger.reportByOrderDate(date,from));
|
||||
assert.equal(f.ledger.one('SELECT total_changes() AS count').count,changes);assert.equal(databaseContents(f.ledger),before);
|
||||
});
|
||||
|
||||
test('开单日快照遇跨日尾款、交付、补费及收款更正会过期,重存同日覆盖并保留库存快照',t=>{
|
||||
const f=fixture(t),id=f.save({lines:[line({sale:'100',costParts:{material:'50',labor:'0',accessories:'0',other:'0'}})]});
|
||||
f.action(id,'confirm');f.action(id,'receipt',{amount:'40',account:'助理微信',verified:true});
|
||||
const first=f.close();assert.equal(first.basis,'orderDate');assert.equal(f.report().close.stale,false);assert.equal(first.reportRevision,f.report().reportRevision);
|
||||
const deposit=f.ledger.detail(id).payments[0].id;
|
||||
f.action(id,'receipt',{date:D2,amount:'60',account:'助理现金',verified:true});assert.equal(f.ledger.one('SELECT stale FROM closes WHERE date=?',D).stale,0);assert.equal(f.report().close.stale,true);
|
||||
f.close();assert.equal(f.report().close.stale,false);
|
||||
f.action(id,'deliver',{date:D2,verified:true});assert.equal(f.report().close.stale,true);f.close();
|
||||
f.action(id,'expense',{date:D3,amount:'8',payer:'assistant',note:'售后快递'});assert.equal(f.report().close.stale,true);f.close();
|
||||
f.action(id,'correct',{date:D3,type:'payment',target:deposit,amount:'40',account:'助理支付宝',reason:'账户更正',verified:true});
|
||||
const corrected=f.report();assert.equal(corrected.close.stale,true);assert.match(corrected.close.staleReason,/开单日/);
|
||||
assert.equal(corrected.accounts.find(row=>row.account==='助理微信').receipt,0);assert.equal(corrected.accounts.find(row=>row.account==='助理支付宝').receipt,4000);
|
||||
f.close();assert.equal(f.report().close.stale,false);
|
||||
assert.equal(f.ledger.rows('SELECT * FROM closes').length,1);assert.equal(f.ledger.inventorySnapshots().snapshots.length,1);assert.deepEqual(first.snapshot.inventory,f.ledger.inventorySnapshot(D).inventory);
|
||||
assert.equal(f.report(D,'2026-09-01').close,null,'单日快照不能冒充整月快照');
|
||||
});
|
||||
|
||||
test('纯复核、打印、库存及其他开单日数据和交款变化不使本日财务快照过期',t=>{
|
||||
const f=fixture(t),id=f.save({},true);f.close();const revision=f.report().reportRevision;
|
||||
f.action(id,'review',{revision:f.ledger.detail(id).revision});f.action(id,'print');
|
||||
f.run({stock:true},()=>f.ledger.stock({kind:'opening',date:D,pocket:'现货',grams:'5',note:'合成独立库存'},actor));
|
||||
f.run({inventory:true},()=>f.ledger.saveInventorySnapshot(D,actor));
|
||||
f.save({date:D2},true);f.action(id,'settlement',{date:D2,amount:'1000',bucket:'cost',direction:'toOwner',note:'实际交款',verified:true});
|
||||
assert.equal(f.ledger.report(D).close.stale,true,'保留旧流水口径的原过期规则');
|
||||
assert.equal(f.report().reportRevision,revision);assert.equal(f.report().close.stale,false);assert.equal(f.report().close.staleReason,null);
|
||||
});
|
||||
|
||||
test('旧口径快照在新对账中明确待重核,读取不迁移,保存新口径后恢复有效',t=>{
|
||||
const f=fixture(t);f.save({},true);f.run({close:true},()=>f.ledger.closeDay(D,actor));
|
||||
const before=databaseContents(f.ledger),r=f.report();assert.equal(r.close.stale,true);assert.equal(r.close.basis,'entryDate');assert.match(r.close.staleReason,/口径已更新/);assert.equal(databaseContents(f.ledger),before);
|
||||
f.close();assert.equal(f.report().close.basis,'orderDate');assert.equal(f.report().close.stale,false);
|
||||
assert.throws(()=>f.ledger.closeDay(D,assistant,'orderDate'),/麦麦账号/);assert.throws(()=>f.ledger.closeDay(D,actor,'wrong'),/口径无效/);
|
||||
});
|
||||
|
||||
test('HTTP新对账要求登录,助理可读,旧接口兼容,快照保留owner权限、CSRF及幂等',async t=>{
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'maimai-daily-report-test-'));
|
||||
const app=createApp({mode:'demo',port:0,dataDir:dir,ledger:new Ledger(':memory:'),feishuConfig:{enabled:false}});
|
||||
await new Promise(resolve=>app.server.listen(0,'127.0.0.1',resolve));
|
||||
t.after(async()=>{await new Promise(resolve=>app.server.close(resolve));app.ledger.close();fs.rmSync(dir,{recursive:true,force:true});});
|
||||
const base='http://127.0.0.1:'+app.server.address().port;let cookie='';
|
||||
const call=(route,data,key=randomUUID(),origin=base)=>fetch(base+route,{method:data?'POST':'GET',headers:{...(cookie?{Cookie:cookie}:{}),...(data?{'Content-Type':'application/json',Origin:origin,'X-Requested-With':'maimai-ledger','Idempotency-Key':key}:{} )},...(data?{body:JSON.stringify(data)}:{})});
|
||||
assert.equal((await call('/api/report?basis=orderDate')).status,401);
|
||||
const login=await call('/api/demo-login',{role:'assistant'});cookie=login.headers.get('set-cookie').split(';')[0];
|
||||
const before=databaseContents(app.ledger),changes=app.ledger.one('SELECT total_changes() AS count').count;
|
||||
const response=await call('/api/report?basis=orderDate'),r=await response.json();assert.equal(response.status,200);assert.equal(r.basis,'orderDate');assert.equal(r.summary.orderCount,1);assert.equal(r.sales,120000);
|
||||
assert.equal(r.payerCosts.owner.goods,100000);assert.equal(r.payerCosts.owner.items[0].component,'unallocated');assert.equal(r.profit,20000);
|
||||
const legacy=await (await call('/api/report')).json();assert.ok(!('basis' in legacy));assert.equal(legacy.sales,r.sales);
|
||||
for(const route of ['/api/report?basis=wrong','/api/report?basis=orderDate&date=2099-01-01','/api/report?basis=orderDate&date=2026-02-30','/api/report?basis=orderDate&from='+D2+'&date='+D])assert.equal((await call(route)).status,400);
|
||||
assert.equal(app.ledger.one('SELECT total_changes() AS count').count,changes);assert.equal(databaseContents(app.ledger),before);
|
||||
assert.equal((await call('/api/close',{date:today(),basis:'orderDate'})).status,403);assert.equal(app.ledger.rows('SELECT * FROM closes').length,0);
|
||||
const ownerLogin=await call('/api/demo-login',{role:'owner'});cookie=ownerLogin.headers.get('set-cookie').split(';')[0];
|
||||
assert.equal((await call('/api/close',{date:today(),basis:'orderDate'},randomUUID(),'https://invalid.example')).status,403);
|
||||
assert.equal((await call('/api/close',{date:today(),basis:'wrong'})).status,400);
|
||||
const payload={date:today(),basis:'orderDate'},key=randomUUID(),closed=await call('/api/close',payload,key);assert.equal(closed.status,200);const first=await closed.json();
|
||||
const retry=await call('/api/close',payload,key);assert.equal(retry.status,200);assert.deepEqual(await retry.json(),first);
|
||||
assert.equal(app.ledger.rows('SELECT * FROM closes').length,1);assert.equal(app.ledger.rows('SELECT * FROM inventory_snapshots').length,1);assert.equal(app.ledger.rows('SELECT * FROM operations WHERE id=?',key).length,1);
|
||||
const saved=await (await call('/api/report?basis=orderDate')).json();assert.equal(saved.close.stale,false);assert.equal(saved.close.basis,'orderDate');
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),{randomUUID}=require('node:crypto');
|
||||
const Estimates=require('../public/fee-estimates'),Calc=require('../public/calculations'),{Ledger}=require('../ledger');
|
||||
const actor={id:'fee-test',name:'测试麦麦',role:'owner'},date='2026-10-17';
|
||||
const charge=(name,amount='10')=>({id:randomUUID(),name,amount});
|
||||
const product=charges=>({name:'足金999',unit:'g',quantity:'2',pocket:'',payer:'owner',cost:'1000',pricingMode:'manual',baseSale:'1200',charges});
|
||||
function fixture(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'maimai-fees-'));const l=new Ledger(path.join(dir,'ledger.sqlite'));t.after(()=>{l.close();fs.rmSync(dir,{recursive:true,force:true});});const run=(data,fn,key=randomUUID())=>l.transact(key,actor,data,fn);const save=input=>run(input,()=>l.saveOrder({date,discount:'0',...input},actor)).id;const act=(id,action,input={})=>run({id,action,input},()=>l.action(id,action,{date,...input},actor));return {l,run,save,act};}
|
||||
test('选入附加项目自动带入成本:证书4、包装3、快递整单6;未知不猜数',()=>{
|
||||
const charges=[charge('附加费'),charge('编绳'),charge('证书'),charge('包装'),charge('物料','')];
|
||||
const rows=Estimates.sync([],[product(charges)],{addShipping:true});assert.deepEqual(rows.map(r=>[r.note,r.amount]),[['快递费','6'],['附加费',''],['编绳',''],['证书','4'],['包装','3'],['物料','']]);assert.ok(rows.every(r=>r.status==='estimated'));
|
||||
assert.deepEqual(rows.map(r=>r.payer),['assistant','assistant','assistant','assistant','owner','assistant']);assert.equal(Estimates.sync([],[product([charge('包装盒')])])[0].payer,'owner');
|
||||
const priced=Calc.sale(product(charges));assert.equal(priced.sale,124000);assert.equal(priced.charges.length,5);assert.equal(priced.charges[4].amount,null);
|
||||
});
|
||||
test('修改默认金额、清空或填0后都不覆盖;切换未修改的项目才更新默认',()=>{
|
||||
const c=charge('证书');let rows=Estimates.sync([],[product([c])]);rows[0]={...rows[0],amount:'4.5',edited:true,payer:'owner'};
|
||||
for(const payer of ['owner','assistant'])for(const amount of ['4.5','','0']){rows[0]={...rows[0],amount,payer};const next=Estimates.sync(rows,[product([{...c,name:'包装'}])]);assert.equal(next[0].amount,amount);assert.equal(next[0].payer,payer);}
|
||||
for(const name of ['编绳','证书']){const untouched=Estimates.sync([],[product([{...c,name}])]),packaging=Estimates.sync(untouched,[product([{...c,name:'包装'}])]);assert.equal(packaging[0].amount,'3');assert.equal(packaging[0].payer,'owner');assert.equal(Estimates.sync(packaging,[product([{...c,name:'证书'}])])[0].payer,'assistant');}
|
||||
});
|
||||
test('删除或调整商品顺序不会串成本,重复项目逐项对应,快递不重复',()=>{
|
||||
const a=charge('证书'),b=charge('证书'),shipping=charge('快递');let rows=Estimates.sync([],[product([a]),product([b,shipping])],{addShipping:true});assert.equal(rows.length,3);rows[1]={...rows[1],amount:'5',edited:true};rows[2]={...rows[2],amount:'7',edited:true};
|
||||
rows=Estimates.sync(rows,[product([b,shipping]),product([a])]);assert.deepEqual(rows.map(r=>r.amount),['6','7','5']);rows=Estimates.sync(rows,[product([b])]);assert.deepEqual(rows.map(r=>r.amount),['6','7']);
|
||||
assert.equal(Estimates.sync([],[product([])]).length,0);
|
||||
});
|
||||
test('旧版已填成本按名称接入,不重复生成也不覆盖原金额',()=>{
|
||||
const rows=Estimates.sync([{key:'certificate',note:'证书',amount:'5.5',payer:'owner'}],[product([charge('证书')])]);assert.equal(rows.length,1);assert.equal(rows[0].amount,'5.5');assert.equal(rows[0].payer,'owner');
|
||||
const c=charge('包装盒'),old={key:'charge:'+c.id,note:'包装',sourceName:'包装',amount:'3',payer:'assistant',edited:false};for(const previous of [old,{...old,key:'box',sourceName:undefined}]){const next=Estimates.sync([previous],[product([c])]);assert.equal(next.length,1);assert.equal(next[0].payer,'assistant');}
|
||||
});
|
||||
test('预估保存与确认订单不造支出;交付前核实真实费用,防重并准确算利润',t=>{
|
||||
const {l,save,act,run}=fixture(t),charges=[charge('证书'),charge('包装')],lines=[product(charges)],fees=Estimates.sync([],lines,{addShipping:true});const id=save({lines,fee_items:fees});assert.equal(l.detail(id).draftFees,1300);assert.equal(l.detail(id).estimatedProfit,20700);
|
||||
save({id,revision:l.detail(id).revision,lines,fee_items:fees});assert.equal(l.detail(id).fee_items.length,3);act(id,'confirm');assert.equal(l.detail(id).expenses.length,0);assert.equal(l.detail(id).pendingFees.length,3);assert.equal(l.report(date).expense,0);assert.ok(l.report(date).warnings.some(w=>w.message==='附加成本待核实'));
|
||||
act(id,'receipt',{amount:'1220',account:'助理微信',verified:true});assert.throws(()=>act(id,'deliver',{verified:true}),/附加成本/);
|
||||
const payload={date,revision:l.detail(id).revision,verified:true,fee_items:fees.map(f=>({...f,amount:f.note==='证书'?'4.5':f.note==='包装'?'0':'6'}))},key=randomUUID();
|
||||
run(payload,()=>l.action(id,'fees',payload,actor),key);run(payload,()=>l.action(id,'fees',payload,actor),key);assert.equal(l.detail(id).expenses.length,2);assert.equal(l.detail(id).directCost,1050);assert.equal(l.detail(id).pendingFees.length,0);assert.equal(l.detail(id).draftFees,0);assert.throws(()=>act(id,'fees',payload),/没有待核实/);
|
||||
act(id,'deliver',{verified:true});assert.equal(l.detail(id).profit,20950);assert.equal(l.report(date).expense,1050);
|
||||
const publicJson=JSON.stringify(l.publicOrder(id));for(const privateKey of ['pendingFees','fee_items','sourceName','estimated','payer','4.5'])assert.ok(!publicJson.includes(privateKey));
|
||||
});
|
||||
test('未知预估成本留空,不能当作0确认;补齐和旧版本检查可阻止漏记',t=>{
|
||||
const {l,save,act}=fixture(t),lines=[product([charge('编绳')])],fees=Estimates.sync([],lines);const id=save({lines,fee_items:fees});assert.equal(l.detail(id).estimatedProfit,null);assert.equal(l.detail(id).fee_items[0].amount,null);
|
||||
assert.throws(()=>act(id,'confirm',{feesVerified:true}),/补齐/);act(id,'confirm');
|
||||
const revision=l.detail(id).revision;assert.throws(()=>act(id,'fees',{revision,verified:true,fee_items:fees}),/补齐/);assert.throws(()=>act(id,'fees',{revision:revision-1,verified:true,fee_items:[{...fees[0],amount:'0'}]}),/更新/);assert.throws(()=>act(id,'fees',{revision,verified:true,fee_items:[]}),/逐项/);
|
||||
act(id,'fees',{revision,verified:true,fee_items:[{...fees[0],amount:'0'}]});assert.equal(l.detail(id).expenses.length,0);assert.equal(l.detail(id).pendingFees.length,0);
|
||||
});
|
||||
test('确认时勾选已付款只记一次;未付预估取消时不扣利润',t=>{
|
||||
const {l,save,act}=fixture(t),lines=[product([charge('证书')])],fee_items=Estimates.sync([],lines,{addShipping:true});const id=save({lines,fee_items});act(id,'confirm',{feesVerified:true});assert.equal(l.detail(id).directCost,1000);assert.equal(l.detail(id).pendingFees.length,0);assert.throws(()=>act(id,'confirm',{feesVerified:true}),/已经确认/);
|
||||
const cancelled=save({lines,fee_items});act(cancelled,'confirm');act(cancelled,'cancel',{reason:'取消预订'});assert.equal(l.detail(cancelled).profit,0);assert.equal(l.detail(cancelled).expenses.length,0);assert.equal(l.detail(cancelled).pendingFees.length,0);
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict'),crypto=require('node:crypto'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
|
||||
const {createApp}=require('../server');
|
||||
test('HTTP权限、登录、CSRF、并发重试、客户页面和备份访问',async t=>{
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'maimai-http-test-'));const app=createApp({mode:'demo',port:0,dataDir:dir});await new Promise(r=>app.server.listen(0,'127.0.0.1',r));
|
||||
t.after(async()=>{await new Promise(r=>app.server.close(r));app.ledger.close();fs.rmSync(dir,{recursive:true,force:true});});
|
||||
const base='http://127.0.0.1:'+app.server.address().port;
|
||||
let cookie='';const call=async(route,data,key=crypto.randomUUID(),extra={})=>{const r=await fetch(base+route,{method:data?'POST':'GET',headers:{...(cookie?{Cookie:cookie}:{}),...(data?{'Content-Type':'application/json',Origin:base,'X-Requested-With':'maimai-ledger','Idempotency-Key':key}:{}),...extra},...(data?{body:JSON.stringify(data)}:{})});return r;};
|
||||
assert.equal((await call('/api/state')).status,401);assert.equal((await call('/api/demo-login',{role:'owner'},undefined,{Origin:'https://evil.example'})).status,403);
|
||||
const login=await call('/api/demo-login',{role:'owner'});cookie=login.headers.get('set-cookie').split(';')[0];assert.match(login.headers.get('set-cookie'),/HttpOnly/);
|
||||
const s=await (await call('/api/state')).json();assert.equal(s.orders[0].status,'delivered');
|
||||
const payload={date:s.today,payment_account:'助理微信',lines:[{name:'HTTP测试商品',unit:'g',quantity:'1.2',pocket:'现货',payer:'owner',cost:'1000',sale:'1200'}],fee_items:[]};
|
||||
const key=crypto.randomUUID();const results=await Promise.all([call('/api/orders/issue',payload,key),call('/api/orders/issue',payload,key)]);assert.deepEqual(results.map(r=>r.status),[200,200]);
|
||||
const a=await results[0].json(),b=await results[1].json(),id=a.id;assert.equal(a.id,b.id);
|
||||
const detail=await (await call('/api/orders/'+id)).json();assert.equal(detail.received,120000);assert.equal(detail.payments.length,1);assert.equal(detail.status,'delivered');assert.equal(detail.profit,20000);
|
||||
const printable=await (await call('/api/orders/'+id+'/public')).json();assert.ok(!('profit' in printable));assert.ok(!('cost' in printable.lines[0]));
|
||||
const html=await (await call('/print/'+id)).text();assert.ok(html.includes('纸单号'));assert.ok(!html.includes('系统单号'));assert.ok(!html.includes('1000.00'));
|
||||
assert.equal((await call('/api/orders/'+id+'/receipt',{date:s.today,amount:'1',account:'助理微信',verified:true})).status,400);
|
||||
const backup=await (await call('/api/backup',{})).json();assert.equal((await call('/api/backup/'+backup.name)).status,200);
|
||||
const login2=await call('/api/demo-login',{role:'assistant'});cookie=login2.headers.get('set-cookie').split(';')[0];assert.equal((await call('/api/backup',{})).status,403);assert.equal((await call('/api/printing',{store:'不允许'})).status,403);assert.equal((await call('/api/backup/'+backup.name)).status,403);
|
||||
await call('/api/logout',{});assert.equal((await call('/api/orders/'+id)).status,401);
|
||||
});
|
||||
test('初始化及密码均哈希保存,非本机演示启动被阻止',async t=>{
|
||||
assert.throws(()=>createApp({mode:'demo',host:'0.0.0.0'}),/只能绑定本机/);
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'maimai-auth-test-'));const app=createApp({mode:'trial',port:0,dataDir:dir});await new Promise(r=>app.server.listen(0,'127.0.0.1',r));
|
||||
t.after(async()=>{await new Promise(r=>app.server.close(r));app.ledger.close();fs.rmSync(dir,{recursive:true,force:true});});const base='http://127.0.0.1:'+app.server.address().port;
|
||||
const call=(p,b)=>fetch(base+p,{method:'POST',headers:{'Content-Type':'application/json','X-Requested-With':'maimai-ledger',Origin:base},body:JSON.stringify(b)});
|
||||
const passwords={ownerPassword:'synthetic-owner-123',assistantPassword:'synthetic-helper-123'};assert.equal((await call('/api/setup',passwords)).status,200);assert.equal((await call('/api/setup',passwords)).status,403);assert.equal((await call('/api/login',{name:'麦麦',password:passwords.ownerPassword})).status,200);assert.equal((await call('/api/login',{name:'麦麦',password:'bad'})).status,401);assert.ok(!JSON.stringify(app.ledger.rows('SELECT * FROM users')).includes(passwords.ownerPassword));
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
'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:'<script>alert(1)</script>',note:'<img onerror=evil()>',lines:[{name:'足金<script>',unit:'g',quantity:'1',pocket:'现货',payer:'owner',cost:'987.65',sale:'1200'}]});const p=l.publicOrder(id),serialized=JSON.stringify(p);for(const key of ['cost','payer','profit','audit','settlement','pocket'])assert.ok(!serialized.includes('"'+key+'"'));const html=receipt(p);assert.ok(!html.includes('987.65'));assert.ok(!html.includes('<img onerror'));assert.ok(html.includes('<img'));assert.ok(html.includes('草稿'));});
|
||||
test('多行单据全部保留在一张纸,仅显示纸单号与一次合计',t=>{const {l,save}=fixture(t);const id=save({lines:Array.from({length:17},(_,i)=>({name:'外配'+i,unit:'件',quantity:'1',pocket:'',payer:'assistant',cost:'1',sale:'2'}))});const html=receipt(l.publicOrder(id));assert.equal((html.match(/<section class="sheet /g)||[]).length,1);assert.equal((html.match(/合计金额/g)||[]).length,1);assert.equal((html.match(/纸单号:/g)||[]).length,1);assert.ok(html.includes('外配16'));assert.ok(!html.includes('系统单号'));assert.ok(receipt(l.publicOrder(id),{},'overlay').includes('sheet overlay'));});
|
||||
test('助理不可开账、调整、复核;有新动作复核重新待办',t=>{const {l,stock,save,act,fulfill}=fixture(t);assert.throws(()=>stock({},assistant),/麦麦账号/);stock();const id=save();fulfill(id);assert.throws(()=>act(id,'review',{revision:l.detail(id).revision},assistant),/麦麦账号/);act(id,'review',{revision:l.detail(id).revision});assert.equal(l.detail(id).reviewed_revision,l.detail(id).revision);act(id,'expense',{amount:'1',payer:'assistant',note:'售后'});assert.notEqual(l.detail(id).reviewed_revision,l.detail(id).revision);});
|
||||
test('旧快照遇补录会过期,不把原记录标成已封账',t=>{const {l,stock,save,act,fulfill,run}=fixture(t);stock();const id=save();fulfill(id);run({},()=>l.closeDay(D,actor));assert.equal(l.report(D).close.stale,false);act(id,'expense',{amount:'1',payer:'assistant',note:'售后'});assert.equal(l.report(D).close.stale,true);});
|
||||
test('数据库重新打开、备份恢复后账单及操作号完整',async t=>{const {l,dir,stock,save,fulfill}=fixture(t);stock();const id=save();fulfill(id);const before=l.detail(id),dest=path.join(dir,'backup.sqlite');await l.backupTo(dest);const copy=new Ledger(dest);assert.equal(copy.detail(id).profit,before.profit);assert.equal(copy.inventory()[0].mg,8800);assert.ok(copy.rows('SELECT * FROM operations').length>=4);copy.close();l.close();const reopened=new Ledger(path.join(dir,'ledger.sqlite'));assert.equal(reopened.detail(id).number,before.number);reopened.close();});
|
||||
test('麦麦直接收款从总待结金额扣除,不重复要求助理上交',t=>{const {l,stock,save,act}=fixture(t);stock();const id=save();act(id,'confirm');act(id,'receipt',{amount:'1200',account:'麦麦微信',verified:true});act(id,'deliver',{verified:true});assert.equal(l.detail(id).settlementDue,0);assert.ok(l.report(D).warnings.some(w=>w.message.includes('直接收客户款')));});
|
||||
test('外配退回供应商不造库存,选择留店才入对应货盘',t=>{const {l,save,act}=fixture(t);const id=save({lines:[{name:'外配',unit:'g',quantity:'1.200',pocket:'',payer:'assistant',cost:'1000',sale:'1200'}]});act(id,'confirm');act(id,'receipt',{amount:'1200',account:'助理微信',verified:true});act(id,'deliver',{verified:true});act(id,'return',{reason:'退回后留店',verified:true,returnPockets:['现货']});assert.equal(l.inventory()[0].mg,1200);});
|
||||
|
||||
test('更正费用保留原流水,利润只修正差额,不能再次冲回同一条',t=>{const {l,stock,save,act,fulfill}=fixture(t);stock();const id=save();fulfill(id);act(id,'expense',{amount:'80',payer:'assistant',note:'误记邮费'});const original=l.detail(id).expenses[0];act(id,'correct',{type:'expense',target:original.id,amount:'8',payer:'assistant',reason:'少一个0',verified:true,date:D2});assert.equal(l.detail(id).profit,19200);assert.equal(l.report(D2).profit,7200);assert.equal(l.detail(id).expenses.length,3);assert.throws(()=>act(id,'correct',{type:'expense',target:original.id,amount:'8',payer:'assistant',reason:'重复',verified:true,date:D2}),/已冲回/);});
|
||||
test('已交付收款账户可更正,不能借更正制造未收齐交货',t=>{const {l,stock,save,act,fulfill}=fixture(t);stock();const id=save();fulfill(id);const original=l.detail(id).payments[0];assert.throws(()=>act(id,'correct',{type:'payment',target:original.id,amount:'1000',account:'助理支付宝',reason:'误记',verified:true,date:D2}),/保持收齐/);assert.equal(l.detail(id).payments.length,1);act(id,'correct',{type:'payment',target:original.id,amount:'1200',account:'助理支付宝',reason:'更正账户',verified:true,date:D2});assert.equal(l.detail(id).received,120000);assert.equal(l.detail(id).profit,20000);assert.equal(l.detail(id).payments.length,3);assert.equal(l.report(D2).accounts.find(a=>a.account==='助理微信').receipt,-120000);});
|
||||
test('交款更正不影响利润,月汇总按业务日期相加',t=>{const {l,stock,save,act,fulfill}=fixture(t);stock();const id=save();fulfill(id);act(id,'settlement',{amount:'1000',bucket:'cost',direction:'toOwner',note:'误记交款',verified:true});const original=l.detail(id).settlements[0];act(id,'correct',{type:'settlement',target:original.id,amount:'500',bucket:'cost',direction:'toOwner',reason:'实际只交500',verified:true,date:D2});assert.equal(l.detail(id).costTransferred,50000);assert.equal(l.detail(id).profit,20000);assert.equal(l.report(D2,D).sales,120000);assert.equal(l.report(D2,D).profit,20000);});
|
||||
test('恢复工具先归档当前账,保留备份并使会话失效',async t=>{const {restore}=require('../restore');const {l,dir,stock,save,act,fulfill}=fixture(t);stock();const id=save();fulfill(id);const dest=path.join(dir,'backup.sqlite');await l.backupTo(dest);act(id,'expense',{amount:'8',payer:'assistant',note:'备份后新增'});l.close();const result=restore(dest,dir);assert.ok(fs.existsSync(path.join(result.archive,'ledger.sqlite')));const restored=new Ledger(path.join(dir,'ledger.sqlite'));assert.equal(restored.detail(id).profit,20000);restored.close();});
|
||||
|
||||
|
||||
test('麦麦直收订单退货:原账户退款和返助理不能重复计算',t=>{const {l,stock,save,act}=fixture(t);stock();const id=save();act(id,'confirm');act(id,'receipt',{amount:'700',account:'麦麦微信',verified:true});act(id,'receipt',{amount:'500',account:'助理微信',verified:true});act(id,'deliver',{verified:true});act(id,'settlement',{amount:'500',bucket:'cost',direction:'toOwner',note:'助理收到的部分已交',verified:true});assert.equal(l.detail(id).settlementDue,0);act(id,'return',{reason:'全部退回',verified:true,date:D2});assert.equal(l.detail(id).settlementDue,-50000);act(id,'refund',{amount:'700',account:'麦麦微信',verified:true,date:D2});act(id,'refund',{amount:'500',account:'助理微信',verified:true,date:D2});assert.equal(l.detail(id).settlementDue,-50000);act(id,'settlement',{amount:'500',bucket:'cost',direction:'toAssistant',note:'只返助理原交款',verified:true,date:D2});assert.equal(l.detail(id).settlementDue,0);assert.equal(l.detail(id).profit,0);});
|
||||
@@ -0,0 +1,104 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),{randomUUID}=require('node:crypto');
|
||||
const Calc=require('../public/calculations'),{Ledger}=require('../ledger'),{receipt}=require('../printing'),{createApp}=require('../server');
|
||||
const actor={id:'material-test',name:'测试麦麦',role:'owner'},date='2026-10-16',nextDate='2026-10-17';
|
||||
const parts=(extra={})=>({material:'9999',labor:'0',accessories:'0',other:'0',...extra});
|
||||
const line=(extra={})=>({name:'足金999',unit:'g',quantity:'2',pocket:'',payer:'owner',pricingMode:'manual',baseSale:'2200',costParts:parts(),costMaterial:{mode:'gram',rate:'900'},costLabor:{mode:'total'},...extra});
|
||||
const yuan=value=>value==null?'':(value/100).toFixed(2);
|
||||
function editLine(saved){
|
||||
return {...saved,quantity:saved.unit==='g'?(saved.quantity/1000).toFixed(3):String(saved.quantity),baseSale:yuan(saved.baseSale),
|
||||
costParts:Object.fromEntries(Object.entries(saved.costParts).map(([key,value])=>[key,yuan(value)])),
|
||||
costMaterial:saved.costMaterial?.mode==='gram'?{mode:'gram',rate:yuan(saved.costMaterial.rate)}:saved.costMaterial,
|
||||
costLabor:saved.costLabor?.mode==='gram'?{mode:'gram',rate:yuan(saved.costLabor.rate)}:saved.costLabor};
|
||||
}
|
||||
function fixture(t){
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'maimai-material-cost-')),filename=path.join(dir,'ledger.sqlite'),l=new Ledger(filename);
|
||||
t.after(()=>{l.close();fs.rmSync(dir,{recursive:true,force:true});});
|
||||
const run=(payload,fn)=>l.transact(randomUUID(),actor,payload,fn);
|
||||
const order=(extra={},issue=false)=>{const input={date,discount:'0',lines:[line()],fee_items:[],...extra};return run(input,()=>issue?l.issueOrder(input,actor):l.saveOrder(input,actor)).id;};
|
||||
const act=(id,action,extra={})=>{const input={date,...extra};return run({id,action,input},()=>l.action(id,action,input,actor));};
|
||||
return {l,dir,filename,run,order,act};
|
||||
}
|
||||
test('每克料价按克重计算料费总成本,2克×900元为1800元,2.2克×940元为2068元',()=>{
|
||||
const a=Calc.purchaseCosts(line());assert.equal(a.parts.material,180000);assert.equal(a.total,180000);assert.deepEqual(a.costMaterial,{mode:'gram',rate:90000});
|
||||
const b=Calc.purchaseCosts(line({quantity:'2.2',costMaterial:{mode:'gram',rate:'940'}}));assert.equal(b.parts.material,206800);assert.equal(b.total,206800);
|
||||
assert.equal(Calc.purchaseCosts(line({quantity:'3'})).parts.material,270000);
|
||||
const combined=Calc.purchaseCosts(line({quantity:'2.2',costMaterial:{mode:'gram',rate:'940'},costLabor:{mode:'gram',rate:'20'}}));
|
||||
assert.equal(combined.parts.material,206800);assert.equal(combined.parts.labor,4400);assert.equal(combined.total,211200);
|
||||
const total=Calc.purchaseCosts(line({quantity:'3',costMaterial:{mode:'total',rate:'900'},costParts:parts({material:'1800',labor:'7'}),costLabor:{mode:'gram',rate:'20'}}));
|
||||
assert.equal(total.parts.material,180000);assert.equal(total.parts.labor,6000);assert.deepEqual(total.costMaterial,{mode:'total'});
|
||||
});
|
||||
test('料价与工费分别精确取整到分,空白不当作0,已计算总额不受客户端总额影响',()=>{
|
||||
assert.equal(Calc.purchaseCosts(line({quantity:'0.001',costMaterial:{mode:'gram',rate:'5'}})).parts.material,1);
|
||||
assert.equal(Calc.purchaseCosts(line({quantity:'0.001',costMaterial:{mode:'gram',rate:'4'}})).parts.material,0);
|
||||
const both=Calc.purchaseCosts(line({quantity:'0.001',costMaterial:{mode:'gram',rate:'5'},costLabor:{mode:'gram',rate:'5'}}));assert.equal(both.total,2);
|
||||
assert.equal(Calc.purchaseCosts(line({quantity:'123.456',costMaterial:{mode:'gram',rate:'789.01'}})).parts.material,9740802);
|
||||
assert.equal(Calc.purchaseCosts(line({quantity:'99999.999',costMaterial:{mode:'gram',rate:'9999.99'}})).parts.material,99999899000);
|
||||
for(const rate of ['',null,undefined]){const result=Calc.purchaseCosts(line({costMaterial:{mode:'gram',rate}}));assert.equal(result.parts.material,null);assert.equal(result.total,null);assert.equal(result.costMaterial.rate,null);}
|
||||
const zero=Calc.purchaseCosts(line({costMaterial:{mode:'gram',rate:'0'},costParts:parts({material:'-9'})}));assert.equal(zero.parts.material,0);assert.equal(zero.total,0);
|
||||
});
|
||||
test('每克料价拒绝按件、非法克重、负数、多余精度及超限总额;按件只接受总额',()=>{
|
||||
for(const extra of [{unit:'件'},{quantity:'0'},{quantity:'-2'},{quantity:'2.0001'},
|
||||
{costMaterial:{mode:'gram',rate:'-1'}},{costMaterial:{mode:'gram',rate:'940.001'}},
|
||||
{costMaterial:{mode:'gram',rate:'abc'}},{costMaterial:{mode:'bad'}},
|
||||
{quantity:'100000',costMaterial:{mode:'gram',rate:'100000'}}])assert.throws(()=>Calc.purchaseCosts(line(extra)));
|
||||
for(const rate of ['',null,'0'])assert.throws(()=>Calc.purchaseCosts(line({unit:'件',costMaterial:{mode:'gram',rate}})),/按件/);
|
||||
const total=Calc.purchaseCosts(line({unit:'件',quantity:'2',costMaterial:{mode:'total'},costParts:parts({material:'1800'})}));assert.equal(total.parts.material,180000);
|
||||
assert.throws(()=>Calc.purchaseCosts(line({costMaterial:{mode:'total'},costParts:parts({material:'-1'})})),/非负/);
|
||||
});
|
||||
test('保存、读回和重复编辑只算一次,改变克重才更新料费总额',t=>{
|
||||
const {l,filename,order}=fixture(t),id=order();
|
||||
assert.equal(l.detail(id).goodsCost,180000);assert.equal(l.detail(id).lines[0].costParts.material,180000);assert.deepEqual(l.detail(id).lines[0].costMaterial,{mode:'gram',rate:90000});
|
||||
for(let i=0;i<2;i++){const saved=l.detail(id);order({id,revision:saved.revision,lines:[editLine(saved.lines[0])]});assert.equal(l.detail(id).goodsCost,180000);}
|
||||
const saved=l.detail(id);order({id,revision:saved.revision,lines:[{...editLine(saved.lines[0]),quantity:'2.2'}]});assert.equal(l.detail(id).goodsCost,198000);
|
||||
const stored=l.one('SELECT lines FROM orders WHERE id=?',id).lines,reloaded=new Ledger(filename);
|
||||
try{assert.equal(reloaded.detail(id).goodsCost,198000);assert.equal(reloaded.one('SELECT lines FROM orders WHERE id=?',id).lines,stored);}finally{reloaded.close();}
|
||||
});
|
||||
test('旧草稿、旧按件接口和旧版未分项订单保留既有总额,读取与库存登记不改历史成本',t=>{
|
||||
const {l,order,run}=fixture(t),id=order({lines:[line({costMaterial:undefined,costParts:parts({material:'1800'})})]});
|
||||
const stored=l.rawOrder(id).lines;delete stored[0].costMaterial;l.run('UPDATE orders SET lines=? WHERE id=?',JSON.stringify(stored),id);
|
||||
const original=l.one('SELECT lines FROM orders WHERE id=?',id).lines;
|
||||
assert.equal(l.detail(id).goodsCost,180000);assert.equal(Calc.orderCosts(l.detail(id)).rows.find(row=>row.name==='料费成本').calculation,null);
|
||||
run({},()=>l.stock({kind:'increase',date,pocket:'现货',grams:'3.000',note:'合成库存调整'},actor));assert.equal(l.one('SELECT lines FROM orders WHERE id=?',id).lines,original);
|
||||
const saved=l.detail(id);order({id,revision:saved.revision,lines:[editLine(saved.lines[0])]});assert.equal(l.detail(id).goodsCost,180000);assert.deepEqual(l.detail(id).lines[0].costMaterial,{mode:'total'});
|
||||
const piece=order({lines:[line({unit:'件',quantity:'2',costMaterial:undefined,costParts:parts({material:'1800'})})]});assert.equal(l.detail(piece).goodsCost,180000);
|
||||
const legacy=order({lines:[line({costParts:undefined,costMaterial:undefined,cost:'1800'})]});assert.equal(l.detail(legacy).goodsCost,180000);assert.ok(!('costMaterial' in l.detail(legacy).lines[0]));
|
||||
});
|
||||
test('交付前补录支持每克料价并由服务端重算,旧版总额接口仍可用,缺失与非法输入完整回滚',t=>{
|
||||
const {l,order,act}=fixture(t),id=order({lines:[line({costMaterial:{mode:'gram',rate:''}})]});act(id,'confirm');assert.equal(l.detail(id).goodsCost,null);
|
||||
act(id,'cost',{costs:[{parts:parts({material:'1',labor:'9999'}),costMaterial:{mode:'gram',rate:'900'},costLabor:{mode:'gram',rate:'20'}}]});
|
||||
let saved=l.detail(id);assert.equal(saved.goodsCost,184000);assert.equal(saved.lines[0].costParts.material,180000);assert.equal(saved.lines[0].costParts.labor,4000);
|
||||
for(const rate of ['', '-1', '900.001']){const before=l.one('SELECT lines,revision FROM orders WHERE id=?',id);assert.throws(()=>act(id,'cost',{costs:[{parts:parts(),costMaterial:{mode:'gram',rate}}]}));assert.deepEqual(l.one('SELECT lines,revision FROM orders WHERE id=?',id),before);}
|
||||
act(id,'cost',{costs:[{material:'1810',labor:'10',accessories:'0',other:'0'}]});saved=l.detail(id);assert.equal(saved.goodsCost,182000);assert.deepEqual(saved.lines[0].costMaterial,{mode:'total'});
|
||||
act(id,'cost',{costs:[{parts:parts(),costMaterial:{mode:'gram',rate:'900'},costLabor:{mode:'total'}}]});assert.equal(l.detail(id).goodsCost,180000);
|
||||
});
|
||||
test('料费成本明细包含每克计算依据,利润、结算及订单簿使用一次计算后的总额',t=>{
|
||||
const {l,order}=fixture(t),id=order({lines:[line({quantity:'2.2',baseSale:'2300',costMaterial:{mode:'gram',rate:'940'},costLabor:{mode:'gram',rate:'20'}})]},true),o=l.detail(id);
|
||||
assert.equal(o.goodsCost,211200);assert.equal(o.profit,18800);assert.equal(o.ownerCost,211200);assert.equal(o.costDue,211200);assert.equal(o.settlementDue,230000);
|
||||
const costs=Calc.orderCosts(o),material=costs.rows.find(row=>row.name==='料费成本');assert.equal(material.amount,206800);assert.deepEqual(material.calculation,{rate:94000,quantity:2200});assert.equal(costs.total.total,211200);
|
||||
const book=l.orderBook({date}),row=book.rows.find(row=>row.id===id);assert.equal(row.material,206800);assert.equal(row.laborAndFees,4400);assert.equal(row.totalCost,211200);assert.equal(row.profit,18800);assert.deepEqual(row.costItems.find(item=>item.component==='material').calculation,{rate:94000,quantity:2200});
|
||||
const before=l.one('SELECT lines FROM orders WHERE id=?',id).lines;Calc.orderCosts(l.detail(id));l.publicOrder(id);l.orderBook({date});assert.equal(l.one('SELECT lines FROM orders WHERE id=?',id).lines,before);
|
||||
});
|
||||
test('交付成本锁定,后续库存采购不重估原单,跨日退货与返款按原成本冲回',t=>{
|
||||
const {l,order,act,run}=fixture(t),id=order({},true),before=l.one('SELECT lines FROM orders WHERE id=?',id).lines;
|
||||
assert.throws(()=>act(id,'cost',{costs:[{parts:parts(),costMaterial:{mode:'gram',rate:'1'}}]}),/锁定/);
|
||||
run({},()=>l.stock({kind:'purchase',date:nextDate,pocket:'现货',grams:'2',cost:'4000',note:'后续采购高价料'},actor));assert.equal(l.detail(id).goodsCost,180000);assert.equal(l.one('SELECT lines FROM orders WHERE id=?',id).lines,before);
|
||||
act(id,'settlement',{bucket:'cost',amount:'1800',direction:'toOwner',note:'合成货款交款',verified:true});act(id,'settlement',{bucket:'profit',amount:'400',direction:'toOwner',note:'合成利润交款',verified:true});assert.equal(l.detail(id).settlementDue,0);
|
||||
act(id,'return',{date:nextDate,reason:'合成退货',verified:true});let returned=l.detail(id);assert.equal(returned.goodsCost,180000);assert.equal(returned.profit,0);assert.equal(returned.costDue,-180000);assert.equal(returned.profitDue,-40000);assert.equal(l.report(nextDate).profit,-40000);assert.equal(l.one('SELECT lines FROM orders WHERE id=?',id).lines,before);
|
||||
act(id,'refund',{date:nextDate,amount:'2200',account:'助理微信',verified:true});
|
||||
act(id,'settlement',{date:nextDate,bucket:'cost',amount:'1800',direction:'toAssistant',note:'返还原成本',verified:true});act(id,'settlement',{date:nextDate,bucket:'profit',amount:'400',direction:'toAssistant',note:'返还原利润',verified:true});returned=l.detail(id);assert.equal(returned.netReceived,0);assert.equal(returned.settlementDue,0);assert.equal(l.orderBook({from:date,date:nextDate}).rows.find(row=>row.id===id).material,0);
|
||||
});
|
||||
test('HTTP内部字段保存每克料价,客户公开接口与打印页隔离成本元数据和金额',async t=>{
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'maimai-material-http-')),app=createApp({mode:'demo',dataDir:dir,feishuConfig:{enabled:false}});
|
||||
await new Promise(resolve=>app.server.listen(0,'127.0.0.1',resolve));
|
||||
t.after(async()=>{await new Promise(resolve=>app.server.close(resolve));app.ledger.close();fs.rmSync(dir,{recursive:true,force:true});});
|
||||
const base='http://127.0.0.1:'+app.server.address().port;let cookie='';
|
||||
const call=(route,data)=>fetch(base+route,{method:data?'POST':'GET',headers:{Cookie:cookie,...(data?{'Content-Type':'application/json',Origin:base,'X-Requested-With':'maimai-ledger','Idempotency-Key':randomUUID()}:{})},...(data?{body:JSON.stringify(data)}:{})});
|
||||
const login=await call('/api/demo-login',{role:'assistant'});assert.equal(login.status,200);cookie=login.headers.get('set-cookie').split(';')[0];
|
||||
const result=await call('/api/orders/issue',{date,lines:[line({costMaterial:{mode:'gram',rate:'913.27'}})]});assert.equal(result.status,200);const {id}=await result.json();
|
||||
const internal=await (await call('/api/orders/'+id)).json();assert.equal(internal.lines[0].costParts.material,182654);assert.deepEqual(internal.lines[0].costMaterial,{mode:'gram',rate:91327});assert.equal(internal.profit,37346);
|
||||
const publicResponse=await call('/api/orders/'+id+'/public');assert.equal(publicResponse.status,200);const customer=await publicResponse.json(),json=JSON.stringify(customer);
|
||||
for(const key of ['costMaterial','costParts','costLabor','payer','profit','costDue'])assert.ok(!json.includes('"'+key+'"'));
|
||||
const printResponse=await call('/print/'+id);assert.equal(printResponse.status,200);const html=await printResponse.text();assert.equal(html,receipt(customer));
|
||||
for(const secret of ['costMaterial','料费成本','进货料价','913.27','1826.54','373.46'])assert.ok(!html.includes(secret));
|
||||
});
|
||||
@@ -0,0 +1,213 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict');
|
||||
const {randomUUID}=require('node:crypto'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
|
||||
const {Ledger,today}=require('../ledger'),{createApp}=require('../server');
|
||||
const actor={id:'book-owner',name:'测试麦麦',role:'owner'};
|
||||
const D='2026-09-30',D2='2026-10-01';
|
||||
const line=(extra={})=>({name:'合成商品',unit:'g',quantity:'1.200',pocket:'',payer:'owner',sale:'1200',costParts:{material:'980',labor:'20',accessories:'0',other:'0'},...extra});
|
||||
function fixture(t){
|
||||
const ledger=new Ledger(':memory:');t.after(()=>ledger.close());
|
||||
const run=(payload,fn,key=randomUUID())=>ledger.transact(key,actor,payload,fn);
|
||||
const save=(extra={},issue=false)=>{
|
||||
const input={date:D,customer:'合成客户',note:'仅用于测试',payment_account:'助理微信',lines:[line()],fee_items:[],...extra};
|
||||
return run(input,()=>issue?ledger.issueOrder(input,actor):ledger.saveOrder(input,actor)).id;
|
||||
};
|
||||
const action=(id,kind,extra={},key=randomUUID())=>{
|
||||
const input={date:D,...extra};return run({id,kind,input},()=>ledger.action(id,kind,input,actor),key);
|
||||
};
|
||||
const book=(query={})=>ledger.orderBook({date:D,...query});
|
||||
return {ledger,save,action,book,run};
|
||||
}
|
||||
function channel(receipts,key){return receipts.channels.find(row=>row.channel===key);}
|
||||
|
||||
test('订单簿与已记账成本、付款人和利润一致,克与件分开,附加成本组成可核对',t=>{
|
||||
const f=fixture(t);
|
||||
const id=f.save({lines:[line({quantity:'2.200',sale:'2300',costParts:{material:'1980',labor:'0',accessories:'5',other:'0'},costLabor:{mode:'gram',rate:'20'}}),
|
||||
line({name:'纯银925',unit:'件',quantity:'2',payer:'assistant',sale:'200',costParts:{material:'80',labor:'10',accessories:'0',other:'0'}})],
|
||||
fee_items:[{key:'shipping',note:'快递费',amount:'6',payer:'assistant'},{key:'certificate',note:'证书',amount:'4',payer:'owner'}]},true);
|
||||
const b=f.book(),r=b.rows[0];
|
||||
assert.equal(r.id,id);assert.deepEqual(r.types,['配货','配货 · 银饰']);assert.equal(r.mg,2200);assert.equal(r.summaryMg,2200);assert.equal(r.pieces,2);
|
||||
assert.equal(r.sale,250000);assert.equal(r.material,206000);assert.equal(r.laborAndFees,6900);assert.equal(r.unallocated,0);
|
||||
assert.equal(r.totalCost,212900);assert.equal(r.ownerCost,203300);assert.equal(r.assistantCost,9600);assert.equal(r.profit,37100);
|
||||
assert.equal(r.profit,f.ledger.detail(id).profit);assert.equal(r.laborAndFeeItems.find(row=>row.component==='labor').amount,4400);
|
||||
assert.equal(r.laborAndFeeItems.reduce((s,row)=>s+row.amount,0),r.laborAndFees);
|
||||
assert.equal(r.material+r.laborAndFees+r.unallocated,r.totalCost);assert.equal(b.summary.sale-b.summary.totalCost,b.summary.profit);
|
||||
assert.equal(b.summary.completedCount,1);assert.equal(b.summary.partial,false);assert.equal(b.summary.mg,2200);assert.equal(b.summary.pieces,2);
|
||||
});
|
||||
|
||||
test('旧单只保存总成本时保留未分项,不伪拆料费和工费,分币仍精确',t=>{
|
||||
const {save,book}=fixture(t);
|
||||
save({lines:[line({unit:'件',quantity:'1',costParts:undefined,cost:'12.34',sale:'50'})],fee_items:[{key:'box',note:'包装',amount:'0.01',payer:'assistant'}]},true);
|
||||
const b=book(),r=b.rows[0];assert.equal(r.material,null);assert.equal(r.laborAndFees,null);
|
||||
assert.equal(r.known.material,0);assert.equal(r.known.laborAndFees,1);assert.equal(r.unallocated,1234);assert.equal(r.totalCost,1235);assert.equal(r.profit,3765);
|
||||
assert.equal(r.costItems.find(row=>row.component==='unallocated').amount,1234);assert.equal(r.laborAndFeeItems.length,1);
|
||||
assert.equal(b.summary.unallocated,1234);assert.equal(b.summary.laborAndFees,1);assert.equal(b.summary.legacyUnallocatedCount,1);
|
||||
assert.equal(b.summary.unknownCostCount,0);assert.equal(b.summary.unknownCounts.material,1);assert.equal(b.summary.incompleteCount,0);assert.equal(b.summary.partial,true);
|
||||
});
|
||||
|
||||
test('缺项旧单只累计已知实际成本,草稿与预估费用不冒充实际销售、成本或利润',t=>{
|
||||
const {save,action,book}=fixture(t);
|
||||
const old=save({lines:[line({costParts:{material:'',labor:'0',accessories:'5',other:'0'}})],
|
||||
fee_items:[{key:'shipping',note:'待核快递',amount:'6',payer:'assistant',status:'estimated'},{key:'box',note:'待补包装',amount:'',payer:'owner',status:'estimated'}]});
|
||||
action(old,'confirm');action(old,'expense',{amount:'24',payer:'assistant',note:'实际付出的证书费'});
|
||||
const draft=save({customer:'草稿客户',lines:[line({sale:'9999'})]});
|
||||
const b=book(),r=b.rows.find(row=>row.id===old),d=b.rows.find(row=>row.id===draft);
|
||||
assert.equal(r.material,null);assert.equal(r.laborAndFees,null);assert.equal(r.totalCost,null);assert.equal(r.ownerCost,null);assert.equal(r.assistantCost,null);assert.equal(r.profit,null);
|
||||
assert.equal(r.known.totalCost,2900);assert.equal(r.known.ownerCost,500);assert.equal(r.known.assistantCost,2400);
|
||||
assert.equal(r.missingCosts,1);assert.equal(r.pendingCosts,2);assert.equal(r.unknownCosts,3);assert.equal(r.pendingCostItems.length,2);
|
||||
assert.equal(r.costItems.filter(row=>row.kind==='paid').length,1);assert.ok(r.costItems.every(row=>row.kind!=='pending'));
|
||||
for(const key of ['sale','material','laborAndFees','unallocated','totalCost','ownerCost','assistantCost','profit'])assert.equal(d[key],null,key);
|
||||
assert.equal(d.originalSale,999900);assert.equal(d.costItems.length,0);
|
||||
assert.equal(b.summary.orderCount,2);assert.equal(b.summary.draftCount,1);assert.equal(b.summary.incompleteCount,1);
|
||||
assert.equal(b.summary.sale,120000);assert.equal(b.summary.totalCost,2900);assert.equal(b.summary.ownerCost,500);assert.equal(b.summary.assistantCost,2400);
|
||||
assert.equal(b.summary.profit,0);assert.equal(b.summary.unknownProfitCount,1);assert.equal(b.summary.unknownCostCount,1);assert.equal(b.summary.partial,true);
|
||||
});
|
||||
|
||||
test('待交付旧单即使录全成本也不产生已完成利润;已退和取消货品净额为0、实际费用保留',t=>{
|
||||
const f=fixture(t);const confirmed=f.save({customer:'成本已齐旧单'});f.action(confirmed,'confirm');
|
||||
let r=f.book().rows[0];assert.equal(r.totalCost,100000);assert.equal(r.profit,null);assert.equal(r.incomplete,true);
|
||||
const returned=f.save({customer:'退货客户',fee_items:[{key:'shipping',note:'已付运费',amount:'8',payer:'assistant'}]},true);
|
||||
f.action(returned,'return',{date:D2,reason:'合成退货',verified:true});f.action(returned,'refund',{date:D2,amount:'1200',account:'助理微信',verified:true});
|
||||
const cancelled=f.save({customer:'取消客户'});f.action(cancelled,'confirm');f.action(cancelled,'expense',{amount:'2',payer:'owner',note:'已付打样'});
|
||||
f.action(cancelled,'receipt',{amount:'100',account:'麦麦现金',verified:true});f.action(cancelled,'cancel',{date:D2,reason:'合成取消'});
|
||||
f.action(cancelled,'refund',{date:D2,amount:'100',account:'麦麦现金',verified:true});
|
||||
const b=f.book();r=b.rows.find(row=>row.id===returned);assert.equal(r.sale,0);assert.equal(r.originalSale,120000);assert.equal(r.material,0);assert.equal(r.laborAndFees,800);assert.equal(r.totalCost,800);assert.equal(r.profit,-800);
|
||||
assert.equal(r.ownerCost,0);assert.equal(r.assistantCost,800);assert.ok(r.costItems.every(item=>item.component==='fee'));
|
||||
r=b.rows.find(row=>row.id===cancelled);assert.equal(r.sale,0);assert.equal(r.totalCost,200);assert.equal(r.profit,-200);assert.equal(r.ownerCost,200);
|
||||
assert.equal(b.receiptsByPaymentDate.receipt,130000);assert.equal(b.receiptsByPaymentDate.refund,0);
|
||||
assert.equal(b.receiptsByOrderDate.receipt,130000);assert.equal(b.receiptsByOrderDate.refund,130000);assert.equal(b.receiptsByOrderDate.net,0);
|
||||
assert.equal(f.book({date:D2}).rows.length,0);assert.equal(f.book({date:D2}).receiptsByPaymentDate.refund,130000);
|
||||
});
|
||||
|
||||
test('取消单保留原明细,订单页数量克重件数收退款成本利润汇总全排除,日报仍保留真实账务',t=>{
|
||||
const f=fixture(t),id=f.save({customer:'取消客户',lines:[line({quantity:'2.345',sale:'900',costParts:{material:'700',labor:'0',accessories:'0',other:'0'}}),
|
||||
line({unit:'件',quantity:'3',sale:'200',payer:'assistant',costParts:{material:'80',labor:'20',accessories:'0',other:'0'}})]});
|
||||
f.action(id,'confirm');f.action(id,'receipt',{amount:'300',account:'助理微信',verified:true});f.action(id,'expense',{amount:'8',payer:'assistant',note:'取消前实际快递'});
|
||||
f.action(id,'cancel',{date:D2,reason:'合成取消'});f.action(id,'refund',{date:D2,amount:'100',account:'助理微信',verified:true});
|
||||
f.run({people:true},()=>f.ledger.savePeopleCount({date:D,count:9,revision:0},actor));
|
||||
const detail=f.ledger.detail(id),daily=f.ledger.reportByOrderDate(D),legacy=f.ledger.report(D2);
|
||||
const snapshot=()=>JSON.stringify(f.ledger.rows("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").map(({name})=>[name,f.ledger.rows('SELECT * FROM "'+name+'"')]));
|
||||
const before=snapshot(),changes=f.ledger.one('SELECT total_changes() AS count').count;
|
||||
for(const query of [{},{status:'cancelled'},{q:'取消客户'},{from:D,date:D2},{from:'2026-09-01',date:D}]){
|
||||
const b=f.book(query),s=b.summaryWithoutCancelled,r=b.receiptsWithoutCancelled;
|
||||
assert.deepEqual(b.rows.map(row=>row.id),[id]);assert.equal(b.rows[0].status,'cancelled');assert.equal(b.rows[0].mg,2345);assert.equal(b.rows[0].pieces,3);assert.equal(b.rows[0].totalCost,800);assert.equal(b.rows[0].profit,-800);
|
||||
for(const key of ['orderCount','recordCount','cancelledCount','mg','pieces','sale','material','laborAndFees','unallocated','totalCost','profit','ownerCost','assistantCost'])assert.equal(s[key],0,key);
|
||||
assert.equal(s.partial,false);assert.equal(r.basis,'orderDate');assert.equal(r.filterScope,'matchingOrdersWithoutCancelled');assert.equal(r.receipt,0);assert.equal(r.refund,0);assert.equal(r.net,0);assert.equal(r.paymentCount,0);assert.ok(r.accounts.every(account=>account.receipt===0&&account.refund===0&&account.net===0));
|
||||
assert.equal(b.summary.orderCount,1);assert.equal(b.summary.mg,2345);assert.equal(b.summary.pieces,3);assert.equal(b.summary.totalCost,800);assert.equal(b.summary.profit,-800);
|
||||
assert.equal(b.receiptsByOrderDate.receipt,30000);assert.equal(b.receiptsByOrderDate.refund,10000);assert.equal(b.receiptsByOrderDate.net,20000);assert.equal(b.peopleCount.total,9);
|
||||
}
|
||||
assert.equal(daily.expense,800);assert.equal(daily.profit,-800);assert.equal(daily.accounts.find(account=>account.account==='助理微信').receipt,30000);assert.equal(daily.accounts.find(account=>account.account==='助理微信').refund,10000);
|
||||
assert.equal(legacy.expense,800);assert.equal(legacy.profit,-800);assert.deepEqual(f.ledger.reportByOrderDate(D),daily);assert.deepEqual(f.ledger.report(D2),legacy);assert.deepEqual(f.ledger.detail(id),detail);
|
||||
assert.equal(f.ledger.one('SELECT total_changes() AS count').count,changes);assert.equal(snapshot(),before);
|
||||
});
|
||||
|
||||
test('排除取消的汇总仍保留有效销售、独立售后及原退货口径,日月搜索状态共同生效',t=>{
|
||||
const f=fixture(t),valid=f.save({customer:'共同有效客户'},true);
|
||||
const returned=f.save({customer:'共同退货客户',payment_account:'助理支付宝',fee_items:[{key:'shipping',note:'已付运费',amount:'8',payer:'assistant'}]},true);
|
||||
f.action(returned,'return',{date:D2,reason:'合成退货',verified:true});f.action(returned,'refund',{date:D2,amount:'1200',account:'助理支付宝',verified:true});
|
||||
const cancelled=f.save({customer:'共同取消客户',lines:[line({quantity:'2.500'}),line({unit:'件',quantity:'2',sale:'20'})]});f.action(cancelled,'confirm');
|
||||
f.action(cancelled,'expense',{amount:'2',payer:'owner',note:'取消前实付'});f.action(cancelled,'receipt',{amount:'100',account:'麦麦微信',verified:true});f.action(cancelled,'cancel',{date:D2,reason:'合成取消'});f.action(cancelled,'refund',{date:D2,amount:'30',account:'麦麦微信',verified:true});
|
||||
const after=f.run({after:true},()=>f.ledger.saveAfterSale({date:D,project:'共同售后',customer:'售后客户',amount:'20',payer:'assistant'},actor));
|
||||
f.run({afterNext:true},()=>f.ledger.saveAfterSale({date:D2,project:'共同隔日售后',customer:'隔日客户',amount:'1',payer:'owner'},actor));
|
||||
for(const query of [{},{q:'共同'},{from:'2026-09-01',date:D}]){
|
||||
const b=f.book(query),s=b.summaryWithoutCancelled,r=b.receiptsWithoutCancelled;
|
||||
assert.equal(b.rows.length,4);assert.ok(b.rows.some(row=>row.id===cancelled));assert.ok(b.rows.some(row=>row.after_sale_id===after.after_sale_id));
|
||||
assert.equal(s.orderCount,2);assert.equal(s.completedCount,1);assert.equal(s.returnedCount,1);assert.equal(s.cancelledCount,0);assert.equal(s.afterSaleCount,1);assert.equal(s.recordCount,3);assert.equal(s.mg,2400);assert.equal(s.pieces,0);
|
||||
assert.equal(s.sale,120000);assert.equal(s.totalCost,102800);assert.equal(s.profit,17200);assert.equal(s.ownerCost,100000);assert.equal(s.assistantCost,2800);
|
||||
assert.equal(r.receipt,240000);assert.equal(r.refund,120000);assert.equal(r.net,120000);assert.equal(b.receiptsByOrderDate.receipt,250000);assert.equal(b.receiptsByOrderDate.refund,123000);
|
||||
assert.equal(b.summary.orderCount,3);assert.equal(b.summary.profit,17000);assert.equal(f.ledger.reportByOrderDate(D).profit,17000);
|
||||
}
|
||||
const onlyCancelled=f.book({q:'共同取消客户',status:'cancelled'});assert.deepEqual(onlyCancelled.rows.map(row=>row.id),[cancelled]);assert.equal(onlyCancelled.summaryWithoutCancelled.orderCount,0);assert.equal(onlyCancelled.receiptsWithoutCancelled.receipt,0);
|
||||
for(const [status,id] of [['delivered',valid],['returned',returned]]){
|
||||
const b=f.book({q:'共同',status});assert.deepEqual(b.rows.map(row=>row.id),[id]);assert.deepEqual(b.summaryWithoutCancelled,b.summary);assert.deepEqual(b.receiptsWithoutCancelled.accounts,b.receiptsByOrderDate.accounts);
|
||||
}
|
||||
const onlyAfter=f.book({status:'after_sale'});assert.equal(onlyAfter.summaryWithoutCancelled.afterSaleCount,1);assert.equal(onlyAfter.summaryWithoutCancelled.profit,-2000);
|
||||
const next=f.book({date:D2});assert.equal(next.summaryWithoutCancelled.afterSaleCount,1);assert.equal(next.summaryWithoutCancelled.profit,-100);assert.equal(next.receiptsWithoutCancelled.receipt,0);
|
||||
const month=f.book({from:D,date:D2,q:'共同'});assert.equal(month.summaryWithoutCancelled.afterSaleCount,2);assert.equal(month.summaryWithoutCancelled.profit,17100);
|
||||
});
|
||||
|
||||
test('费用连续更正、换付款人与撤销只计最新有效费用,不重复原行和冲回行',t=>{
|
||||
const f=fixture(t),id=f.save({fee_items:[{key:'shipping',note:'邮费',amount:'6',payer:'assistant'}]},true);
|
||||
let target=f.ledger.detail(id).expenses[0].id;
|
||||
for(const [amount,payer,expected] of [['8','owner',100800],['5','assistant',100500],['0','assistant',100000]]){
|
||||
f.action(id,'correct',{type:'expense',target,amount,payer,reason:'合成费用更正',verified:true,date:D2});
|
||||
const r=f.book().rows[0];assert.equal(r.totalCost,expected);assert.equal(r.profit,120000-expected);assert.equal(r.profit,f.ledger.detail(id).profit);
|
||||
assert.equal(r.costItems.filter(item=>item.component==='fee').length,amount==='0'?0:1);
|
||||
assert.equal(r.ownerCost+r.assistantCost,r.totalCost);
|
||||
if(amount!=='0')target=f.ledger.detail(id).expenses.find(item=>item.amount===Number(amount)*100).id;
|
||||
}
|
||||
});
|
||||
|
||||
test('跨年开单与跨天尾款分开,重试不重复收款,收款更正按实际日期带符号汇总、退款另列',t=>{
|
||||
const f=fixture(t),start='2025-12-31',end='2026-01-01',correction='2026-01-02',refund='2026-01-03';
|
||||
const id=f.save({date:start,lines:[line({sale:'100',costParts:{material:'8',labor:'2',accessories:'0',other:'0'}})]});
|
||||
f.action(id,'confirm',{date:start});
|
||||
const key=randomUUID(),deposit={date:start,amount:'40',account:'助理微信',verified:true};f.action(id,'receipt',deposit,key);f.action(id,'receipt',deposit,key);
|
||||
f.action(id,'receipt',{date:end,amount:'60',account:'麦麦支付宝',verified:true});f.action(id,'deliver',{date:end,verified:true});
|
||||
const cash=f.save({date:end,customer:'现金客户',payment_account:'助理现金',lines:[line({sale:'30',costParts:{material:'10',labor:'0',accessories:'0',other:'0'}})]},true);
|
||||
let b=f.book({date:end});assert.deepEqual(b.rows.map(row=>row.id),[cash]);assert.equal(b.receiptsByPaymentDate.receipt,9000);assert.equal(channel(b.receiptsByPaymentDate,'alipay').receipt,6000);assert.equal(channel(b.receiptsByPaymentDate,'cash').receipt,3000);
|
||||
b=f.book({date:start});assert.deepEqual(b.rows.map(row=>row.id),[id]);assert.equal(b.receiptsByPaymentDate.receipt,4000);assert.equal(b.receiptsByOrderDate.receipt,10000);
|
||||
f.action(id,'correct',{date:correction,type:'payment',target:f.ledger.detail(id).payments[0].id,amount:'40',account:'助理支付宝',reason:'实际为支付宝',verified:true});
|
||||
b=f.book({date:correction});assert.equal(b.rows.length,0);assert.equal(b.receiptsByPaymentDate.receipt,0);assert.equal(b.receiptsByPaymentDate.refund,0);
|
||||
assert.equal(channel(b.receiptsByPaymentDate,'wechat').receipt,-4000);assert.equal(channel(b.receiptsByPaymentDate,'alipay').receipt,4000);
|
||||
b=f.book({date:start});assert.equal(channel(b.receiptsByPaymentDate,'wechat').receipt,4000);assert.equal(channel(b.receiptsByOrderDate,'wechat').receipt,0);assert.equal(channel(b.receiptsByOrderDate,'alipay').receipt,10000);
|
||||
f.action(id,'return',{date:refund,reason:'合成跨月退货',verified:true});
|
||||
f.action(id,'refund',{date:refund,amount:'60',account:'麦麦支付宝',verified:true});f.action(id,'refund',{date:refund,amount:'40',account:'助理支付宝',verified:true});
|
||||
const originalRefund=f.ledger.detail(id).payments.find(payment=>payment.kind==='refund'&&payment.account==='助理支付宝');
|
||||
f.action(id,'correct',{date:refund,type:'payment',target:originalRefund.id,amount:'40',account:'助理支付宝',reason:'退款凭据确认',verified:true});
|
||||
b=f.book({date:refund});assert.equal(b.receiptsByPaymentDate.receipt,0);assert.equal(b.receiptsByPaymentDate.refund,10000);assert.equal(b.receiptsByPaymentDate.net,-10000);
|
||||
const month=f.book({from:'2026-01-01',date:'2026-01-31'});assert.deepEqual(month.rows.map(row=>row.id),[cash]);assert.equal(month.receiptsByPaymentDate.receipt,9000);assert.equal(month.receiptsByPaymentDate.refund,10000);assert.equal(month.receiptsByPaymentDate.net,-1000);
|
||||
});
|
||||
|
||||
test('日期、搜索与状态共同约束列表和汇总,空结果不误清除该日实际收款',t=>{
|
||||
const f=fixture(t);
|
||||
const id=f.save({customer:'林客户',note:'定制字样',lines:[line({name:'足金指定款',code:'ABc-01'})]},true);
|
||||
f.save({customer:'其他客户'});
|
||||
f.save({customer:'别的已完成客户',payment_account:'助理现金',lines:[line({sale:'50',costParts:{material:'20',labor:'0',accessories:'0',other:'0'}})]},true);
|
||||
f.action(id,'settlement',{amount:'1000',bucket:'cost',direction:'toOwner',note:'合成货款交款',verified:true});
|
||||
f.action(id,'settlement',{amount:'200',bucket:'profit',direction:'toOwner',note:'合成利润交款',verified:true});
|
||||
for(const q of ['林客户','定制字样','足金指定款','abc-01',f.ledger.detail(id).paper_number]){
|
||||
const b=f.book({q,status:'delivered'});assert.deepEqual(b.rows.map(row=>row.id),[id]);assert.equal(b.summary.orderCount,1);assert.equal(b.summary.sale,120000);assert.equal(b.summary.totalCost,100000);assert.equal(b.receiptsByOrderDate.receipt,120000);
|
||||
}
|
||||
const empty=f.book({q:'没有这个客户',status:'delivered'});assert.deepEqual(empty.rows,[]);assert.equal(empty.summary.orderCount,0);assert.equal(empty.summary.sale,0);assert.equal(empty.summary.totalCost,0);assert.equal(empty.summary.partial,false);
|
||||
assert.equal(empty.receiptsByPaymentDate.receipt,125000);assert.equal(empty.receiptsByOrderDate.receipt,0);
|
||||
assert.equal(f.book().receiptsByOrderDate.receipt,125000,'双方交款不属于客户收款');
|
||||
assert.equal(f.book({status:'draft'}).summary.draftCount,1);assert.equal(f.book({status:'draft'}).summary.sale,0);
|
||||
const defaults=f.ledger.orderBook();assert.equal(defaults.date,today());assert.equal(defaults.from,today());
|
||||
for(const query of [{date:'2026-02-30'},{date:'2026-2-03'},{date:'2025-02-29'},{date:'1999-12-31'},{date:'2099-01-01'},{date:''},{from:D2,date:D},{status:'made-up'},{q:'字'.repeat(101)}])assert.throws(()=>f.ledger.orderBook(query));
|
||||
assert.doesNotThrow(()=>f.book({date:'2024-02-29'}));assert.doesNotThrow(()=>f.book({from:'2025-12-31',date:'2026-01-01'}));
|
||||
});
|
||||
|
||||
test('货盘类型按实际货盘去重,旧分精度混合商品的毫克和件数分别加总',t=>{
|
||||
const f=fixture(t);
|
||||
for(const pocket of ['现货','金料'])f.run({pocket},()=>f.ledger.stock({kind:'opening',date:D,pocket,grams:'10',note:'合成库存'},actor));
|
||||
f.save({rounding_mode:'cent',lines:[line({quantity:'0.001',pocket:'现货',sale:'0.01',costParts:{material:'0',labor:'0',accessories:'0',other:'0'}}),line({quantity:'1.001',pocket:'现货'}),line({quantity:'2',pocket:'金料'}),line({unit:'件',quantity:'3',sale:'80'}),line({unit:'件',quantity:'2',sale:'20'})]},true);
|
||||
const b=f.book(),r=b.rows[0];assert.deepEqual(r.types,['货盘现货','货盘·金料','配货']);assert.equal(r.mg,3002);assert.equal(r.pieces,5);assert.equal(b.summary.mg,3002);assert.equal(b.summary.pieces,5);assert.equal(r.sale,250001);
|
||||
});
|
||||
|
||||
test('反复读取订单簿不改账本、操作号、审计、同步或纸单序号,客户投影不含内部聚合',t=>{
|
||||
const f=fixture(t),id=f.save({},true);
|
||||
const snapshot=()=>JSON.stringify(f.ledger.rows("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").map(({name})=>[name,f.ledger.rows('SELECT * FROM "'+name+'"')]));
|
||||
const before=snapshot(),changes=f.ledger.one('SELECT total_changes() AS count').count;
|
||||
const first=f.book();assert.deepEqual(f.book(),first);f.book({q:'合成'});f.book({from:'2026-09-01',date:D});
|
||||
assert.equal(f.ledger.one('SELECT total_changes() AS count').count,changes);assert.equal(snapshot(),before);
|
||||
const customer=JSON.stringify(f.ledger.publicOrder(id));for(const key of ['costItems','laborAndFeeItems','ownerCost','assistantCost','profit','payments','expenses','corrections','known'])assert.ok(!customer.includes('"'+key+'"'));
|
||||
});
|
||||
|
||||
test('订单簿 HTTP 只允许已登录读取,助理可用,未来日期拒绝,不改变流水且打印不泄漏',async t=>{
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'maimai-order-book-test-'));
|
||||
const app=createApp({mode:'demo',port:0,dataDir:dir,ledger:new Ledger(':memory:')});await new Promise(resolve=>app.server.listen(0,'127.0.0.1',resolve));
|
||||
t.after(async()=>{await new Promise(resolve=>app.server.close(resolve));app.ledger.close();fs.rmSync(dir,{recursive:true,force:true});});
|
||||
const base='http://127.0.0.1:'+app.server.address().port;let cookie='';
|
||||
const call=(route,data)=>fetch(base+route,{method:data?'POST':'GET',headers:{...(cookie?{Cookie:cookie}:{}),...(data?{'Content-Type':'application/json',Origin:base,'X-Requested-With':'maimai-ledger','Idempotency-Key':randomUUID()}:{} )},...(data?{body:JSON.stringify(data)}:{})});
|
||||
assert.equal((await call('/api/order-book')).status,401);assert.equal((await call('/api/order-book?date=2099-01-01')).status,401);
|
||||
const login=await call('/api/demo-login',{role:'assistant'});cookie=login.headers.get('set-cookie').split(';')[0];
|
||||
const changes=app.ledger.one('SELECT total_changes() AS count').count;
|
||||
const response=await call('/api/order-book'),b=await response.json();assert.equal(response.status,200);assert.equal(b.summary.completedCount,1);assert.equal(b.summary.totalCost,100000);assert.equal(b.summary.profit,20000);
|
||||
assert.deepEqual(b.summaryWithoutCancelled,b.summary);assert.equal(b.receiptsWithoutCancelled.filterScope,'matchingOrdersWithoutCancelled');assert.equal(b.receiptsWithoutCancelled.receipt,b.receiptsByOrderDate.receipt);
|
||||
assert.equal((await call('/api/order-book?date=2099-01-01')).status,400);assert.equal((await call('/api/order-book?date=2026-02-30')).status,400);
|
||||
assert.equal((await call('/api/order-book?status=all&q=%E6%BC%94%E7%A4%BA')).status,200);
|
||||
assert.equal((await call('/api/order-book',{})).status,404);assert.equal(app.ledger.one('SELECT total_changes() AS count').count,changes);
|
||||
const customer=await (await call('/api/orders/'+b.rows[0].id+'/public')).json();assert.ok(!('profit' in customer));assert.ok(!('costItems' in customer));
|
||||
const printed=await (await call('/print/'+b.rows[0].id)).text();assert.ok(!printed.includes('1000.00'));assert.ok(!printed.includes('laborAndFeeItems'));
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict'),{randomUUID}=require('node:crypto');
|
||||
const {Ledger}=require('../ledger'),Calc=require('../public/calculations'),{receipt}=require('../printing');
|
||||
const date='2026-10-17',actor={id:'cost-owner',name:'测试麦麦',role:'owner'};
|
||||
function input(){return {date,payment_account:'助理微信',lines:[
|
||||
{name:'足金999',unit:'g',quantity:'2.2',pocket:'',payer:'owner',sale:'2300',costParts:{material:'1980',labor:'0',accessories:'5',other:'0'},costLabor:{mode:'gram',rate:'20'},charges:[{name:'证书',amount:'10'}]},
|
||||
{name:'纯银925',unit:'件',quantity:'1',pocket:'',payer:'assistant',sale:'200',costParts:{material:'80',labor:'10',accessories:'0',other:'0'}}
|
||||
],fee_items:[{key:'shipping',note:'快递费',amount:'6',payer:'assistant',status:'estimated'},{key:'certificate',note:'证书',amount:'4',payer:'owner',status:'estimated'},{key:'box',note:'包装',amount:'3',payer:'owner',status:'estimated'}]};}
|
||||
function fixture(t,p=input(),legacy=false){
|
||||
const ledger=new Ledger(':memory:');t.after(()=>ledger.close());
|
||||
const run=(p,fn)=>ledger.transact(randomUUID(),actor,p,fn);
|
||||
const id=run(p,()=>legacy?ledger.saveOrder(p,actor):ledger.issueOrder(p,actor)).id;
|
||||
const action=(kind,p={})=>run({kind,p},()=>ledger.action(id,kind,{date,...p},actor));
|
||||
if(legacy)action('confirm');
|
||||
const detail=()=>ledger.detail(id),costs=()=>Calc.orderCosts(detail());
|
||||
return {ledger,id,action,detail,costs};
|
||||
}
|
||||
test('开单后按两名付款人汇总货品与实际费用,克工费只乘一次且不把客户收费当成本',t=>{
|
||||
const {ledger,id,detail,costs}=fixture(t),before=detail(),c=costs();
|
||||
assert.equal(before.total,251000);assert.equal(c.byPayer.owner.goods,202900);assert.equal(c.byPayer.assistant.goods,9000);
|
||||
assert.equal(c.byPayer.owner.paidFees,700);assert.equal(c.byPayer.assistant.paidFees,600);
|
||||
assert.equal(c.byPayer.owner.total,203600);assert.equal(c.byPayer.assistant.total,9600);assert.equal(c.total.total,213200);
|
||||
assert.equal(c.total.paidFees,1300);assert.equal(c.total.pendingFees,0);assert.equal(c.total.missing,0);assert.equal(before.profit,before.total-c.total.total);
|
||||
assert.equal(c.rows.filter(r=>r.name==='进货工费')[0].amount,4400);
|
||||
assert.deepEqual(detail(),before,'查看成本不应修改任何账务');
|
||||
const customer=ledger.publicOrder(id),html=receipt(customer);
|
||||
for(const key of ['payer','costParts','expenses','fee_items','orderCosts'])assert.ok(!JSON.stringify(customer).includes('"'+key+'"'));
|
||||
for(const text of ['成本明细与付款人','1980.00','2029.00','2132.00'])assert.ok(!html.includes(text));
|
||||
});
|
||||
test('开单同时完成费用与交付后只计一次,付款人与利润对得上',t=>{
|
||||
const {detail,costs,action}=fixture(t);
|
||||
let c=costs();assert.equal(c.pendingCount,0);assert.equal(c.total.pendingFees,0);assert.equal(c.total.paidFees,1300);assert.equal(c.total.total,213200);
|
||||
assert.equal(c.rows.filter(r=>r.name==='证书').length,1);assert.equal(c.rows.filter(r=>r.kind==='paid').length,3);
|
||||
assert.throws(()=>action('fees',{revision:detail().revision,verified:true,fee_items:[]}),/没有待核实/);c=costs();assert.equal(detail().profit,37800);assert.equal(detail().total-c.total.total,detail().profit);
|
||||
assert.equal(c.byPayer.owner.total,detail().ownerCost);
|
||||
});
|
||||
test('更正费用金额或付款人后按最新有效支出汇总,连续更正和撤销不重复累计',t=>{
|
||||
const {detail,costs,action}=fixture(t);
|
||||
let target=detail().expenses.find(f=>f.note==='快递费').id;
|
||||
action('correct',{type:'expense',target,amount:'8',payer:'owner',reason:'快递实际由麦麦支付8元',verified:true});
|
||||
let c=costs();assert.equal(c.byPayer.owner.paidFees,1500);assert.equal(c.byPayer.assistant.paidFees,0);assert.equal(c.total.total,213400);
|
||||
assert.equal(c.rows.filter(r=>r.kind==='paid').length,3);assert.equal(detail().total-c.total.total,detail().profit);
|
||||
target=detail().expenses.find(f=>f.amount===800).id;
|
||||
action('correct',{type:'expense',target,amount:'5',payer:'assistant',reason:'最终核实快递助理支付5元',verified:true});
|
||||
c=costs();assert.equal(c.byPayer.owner.paidFees,700);assert.equal(c.byPayer.assistant.paidFees,500);assert.equal(c.total.total,213100);
|
||||
target=detail().expenses.find(f=>f.amount===500).id;
|
||||
action('correct',{type:'expense',target,amount:'0',payer:'assistant',reason:'撤销误记费用',verified:true});
|
||||
c=costs();assert.equal(c.total.paidFees,700);assert.equal(c.rows.filter(r=>r.kind==='paid').length,2);assert.equal(detail().total-c.total.total,detail().profit);
|
||||
});
|
||||
test('旧单未知成本仍显示待补,新单0元费用直接核实且不会伪造付款',t=>{
|
||||
const p=input();p.lines[0].costParts.material='';p.fee_items[0].amount='';p.fee_items[2].amount='0';
|
||||
const {detail,costs}=fixture(t,p,true),c=costs();
|
||||
assert.equal(c.byPayer.owner.goodsMissing,1);assert.equal(c.byPayer.assistant.pendingMissing,1);assert.equal(c.total.missing,2);assert.equal(c.total.total,14300);assert.equal(detail().estimatedProfit,null);
|
||||
assert.equal(c.rows.find(r=>r.name==='快递费').amount,null);assert.equal(c.rows.find(r=>r.name==='包装').amount,0);
|
||||
const zero=input();zero.fee_items[2].amount='0';const f=fixture(t,zero);
|
||||
assert.equal(f.costs().rows.find(r=>r.name==='包装').kind,'zero');assert.equal(f.detail().expenses.length,2);assert.equal(f.costs().total.paidFees,1000);
|
||||
});
|
||||
test('退货与取消不再计算原货品垫资,实际费用保留,未核实预估不冒充支出',t=>{
|
||||
const f=fixture(t);f.action('return',{verified:true,reason:'测试退货'});
|
||||
let c=f.costs();assert.equal(c.goodsExcluded,true);assert.equal(c.total.goods,0);assert.equal(c.total.total,1300);assert.equal(f.detail().profit,-c.total.total);assert.ok(c.rows.filter(r=>r.kind==='goods').every(r=>r.excluded));
|
||||
const g=fixture(t,input(),true);g.action('expense',{amount:'2',payer:'owner',note:'已支付的打样费用'});g.action('cancel',{reason:'取消订单'});
|
||||
c=g.costs();assert.equal(c.pendingCount,0);assert.equal(c.total.total,200);assert.equal(c.byPayer.assistant.total,0);assert.equal(g.detail().profit,-200);
|
||||
});
|
||||
test('旧单只显示已存总成本,分币金额精确累加并保留附加项目来源',t=>{
|
||||
const p=input(),chargeId=randomUUID();p.lines=[{name:'旧款',unit:'件',quantity:'1',pocket:'',payer:'owner',cost:'12.34',sale:'50',charges:[{id:chargeId,name:'特殊包装',amount:'10'}]}];
|
||||
p.fee_items=[{key:'charge:'+chargeId,note:'特殊包装',amount:'0.01',payer:'assistant',status:'estimated'}];
|
||||
const {costs,detail}=fixture(t,p),c=costs();assert.equal(c.total.total,1235);assert.equal(c.rows.length,2);assert.equal(c.rows[0].name,'货品成本(原单未分项)');assert.equal(c.rows[1].source,date);assert.equal(detail().fee_items[0].key,'charge:'+chargeId);assert.equal(detail().lines[0].charges[0].id,chargeId);
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict');
|
||||
const {randomUUID,createHash}=require('node:crypto');
|
||||
const {Ledger}=require('../ledger'),Calc=require('../public/calculations');
|
||||
const actor={id:'display-owner',name:'测试麦麦',role:'owner'};
|
||||
const D='2026-09-30',D2='2026-10-01';
|
||||
const line=(extra={})=>({name:'足金饰品',unit:'g',quantity:'1.200',pocket:'',payer:'owner',sale:'1200',costParts:{material:'980',labor:'20',accessories:'0',other:'0'},...extra});
|
||||
function fixture(t){
|
||||
const ledger=new Ledger(':memory:');t.after(()=>ledger.close());
|
||||
const run=(payload,fn)=>ledger.transact(randomUUID(),actor,payload,fn);
|
||||
const save=(extra={},issue=false)=>{
|
||||
const input={date:D,customer:'合成客户',note:'仅用于测试',payment_account:'助理微信',lines:[line()],fee_items:[],...extra};
|
||||
return run(input,()=>issue?ledger.issueOrder(input,actor):ledger.saveOrder(input,actor)).id;
|
||||
};
|
||||
const action=(id,kind,extra={})=>{const input={date:D,...extra};return run({id,kind,input},()=>ledger.action(id,kind,input,actor));};
|
||||
const after=(extra={})=>{const input={date:D,project:'合成售后',customer:'合成客户',amount:'20',payer:'assistant',...extra};return run(input,()=>ledger.saveAfterSale(input,actor)).after_sale_id;};
|
||||
const close=(date=D)=>run({date,basis:'orderDate'},()=>ledger.closeDay(date,actor,'orderDate'));
|
||||
const book=(query={})=>ledger.orderBook({date:D,...query});
|
||||
return {ledger,run,save,action,after,close,book};
|
||||
}
|
||||
function contents(ledger){return JSON.stringify(ledger.rows("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").map(({name})=>[name,ledger.rows('SELECT * FROM "'+name+'"')]));}
|
||||
|
||||
// 使用本次显示调整前的 SQL 次序和全部商品克重生成旧版财务版本,独立于新显示排序。
|
||||
function legacyRevision(ledger,date,from=date){
|
||||
const book=ledger.orderBook({date,from}),byId=new Map(book.rows.map(row=>[row.id,row]));
|
||||
const orders=ledger.rows('SELECT id FROM orders WHERE date>=? AND date<=? ORDER BY date DESC,paper_number DESC,created DESC,id',from,date).map(({id})=>byId.get(id));
|
||||
const afterSales=ledger.rows('SELECT id FROM after_sales WHERE date>=? AND date<=? ORDER BY date DESC,created DESC,id',from,date).map(({id})=>byId.get(id));
|
||||
const legacyRows=[...orders,...afterSales].sort((a,b)=>b.date.localeCompare(a.date)||Number(b.kind==='afterSale')-Number(a.kind==='afterSale'));
|
||||
const {afterSaleCount,recordCount,...summary}=book.summary;summary.mg=legacyRows.reduce((total,row)=>total+row.mg,0);
|
||||
const rows=legacyRows.map(row=>({id:row.id,date:row.date,status:row.status,
|
||||
sale:row.sale,material:row.material,laborAndFees:row.laborAndFees,unallocated:row.unallocated,
|
||||
totalCost:row.totalCost,profit:row.profit,ownerCost:row.ownerCost,assistantCost:row.assistantCost,
|
||||
known:row.known,costItems:row.costItems,pendingCostItems:row.pendingCostItems,balance:row.balance}));
|
||||
return {revision:createHash('sha256').update(JSON.stringify({basis:'orderDate',date,from,summary,rows,receipts:book.receiptsByOrderDate})).digest('hex'),legacyRows,summary};
|
||||
}
|
||||
|
||||
test('订单和售后按真实创建先后混排,同毫秒顺序稳定,999到1000不按单号字符串排序',t=>{
|
||||
const f=fixture(t);
|
||||
f.ledger.setMeta('paper-sequence',998);
|
||||
const first=f.save({date:D2,customer:'同组首单'},true),after=f.after({date:D2,project:'同组售后'}),second=f.save({date:D2,customer:'同组次单'},true);
|
||||
const backfilled=f.save({date:D,customer:'同组回填日期'});
|
||||
for(const id of [first,second])f.ledger.run('UPDATE orders SET created=? WHERE id=?','2026-10-01T01:00:00.000Z',id);
|
||||
f.ledger.run('UPDATE after_sales SET created=? WHERE id=?','2026-10-01T01:00:00.000Z',after);
|
||||
f.ledger.run('UPDATE orders SET created=? WHERE id=?','2026-10-01T02:00:00.000Z',backfilled);
|
||||
assert.equal(f.ledger.detail(first).paper_number,'20261001999');assert.equal(f.ledger.detail(second).paper_number,'202610011000');
|
||||
assert.deepEqual(f.book({from:D,date:D2}).rows.map(row=>row.id),[first,after,second,backfilled]);
|
||||
assert.deepEqual(f.book({date:D2}).rows.map(row=>row.id),[first,after,second]);
|
||||
assert.deepEqual(f.book({from:D,date:D2,status:'delivered',q:'同组'}).rows.map(row=>row.id),[first,second]);
|
||||
assert.deepEqual(f.book({from:D,date:D2,status:'after_sale',q:'同组'}).rows.map(row=>row.id),[after]);
|
||||
assert.deepEqual(f.book({date:D}).rows.map(row=>row.id),[backfilled]);
|
||||
const before=contents(f.ledger);assert.deepEqual(f.book({from:D,date:D2}).rows.map(row=>row.id),[first,after,second,backfilled]);assert.equal(contents(f.ledger),before);
|
||||
});
|
||||
|
||||
test('草稿修改不改变开单顺序,缺少历史创建审计时按原插入次序稳定回退',t=>{
|
||||
const f=fixture(t),first=f.save({customer:'先开草稿'}),second=f.save({customer:'后开草稿'});
|
||||
for(const id of [first,second])f.ledger.run('UPDATE orders SET created=? WHERE id=?','2026-09-30T01:00:00.000Z',id);
|
||||
assert.deepEqual(f.book().rows.map(row=>row.id),[first,second]);
|
||||
const old=f.ledger.detail(first),input={id:first,revision:old.revision,date:D,customer:'先开草稿已编辑',lines:[line()],fee_items:[]};
|
||||
f.run(input,()=>f.ledger.saveOrder(input,actor));
|
||||
assert.equal(f.ledger.detail(first).created,old.created);assert.deepEqual(f.book().rows.map(row=>row.id),[first,second]);
|
||||
f.ledger.run("DELETE FROM audit WHERE entity IN (?,?) AND action='保存草稿'",first,second);
|
||||
assert.deepEqual(f.book().rows.map(row=>row.id),[first,second]);
|
||||
});
|
||||
|
||||
test('只识别预设银饰,混合金银保留原克重与各来源类型,银饰金额成本和件数照常汇总',t=>{
|
||||
const f=fixture(t);
|
||||
for(const name of ['足银999','纯银925']){
|
||||
assert.equal(Calc.isSilver(name),true);
|
||||
assert.throws(()=>f.save({lines:[line({name,pocket:'现货'})]}),/银饰不扣黄金/);
|
||||
}
|
||||
for(const name of ['银色足金吊坠','足银999测试','纯银925吊坠','足金饰品'])assert.equal(Calc.isSilver(name),false);
|
||||
for(const pocket of ['现货','金料'])f.run({pocket},()=>f.ledger.stock({kind:'opening',date:D,pocket,grams:'20',note:'合成库存'},actor));
|
||||
const id=f.save({lines:[line({quantity:'2.200',pocket:'现货'}),line({name:'足银999',quantity:'10.321',payer:'assistant'}),
|
||||
line({name:'纯银925',quantity:'5.678',payer:'assistant'}),line({name:'足银999',unit:'件',quantity:'3',payer:'assistant'}),
|
||||
line({name:'银色足金吊坠',quantity:'0.500'}),line({quantity:'0.700'}),line({quantity:'0.300',pocket:'金料'}),line({name:'足银999测试',quantity:'0.900'})]},true);
|
||||
const b=f.book(),row=b.rows.find(row=>row.id===id);
|
||||
assert.equal(row.mg,20599);assert.equal(row.summaryMg,4600);assert.equal(row.pieces,3);assert.equal(b.summary.mg,4600);assert.equal(b.summaryWithoutCancelled.mg,4600);assert.equal(b.summary.pieces,3);
|
||||
assert.deepEqual(row.types,['货盘现货','配货 · 银饰','配货','货盘·金料']);
|
||||
assert.equal(row.sale,960000);assert.equal(row.totalCost,800000);assert.equal(row.profit,160000);assert.equal(row.assistantCost,300000);assert.equal(row.ownerCost,500000);
|
||||
assert.equal(b.receiptsByOrderDate.receipt,960000);assert.equal(f.ledger.inventory().find(item=>item.pocket==='现货').mg,17800);assert.equal(f.ledger.inventory().find(item=>item.pocket==='金料').mg,19700);
|
||||
const report=f.ledger.reportByOrderDate(D);assert.equal(report.sales,960000);assert.equal(report.goods,800000);assert.equal(report.profit,160000);assert.equal(report.payerCosts.assistant.goods,300000);
|
||||
assert.deepEqual(f.ledger.publicOrder(id).lines.map(item=>item.quantity),f.ledger.detail(id).lines.map(item=>item.quantity));
|
||||
});
|
||||
|
||||
test('全银克单的汇总克重为0,计件银饰件数仍累计,取消单和售后保留各自原规则',t=>{
|
||||
const f=fixture(t),grams=f.save({customer:'全银克单',lines:[line({name:'足银999',quantity:'10.005'}),line({name:'纯银925',quantity:'2.555'})]},true);
|
||||
const pieces=f.save({customer:'全银件单',lines:[line({name:'纯银925',unit:'件',quantity:'2'})]},true);
|
||||
let b=f.book();assert.equal(b.rows.find(row=>row.id===grams).mg,12560);assert.equal(b.rows.find(row=>row.id===grams).summaryMg,0);assert.deepEqual(b.rows.find(row=>row.id===grams).types,['配货 · 银饰']);
|
||||
assert.equal(b.summary.mg,0);assert.equal(b.summary.pieces,2);assert.equal(b.summary.sale,360000);assert.equal(b.summary.totalCost,300000);assert.equal(b.summary.profit,60000);
|
||||
const cancelled=f.save({customer:'取消混合单',lines:[line({quantity:'1.200'}),line({name:'足银999',quantity:'4.567'}),line({name:'纯银925',unit:'件',quantity:'2'})]});
|
||||
f.action(cancelled,'confirm');f.action(cancelled,'expense',{amount:'8',payer:'assistant',note:'实际费用'});f.action(cancelled,'receipt',{amount:'300',account:'助理微信',verified:true});f.action(cancelled,'cancel',{date:D2,reason:'合成取消'});f.action(cancelled,'refund',{date:D2,amount:'100',account:'助理微信',verified:true});
|
||||
const after=f.after();b=f.book();const c=b.rows.find(row=>row.id===cancelled);
|
||||
assert.equal(c.mg,5767);assert.equal(c.summaryMg,1200);assert.equal(c.pieces,2);assert.equal(b.summary.mg,1200);assert.equal(b.summary.pieces,4);
|
||||
assert.equal(b.summaryWithoutCancelled.mg,0);assert.equal(b.summaryWithoutCancelled.pieces,2);assert.equal(b.summaryWithoutCancelled.orderCount,2);assert.equal(b.summaryWithoutCancelled.afterSaleCount,1);assert.equal(b.summaryWithoutCancelled.profit,58000);
|
||||
assert.equal(b.summary.profit,57200);assert.equal(b.receiptsByOrderDate.receipt,390000);assert.equal(b.receiptsByOrderDate.refund,10000);assert.equal(b.receiptsWithoutCancelled.receipt,360000);assert.equal(b.receiptsWithoutCancelled.refund,0);
|
||||
assert.equal(b.rows.find(row=>row.id===after).summaryMg,0);assert.equal(b.rows.find(row=>row.id===pieces).pieces,2);
|
||||
const only=f.book({status:'cancelled'});assert.deepEqual(only.rows.map(row=>row.id),[cancelled]);assert.equal(only.summaryWithoutCancelled.mg,0);assert.equal(only.summaryWithoutCancelled.profit,0);
|
||||
});
|
||||
|
||||
test('历史银饰货盘保留实际来源和原行重量,读取新汇总不改库存或已保存订单',t=>{
|
||||
const f=fixture(t);f.run({stock:true},()=>f.ledger.stock({kind:'opening',date:D,pocket:'现货',grams:'20',note:'合成库存'},actor));
|
||||
const id=f.save({lines:[line({pocket:'现货',quantity:'3.456'})]},true),old=f.ledger.detail(id),lines=old.lines.map(item=>({...item,name:'足银999'}));
|
||||
// 模拟旧库历史事实;当前表单仍禁止银饰扣黄金货盘。
|
||||
f.ledger.run('UPDATE orders SET lines=? WHERE id=?',JSON.stringify(lines),id);
|
||||
const before=contents(f.ledger),b=f.book(),row=b.rows[0];
|
||||
assert.equal(row.mg,3456);assert.equal(row.summaryMg,0);assert.equal(b.summary.mg,0);assert.deepEqual(row.types,['货盘现货 · 银饰']);assert.equal(row.sale,old.total);assert.equal(row.profit,old.profit);
|
||||
f.ledger.reportByOrderDate(D);assert.equal(contents(f.ledger),before);assert.equal(f.ledger.inventory().find(item=>item.pocket==='现货').mg,16544);
|
||||
});
|
||||
|
||||
test('新显示排序及银饰克重规则兼容旧财务快照,真实收款更正与成本变动仍使快照过期',t=>{
|
||||
const f=fixture(t);f.ledger.setMeta('paper-sequence',998);
|
||||
const first=f.save({lines:[line({name:'足银999',quantity:'10.005'}),line({quantity:'1.200'})]},true),after=f.after(),second=f.save({lines:[line({name:'纯银925',quantity:'2.555'})]},true);
|
||||
const cancelled=f.save({customer:'取消单'});f.action(cancelled,'confirm');f.action(cancelled,'expense',{amount:'3',payer:'assistant',note:'实际打样费'});f.action(cancelled,'cancel',{date:D,reason:'合成取消'});
|
||||
for(const [index,id] of [first,second,cancelled].entries())f.ledger.run('UPDATE orders SET created=? WHERE id=?',`2026-09-30T0${index+1}:00:00.000Z`,id);
|
||||
f.ledger.run('UPDATE after_sales SET created=? WHERE id=?','2026-09-30T01:30:00.000Z',after);
|
||||
const b=f.book(),legacy=legacyRevision(f.ledger,D);assert.deepEqual(b.rows.map(row=>row.id),[first,after,second,cancelled]);assert.deepEqual(legacy.legacyRows.map(row=>row.id),[after,first,cancelled,second]);
|
||||
assert.equal(b.summary.mg,2400);assert.equal(legacy.summary.mg,14960);assert.equal(f.ledger.reportByOrderDate(D).reportRevision,legacy.revision);
|
||||
const range=legacyRevision(f.ledger,D2,D);assert.equal(f.ledger.reportByOrderDate(D2,D).reportRevision,range.revision);
|
||||
f.close();const stored=JSON.parse(f.ledger.one('SELECT report FROM closes WHERE date=?',D).report);
|
||||
stored.summary=legacy.summary;stored.orderRows=legacy.legacyRows;stored.reportRevision=legacy.revision;
|
||||
f.ledger.run('UPDATE closes SET report=? WHERE date=?',JSON.stringify(stored),D);
|
||||
const before=contents(f.ledger),initial=f.ledger.reportByOrderDate(D);assert.equal(initial.close.stale,false);assert.equal(initial.reportRevision,legacy.revision);assert.equal(contents(f.ledger),before);
|
||||
const payment=f.ledger.detail(first).payments[0];
|
||||
f.action(first,'correct',{date:D2,type:'payment',target:payment.id,amount:(payment.amount/100).toFixed(2),account:'助理支付宝',reason:'实际渠道更正',verified:true});
|
||||
const corrected=f.ledger.reportByOrderDate(D);assert.equal(corrected.close.stale,true);assert.notEqual(corrected.reportRevision,legacy.revision);assert.equal(f.ledger.one('SELECT stale FROM closes WHERE date=?',D).stale,0);
|
||||
f.close();const closed=f.ledger.reportByOrderDate(D);assert.equal(closed.close.stale,false);
|
||||
f.action(first,'expense',{date:D2,amount:'2',payer:'owner',note:'跨日补记实际费用'});const changed=f.ledger.reportByOrderDate(D);assert.equal(changed.close.stale,true);assert.notEqual(changed.reportRevision,closed.reportRevision);assert.equal(changed.profit,closed.profit-200);
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
|
||||
const {randomUUID}=require('node:crypto');
|
||||
const {Ledger}=require('../ledger'),Calc=require('../public/calculations'),{receipt}=require('../printing'),{createApp}=require('../server');
|
||||
const actor={id:'entry-owner',name:'测试麦麦',role:'owner'},D='2026-10-16',D2='2026-10-17';
|
||||
const line=(extra={})=>({name:'足金999',unit:'g',quantity:'2.2',pocket:'',payer:'owner',pricingMode:'auto',goldPrice:'940',laborRate:'45',laborMode:'gram',pieces:'1',costParts:{material:'1980',labor:'44',accessories:'0',other:'0'},...extra});
|
||||
function fixture(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'maimai-entry-'));const file=path.join(dir,'ledger.sqlite');const l=new Ledger(file);t.after(()=>{try{l.close();}catch{}fs.rmSync(dir,{recursive:true,force:true});});const run=(p,fn,key=randomUUID())=>l.transact(key,actor,p,fn);const save=(extra={})=>{const p={date:D,lines:[line()],discount:'0',...extra};return run(p,()=>l.saveOrder(p,actor)).id;};const act=(id,a,p={})=>run({id,a,p},()=>l.action(id,a,{date:D,...p},actor));return {dir,file,l,run,save,act};}
|
||||
test('克工费与件工费:用户给定案例、整数分舍入、件数及非法输入',()=>{
|
||||
assert.equal(Calc.calculate(line()).sale,216700);
|
||||
assert.equal(Calc.calculate(line({laborMode:'piece'})).sale,211300);
|
||||
assert.equal(Calc.calculate(line({laborMode:'piece',pieces:'2'})).sale,215800);
|
||||
assert.equal(Calc.calculate(line({quantity:'0.001',goldPrice:'1',laborRate:'4'})).sale,1);
|
||||
assert.equal(Calc.calculate(line({quantity:'0.001',goldPrice:'1',laborRate:'3'})).sale,0);
|
||||
for(const change of [{goldPrice:'-1'},{quantity:'2.2001'},{laborRate:''},{laborMode:'other'},{laborMode:'piece',pieces:'0'},{laborMode:'piece',pieces:'1.2'},{unit:'件'}])assert.throws(()=>Calc.calculate(line(change)));
|
||||
});
|
||||
test('附加项目选填、逐项按分相加,支持两种工费与直接报价',()=>{
|
||||
const charges=[{name:'编绳',amount:'10'},{name:'证书',amount:'5.01'},{name:'包装',amount:''},{name:'附加费',amount:'0'}];
|
||||
assert.equal(Calc.sale(line({charges})).sale,218201);
|
||||
assert.equal(Calc.sale(line({laborMode:'piece',charges})).sale,212801);
|
||||
const manual=Calc.sale({pricingMode:'manual',baseSale:'100',sale:'999',charges});assert.equal(manual.baseSale,10000);assert.equal(manual.sale,11501);assert.equal(manual.charges.length,3);
|
||||
assert.equal(Calc.sale(line({charges:[]})).sale,216700);
|
||||
for(const raw of [[{name:'编绳',amount:'-1'}],[{name:'',amount:'1'}],[{name:'编绳',amount:'0.001'}],{}])assert.throws(()=>Calc.sale(line({charges:raw})));
|
||||
});
|
||||
test('附加收费进入销售和收款,内部成本独立;编辑不重复加,退款按含附加总额',t=>{
|
||||
const {l,save,act}=fixture(t),charges=[{name:'编绳',amount:'10'},{name:'证书',amount:'5'}];
|
||||
const input=line({charges,sale:'0.01'}),id=save({lines:[input]});assert.equal(l.detail(id).total,218200);assert.equal(l.detail(id).goodsCost,202400);assert.equal(l.detail(id).expenses.length,0);
|
||||
save({id,revision:l.detail(id).revision,lines:[input]});assert.equal(l.detail(id).total,218200);
|
||||
act(id,'confirm');act(id,'expense',{amount:'3',payer:'assistant',note:'实际编绳成本'});act(id,'receipt',{amount:'2182',account:'助理微信',verified:true});act(id,'deliver',{verified:true});assert.equal(l.detail(id).profit,15500);
|
||||
act(id,'return',{date:D2,reason:'含附加项目整单退回',verified:true});assert.equal(l.detail(id).balance,-218200);assert.equal(l.detail(id).profit,-300);
|
||||
act(id,'refund',{date:D2,amount:'2182',account:'助理微信',verified:true});assert.equal(l.detail(id).balance,0);
|
||||
});
|
||||
test('附加收费可删除、修改及清空;手填金额重复保存不翻倍',t=>{
|
||||
const {l,save}=fixture(t);const base={name:'其他商品',unit:'件',quantity:'1',pocket:'',payer:'owner',cost:'50',pricingMode:'manual',baseSale:'100',charges:[{name:'包装',amount:'5'},{name:'附加费',amount:'10'}]};
|
||||
const id=save({lines:[base]});assert.equal(l.detail(id).total,11500);
|
||||
save({id,revision:l.detail(id).revision,lines:[{...base,charges:[{name:'包装',amount:'3'}]}]});assert.equal(l.detail(id).total,10300);
|
||||
save({id,revision:l.detail(id).revision,lines:[{...base,charges:[]}]});assert.equal(l.detail(id).total,10000);
|
||||
});
|
||||
test('旧分精度订单的多个附加项目完整保留在一页,分项金额与整单一致且名称转义',t=>{
|
||||
const {l,save}=fixture(t);const charges=Array.from({length:21},(_,i)=>({name:'项目'+i,amount:'1.01'}));charges[0].name='<img src=x onerror=evil()>';
|
||||
const id=save({rounding_mode:'cent',lines:[line({charges})]});const o=l.publicOrder(id),html=receipt(o);assert.equal(o.total,218821);assert.equal(o.lines[0].charges.length,21);assert.ok(!JSON.stringify(o).includes('costParts'));assert.ok(!html.includes('<img src=x'));assert.ok(html.includes('<img'));assert.ok(html.includes('附加:项目20'));
|
||||
assert.equal((html.match(/<section class="sheet /g)||[]).length,1);const rowAmounts=[...html.matchAll(/<td>(\d+\.\d{2})<\/td><\/tr>/g)].map(m=>Math.round(Number(m[1])*100));assert.equal(rowAmounts.length,22);assert.equal(rowAmounts.reduce((a,b)=>a+b,0),o.total);assert.equal((html.match(/合计金额/g)||[]).length,1);assert.ok(html.includes('贰仟壹佰捌拾捌元贰角壹分'));
|
||||
});
|
||||
test('新纸单号不带横线,旧有横线号仍计入累计且草稿改号不新增序号',t=>{
|
||||
const {l,save}=fixture(t);const id=save();l.run('UPDATE orders SET paper_number=? WHERE id=?','20261016-008',id);
|
||||
assert.equal(l.paperNumber(D2),'20261017009');assert.equal(l.detail(id).paper_number,'20261016-008');
|
||||
save({id,revision:l.detail(id).revision,date:D2});assert.equal(l.detail(id).paper_number,'20261017008');assert.equal(l.paperNumber(D),'20261016009');
|
||||
});
|
||||
test('服务器重新计算销售额和成本,忽略伪造总额,成本空项阻止交付',t=>{
|
||||
const {l,save,act}=fixture(t);const id=save({lines:[line({sale:'1',cost:'1',costParts:{material:'1980',labor:'',accessories:'0',other:'0'}})]});
|
||||
assert.equal(l.detail(id).total,216700);assert.equal(l.detail(id).goodsCost,null);act(id,'confirm');act(id,'receipt',{amount:'2167',account:'助理支付宝',verified:true});
|
||||
assert.throws(()=>act(id,'deliver',{verified:true}),/补齐/);assert.throws(()=>act(id,'cost',{costs:['2024']}),/逐项/);
|
||||
act(id,'cost',{costs:[{material:'1980',labor:'44',accessories:'0',other:'0'}]});act(id,'deliver',{verified:true});assert.equal(l.detail(id).profit,14300);
|
||||
});
|
||||
test('纸单跨日持续累计、预览不占号、取消不复用、改日期保留原序号',t=>{
|
||||
const {l,save,act}=fixture(t);assert.equal(l.paperNumber(D),'20261016001');assert.equal(l.paperNumber(D),'20261016001');
|
||||
const a=save();assert.equal(l.detail(a).paper_number,'20261016001');
|
||||
save({id:a,revision:l.detail(a).revision});assert.equal(l.detail(a).paper_number,'20261016001');act(a,'cancel',{reason:'合成测试'});
|
||||
const b=save();assert.equal(l.detail(b).paper_number,'20261016002');const c=save({date:D2});assert.equal(l.detail(c).paper_number,'20261017003');
|
||||
save({id:b,revision:l.detail(b).revision,date:D2});assert.equal(l.detail(b).paper_number,'20261017002');assert.equal(l.paperNumber(D),'20261016004');
|
||||
assert.throws(()=>save({lines:[line({goldPrice:'bad'})]}));assert.equal(l.paperNumber(D),'20261016004');
|
||||
});
|
||||
test('重复保存只生成一张单一个号码;重开数据库接续流水号',t=>{
|
||||
const {l,run,file}=fixture(t),p={date:D,lines:[line()],payment_account:'助理支付宝'},key=randomUUID();
|
||||
const a=run(p,()=>l.saveOrder(p,actor),key);const b=run(p,()=>l.saveOrder(p,actor),key);assert.equal(a.id,b.id);assert.equal(l.rows('SELECT id FROM orders').length,1);
|
||||
l.close();const reopened=new Ledger(file);assert.equal(reopened.paperNumber(D2),'20261017002');assert.equal(reopened.detail(a.id).payment_account,'助理支付宝');reopened.close();
|
||||
});
|
||||
test('接续旧版最大序号,跨月跨年不归零,超过999继续累计,历史单号不改写',t=>{
|
||||
const {l,save,act}=fixture(t);
|
||||
const old=save({date:'2025-12-31'});const original=l.detail(old).paper_number;
|
||||
l.setMeta('paper-seq:2025-12-31',999);
|
||||
assert.equal(l.paperNumber('2026-01-01'),'202601011000');
|
||||
const next=save({date:'2026-01-01'});assert.equal(l.detail(next).paper_number,'202601011000');
|
||||
assert.equal(l.detail(old).paper_number,original);
|
||||
act(next,'print');act(next,'print');assert.equal(l.paperNumber('2026-02-01'),'202602011001');
|
||||
const nextMonth=save({date:'2026-02-01'});assert.equal(l.detail(nextMonth).paper_number,'202602011001');
|
||||
});
|
||||
test('快递包装按整单登记一次;各付款人分开;退货保留实际已付费用',t=>{
|
||||
const {l,save,act,run}=fixture(t);const id=save({payment_account:'助理支付宝',fees_date:D,fee_items:[{key:'shipping',amount:'8',payer:'assistant'},{key:'box',amount:'3',payer:'owner'}]});
|
||||
assert.equal(l.detail(id).draftFees,1100);assert.equal(l.detail(id).estimatedProfit,13200);assert.equal(l.detail(id).expenses.length,0);
|
||||
assert.throws(()=>act(id,'confirm'),/实际支付/);const p={date:D,feesVerified:true},key=randomUUID();run(p,()=>l.action(id,'confirm',p,actor),key);run(p,()=>l.action(id,'confirm',p,actor),key);
|
||||
assert.equal(l.detail(id).expenses.length,2);assert.equal(l.detail(id).draftFees,0);assert.equal(l.detail(id).directCost,1100);
|
||||
act(id,'receipt',{amount:'2167',account:'助理支付宝',verified:true});act(id,'deliver',{verified:true});assert.equal(l.detail(id).profit,13200);assert.equal(l.detail(id).ownerCost,202700);
|
||||
act(id,'return',{date:D2,reason:'合成退货',verified:true});assert.equal(l.detail(id).profit,-1100);assert.equal(l.report(D2).profit,-14300);
|
||||
});
|
||||
test('取消未确认草稿不把暂填费用记成已支出;费用重复及日期错误被拒绝',t=>{
|
||||
const {l,save,act}=fixture(t);const fees=[{key:'shipping',amount:'8',payer:'assistant'}];const id=save({fee_items:fees});act(id,'cancel',{reason:'测试取消'});assert.equal(l.detail(id).profit,0);assert.equal(l.detail(id).expenses.length,0);
|
||||
assert.throws(()=>save({fee_items:[...fees,...fees]}),/重复/);assert.throws(()=>save({fee_items:fees,fees_date:'2026-10-15'}),/业务日期/);
|
||||
});
|
||||
test('银饰不会扣黄金库存,其他商品可手填名称并按件报价',t=>{
|
||||
const {l,save}=fixture(t);assert.throws(()=>save({lines:[line({name:'足银999',pocket:'现货'})]}),/银饰/);
|
||||
const id=save({lines:[line({name:'纯银925'}),line({name:'定制吊坠',pricingMode:'manual',unit:'件',quantity:'1',sale:'500',priceNote:'定制一口价'})]});assert.equal(l.detail(id).lines[1].sale,50000);
|
||||
});
|
||||
test('打印独立显示金价、工费、纸单号和实际付款方式,内部费用不泄露',t=>{
|
||||
const {l,save,act}=fixture(t);const id=save({lines:[line({laborMode:'piece',costParts:{material:'1876.54',labor:'32.19',accessories:'6.78',other:'0'}})],fee_items:[{key:'other',amount:'9.87',payer:'assistant',note:'内部供应商费用'}]});act(id,'confirm',{feesVerified:true});act(id,'receipt',{amount:'100',account:'助理支付宝',verified:true});
|
||||
const p=l.publicOrder(id),html=receipt(p),json=JSON.stringify(p);for(const k of ['costParts','fee_items','payment_account','payer','profit'])assert.ok(!json.includes('"'+k+'"'));
|
||||
for(const value of ['1876.54','32.19','6.78','9.87','内部供应商'])assert.ok(!html.includes(value));
|
||||
for(const value of ['20261016001','940.00元/克','45.00元/件 × 1件','销售工费','支付宝'])assert.ok(html.includes(value));
|
||||
});
|
||||
test('打印沿用开单收款方式,不虚增流水;实际混合收款及更正以有效账户显示',t=>{
|
||||
const {l,save,act}=fixture(t),id=save({payment_account:'助理微信'});
|
||||
for(const confirmed of [false,true]){
|
||||
if(confirmed)act(id,'confirm');
|
||||
const before=l.detail(id),p=l.publicOrder(id),html=receipt(p);
|
||||
assert.deepEqual(p.paymentMethods,['微信']);assert.ok(html.includes('收款方式:微信'));assert.ok(!html.includes('收款方式:尚未登记'));
|
||||
assert.ok(!html.includes('助理微信'));assert.deepEqual(l.detail(id),before);assert.equal(p.received,0);
|
||||
}
|
||||
act(id,'receipt',{amount:'300',account:'助理支付宝',verified:true});
|
||||
assert.deepEqual(l.publicOrder(id).paymentMethods,['支付宝']);
|
||||
act(id,'receipt',{amount:'100',account:'麦麦微信',verified:true});
|
||||
assert.deepEqual(new Set(l.publicOrder(id).paymentMethods),new Set(['支付宝','微信']));
|
||||
const old=l.detail(id).payments.find(p=>p.account==='助理支付宝');
|
||||
act(id,'correct',{type:'payment',target:old.id,amount:'300',account:'助理现金',reason:'测试更正收款渠道',verified:true});
|
||||
assert.deepEqual(new Set(l.publicOrder(id).paymentMethods),new Set(['现金','微信']));assert.equal(l.detail(id).received,40000);
|
||||
});
|
||||
test('旧版库升级保留历史金额和纸单;旧草稿编辑保留原总成本',t=>{
|
||||
const {l,save,file}=fixture(t);const id=save({lines:[{name:'旧版',unit:'g',quantity:'1',pocket:'',payer:'owner',cost:'900',sale:'1000'}]});
|
||||
l.run('UPDATE orders SET paper_number=? WHERE id=?','原纸号-88',id);const before=l.rawOrder(id);
|
||||
for(const name of ['paper_date','payment_account','fee_items','fees_date'])l.db.exec('ALTER TABLE orders DROP COLUMN '+name);l.close();
|
||||
const upgraded=new Ledger(file);const after=upgraded.rawOrder(id);assert.equal(after.paper_number,before.paper_number);assert.deepEqual(after.lines,before.lines);assert.equal(after.total,before.total);assert.equal(after.fee_items.length,0);upgraded.close();
|
||||
});
|
||||
test('HTTP并行开单编号不同,同操作重试同单号;端点预览不占号',async t=>{
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'maimai-entry-http-'));const app=createApp({mode:'demo',dataDir:dir});await new Promise(r=>app.server.listen(0,'127.0.0.1',r));
|
||||
t.after(async()=>{await new Promise(r=>app.server.close(r));app.ledger.close();fs.rmSync(dir,{recursive:true,force:true});});const base='http://127.0.0.1:'+app.server.address().port;let cookie='';
|
||||
const call=(route,data,key=randomUUID())=>fetch(base+route,{method:data?'POST':'GET',headers:{Cookie:cookie,...(data?{'Content-Type':'application/json',Origin:base,'X-Requested-With':'maimai-ledger','Idempotency-Key':key}:{})},...(data?{body:JSON.stringify(data)}:{})});
|
||||
assert.equal((await call('/api/paper-number')).status,401);cookie=(await call('/api/demo-login',{role:'owner'})).headers.get('set-cookie').split(';')[0];
|
||||
const p={date:D,lines:[line()]},key=randomUUID();const responses=await Promise.all([call('/api/orders',p,key),call('/api/orders',p,key),call('/api/orders',p)]);assert.ok(responses.every(r=>r.status===200));const ids=await Promise.all(responses.map(r=>r.json()));assert.equal(ids[0].id,ids[1].id);assert.notEqual(ids[0].id,ids[2].id);assert.notEqual(app.ledger.detail(ids[0].id).paper_number,app.ledger.detail(ids[2].id).paper_number);
|
||||
const preview=await (await call('/api/paper-number?date='+D)).json();assert.equal(preview.number,app.ledger.paperNumber(D));assert.equal((await call('/calculations.js')).status,200);
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict');
|
||||
const {randomUUID}=require('node:crypto'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),vm=require('node:vm');
|
||||
const {Ledger}=require('../ledger'),Calc=require('../public/calculations'),{receipt,uppercaseMoney}=require('../printing'),{createApp}=require('../server');
|
||||
const actor={id:'round-owner',name:'测试麦麦',role:'owner'},D='2026-10-16',D2='2026-10-17';
|
||||
const item=(extra={})=>({name:'合成商品',unit:'件',quantity:'1',pocket:'',payer:'owner',cost:'9.99',sale:'12.60',...extra});
|
||||
const input=(extra={})=>({date:D,customer:'合成客户',payment_account:'助理微信',discount:'0',lines:[item()],fee_items:[],...extra});
|
||||
function fixture(t){
|
||||
const ledger=new Ledger(':memory:');t.after(()=>ledger.close());
|
||||
const run=(value,fn,key=randomUUID())=>ledger.transact(key,actor,value,fn);
|
||||
const save=(value=input(),issue=false,key=randomUUID())=>run(value,()=>issue?ledger.issueOrder(value,actor):ledger.saveOrder(value,actor),key).id;
|
||||
const action=(id,kind,extra={})=>{const value={date:D,...extra};return run({id,kind,value},()=>ledger.action(id,kind,value,actor));};
|
||||
return {ledger,run,save,action};
|
||||
}
|
||||
const contents=ledger=>JSON.stringify(ledger.rows("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").map(({name})=>[name,ledger.rows('SELECT * FROM "'+name+'"')]));
|
||||
|
||||
test('整单共享算法按.49/.50/.99取整,整元不变,差额符号准确且旧cent保留分',()=>{
|
||||
for(const [raw,total,adjustment] of [[12949,12900,-49],[12950,13000,50],[12999,13000,1],[350660,350700,40],[350640,350600,-40],[13000,13000,0],[50,100,50],[100000000000,100000000000,0]]){
|
||||
assert.deepEqual(Calc.orderTotal([raw]),{subtotal:raw,discount:0,unroundedTotal:raw,total,rounding_mode:'yuan',rounding_adjustment:adjustment});
|
||||
assert.equal(Calc.orderTotal([raw],0,'cent').total,raw);assert.equal(Calc.orderTotal([raw],0,'cent').rounding_adjustment,0);
|
||||
}
|
||||
assert.equal(Calc.orderTotal([1],0,'cent').total,1);
|
||||
});
|
||||
|
||||
test('跨商品和附加收费先按分合计,减优惠后整单只取整一次,单行金额始终不取整',t=>{
|
||||
const f=fixture(t),lines=[item({sale:'11.49',cost:'1.11',charges:[{name:'附加一',amount:'0.01'}]}),item({sale:'12.49',cost:'1.11',charges:[{name:'附加二',amount:'0.01'}]})];
|
||||
for(const [discount,total,adjustment] of [['0',2400,0],['0.51',2300,-49],['0.50',2400,50],['0.01',2400,1]]){
|
||||
const id=f.save(input({lines,discount}),true),o=f.ledger.detail(id);
|
||||
assert.deepEqual(o.lines.map(line=>line.sale),[1150,1250]);assert.deepEqual(o.lines.map(line=>line.baseSale),[1149,1249]);assert.equal(o.total,total);assert.equal(o.rounding_adjustment,adjustment);
|
||||
assert.equal(o.discount,Calc.cents(discount));assert.equal(o.goodsCost,222);assert.equal(o.profit,total-222);assert.equal(o.expenses.length,0);
|
||||
}
|
||||
const plain=f.save(input({lines:lines.map(({charges,...line})=>line)}),true);assert.equal(f.ledger.detail(plain).total,2400);assert.equal(f.ledger.detail(plain).rounding_adjustment,2);
|
||||
});
|
||||
|
||||
test('浏览器与服务器加载同一整数算法,输入分精度销售与成本时结果一致',()=>{
|
||||
const context=vm.createContext({});vm.runInContext(fs.readFileSync(path.join(__dirname,'../public/calculations.js'),'utf8'),context);const browser=context.LedgerCalc;
|
||||
for(const args of [[[12949]],[[12950]],[[12999]],[[1150,1250],51,'yuan'],[[1150,1250],50,'yuan'],[[12949],0,'cent'],[[50],0,'yuan']])assert.deepEqual(JSON.parse(JSON.stringify(browser.orderTotal(...args))),Calc.orderTotal(...args));
|
||||
const line={unit:'g',quantity:'3.56',pricingMode:'auto',goldPrice:'940',laborRate:'45',laborMode:'gram',costParts:{material:'0',labor:'0',accessories:'0',other:'0'},costMaterial:{mode:'gram',rate:'902'},costLabor:{mode:'gram',rate:'27'}};
|
||||
assert.equal(browser.sale(line).sale,350660);assert.equal(browser.orderTotal([browser.sale(line).sale]).total,350700);assert.equal(browser.purchaseCosts(line).total,330724);
|
||||
});
|
||||
|
||||
test('非法、优惠后非正、取整后0及超范围金额拒绝,服务器失败不占号、不留半笔',t=>{
|
||||
for(const amounts of [[],Array(61).fill(100),['100'],[null],[undefined],[-1],[1.1],[NaN],[Infinity],[true],[100000000001],[100000000000,1]])assert.throws(()=>Calc.orderTotal(amounts));
|
||||
for(const discount of [-1,0.1,'0',null,NaN,Infinity,100000000001])assert.throws(()=>Calc.orderTotal([100],discount));
|
||||
for(const mode of ['',null,'other',false])assert.throws(()=>Calc.orderTotal([100],0,mode));
|
||||
for(const amounts of [[0],[1],[49]])assert.throws(()=>Calc.orderTotal(amounts),/大于0/);
|
||||
assert.throws(()=>Calc.orderTotal([100],100),/大于0/);assert.throws(()=>Calc.orderTotal([100],101),/大于0/);
|
||||
const f=fixture(t),before=contents(f.ledger),paper=f.ledger.paperNumber(D);
|
||||
for(const value of [input({lines:[item({sale:'0.49'})]}),input({discount:'12.60'}),input({discount:'12.11'}),input({rounding_mode:null}),input({rounding_mode:'invalid'}),input({lines:[item({sale:'1000000000'}),item({sale:'0.01'})]})]){assert.throws(()=>f.save(value,true));assert.equal(contents(f.ledger),before);assert.equal(f.ledger.paperNumber(D),paper);}
|
||||
});
|
||||
|
||||
test('新API省略取整字段仍按元,实收利润结算报表统一total,内部成本与库存保留原精度且幂等',t=>{
|
||||
const f=fixture(t);f.run({stock:true},()=>f.ledger.stock({kind:'opening',date:D,pocket:'现货',grams:'10',note:'合成库存'},actor));
|
||||
const value=input({total:1,rounding_adjustment:999,lines:[item({unit:'g',quantity:'3.56',pocket:'现货',pricingMode:'auto',goldPrice:'940',laborRate:'45',laborMode:'gram',costParts:{material:'0',labor:'0',accessories:'0',other:'0'},costMaterial:{mode:'gram',rate:'902'},costLabor:{mode:'gram',rate:'27'},costPayers:{material:'owner',labor:'assistant'}})],fee_items:[{key:'shipping',amount:'6',payer:'assistant'}]});
|
||||
const key=randomUUID(),id=f.save(value,true,key);assert.equal(f.save(value,true,key),id);const o=f.ledger.detail(id);
|
||||
assert.equal(o.rounding_mode,'yuan');assert.equal(o.total,350700);assert.equal(o.rounding_adjustment,40);assert.equal(o.discount,0);assert.equal(o.lines[0].sale,350660);assert.equal(o.goodsCost,330724);assert.equal(o.directCost,600);assert.equal(o.profit,19376);
|
||||
assert.equal(o.received,350700);assert.equal(o.balance,0);assert.equal(o.ownerCost,321112);assert.equal(o.costDue,321112);assert.equal(o.settlementDue,340488);
|
||||
assert.equal(o.payments.length,1);assert.equal(o.expenses.length,1);assert.equal(f.ledger.rows('SELECT * FROM journal').length,1);assert.equal(f.ledger.rows("SELECT * FROM movements WHERE kind='sale'").length,1);assert.equal(f.ledger.inventory()[0].mg,6440);
|
||||
const book=f.ledger.orderBook({date:D}),report=f.ledger.reportByOrderDate(D);assert.equal(book.summary.sale,350700);assert.equal(book.summary.profit,19376);assert.equal(report.receiptsByOrderDate.receipt,350700);assert.equal(report.profit,19376);assert.equal(report.payerCosts.assistant.total,10212);
|
||||
f.action(id,'settlement',{amount:'3211.12',bucket:'cost',direction:'toOwner',note:'合成实际货款交付',verified:true});f.action(id,'settlement',{amount:'193.76',bucket:'profit',direction:'toOwner',note:'合成利润交付',verified:true});assert.equal(f.ledger.detail(id).settlementDue,0);
|
||||
});
|
||||
|
||||
test('整元订单退货退款使用原保存total,利润仅冲回原销售成本,售后和实际费用不取整',t=>{
|
||||
const f=fixture(t),id=f.save(input({lines:[item({sale:'12.60',cost:'9.99'})],fee_items:[{key:'shipping',amount:'0.49',payer:'assistant'}]}),true);
|
||||
assert.equal(f.ledger.detail(id).profit,252);f.action(id,'return',{date:D2,reason:'合成退货',verified:true});assert.equal(f.ledger.detail(id).balance,-1300);assert.equal(f.ledger.detail(id).profit,-49);
|
||||
assert.throws(()=>f.action(id,'refund',{date:D2,amount:'13.01',account:'助理微信',verified:true}),/超过/);f.action(id,'refund',{date:D2,amount:'13',account:'助理微信',verified:true});
|
||||
assert.equal(f.ledger.detail(id).netReceived,0);assert.equal(f.ledger.detail(id).profit,-49);assert.equal(f.ledger.report(D2).sales,-1300);assert.equal(f.ledger.report(D2).profit,-301);
|
||||
f.run({after:true},()=>f.ledger.saveAfterSale({date:D2,project:'合成售后',customer:'合成客户',amount:'0.49',payer:'owner'},actor));assert.equal(f.ledger.reportByOrderDate(D2).profit,-49);
|
||||
});
|
||||
|
||||
test('打印商品和附加项保留分,整数合计大小写一致,仅提示整单取整规则而不输出优惠差额或成本',t=>{
|
||||
const f=fixture(t);
|
||||
for(const [sale,total,adjustment,upper] of [['12.60',1300,40,'壹拾叁元整'],['12.40',1200,-40,'壹拾贰元整']]){
|
||||
const id=f.save(input({lines:[item({sale,cost:'9.99'})]}),true),p=f.ledger.publicOrder(id);
|
||||
assert.equal(p.total,total);assert.equal(p.rounding_mode,'yuan');assert.equal(p.rounding_adjustment,adjustment);
|
||||
for(const mode of ['full','overlay']){
|
||||
const html=receipt(p,{},mode);assert.ok(html.includes('<td>'+sale+'</td>'));assert.ok(html.includes('<strong>¥'+total/100+'</strong>'));assert.ok(html.includes(upper));assert.ok(html.includes('整单金额四舍五入到元'));assert.ok(!html.includes('+0.40元'));assert.ok(!html.includes('-0.40元'));assert.equal((html.match(/<section class="sheet /g)||[]).length,1);
|
||||
for(const hidden of ['整单优惠','costPayers','costParts','costMaterial','costLabor','ownerCost','9.99'])assert.ok(!html.includes(hidden),hidden);
|
||||
}
|
||||
assert.equal(uppercaseMoney(p.total),upper);
|
||||
}
|
||||
const exact=f.save(input({lines:[item({sale:'12.00'})]}),true);assert.ok(!receipt(f.ledger.publicOrder(exact)).includes('四舍五入'));
|
||||
});
|
||||
|
||||
test('草稿重复保存重新按原始行合计计算,保留模式,不把取整差额写成优惠或实际费用',t=>{
|
||||
const f=fixture(t),value=input({discount:'0.20',lines:[item({sale:'12.60'})]}),id=f.save(value),paper=f.ledger.detail(id).paper_number;
|
||||
for(let i=0;i<3;i++){const o=f.ledger.detail(id);f.save({...value,id,revision:o.revision});const saved=f.ledger.detail(id);assert.equal(saved.total,1200);assert.equal(saved.rounding_adjustment,-40);assert.equal(saved.discount,20);assert.equal(saved.paper_number,paper);assert.equal(saved.expenses.length,0);}
|
||||
f.save({...value,id,revision:f.ledger.detail(id).revision,lines:[item({sale:'12.80'})]});assert.equal(f.ledger.detail(id).total,1300);assert.equal(f.ledger.detail(id).rounding_adjustment,40);
|
||||
});
|
||||
|
||||
test('旧库金额升级不迁移,旧草稿省略模式保留cent,只有明确yuan才改新报价',t=>{
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'maimai-round-upgrade-')),filename=path.join(dir,'ledger.sqlite');let ledger=new Ledger(filename);
|
||||
t.after(()=>{try{ledger.close();}catch{}fs.rmSync(dir,{recursive:true,force:true});});
|
||||
const transact=(value,fn)=>ledger.transact(randomUUID(),actor,value,fn),old=input({rounding_mode:'cent'}),completed=transact(old,()=>ledger.issueOrder(old,actor)).id;
|
||||
const draftValue=input({rounding_mode:'cent',lines:[item({sale:'12.49'})]}),draft=transact(draftValue,()=>ledger.saveOrder(draftValue,actor)).id;
|
||||
const original=ledger.detail(completed),beforeReport=ledger.reportByOrderDate(D),oldBusiness=JSON.stringify(['payments','expenses','movements','journal'].map(table=>ledger.rows('SELECT * FROM '+table)));
|
||||
ledger.db.exec('ALTER TABLE orders DROP COLUMN rounding_mode');ledger.close();ledger=new Ledger(filename);
|
||||
assert.deepEqual(ledger.detail(completed),original);assert.equal(ledger.detail(completed).total,1260);assert.equal(ledger.detail(completed).rounding_mode,'cent');assert.equal(ledger.reportByOrderDate(D).reportRevision,beforeReport.reportRevision);assert.equal(JSON.stringify(['payments','expenses','movements','journal'].map(table=>ledger.rows('SELECT * FROM '+table))),oldBusiness);
|
||||
const {rounding_mode,...omitted}=draftValue,edit={...omitted,id:draft,revision:ledger.detail(draft).revision};transact(edit,()=>ledger.saveOrder(edit,actor));assert.equal(ledger.detail(draft).total,1249);assert.equal(ledger.detail(draft).rounding_mode,'cent');
|
||||
const issue={...edit,revision:ledger.detail(draft).revision};transact(issue,()=>ledger.issueOrder(issue,actor));assert.equal(ledger.detail(draft).total,1249);assert.equal(ledger.detail(draft).received,1249);
|
||||
const explicit=transact(draftValue,()=>ledger.saveOrder(draftValue,actor)).id,change={...draftValue,id:explicit,revision:ledger.detail(explicit).revision,rounding_mode:'yuan'};transact(change,()=>ledger.saveOrder(change,actor));assert.equal(ledger.detail(explicit).total,1200);assert.equal(ledger.detail(explicit).rounding_mode,'yuan');
|
||||
assert.throws(()=>transact({...old,id:completed,revision:original.revision,rounding_mode:'yuan'},()=>ledger.issueOrder({...old,id:completed,revision:original.revision,rounding_mode:'yuan'},actor)),/不能直接改写/);
|
||||
const html=receipt(ledger.publicOrder(completed));assert.ok(html.includes('¥12.60'));assert.ok(html.includes('壹拾贰元陆角'));assert.ok(!html.includes('四舍五入'));
|
||||
});
|
||||
|
||||
test('HTTP缺省新政策、旧明确cent和请求幂等正确,白名单仅新增取整字段',async t=>{
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'maimai-round-http-')),app=createApp({mode:'demo',dataDir:dir,ledger:new Ledger(':memory:'),feishuConfig:{enabled:false}});
|
||||
await new Promise(resolve=>app.server.listen(0,'127.0.0.1',resolve));t.after(async()=>{await new Promise(resolve=>app.server.close(resolve));app.ledger.close();fs.rmSync(dir,{recursive:true,force:true});});
|
||||
const base='http://127.0.0.1:'+app.server.address().port;let cookie='';const call=(route,value,key=randomUUID())=>fetch(base+route,{method:value?'POST':'GET',headers:{Cookie:cookie,...(value?{'Content-Type':'application/json',Origin:base,'X-Requested-With':'maimai-ledger','Idempotency-Key':key}:{})},...(value?{body:JSON.stringify(value)}:{})});
|
||||
const login=await call('/api/demo-login',{role:'assistant'});cookie=login.headers.get('set-cookie').split(';')[0];const key=randomUUID(),rs=await Promise.all([call('/api/orders/issue',input(),key),call('/api/orders/issue',input(),key)]);assert.deepEqual(rs.map(r=>r.status),[200,200]);const result=await rs[0].json();assert.deepEqual(await rs[1].json(),result);
|
||||
const p=await (await call('/api/orders/'+result.id+'/public')).json();assert.equal(p.total,1300);assert.equal(p.received,1300);assert.equal(p.rounding_mode,'yuan');assert.equal(p.rounding_adjustment,40);for(const key of ['costPayers','costParts','ownerCost','profit','expenses'])assert.ok(!Object.hasOwn(p,key));
|
||||
assert.equal((await call('/api/orders/issue',input({rounding_mode:'bad'}))).status,400);assert.equal((await call('/api/orders/issue',input({lines:[item({sale:'0.49'})]}))).status,400);
|
||||
const legacy=await call('/api/orders/issue',input({rounding_mode:'cent'}));assert.equal(legacy.status,200);const old=await legacy.json();assert.equal((await (await call('/api/orders/'+old.id)).json()).total,1260);
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict'),{randomUUID}=require('node:crypto');
|
||||
const fs=require('node:fs'),os=require('node:os'),path=require('node:path');
|
||||
const {Ledger}=require('../ledger'),{createApp}=require('../server'),{receipt}=require('../printing');
|
||||
const actor={id:'paid-test',name:'测试助理',role:'assistant'},owner={id:'paid-owner',name:'测试麦麦',role:'owner'},date='2026-10-17';
|
||||
const input=(extra={})=>({date,discount:'7',payment_account:'助理支付宝',lines:[{name:'足金999',unit:'g',quantity:'2.2',pocket:'现货',payer:'owner',pricingMode:'auto',goldPrice:'940',laborMode:'gram',laborRate:'45',costParts:{material:'1980',labor:'999',accessories:'0',other:'0'},costLabor:{mode:'gram',rate:'20'}}],fee_items:[{key:'shipping',amount:'6',payer:'assistant',status:'estimated'}],...extra});
|
||||
const snapshot=l=>Object.fromEntries(['orders','payments','expenses','movements','journal','audit','operations','meta','sync'].map(table=>[table,l.rows('SELECT * FROM '+table)]));
|
||||
function fixture(t){
|
||||
const l=new Ledger(':memory:');t.after(()=>l.close());
|
||||
const run=(p,fn,key=randomUUID())=>l.transact(key,actor,p,fn);
|
||||
run({stock:true},()=>l.stock({kind:'opening',date,pocket:'现货',grams:'10',note:'测试库存'},owner));
|
||||
const issue=(p=input(),key)=>run(p,()=>l.issueOrder(p,actor),key).id;
|
||||
const save=p=>run(p,()=>l.saveOrder(p,actor)).id;
|
||||
const act=(id,a,p={})=>run({id,a,p},()=>l.action(id,a,{date,...p},actor));
|
||||
return {l,run,issue,save,act};
|
||||
}
|
||||
test('一步开单同时收全款、核实费用和实际交付,确认利润且直接扣库存',t=>{
|
||||
const {l,issue,act}=fixture(t),id=issue(),o=l.detail(id);
|
||||
assert.equal(o.status,'delivered');assert.equal(o.delivered_date,date);assert.equal(o.total,216000);assert.equal(o.balance,0);
|
||||
assert.equal(o.payments.length,1);assert.equal(o.payments[0].amount,216000);assert.equal(o.payments[0].account,'助理支付宝');assert.equal(o.payments[0].date,date);
|
||||
assert.equal(o.goodsCost,202400);assert.equal(o.draftFees,0);assert.equal(o.pendingFees.length,0);assert.equal(o.estimatedProfit,13000);
|
||||
assert.equal(o.expenses.length,1);assert.equal(o.expenses[0].amount,600);assert.equal(o.fee_items[0].status,'recorded');assert.equal(o.profit,13000);assert.equal(o.ownerCost,202400);assert.equal(o.settlementDue,215400);
|
||||
const inv=l.inventory().find(r=>r.pocket==='现货');assert.equal(inv.mg,7800);assert.equal(inv.reserved,0);assert.equal(inv.available,7800);
|
||||
const report=l.report(date);assert.equal(report.sales,216000);assert.equal(report.expense,600);assert.equal(report.profit,13000);assert.equal(report.delivered,1);
|
||||
assert.throws(()=>act(id,'receipt',{amount:'2160',account:'助理支付宝',verified:true}),/待交付/);
|
||||
assert.throws(()=>act(id,'deliver',{verified:true}),/待交付/);assert.throws(()=>act(id,'fees',{revision:o.revision,verified:true,fee_items:[]}),/没有待核实/);
|
||||
const html=receipt(l.publicOrder(id));assert.ok(!html.includes('进货'));assert.ok(!html.includes('预计订单利润'));assert.ok(html.includes('支付宝'));
|
||||
});
|
||||
test('重复请求只开一单、收款和出库各一次,库存不足时单号与全部流水回滚',t=>{
|
||||
const {l,issue}=fixture(t),p=input(),key=randomUUID(),id=issue(p,key);
|
||||
assert.equal(issue(p,key),id);assert.equal(l.rows('SELECT * FROM orders').length,1);assert.equal(l.rows('SELECT * FROM payments').length,1);assert.equal(l.rows('SELECT * FROM expenses').length,1);
|
||||
assert.equal(l.rows("SELECT * FROM movements WHERE kind='sale'").length,1);assert.equal(l.rows('SELECT * FROM journal').length,1);
|
||||
const before=snapshot(l),number=l.paperNumber(date),tooMuch=input({lines:[{...p.lines[0],quantity:'20'}]});
|
||||
assert.throws(()=>issue(tooMuch),/库存不足/);assert.deepEqual(snapshot(l),before);assert.equal(l.paperNumber(date),number);
|
||||
assert.throws(()=>issue({...p,id,revision:l.detail(id).revision}),/不能直接改写/);
|
||||
});
|
||||
test('货品成本、克工费和附加成本缺项均不生成单据,未提交的附加成本不能当0',t=>{
|
||||
const {l,issue}=fixture(t),before=snapshot(l),number=l.paperNumber(date);
|
||||
const missingMaterial=input();missingMaterial.lines[0].costParts.material='';
|
||||
const missingLabor=input();missingLabor.lines[0].costLabor.rate='';
|
||||
const missingFee=input();missingFee.fee_items[0].amount='';
|
||||
const omittedFee=input();omittedFee.lines[0].charges=[{id:randomUUID(),name:'编绳',amount:'10'}];
|
||||
for(const [p,error] of [[missingMaterial,/商品1的料费成本/],[missingLabor,/商品1的进货工费/],[missingFee,/附加成本:快递费/],[omittedFee,/商品1的编绳/]]){
|
||||
assert.throws(()=>issue(p),error);assert.deepEqual(snapshot(l),before);assert.equal(l.paperNumber(date),number);
|
||||
}
|
||||
});
|
||||
test('交付后取消改走退货,退款从开单收款账户冲回,已发生费用保留',t=>{
|
||||
const {l,issue,act}=fixture(t),id=issue();
|
||||
assert.throws(()=>act(id,'cancel',{reason:'测试取消'}),/已交付/);
|
||||
act(id,'return',{reason:'测试退货',verified:true});assert.equal(l.detail(id).balance,-216000);assert.equal(l.detail(id).profit,-600);assert.equal(l.inventory().find(r=>r.pocket==='现货').mg,10000);
|
||||
assert.throws(()=>act(id,'refund',{amount:'2160',account:'助理微信',verified:true}),/原收款账户/);
|
||||
act(id,'refund',{amount:'2160',account:'助理支付宝',verified:true});assert.equal(l.detail(id).netReceived,0);assert.equal(l.detail(id).expenses.length,1);
|
||||
});
|
||||
test('旧草稿可生成已交付单并沿用纸号,新开单不自动处理旧定金单',t=>{
|
||||
const {l,save,issue,act}=fixture(t),p=input({fee_items:[{key:'shipping',amount:'6',payer:'assistant'}]});
|
||||
const id=save(p),paper=l.detail(id).paper_number;
|
||||
issue({...p,id,revision:l.detail(id).revision});assert.equal(l.detail(id).paper_number,paper);assert.equal(l.detail(id).status,'delivered');assert.equal(l.detail(id).payments.length,1);assert.equal(l.detail(id).expenses.length,1);
|
||||
const old=save({...p,fee_items:[]});act(old,'confirm');act(old,'receipt',{amount:'300',account:'助理微信',verified:true});const before=l.detail(old);
|
||||
issue();assert.deepEqual(l.detail(old),before);
|
||||
assert.throws(()=>act(old,'complete',{verified:true}),/未收齐/);assert.deepEqual(l.detail(old),before);
|
||||
});
|
||||
test('旧已付款订单明确完成后才核实费用并交付,同操作号重试和再次完成不重复记账',t=>{
|
||||
const {l,run,save,act}=fixture(t),p=input(),id=save(p);act(id,'confirm');act(id,'receipt',{amount:'2160',account:'助理支付宝',verified:true});
|
||||
const before=snapshot(l);assert.throws(()=>act(id,'complete'),/核实费用/);assert.deepEqual(snapshot(l),before);
|
||||
assert.throws(()=>act(id,'complete',{revision:l.detail(id).revision-1,verified:true}),/新变动/);assert.deepEqual(snapshot(l),before);
|
||||
const data={date,revision:l.detail(id).revision,verified:true},key=randomUUID(),complete=()=>run(data,()=>l.action(id,'complete',data,actor),key);
|
||||
complete();complete();const o=l.detail(id);assert.equal(o.status,'delivered');assert.equal(o.payments.length,1);assert.equal(o.expenses.length,1);assert.equal(o.profit,13000);assert.equal(o.pendingFees.length,0);assert.equal(l.inventory()[0].mg,7800);
|
||||
assert.throws(()=>act(id,'complete',{verified:true}),/只有待交付/);assert.equal(l.rows('SELECT * FROM journal').length,1);
|
||||
});
|
||||
test('旧单费用已记账或旧版无status时不重复支出,空成本和空费用仍阻止完成',t=>{
|
||||
const {l,save,act}=fixture(t),paid=save(input());act(paid,'confirm',{feesVerified:true});act(paid,'receipt',{amount:'2160',account:'助理支付宝',verified:true});
|
||||
const oldFees=l.rawOrder(paid).fee_items.map(({status,...f})=>f);l.run('UPDATE orders SET fee_items=? WHERE id=?',JSON.stringify(oldFees),paid);
|
||||
act(paid,'complete',{verified:true});assert.equal(l.detail(paid).expenses.length,1);assert.equal(l.detail(paid).profit,13000);
|
||||
const p=input();p.lines[0].costParts.material='';p.fee_items[0].amount='';const missing=save(p);act(missing,'confirm');act(missing,'receipt',{amount:'2160',account:'助理支付宝',verified:true});
|
||||
let before=snapshot(l);assert.throws(()=>act(missing,'complete',{verified:true}),/料费成本/);assert.deepEqual(snapshot(l),before);
|
||||
act(missing,'cost',{costs:[{parts:{material:'1980',labor:'0',accessories:'0',other:'0'},costLabor:{mode:'gram',rate:'20'}}]});
|
||||
before=snapshot(l);assert.throws(()=>act(missing,'complete',{verified:true}),/附加成本/);assert.deepEqual(snapshot(l),before);
|
||||
});
|
||||
test('新单后置出库失败和旧单费用日期冲突时,收款、费用、库存与订单原状一起回滚',t=>{
|
||||
const {l,issue,save,act}=fixture(t),before=snapshot(l);
|
||||
assert.throws(()=>issue(input({date:'2026-10-16'})),/2026-10-16库存不足/);assert.deepEqual(snapshot(l),before);
|
||||
const id=save(input({date:'2026-10-16',fees_date:date}));act(id,'confirm',{date:'2026-10-16'});act(id,'receipt',{date:'2026-10-16',amount:'2160',account:'助理支付宝',verified:true});
|
||||
const legacyBefore=snapshot(l);assert.throws(()=>act(id,'complete',{date:'2026-10-16',verified:true}),/交付日期不能早于/);assert.deepEqual(snapshot(l),legacyBefore);
|
||||
});
|
||||
test('HTTP开单接口受登录和CSRF保护,并发重试只记一次交付,重启后保留',async t=>{
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'maimai-paid-http-')),app=createApp({mode:'demo',dataDir:dir,feishuConfig:{enabled:false}});
|
||||
await new Promise(r=>app.server.listen(0,'127.0.0.1',r));
|
||||
t.after(async()=>{await new Promise(r=>app.server.close(r));app.ledger.close();fs.rmSync(dir,{recursive:true,force:true});});
|
||||
const base='http://127.0.0.1:'+app.server.address().port;let cookie='';
|
||||
const call=(route,data,key=randomUUID(),origin=base)=>fetch(base+route,{method:data?'POST':'GET',headers:{Cookie:cookie,...(data?{'Content-Type':'application/json',Origin:origin,'X-Requested-With':'maimai-ledger','Idempotency-Key':key}:{})},...(data?{body:JSON.stringify(data)}:{})});
|
||||
const p=input(),before=app.ledger.rows('SELECT * FROM orders').length;
|
||||
assert.equal((await call('/api/orders/issue',p)).status,401);
|
||||
const login=await call('/api/demo-login',{role:'assistant'});cookie=login.headers.get('set-cookie').split(';')[0];
|
||||
assert.equal((await call('/api/orders/issue',p,randomUUID(),'https://invalid.example')).status,403);
|
||||
const key=randomUUID(),rs=await Promise.all([call('/api/orders/issue',p,key),call('/api/orders/issue',p,key)]);assert.deepEqual(rs.map(r=>r.status),[200,200]);
|
||||
const a=await rs[0].json(),b=await rs[1].json();assert.equal(a.id,b.id);
|
||||
const detail=await (await call('/api/orders/'+a.id)).json();assert.equal(detail.status,'delivered');assert.equal(detail.payments.length,1);assert.equal(detail.netReceived,216000);assert.equal(detail.expenses.length,1);assert.equal(detail.profit,13000);assert.equal(app.ledger.rows('SELECT * FROM orders').length,before+1);
|
||||
const reloaded=new Ledger(path.join(dir,'ledger.sqlite'));try{assert.equal(reloaded.detail(a.id).status,'delivered');assert.equal(reloaded.detail(a.id).payments.length,1);assert.equal(reloaded.detail(a.id).profit,13000);assert.equal(reloaded.rows("SELECT * FROM movements WHERE order_id=? AND kind='sale'",a.id).length,1);}finally{reloaded.close();}
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict');
|
||||
const {randomUUID}=require('node:crypto'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
|
||||
const {Ledger,today}=require('../ledger'),{createApp}=require('../server');
|
||||
const owner={id:'people-owner',name:'测试麦麦',role:'owner'},assistant={id:'people-assistant',name:'测试助理',role:'assistant'};
|
||||
const D='2026-09-30',D2='2026-10-01',D3='2026-10-02';
|
||||
function fixture(t){
|
||||
const ledger=new Ledger(':memory:');t.after(()=>ledger.close());
|
||||
const save=(date,count,revision,actor=owner,key=randomUUID())=>{
|
||||
const input={date,count,revision};return ledger.transact(key,actor,input,()=>ledger.savePeopleCount(input,actor));
|
||||
};
|
||||
return {ledger,save};
|
||||
}
|
||||
function contents(ledger,tables){return JSON.stringify(tables.map(table=>[table,ledger.rows('SELECT * FROM "'+table+'"')]));}
|
||||
function allContents(ledger){return contents(ledger,ledger.rows("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").map(row=>row.name));}
|
||||
|
||||
test('每日人数区分未登记与0,按日期保存总数而非累加,双方修改保留版本和审计',t=>{
|
||||
const f=fixture(t);assert.deepEqual(f.ledger.peopleCount(D),{date:D,count:null,revision:0});
|
||||
assert.deepEqual(f.save(D,0,0,assistant),{date:D,count:0,revision:1});const initial=f.ledger.one('SELECT * FROM daily_people_counts WHERE date=?',D);
|
||||
assert.equal(initial.actor,assistant.name);assert.equal(initial.revision,1);assert.equal(initial.count,0);
|
||||
assert.deepEqual(f.save(D,15,1,owner),{date:D,count:15,revision:2});
|
||||
assert.deepEqual(f.save(D,4,2,assistant),{date:D,count:4,revision:3});assert.equal(f.ledger.rows('SELECT * FROM daily_people_counts').length,1);
|
||||
const record=f.ledger.one('SELECT * FROM daily_people_counts WHERE date=?',D);assert.equal(record.created,initial.created);assert.ok(record.updated>=initial.updated);assert.equal(record.actor,assistant.name);
|
||||
assert.deepEqual(f.ledger.peopleCount(D),{date:D,count:4,revision:3});assert.deepEqual(f.ledger.peopleCount(D2),{date:D2,count:null,revision:0});
|
||||
const audits=f.ledger.rows("SELECT * FROM audit WHERE entity=? ORDER BY id",'people-count:'+D);assert.equal(audits.length,3);
|
||||
assert.deepEqual(audits.map(row=>JSON.parse(row.detail).previousCount),[null,0,15]);assert.deepEqual(audits.map(row=>JSON.parse(row.detail).count),[0,15,4]);
|
||||
});
|
||||
|
||||
test('人数拒绝空白、负数、非整数、超限、非法日期和非法版本,失败不改已有记录',t=>{
|
||||
const f=fixture(t),before=allContents(f.ledger);
|
||||
for(const count of ['',undefined,null,' ',true,false,[],{},'-1','1.5','1.0','1e2','NaN',Infinity,NaN,1000001,Number.MAX_SAFE_INTEGER+1])assert.throws(()=>f.save(D,count,0));
|
||||
for(const date of ['',undefined,null,'2026-02-30','2026-9-30','1999-12-31','2099-01-01'])assert.throws(()=>f.save(date,1,0));
|
||||
for(const revision of [undefined,null,-1,1.5,'0',Number.MAX_SAFE_INTEGER+1])assert.throws(()=>f.save(D,1,revision));
|
||||
assert.throws(()=>f.ledger.savePeopleCount(null,owner));assert.throws(()=>f.ledger.savePeopleCount([],owner));assert.throws(()=>f.save(D,1,0,{...owner,role:'customer'}),/麦麦或助理账号/);
|
||||
assert.equal(allContents(f.ledger),before);assert.deepEqual(f.save(D,'1000000',0),{date:D,count:1000000,revision:1});
|
||||
const existing=allContents(f.ledger);assert.throws(()=>f.save(D,9,0),{status:409});assert.throws(()=>f.save(D2,9,1),{status:409});assert.equal(allContents(f.ledger),existing);
|
||||
});
|
||||
|
||||
test('人数操作幂等只保存一次,旧版本不能覆盖新记录,操作号内容或用户改变会冲突',t=>{
|
||||
const f=fixture(t),key=randomUUID(),first=f.save(D,7,0,assistant,key);assert.deepEqual(f.save(D,7,0,assistant,key),first);
|
||||
assert.equal(f.ledger.peopleCount(D).revision,1);assert.equal(f.ledger.rows('SELECT * FROM audit').length,1);assert.equal(f.ledger.rows('SELECT * FROM operations').length,1);
|
||||
assert.throws(()=>f.save(D,8,0,assistant,key),{status:409});assert.throws(()=>f.save(D,7,0,owner,key),{status:409});
|
||||
f.save(D,12,1,owner);const before=allContents(f.ledger);assert.throws(()=>f.save(D,3,1,assistant),{status:409});assert.equal(allContents(f.ledger),before);
|
||||
assert.deepEqual(f.ledger.peopleCount(D),{date:D,count:12,revision:2});
|
||||
});
|
||||
|
||||
test('日期范围人数独立于订单搜索状态,零人数为已登记,日报透传同一聚合',t=>{
|
||||
const f=fixture(t);f.save(D,3,0);f.save(D2,0,0);f.save(D3,4,0);
|
||||
const expected={from:D,date:D3,total:7,recordedDays:3};
|
||||
for(const query of [{},{q:'不存在'},{status:'after_sale'},{status:'draft'},{q:'售后',status:'delivered'}]){
|
||||
const b=f.ledger.orderBook({from:D,date:D3,...query});assert.deepEqual(b.peopleCount,expected);assert.equal(b.summary.recordCount,0);assert.equal(b.summary.profit,0);
|
||||
}
|
||||
assert.deepEqual(f.ledger.reportByOrderDate(D3,D).peopleCount,expected);
|
||||
assert.deepEqual(f.ledger.orderBook({date:D2}).peopleCount,{from:D2,date:D2,total:0,recordedDays:1});
|
||||
assert.deepEqual(f.ledger.orderBook({date:'2026-09-29'}).peopleCount,{from:'2026-09-29',date:'2026-09-29',total:0,recordedDays:0});
|
||||
assert.deepEqual(f.ledger.orderBook({from:'2026-09-01',date:D}).peopleCount,{from:'2026-09-01',date:D,total:3,recordedDays:1});
|
||||
assert.deepEqual(f.ledger.orderBook({from:D2,date:D3}).peopleCount,{from:D2,date:D3,total:4,recordedDays:2});
|
||||
});
|
||||
|
||||
test('人数登记修改不改变销售成本利润、收款、库存、财务版本、核对快照或同步',t=>{
|
||||
const f=fixture(t),input={date:D,customer:'合成客户',lines:[{name:'合成商品',unit:'g',quantity:'1',pocket:'',payer:'owner',cost:'80',sale:'100'}],fee_items:[]};
|
||||
f.ledger.transact(randomUUID(),owner,input,()=>f.ledger.issueOrder(input,owner));f.ledger.transact(randomUUID(),owner,{date:D},()=>f.ledger.closeDay(D,owner,'orderDate'));
|
||||
const tables=['orders','payments','expenses','after_sales','settlements','movements','journal','meta','sync','closes','inventory_snapshots'],before=contents(f.ledger,tables),r=f.ledger.reportByOrderDate(D),book=f.ledger.orderBook({date:D});
|
||||
f.save(D,0,0);f.save(D,20,1,assistant);f.save(D2,9,0);
|
||||
assert.equal(contents(f.ledger,tables),before);const after=f.ledger.reportByOrderDate(D);
|
||||
assert.equal(after.reportRevision,r.reportRevision);assert.equal(after.close.stale,false);assert.equal(f.ledger.report(D).close.stale,false);assert.equal(f.ledger.inventorySnapshot(D).stale,false);
|
||||
assert.deepEqual(after.summary,r.summary);assert.deepEqual(after.orderRows,r.orderRows);assert.deepEqual(after.accounts,r.accounts);assert.deepEqual(after.payerCosts,r.payerCosts);
|
||||
assert.deepEqual(f.ledger.orderBook({date:D}).summary,book.summary);assert.deepEqual(after.peopleCount,{from:D,date:D,total:20,recordedDays:1});
|
||||
const readBefore=allContents(f.ledger),changes=f.ledger.one('SELECT total_changes() AS count').count;
|
||||
f.ledger.peopleCount(D);f.ledger.peopleCount(D3);f.ledger.peopleCountSummary(D3,D);f.ledger.orderBook({date:D});f.ledger.reportByOrderDate(D);assert.equal(allContents(f.ledger),readBefore);assert.equal(f.ledger.one('SELECT total_changes() AS count').count,changes);
|
||||
});
|
||||
|
||||
test('旧库增量建人数表,0与版本重启后保留,重试不再覆盖新总人数',t=>{
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'maimai-people-persist-')),filename=path.join(dir,'ledger.sqlite');let ledger=new Ledger(filename);
|
||||
t.after(()=>{try{ledger.close();}catch{}fs.rmSync(dir,{recursive:true,force:true});});
|
||||
ledger.setMeta('synthetic-existing',7);ledger.db.exec('DROP TABLE daily_people_counts');ledger.close();ledger=new Ledger(filename);
|
||||
assert.equal(ledger.meta('synthetic-existing'),7);assert.deepEqual(ledger.peopleCount(D),{date:D,count:null,revision:0});
|
||||
const value={date:D,count:0,revision:0},key=randomUUID(),result=ledger.transact(key,owner,value,()=>ledger.savePeopleCount(value,owner));ledger.close();ledger=new Ledger(filename);
|
||||
assert.deepEqual(ledger.peopleCount(D),{date:D,count:0,revision:1});assert.deepEqual(ledger.transact(key,owner,value,()=>ledger.savePeopleCount(value,owner)),result);
|
||||
const changed={date:D,count:11,revision:1};ledger.transact(randomUUID(),assistant,changed,()=>ledger.savePeopleCount(changed,assistant));
|
||||
assert.deepEqual(ledger.transact(key,owner,value,()=>ledger.savePeopleCount(value,owner)),result);assert.deepEqual(ledger.peopleCount(D),{date:D,count:11,revision:2});assert.deepEqual(ledger.peopleCount(D2),{date:D2,count:null,revision:0});
|
||||
});
|
||||
|
||||
test('HTTP人数须登录与CSRF,双方可改,相同版本并发只成功一笔,GET不补造未登记记录',async t=>{
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'maimai-people-http-')),app=createApp({mode:'demo',dataDir:dir,ledger:new Ledger(':memory:'),feishuConfig:{enabled:false}});
|
||||
await new Promise(resolve=>app.server.listen(0,'127.0.0.1',resolve));
|
||||
t.after(async()=>{await new Promise(resolve=>app.server.close(resolve));app.ledger.close();fs.rmSync(dir,{recursive:true,force:true});});
|
||||
const base='http://127.0.0.1:'+app.server.address().port;let cookie='';
|
||||
const call=(route,data,key=randomUUID(),origin=base)=>fetch(base+route,{method:data?'POST':'GET',headers:{...(cookie?{Cookie:cookie}:{}),...(data?{'Content-Type':'application/json',Origin:origin,'X-Requested-With':'maimai-ledger','Idempotency-Key':key}:{} )},...(data?{body:JSON.stringify(data)}:{})});
|
||||
assert.equal((await call('/api/people-count?date='+D)).status,401);assert.equal((await call('/api/people-count',{date:D,count:0,revision:0})).status,401);
|
||||
let login=await call('/api/demo-login',{role:'assistant'});cookie=login.headers.get('set-cookie').split(';')[0];
|
||||
assert.deepEqual(await (await call('/api/people-count')).json(),{date:today(),count:null,revision:0});assert.equal(app.ledger.rows('SELECT * FROM daily_people_counts').length,0);
|
||||
for(const date of ['2099-01-01','2026-02-30',''])assert.equal((await call('/api/people-count?date='+date)).status,400);
|
||||
assert.equal((await call('/api/people-count',{date:D,count:0,revision:0},randomUUID(),'https://invalid.example')).status,403);
|
||||
assert.equal((await call('/api/people-count',{date:D,count:1})).status,400);assert.equal((await call('/api/people-count',{date:D,count:1.5,revision:0})).status,400);
|
||||
const key=randomUUID(),retries=await Promise.all([call('/api/people-count',{date:D,count:0,revision:0},key),call('/api/people-count',{date:D,count:0,revision:0},key)]);assert.deepEqual(retries.map(r=>r.status),[200,200]);const first=await retries[0].json();assert.deepEqual(await retries[1].json(),first);assert.deepEqual(first,{date:D,count:0,revision:1});
|
||||
const writes=await Promise.all([call('/api/people-count',{date:D,count:5,revision:1}),call('/api/people-count',{date:D,count:7,revision:1})]);assert.deepEqual(writes.map(r=>r.status).sort(),[200,409]);
|
||||
const saved=await writes.find(r=>r.status===200).json();assert.equal(saved.revision,2);assert.deepEqual(await (await call('/api/people-count?date='+D)).json(),saved);
|
||||
assert.equal(app.ledger.rows('SELECT * FROM daily_people_counts').length,1);assert.equal(app.ledger.rows("SELECT * FROM audit WHERE entity=?",'people-count:'+D).length,2);
|
||||
login=await call('/api/demo-login',{role:'owner'});cookie=login.headers.get('set-cookie').split(';')[0];const ownerWrite=await call('/api/people-count',{date:D,count:0,revision:2});assert.equal(ownerWrite.status,200);assert.deepEqual(await ownerWrite.json(),{date:D,count:0,revision:3});
|
||||
assert.equal((await call('/api/people-count',{date:D,count:20,revision:2})).status,409);
|
||||
const book=await (await call('/api/order-book?date='+D+'&q=none&status=after_sale')).json();assert.deepEqual(book.peopleCount,{from:D,date:D,total:0,recordedDays:1});
|
||||
const report=await (await call('/api/report?date='+D+'&basis=orderDate')).json();assert.deepEqual(report.peopleCount,book.peopleCount);assert.equal(report.profit,0);
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict');
|
||||
const {receipt,uppercaseMoney,settings}=require('../printing');
|
||||
const sample={number:'MM-INTERNAL-UNIQUE',paper_number:'20261017003',date:'2026-10-17',customer:'示例客户',salesperson:'助理',status:'delivered',total:216750,discount:1000,received:216750,refunded:0,balance:0,paymentMethods:['支付宝'],note:'客户备注',lines:[{name:'足金999',unit:'g',quantity:2200,pricingMode:'auto',goldPrice:94000,laborRate:4500,laborMode:'gram',baseSale:216700,sale:217750,charges:[{name:'编绳',amount:1050}]}]};
|
||||
test('人民币大写按整数分覆盖零、角分、跨万亿及连续零',()=>{
|
||||
for(const [value,text] of [[0,'零元整'],[1,'零元壹分'],[10,'零元壹角'],[105,'壹元零伍分'],[115,'壹元壹角伍分'],[1000,'壹拾元整'],[216750,'贰仟壹佰陆拾柒元伍角'],[203400,'贰仟零叁拾肆元整'],[1000000,'壹万元整'],[1000100,'壹万零壹元整'],[1001000,'壹万零壹拾元整'],[100000001,'壹佰万元零壹分'],[10001000101,'壹亿零壹万零壹元零壹分'],[100000000000,'壹拾亿元整'],[100000000000000,'壹兆元整']])assert.equal(uppercaseMoney(value),text,String(value));
|
||||
for(const invalid of [-1,1.1,NaN,Infinity,'100',Number.MAX_SAFE_INTEGER+1])assert.throws(()=>uppercaseMoney(invalid));
|
||||
});
|
||||
test('客户单只保留纸单号、最终金额大小写和经办人,不显示优惠与收退款汇总',()=>{
|
||||
const html=receipt(sample);
|
||||
for(const hidden of ['系统单号','MM-INTERNAL-UNIQUE','整单优惠','累计收款','累计退款','客户确认','待收款','待退款'])assert.ok(!html.includes(hidden),hidden);
|
||||
for(const visible of ['纸单号:20261017003','合计金额','¥2167.50','贰仟壹佰陆拾柒元伍角','经办人:助理','附加:编绳','10.50','支付宝'])assert.ok(html.includes(visible),visible);
|
||||
assert.equal((html.match(/<section class="sheet /g)||[]).length,1);
|
||||
});
|
||||
test('正常客户单不标注预订或交付状态,草稿、取消和退货保留提示',()=>{
|
||||
for(const mode of ['full','overlay'])for(const status of ['confirmed','delivered']){
|
||||
const html=receipt({...sample,status},{},mode);
|
||||
for(const hidden of ['预订单','待交付','销售单 · 已交付'])assert.ok(!html.includes(hidden),status+' '+hidden);
|
||||
assert.ok(html.includes('<div class="meta secondary"><span>收款方式:支付宝</span></div>'));
|
||||
}
|
||||
for(const [status,notice] of [['draft','草稿 · 未确认'],['returned','退货单 · 已退货'],['cancelled','取消单 · 已取消']]){
|
||||
const html=receipt({...sample,status});assert.ok(html.includes(notice),status);assert.ok(html.includes('收款方式:支付宝'));
|
||||
}
|
||||
});
|
||||
test('注意事项按最新要求去掉维修承诺,取消退货仍注明原单金额',()=>{
|
||||
const html=receipt(sample);
|
||||
for(const text of ['国家法定机构检测合格','如无质量问题,概不退换','票据、标签、证书','珠宝首饰保养须知','避免接触水银、铅等金属','漂白剂、涂改液','最好每天清水清洗','首饰质量监督检验中心鉴定','凭本票无条件退换货'])assert.ok(html.includes(text),text);
|
||||
assert.ok(!html.includes('免费维修'));assert.ok(!html.includes('仅收取配件费用'));
|
||||
for(const status of ['returned','cancelled'])assert.ok(receipt({...sample,status}).includes('原单成交额'));
|
||||
});
|
||||
test('单页模板接受紧凑纸张和长备注,所有商品与收费完整保留',()=>{
|
||||
const lines=Array.from({length:60},(_,i)=>({...sample.lines[0],name:'测试商品'+i,charges:[{name:'附加服务'+i,amount:100}]}));
|
||||
const html=receipt({...sample,lines,note:'长备注'.repeat(80)},settings({width:241,height:140,rows:12,rowHeight:16}));
|
||||
assert.equal((html.match(/<section class="sheet /g)||[]).length,1);assert.ok(html.includes('测试商品59'));assert.ok(html.includes('附加服务59'));assert.ok(html.includes('长备注'.repeat(80)));assert.ok(!html.includes('overflow:hidden'));assert.ok(html.includes('/print.js'));
|
||||
for(const mode of ['full','overlay']){
|
||||
const printed=receipt({...sample,lines},{},mode);
|
||||
const numbers=[...printed.matchAll(/<tr><td>([^<]+)<\/td>/g)].map(m=>m[1]);
|
||||
assert.deepEqual(numbers,Array.from({length:120},(_,i)=>String(i+1)));
|
||||
assert.ok(!printed.includes('免费维修'));assert.ok(!printed.includes('仅收取配件费用'));
|
||||
}
|
||||
});
|
||||
|
||||
test('旧格式纸单号打印时去掉日期间隔符,保留账内原编号',()=>{
|
||||
const old={...sample,paper_number:'20261017-003'};const html=receipt(old);assert.ok(html.includes('纸单号:20261017003'));assert.ok(!html.includes('20261017-003'));assert.equal(old.paper_number,'20261017-003');
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),{randomUUID}=require('node:crypto');
|
||||
const Calc=require('../public/calculations'),{Ledger}=require('../ledger'),{receipt}=require('../printing');
|
||||
const actor={id:'labor-test',name:'测试麦麦',role:'owner'},date='2026-10-17';
|
||||
const line=(extra={})=>({name:'足金999',unit:'g',quantity:'2.2',pocket:'',payer:'owner',pricingMode:'manual',baseSale:'2167',costParts:{material:'1980',labor:'9999',accessories:'0',other:'0'},costLabor:{mode:'gram',rate:'20'},...extra});
|
||||
function fixture(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'maimai-purchase-labor-'));const l=new Ledger(path.join(dir,'ledger.sqlite'));t.after(()=>{l.close();fs.rmSync(dir,{recursive:true,force:true});});const run=(p,fn,key=randomUUID())=>l.transact(key,actor,p,fn);const save=(data={})=>run(data,()=>l.saveOrder({date,discount:'0',lines:[line()],...data},actor)).id;const act=(id,a,p={})=>run({id,a,p},()=>l.action(id,a,{date,...p},actor));return {l,run,save,act};}
|
||||
test('进货克工费按克重算总额;总工费直接使用,不跟销售工费混算',()=>{
|
||||
const a=Calc.purchaseCosts(line());assert.equal(a.parts.labor,4400);assert.equal(a.total,202400);assert.deepEqual(a.costLabor,{mode:'gram',rate:2000});
|
||||
const b=Calc.purchaseCosts(line({quantity:'3',costLabor:{mode:'total',rate:'999'},costParts:{material:'1980',labor:'45',accessories:'0',other:'0'}}));assert.equal(b.parts.labor,4500);assert.equal(b.total,202500);assert.deepEqual(b.costLabor,{mode:'total'});
|
||||
assert.equal(Calc.purchaseCosts(line({quantity:'3'})).parts.labor,6000);
|
||||
});
|
||||
test('进货工费整数分四舍五入,空白和0分别处理,拒绝非法单位与数据',()=>{
|
||||
assert.equal(Calc.purchaseCosts(line({quantity:'0.001',costLabor:{mode:'gram',rate:'5'}})).parts.labor,1);
|
||||
assert.equal(Calc.purchaseCosts(line({quantity:'0.001',costLabor:{mode:'gram',rate:'4'}})).parts.labor,0);
|
||||
assert.equal(Calc.purchaseCosts(line({costLabor:{mode:'gram',rate:''}})).total,null);assert.equal(Calc.purchaseCosts(line({costLabor:{mode:'gram',rate:'0'}})).parts.labor,0);
|
||||
for(const extra of [{unit:'件'},{quantity:'0'},{quantity:'2.2001'},{costLabor:{mode:'gram',rate:'-1'}},{costLabor:{mode:'gram',rate:'1.001'}},{costLabor:{mode:'bad'}},{quantity:'100000',costLabor:{mode:'gram',rate:'100000'}}])assert.throws(()=>Calc.purchaseCosts(line(extra)));
|
||||
});
|
||||
test('服务端重新计算工费,保存和再编辑不把总额乘第二次,改变克重跟着更新',t=>{
|
||||
const {l,save}=fixture(t),id=save();assert.equal(l.detail(id).goodsCost,202400);assert.equal(l.detail(id).lines[0].costParts.labor,4400);
|
||||
for(let i=0;i<2;i++)save({id,revision:l.detail(id).revision,lines:[line({costParts:{material:'1980',labor:'44',accessories:'0',other:'0'}})]});assert.equal(l.detail(id).goodsCost,202400);
|
||||
save({id,revision:l.detail(id).revision,lines:[line({quantity:'3'})]});assert.equal(l.detail(id).lines[0].costParts.labor,6000);assert.equal(l.detail(id).goodsCost,204000);
|
||||
});
|
||||
test('补录成本也支持两种方式,利润和退货用锁定总额,客户单不泄露进货工费',t=>{
|
||||
const {l,save,act}=fixture(t),id=save({lines:[line({costLabor:{mode:'gram',rate:''}})]});act(id,'confirm');
|
||||
act(id,'cost',{costs:[{parts:{material:'1980',labor:'7777',accessories:'0',other:'0'},costLabor:{mode:'gram',rate:'20'}}]});assert.equal(l.detail(id).goodsCost,202400);
|
||||
act(id,'cost',{costs:[{parts:{material:'1980',labor:'45',accessories:'0',other:'0'},costLabor:{mode:'total'}}]});assert.equal(l.detail(id).goodsCost,202500);
|
||||
act(id,'cost',{costs:[{parts:{material:'1980',labor:'7777',accessories:'0',other:'0'},costLabor:{mode:'gram',rate:'20'}}]});
|
||||
act(id,'receipt',{amount:'2167',account:'助理微信',verified:true});act(id,'deliver',{verified:true});assert.equal(l.detail(id).profit,14300);assert.throws(()=>act(id,'cost',{costs:[{}]}),/锁定/);
|
||||
const p=l.publicOrder(id),html=receipt(p);assert.ok(!JSON.stringify(p).includes('costLabor'));assert.ok(!html.includes('进货'));assert.ok(!html.includes('44.00'));
|
||||
act(id,'return',{reason:'测试退货',verified:true});assert.equal(l.detail(id).profit,0);
|
||||
});
|
||||
test('历史总工费、按件商品和旧版补录接口保持原金额',t=>{
|
||||
const {l,save,act}=fixture(t);const parts={material:'100',labor:'30',accessories:'0',other:'0'};const id=save({lines:[line({unit:'件',quantity:'2',costLabor:undefined,costParts:parts})]});assert.equal(l.detail(id).goodsCost,13000);assert.deepEqual(l.detail(id).lines[0].costLabor,{mode:'total'});act(id,'confirm');act(id,'cost',{costs:[{...parts,labor:'35'}]});assert.equal(l.detail(id).goodsCost,13500);
|
||||
});
|
||||
@@ -0,0 +1,162 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict');
|
||||
const {randomUUID}=require('node:crypto'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
|
||||
const {Ledger,POCKETS,ACTIVE_POCKETS,today}=require('../ledger');
|
||||
const {createApp}=require('../server');
|
||||
const owner={id:'snapshot-owner',name:'测试麦麦',role:'owner'},assistant={id:'snapshot-assistant',name:'测试助理',role:'assistant'};
|
||||
const offset=n=>new Date(Date.parse(today()+'T00:00:00Z')+n*86400000).toISOString().slice(0,10);
|
||||
const D0=offset(-3),D1=offset(-2),D2=offset(-1),D3=today();
|
||||
const mg=(rows,pocket='现货')=>rows.find(r=>r.pocket===pocket).mg;
|
||||
function fixture(t){
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'maimai-stock-snapshots-')),filename=path.join(dir,'ledger.sqlite'),l=new Ledger(filename);
|
||||
t.after(()=>{try{l.close();}catch{}fs.rmSync(dir,{recursive:true,force:true});});
|
||||
const run=(payload,fn,actor=assistant,key=randomUUID())=>l.transact(key,actor,payload,fn);
|
||||
const stock=(input={},actor=assistant)=>{const payload={kind:'increase',date:D0,pocket:'现货',grams:'10.000',...input};return run(payload,()=>l.stock(payload,actor),actor);};
|
||||
const review=(date=D3,actor=owner,key=randomUUID())=>{const payload={date,verified:true,revision:l.inventoryRevision(date)};return run(payload,()=>l.reviewInventory(payload,actor),actor,key);};
|
||||
const save=(pocket='现货')=>{const payload={date:D0,lines:[{name:'合成测试商品',unit:'g',quantity:'1.000',pocket,payer:'owner',cost:'1',sale:'2'}],fee_items:[]};return run(payload,()=>l.saveOrder(payload,assistant)).id;};
|
||||
const act=(id,action,input={})=>{const payload={date:D0,...input};return run({id,action,...payload},()=>l.action(id,action,payload,assistant));};
|
||||
return {l,dir,filename,run,stock,review,save,act};
|
||||
}
|
||||
|
||||
test('打开旧库和只读查询不补造昨日快照,也不将财务快照当成库存复核',t=>{
|
||||
const {l,filename,stock}=fixture(t);stock();
|
||||
l.run('INSERT INTO closes VALUES (?,?,?,?,0)',D2,JSON.stringify({inventory:l.inventory(D2)}),owner.name,new Date().toISOString());
|
||||
l.close();const reopened=new Ledger(filename);t.after(()=>reopened.close());
|
||||
const status=reopened.inventoryStatus(owner);
|
||||
assert.equal(status.yesterdayDate,D2);assert.equal(status.yesterday,null);assert.equal(status.todaySnapshot,null);assert.equal(mg(status.current),10000);
|
||||
assert.deepEqual(status.pockets,ACTIVE_POCKETS);assert.equal(status.current.length,5);assert.equal(reopened.inventory().length,8);
|
||||
assert.deepEqual(reopened.inventorySnapshots().snapshots,[]);assert.equal(reopened.rows('SELECT * FROM inventory_snapshots').length,0);
|
||||
});
|
||||
|
||||
test('同一日期只保留最新复核,其他日期保留,历史读取使用已存数值',t=>{
|
||||
const {l,stock,review}=fixture(t);stock();
|
||||
const first=review(D1).snapshot;assert.equal(mg(first.inventory),10000);
|
||||
stock({date:D2,grams:'1.000'});review(D2);stock({date:D1,grams:'0.001'});
|
||||
assert.equal(mg(l.inventorySnapshot(D1).inventory),10000);assert.equal(l.inventorySnapshot(D1).stale,true);assert.equal(l.inventorySnapshot(D2).stale,true);
|
||||
const replaced=review(D1).snapshot;assert.equal(mg(replaced.inventory),10001);assert.equal(replaced.created,first.created);assert.equal(replaced.stale,false);assert.notEqual(replaced.revision,first.revision);
|
||||
const history=l.inventorySnapshots({from:D1,date:D2}).snapshots;
|
||||
assert.deepEqual(history.map(s=>s.date),[D2,D1]);assert.equal(history.length,2);assert.equal(mg(history[0].inventory),11000);assert.equal(history[0].stale,true);
|
||||
assert.equal(l.rows('SELECT * FROM inventory_snapshots').length,2);assert.equal(l.inventorySnapshot(D0),null);
|
||||
});
|
||||
|
||||
test('助理可按正数三位克重登记增减和平移,备注与采购金额均可空',t=>{
|
||||
const {l,stock}=fixture(t);stock({grams:'1.234'});stock({kind:'decrease',grams:'0.001'});
|
||||
const {group}=stock({kind:'transfer',grams:'0.123',to:'金料'});
|
||||
assert.equal(mg(l.inventory()),1110);assert.equal(mg(l.inventory(),'金料'),123);assert.equal(l.inventory().reduce((s,r)=>s+r.mg,0),1233);
|
||||
const pair=l.rows('SELECT * FROM movements WHERE group_id=?',group);
|
||||
assert.equal(pair.length,2);assert.equal(pair[0].mg+pair[1].mg,0);assert.ok(pair.every(r=>r.date===D0&&r.actor===assistant.name&&r.note===''&&r.purchase_cost===null));
|
||||
stock({kind:'purchase',pocket:'找金',grams:'0.001'});assert.equal(mg(l.inventory(),'找金'),1);
|
||||
stock({pocket:'君宝汇',grams:'0.001',note:'实物交接留档'});assert.equal(l.rows("SELECT note FROM movements WHERE pocket='君宝汇'")[0].note,'实物交接留档');
|
||||
});
|
||||
|
||||
test('新的增减平移动作拒绝负数、零、超精度与无效日期',t=>{
|
||||
const {l,stock}=fixture(t);stock();const count=l.rows('SELECT * FROM movements').length;
|
||||
for(const kind of ['increase','decrease','transfer'])for(const grams of ['-1','0','0.000','0.0001','NaN','1e2','',null])assert.throws(()=>stock({kind,grams,to:'金料'}),/克重/);
|
||||
assert.throws(()=>stock({kind:'transfer',grams:'0.001',to:'现货'}),/不能相同/);
|
||||
assert.throws(()=>stock({date:'2099-01-01'}),/业务日期/);assert.throws(()=>stock({date:'2026-02-30'}),/业务日期/);
|
||||
assert.equal(l.rows('SELECT * FROM movements').length,count);
|
||||
});
|
||||
|
||||
test('助理不能开账、旧调整或保存复核,老板复核须明确确认且版本一致',t=>{
|
||||
const {l,stock,review}=fixture(t);
|
||||
assert.throws(()=>stock({kind:'opening'}),e=>e.status===403);assert.throws(()=>stock({kind:'adjustment'}),e=>e.status===403);
|
||||
stock();assert.throws(()=>review(D3,assistant),e=>e.status===403);
|
||||
assert.throws(()=>l.reviewInventory({date:D3,revision:l.inventoryRevision(D3)},owner),/先核对/);
|
||||
assert.throws(()=>l.reviewInventory({date:D3,verified:true},owner),e=>e.status===409);
|
||||
const payload={date:D3,verified:true,revision:l.inventoryRevision(D3)};
|
||||
stock({grams:'0.001',date:D3});
|
||||
assert.throws(()=>l.reviewInventory(payload,owner),e=>e.status===409);assert.equal(l.inventorySnapshot(D3),null);
|
||||
const current=l.inventoryRevision(D3);stock({grams:'0.001',date:D3});stock({kind:'decrease',grams:'0.001',date:D3});
|
||||
assert.notEqual(l.inventoryRevision(D3),current);assert.throws(()=>l.reviewInventory({...payload,revision:current},owner),e=>e.status===409);
|
||||
});
|
||||
|
||||
test('禁止历史负库存和消耗订单占用,失败不改流水或快照状态',t=>{
|
||||
const {l,stock,review,save,act}=fixture(t);stock({date:D1,grams:'1.000'});review(D3);
|
||||
assert.throws(()=>stock({kind:'decrease',date:D0,grams:'0.001'}),/库存不足/);
|
||||
const id=save();act(id,'confirm');
|
||||
const before=l.rows('SELECT * FROM movements'),revision=l.inventoryRevision(D3);
|
||||
assert.throws(()=>stock({kind:'decrease',date:D1,grams:'0.001'}),/可用库存不足/);
|
||||
assert.throws(()=>stock({kind:'transfer',date:D1,grams:'0.001',to:'金料'}),/可用库存不足/);
|
||||
assert.deepEqual(l.rows('SELECT * FROM movements'),before);assert.equal(l.inventoryRevision(D3),revision);assert.equal(l.inventorySnapshot(D3).stale,false);
|
||||
});
|
||||
|
||||
test('平移目标写入失败时两边、过期标记与审计一起回滚',t=>{
|
||||
const {l,stock,review}=fixture(t);stock();review(D3);
|
||||
const count=l.rows('SELECT * FROM movements').length,audits=l.rows('SELECT * FROM audit').length,revision=l.inventoryRevision(D3);
|
||||
l.db.exec("CREATE TRIGGER reject_transfer_target BEFORE INSERT ON movements WHEN NEW.kind='transfer' AND NEW.pocket='金料' BEGIN SELECT RAISE(ABORT,'合成测试拒绝目标'); END;");
|
||||
assert.throws(()=>l.stock({kind:'transfer',date:D3,pocket:'现货',to:'金料',grams:'0.001'},assistant),/拒绝目标/);
|
||||
assert.equal(l.rows('SELECT * FROM movements').length,count);assert.equal(l.rows('SELECT * FROM audit').length,audits);assert.equal(mg(l.inventory()),10000);assert.equal(mg(l.inventory(),'金料'),0);
|
||||
assert.equal(l.inventoryRevision(D3),revision);assert.equal(l.inventorySnapshot(D3).stale,false);
|
||||
});
|
||||
|
||||
test('历史更正只标记受影响日期的快照,费用与利润变动不影响库存复核',t=>{
|
||||
const {l,stock,review,save,act,run}=fixture(t);stock();const id=save('');act(id,'confirm');
|
||||
for(const date of [D0,D1,D2])review(date);
|
||||
run({date:D2},()=>l.closeDay(D2,owner),owner);
|
||||
act(id,'expense',{date:D2,amount:'1',payer:'assistant',note:'实际运费'});
|
||||
assert.equal(l.report(D2).close.stale,true);assert.equal(l.inventorySnapshot(D2).stale,false);
|
||||
stock({date:D1,kind:'decrease',grams:'0.001'});
|
||||
assert.equal(l.inventorySnapshot(D0).stale,false);assert.equal(l.inventorySnapshot(D1).stale,true);assert.equal(l.inventorySnapshot(D2).stale,true);
|
||||
assert.equal(mg(l.inventorySnapshot(D2).inventory),10000);assert.equal(mg(l.inventory()),9999);
|
||||
run({date:D2},()=>l.closeDay(D2,owner),owner);
|
||||
assert.equal(l.inventorySnapshot(D2).stale,false);assert.equal(mg(l.inventorySnapshot(D2).inventory),9999);assert.equal(l.inventorySnapshot(D1).stale,true);
|
||||
});
|
||||
|
||||
test('保存快照和库存变动幂等重试,重启仍保留操作号与历史',t=>{
|
||||
const {l,filename,run}=fixture(t);
|
||||
const stockKey=randomUUID(),stockInput={kind:'increase',date:D3,pocket:'现货',grams:'0.001'};
|
||||
const stockCall=()=>run(stockInput,()=>l.stock(stockInput,assistant),assistant,stockKey);assert.deepEqual(stockCall(),stockCall());
|
||||
const reviewKey=randomUUID(),reviewInput={date:D3,verified:true,revision:l.inventoryRevision(D3)};
|
||||
const reviewCall=()=>run(reviewInput,()=>l.reviewInventory(reviewInput,owner),owner,reviewKey);const saved=reviewCall();assert.deepEqual(reviewCall(),saved);
|
||||
l.stock({...stockInput,grams:'0.001'},assistant);assert.equal(l.inventorySnapshot(D3).stale,true);
|
||||
assert.deepEqual(reviewCall(),saved);assert.equal(l.inventorySnapshot(D3).stale,true);
|
||||
l.close();const reopened=new Ledger(filename);t.after(()=>reopened.close());
|
||||
assert.deepEqual(reopened.transact(reviewKey,owner,reviewInput,()=>reopened.reviewInventory(reviewInput,owner)),saved);
|
||||
assert.deepEqual(reopened.transact(stockKey,assistant,stockInput,()=>reopened.stock(stockInput,assistant)),JSON.parse(reopened.one('SELECT result FROM operations WHERE id=?',stockKey).result));
|
||||
assert.equal(mg(reopened.inventory()),2);assert.equal(mg(reopened.inventorySnapshot(D3).inventory),1);assert.equal(reopened.inventorySnapshot(D3).stale,true);assert.equal(reopened.inventorySnapshots().snapshots.length,1);
|
||||
assert.throws(()=>reopened.transact(stockKey,assistant,{...stockInput,grams:'0.002'},()=>({})),e=>e.status===409);
|
||||
});
|
||||
|
||||
test('停用货盘仍能核算旧订单与退货,新登记不再使用,也不静默隐藏余额',t=>{
|
||||
const {l,stock,review,save,act,run}=fixture(t);
|
||||
assert.deepEqual(ACTIVE_POCKETS,['现货','金料','找金','回收旧料','君宝汇']);assert.equal(POCKETS.length,8);
|
||||
const oldNote='历史采购来源与工费备注';
|
||||
run({},()=>{l.move({date:D0,pocket:'臻金汇',mg:5000,kind:'purchase',note:oldNote,cost:12345},owner);return {};},owner);
|
||||
const original=l.one("SELECT * FROM movements WHERE pocket='臻金汇'");
|
||||
const id=save(''),order=l.rawOrder(id);order.lines[0].pocket='臻金汇';l.run('UPDATE orders SET lines=? WHERE id=?',JSON.stringify(order.lines),id);
|
||||
act(id,'confirm');assert.equal(l.inventoryStatus(owner).legacyInventory[0].reserved,1000);
|
||||
act(id,'receipt',{amount:'2',account:'助理微信',verified:true});act(id,'deliver',{verified:true});assert.equal(mg(l.inventory(),'臻金汇'),4000);
|
||||
act(id,'return',{reason:'历史原单退回',verified:true});assert.equal(mg(l.inventory(),'臻金汇'),5000);
|
||||
assert.throws(()=>stock({pocket:'臻金汇'}),/货盘无效/);assert.throws(()=>stock({kind:'transfer',to:'臻金汇'}),/目标货盘无效/);assert.throws(()=>save('臻金汇'),/已停用/);
|
||||
const status=l.inventoryStatus(owner);assert.ok(!status.current.some(r=>r.pocket==='臻金汇'));assert.equal(mg(status.legacyInventory,'臻金汇'),5000);
|
||||
assert.equal(mg(review(D3).snapshot.inventory,'臻金汇'),5000);assert.deepEqual(l.one('SELECT * FROM movements WHERE id=?',original.id),original);
|
||||
});
|
||||
|
||||
test('HTTP库存查询须登录,助理可增减平移,老板按看到的版本复核并查询历史',async t=>{
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'maimai-stock-http-')),app=createApp({mode:'demo',port:0,dataDir:dir});
|
||||
await new Promise(resolve=>app.server.listen(0,'127.0.0.1',resolve));
|
||||
t.after(async()=>{await new Promise(resolve=>app.server.close(resolve));app.ledger.close();fs.rmSync(dir,{recursive:true,force:true});});
|
||||
const base='http://127.0.0.1:'+app.server.address().port;let cookie='';
|
||||
const call=(route,body,key=randomUUID())=>fetch(base+route,{method:body?'POST':'GET',headers:{...(cookie?{Cookie:cookie}:{}),...(body?{'Content-Type':'application/json',Origin:base,'X-Requested-With':'maimai-ledger','Idempotency-Key':key}:{})},...(body?{body:JSON.stringify(body)}:{})});
|
||||
const login=async role=>{const res=await call('/api/demo-login',{role});cookie=res.headers.get('set-cookie').split(';')[0];};
|
||||
assert.equal((await call('/api/inventory')).status,401);assert.equal((await call('/api/inventory/snapshots')).status,401);
|
||||
await login('assistant');const initial=await (await call('/api/inventory')).json();assert.equal(initial.canReview,false);assert.equal(initial.yesterday,null);assert.equal(initial.todaySnapshot,null);assert.equal(initial.current.length,5);
|
||||
for(const body of [{kind:'increase',pocket:'现货',grams:'0.003'},{kind:'decrease',pocket:'现货',grams:'0.001'},{kind:'transfer',pocket:'现货',to:'金料',grams:'0.001'}])assert.equal((await call('/api/stock',{date:D3,...body})).status,200);
|
||||
assert.equal((await call('/api/inventory/review',{date:D3,verified:true,revision:initial.revision})).status,403);
|
||||
assert.deepEqual((await (await call('/api/inventory/snapshots')).json()).snapshots,[]);
|
||||
await login('owner');const status=await (await call('/api/inventory')).json();assert.equal(status.canReview,true);
|
||||
assert.equal((await call('/api/inventory/review',{date:D3,verified:true,revision:initial.revision})).status,409);
|
||||
const payload={date:status.date,verified:true,revision:status.revision},key=randomUUID();
|
||||
const responses=await Promise.all([call('/api/inventory/review',payload,key),call('/api/inventory/review',payload,key)]);assert.deepEqual(responses.map(r=>r.status),[200,200]);assert.deepEqual(await responses[0].json(),await responses[1].json());
|
||||
let history=await (await call('/api/inventory/snapshots?from='+D3+'&date='+D3)).json();assert.equal(history.snapshots.length,1);assert.equal(history.snapshots[0].date,D3);assert.equal(history.snapshots[0].stale,false);
|
||||
assert.equal((await call('/api/inventory/snapshots?from='+D3+'&date='+D2)).status,400);assert.equal((await call('/api/inventory/snapshots?date=invalid')).status,400);
|
||||
assert.equal((await call('/api/stock',{kind:'increase',date:D3,pocket:'臻金汇',grams:'1'})).status,400);
|
||||
assert.equal((await call('/api/stock',{kind:'decrease',date:D3,pocket:'现货',grams:'-1'})).status,400);
|
||||
await call('/api/stock',{kind:'increase',date:D3,pocket:'现货',grams:'0.001'});
|
||||
history=await (await call('/api/inventory/snapshots')).json();assert.equal(history.snapshots.length,1);assert.equal(history.snapshots[0].stale,true);
|
||||
const updated=await (await call('/api/inventory')).json();assert.equal((await call('/api/inventory/review',{date:updated.date,verified:true,revision:updated.revision})).status,200);
|
||||
assert.equal((await call('/api/close',{date:D3})).status,200);history=await (await call('/api/inventory/snapshots')).json();assert.equal(history.snapshots.length,1);assert.equal(history.snapshots[0].stale,false);
|
||||
const state=await (await call('/api/state')).json();assert.deepEqual(state.pockets,ACTIVE_POCKETS);assert.equal(state.inventory.length,8);
|
||||
assert.equal((await (await call('/api/inventory')).json()).yesterday,null);
|
||||
await call('/api/logout',{});assert.equal((await call('/api/inventory/snapshots')).status,401);
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict');const {Ledger}=require('../ledger');const {FeishuSync,FIELDS,TABLE_NAME}=require('../sync');
|
||||
test('同步写后超时保留待办;重试先查稳定键,不再新建记录',async()=>{
|
||||
const l=new Ledger(':memory:');l.enqueue('inventory');const records=[];let creates=0,throwAfterWrite=true;
|
||||
const fake=async(url,opt)=>{let d;const body=opt.body?JSON.parse(opt.body):{};
|
||||
if(url.includes('/auth/'))return {ok:true,json:async()=>({code:0,tenant_access_token:'fake',expire:7200})};
|
||||
if(url.includes('/tables?'))d={items:[{table_id:'tbl-new',name:TABLE_NAME}],has_more:false};
|
||||
else if(url.includes('/fields?'))d={items:FIELDS.map(([field_name,type])=>({field_name,type})),has_more:false};
|
||||
else if(url.includes('/records/search'))d={items:records,has_more:false};
|
||||
else if(opt.method==='POST'){creates++;records.push({record_id:'rec-new',fields:body.fields});if(throwAfterWrite){throwAfterWrite=false;throw new Error('模拟写已完成但网络超时');}d={record:records[0]};}
|
||||
else if(opt.method==='PUT'){records[0].fields=body.fields;d={record:records[0]};}
|
||||
else d={record:records[0]};return {ok:true,json:async()=>({code:0,data:d})};
|
||||
};
|
||||
const sync=new FeishuSync(l,{enabled:true,appId:'fake',appSecret:'fake',baseToken:'fake',tableId:'tbl-new'},fake);await sync.tick();assert.equal(sync.status().failed,1);assert.equal(sync.status().pending,1);await sync.tick();assert.equal(creates,1);assert.equal(sync.status().pending,0);assert.equal(sync.status().failed,0);l.close();
|
||||
});
|
||||
test('未配置不调用网络;配置旧表名时禁止写入',async()=>{
|
||||
const l=new Ledger(':memory:');let calls=0;await new FeishuSync(l,null,()=>{calls++;}).tick();assert.equal(calls,0);
|
||||
const fake=async url=>({ok:true,json:async()=>url.includes('/auth/')?{code:0,tenant_access_token:'fake'}:{code:0,data:{items:[{table_id:'old',name:'10月_销售单据'}],has_more:false}}});
|
||||
const sync=new FeishuSync(l,{enabled:true,appId:'x',appSecret:'x',baseToken:'x',tableId:'old'},fake);await sync.tick();assert.match(sync.status().error,/只允许同步到专用表/);l.close();
|
||||
});
|
||||
Reference in new issue
Block a user