2026-10-17 19:50:24 +08:00
'use strict' ;
2026-10-23 00:38:04 +08:00
const { historicalAction } = require ( './fixtures/legacy-cancellation.cjs' );
2026-10-17 19:50:24 +08:00
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 ;
};
2026-10-23 00:38:04 +08:00
const action = ( id , kind , extra = {})=>{ const input = { date : D ,... extra }; return run ({ id , kind , input },()=> historicalAction ( ledger , id , kind , input , actor ));};
2026-10-17 19:50:24 +08:00
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 );
});