格式化:Prettier统一代码风格(仅格式,无逻辑变化)

仅为 npm run format 的输出;黄金对照、旧库兼容、浏览器流程与单元测试全部通过且零差异。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
黄健铭andClaude Opus 5.5 committed 2026-12-04 08:58:53 -08:00
1 parent 3743d687e7
commit 28c64814f0
221 files changed
+116943 -26708

No files matched your search

+526 -70
View File
@@ -1,79 +1,535 @@
'use strict';
const {test}=require('node:test'),assert=require('node:assert/strict'),{randomUUID}=require('node:crypto'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),{DatabaseSync}=require('node:sqlite');
const {Ledger,today}=require('../ledger'),RecoveryMaterial=require('../recovery-material');
const D='2026-11-01',D2='2026-11-02',D3='2026-11-03';
const clone=value=>JSON.parse(JSON.stringify(value));
function fixture(t,{filename=':memory:'}={}){
t.mock.timers.enable({apis:['Date'],now:Date.parse(D+'T04:00:00Z')});
let l=new Ledger(filename);t.after(()=>{if(l){l.close();l=null;}});const actors={};
for(const member of ['owner','assistant','assistant2']){const actor={id:randomUUID(),name:'合成多行-'+member,role:member==='owner'?'owner':'assistant'};actors[member]=actor;l.run('INSERT INTO users VALUES (?,?,?,?,?)',actor.id,actor.name,actor.role,'synthetic-salt','synthetic-hash');l.bindMemberUser(actor.id,member);}
l.enableTeamMode();const run=(p,fn,member='owner')=>l.scope(actors[member],()=>l.transact(randomUUID(),actors[member],p,fn)),at=date=>t.mock.timers.setTime(Date.parse(date+'T04:00:00Z'));
run({},()=>l.stock({date:D,kind:'opening',pocket:'现货',grams:'100',note:'合成现货'},actors.owner));
const buy=(grams='5',total='4400',payer='owner')=>{const p={date:today(),grams,total,payer,note:'合成公共购料'};return run(p,()=>l.createMaterialPurchase(p,actors.owner));};
const enable=()=>{const p=l.rollingMaterialPreview({},actors.owner);run(p,()=>l.enableRollingMaterial({date:today(),revision:p.revision,verified:true},actors.owner));};
const create=(lines,payment='2815')=>{const p={date:today(),member:'assistant',customer:'合成多商品客户',salesperson:'合成开单人',lines,payment:{amount:payment,account:'助理微信',verified:true}};return run(p,()=>l.createPriceLock(p,actors.owner)).id;};
const line=(name,quantity,goldPrice,laborRate,material)=>({name,unit:'g',quantity,goldPrice,laborRate,laborMode:'gram',material});
const deliver=(lockId,actuals,payment)=>{const lock=l.priceLockDetail(lockId),p={date:today(),revision:lock.revision,verified:true,lines:lock.lines.map((row,index)=>({lineId:row.id,quantity:actuals[index].quantity,laborRate:(row.line.laborRate/100).toFixed(2),laborMode:'gram',payer:'assistant',costParts:{labor:'0',accessories:'0',other:'0'},costPayers:{material:row.buy_payer,labor:'assistant'},inventory:{pocket:'现货',original:row.material_source==='pool'?'stocked':'receive',extra:'receive'},...actuals[index]})),settlement:{amount:payment,account:'助理微信',verified:true},fee_items:[]};return run(p,()=>l.deliverPriceLock(lockId,p,actors.owner)).id;};
return {get l(){return l;},actors,run,at,buy,enable,create,line,deliver,reopen(){l.close();l=new Ledger(filename);},close(){l.close();l=null;}};
const { test } = require('node:test'),
assert = require('node:assert/strict'),
{ randomUUID } = require('node:crypto'),
fs = require('node:fs'),
os = require('node:os'),
path = require('node:path'),
{ DatabaseSync } = require('node:sqlite');
const { Ledger, today } = require('../ledger'),
RecoveryMaterial = require('../recovery-material');
const D = '2026-11-01',
D2 = '2026-11-02',
D3 = '2026-11-03';
const clone = value => JSON.parse(JSON.stringify(value));
function fixture(t, { filename = ':memory:' } = {}) {
t.mock.timers.enable({ apis: ['Date'], now: Date.parse(D + 'T04:00:00Z') });
let l = new Ledger(filename);
t.after(() => {
if (l) {
l.close();
l = null;
}
});
const actors = {};
for (const member of ['owner', 'assistant', 'assistant2']) {
const actor = { id: randomUUID(), name: '合成多行-' + member, role: member === 'owner' ? 'owner' : 'assistant' };
actors[member] = actor;
l.run('INSERT INTO users VALUES (?,?,?,?,?)', actor.id, actor.name, actor.role, 'synthetic-salt', 'synthetic-hash');
l.bindMemberUser(actor.id, member);
}
l.enableTeamMode();
const run = (p, fn, member = 'owner') =>
l.scope(actors[member], () => l.transact(randomUUID(), actors[member], p, fn)),
at = date => t.mock.timers.setTime(Date.parse(date + 'T04:00:00Z'));
run({}, () => l.stock({ date: D, kind: 'opening', pocket: '现货', grams: '100', note: '合成现货' }, actors.owner));
const buy = (grams = '5', total = '4400', payer = 'owner') => {
const p = { date: today(), grams, total, payer, note: '合成公共购料' };
return run(p, () => l.createMaterialPurchase(p, actors.owner));
};
const enable = () => {
const p = l.rollingMaterialPreview({}, actors.owner);
run(p, () => l.enableRollingMaterial({ date: today(), revision: p.revision, verified: true }, actors.owner));
};
const create = (lines, payment = '2815') => {
const p = {
date: today(),
member: 'assistant',
customer: '合成多商品客户',
salesperson: '合成开单人',
lines,
payment: { amount: payment, account: '助理微信', verified: true },
};
return run(p, () => l.createPriceLock(p, actors.owner)).id;
};
const line = (name, quantity, goldPrice, laborRate, material) => ({
name,
unit: 'g',
quantity,
goldPrice,
laborRate,
laborMode: 'gram',
material,
});
const deliver = (lockId, actuals, payment) => {
const lock = l.priceLockDetail(lockId),
p = {
date: today(),
revision: lock.revision,
verified: true,
lines: lock.lines.map((row, index) => ({
lineId: row.id,
quantity: actuals[index].quantity,
laborRate: (row.line.laborRate / 100).toFixed(2),
laborMode: 'gram',
payer: 'assistant',
costParts: { labor: '0', accessories: '0', other: '0' },
costPayers: { material: row.buy_payer, labor: 'assistant' },
inventory: {
pocket: '现货',
original: row.material_source === 'pool' ? 'stocked' : 'receive',
extra: 'receive',
},
...actuals[index],
})),
settlement: { amount: payment, account: '助理微信', verified: true },
fee_items: [],
};
return run(p, () => l.deliverPriceLock(lockId, p, actors.owner)).id;
};
return {
get l() {
return l;
},
actors,
run,
at,
buy,
enable,
create,
line,
deliver,
reopen() {
l.close();
l = new Ledger(filename);
},
close() {
l.close();
l = null;
},
};
}
test('两件黄金各自金价工费和成本来源,一超一少整单只补11元,原锁池跨日冻结',t=>{
const f=fixture(t);f.buy();f.enable();const pool=f.l.materialPoolDetail(D),stock=clone(f.l.rows('SELECT * FROM movements'));
const id=f.create([f.line('合成自定义黄金甲','2','900','20',{source:'manual',rate:'850',payer:'assistant',verified:true}),f.line('合成自定义黄金乙','1','950','25',{source:'pool',poolId:D,revision:pool.revision})]),lock=f.l.priceLockDetail(id);
assert.equal(lock.estimated_total,281500);assert.equal(lock.material_source,'mixed');assert.equal(lock.locked_mg,3000);assert.equal(lock.cash_events.length,1);assert.equal(lock.material_events.length,1);assert.equal(lock.material_events[0].line_index,0);assert.deepEqual(clone(f.l.rows('SELECT * FROM movements')),stock);assert.equal(f.l.rows('SELECT * FROM orders').length,0);
f.at(D2);f.buy('1','1000','assistant2');const orderId=f.deliver(id,[{quantity:'1.8'},{quantity:'1.2',extraMaterial:{rate:'900',payer:'assistant2',verified:true}}],'11'),order=f.l.detail(orderId),after=f.l.priceLockDetail(id);
assert.equal(order.lines.length,2);assert.deepEqual(order.lines.map(row=>row.goldPrice),[90000,95000]);assert.deepEqual(order.lines.map(row=>row.costParts.material),[153000,106000]);assert.equal(order.total,282600);assert.equal(order.netReceived,282600);assert.equal(order.goodsCost,259000);assert.equal(order.profit,23600);assert.equal(after.delivery.difference,1100);assert.equal(after.delivery.leftover_cost,17000);assert.deepEqual(after.lines.map(row=>row.delivery.leftover_mg),[200,0]);assert.equal(after.lines[1].material_amount,88000);assert.equal(after.lines[1].materialPool.frozen,true);
assert.deepEqual(after.material_events.map(row=>[row.date,row.line_index,row.source,row.amount,row.payer]),[[D,0,'original',170000,'assistant'],[D2,1,'extra',18000,'assistant2']]);assert.equal(f.l.reportByOrderDate(D).sales,0);assert.equal(f.l.reportByOrderDate(D2).profit,23600);assert.equal(f.l.rows('SELECT * FROM payments WHERE order_id=?',orderId).length,0);assert.equal(f.l.rows('SELECT * FROM journal WHERE order_id=?',orderId).length,1);
assert.deepEqual(f.l.rows("SELECT mg FROM movements WHERE order_id=? ORDER BY rowid",orderId).map(row=>row.mg),[2000,200,-1800,-1200]);assert.equal(f.l.priceLockReporting({from:D,to:D}).customerCash.length,1);assert.equal(f.l.priceLockReporting({from:D2,to:D2}).customerCash.length,1);
test('两件黄金各自金价工费和成本来源,一超一少整单只补11元,原锁池跨日冻结', t => {
const f = fixture(t);
f.buy();
f.enable();
const pool = f.l.materialPoolDetail(D),
stock = clone(f.l.rows('SELECT * FROM movements'));
const id = f.create([
f.line('合成自定义黄金甲', '2', '900', '20', {
source: 'manual',
rate: '850',
payer: 'assistant',
verified: true,
}),
f.line('合成自定义黄金乙', '1', '950', '25', { source: 'pool', poolId: D, revision: pool.revision }),
]),
lock = f.l.priceLockDetail(id);
assert.equal(lock.estimated_total, 281500);
assert.equal(lock.material_source, 'mixed');
assert.equal(lock.locked_mg, 3000);
assert.equal(lock.cash_events.length, 1);
assert.equal(lock.material_events.length, 1);
assert.equal(lock.material_events[0].line_index, 0);
assert.deepEqual(clone(f.l.rows('SELECT * FROM movements')), stock);
assert.equal(f.l.rows('SELECT * FROM orders').length, 0);
f.at(D2);
f.buy('1', '1000', 'assistant2');
const orderId = f.deliver(
id,
[{ quantity: '1.8' }, { quantity: '1.2', extraMaterial: { rate: '900', payer: 'assistant2', verified: true } }],
'11',
),
order = f.l.detail(orderId),
after = f.l.priceLockDetail(id);
assert.equal(order.lines.length, 2);
assert.deepEqual(
order.lines.map(row => row.goldPrice),
[90000, 95000],
);
assert.deepEqual(
order.lines.map(row => row.costParts.material),
[153000, 106000],
);
assert.equal(order.total, 282600);
assert.equal(order.netReceived, 282600);
assert.equal(order.goodsCost, 259000);
assert.equal(order.profit, 23600);
assert.equal(after.delivery.difference, 1100);
assert.equal(after.delivery.leftover_cost, 17000);
assert.deepEqual(
after.lines.map(row => row.delivery.leftover_mg),
[200, 0],
);
assert.equal(after.lines[1].material_amount, 88000);
assert.equal(after.lines[1].materialPool.frozen, true);
assert.deepEqual(
after.material_events.map(row => [row.date, row.line_index, row.source, row.amount, row.payer]),
[
[D, 0, 'original', 170000, 'assistant'],
[D2, 1, 'extra', 18000, 'assistant2'],
],
);
assert.equal(f.l.reportByOrderDate(D).sales, 0);
assert.equal(f.l.reportByOrderDate(D2).profit, 23600);
assert.equal(f.l.rows('SELECT * FROM payments WHERE order_id=?', orderId).length, 0);
assert.equal(f.l.rows('SELECT * FROM journal WHERE order_id=?', orderId).length, 1);
assert.deepEqual(
f.l.rows('SELECT mg FROM movements WHERE order_id=? ORDER BY rowid', orderId).map(row => row.mg),
[2000, 200, -1800, -1200],
);
assert.equal(f.l.priceLockReporting({ from: D, to: D }).customerCash.length, 1);
assert.equal(f.l.priceLockReporting({ from: D2, to: D2 }).customerCash.length, 1);
});
test('多池行分别追溯个人先用与公共来源,短交回料按行释放,取消回收后不复活私料批次',t=>{
const f=fixture(t);f.buy('3','2700');f.enable();const p={mode:'direct',date:D,member:'assistant',customer:'合成回收客户',salesperson:'合成经办',old_lines:[{name:'合成旧料',incoming_weight:'2',melted_weight:'2',purity:'100'}],buy_rate:'800',buy_total:'1600',payer:'assistant2',payment_account:'助理2微信',verified:true},recovery=f.run(p,()=>f.l.createRecovery(p,f.actors.owner));
const pool=f.l.materialPoolDetail(D),material={source:'pool',poolId:D,revision:pool.revision},id=f.create([f.line('合成私料第一件','1.5','2000','0',material),f.line('合成混料第二件','1.5','2000','0',material)],'6000'),before=f.l.priceLockDetail(id);
assert.deepEqual(before.lines.map(row=>row.material_amount),[120000,130000]);assert.deepEqual(before.lines[0].materialPool.materialSources.map(row=>[row.kind,row.quantity]),[['personal_recovery',1500]]);assert.deepEqual(before.lines[1].materialPool.materialSources.map(row=>[row.kind,row.quantity]),[['personal_recovery',500],['public',1000]]);assert.equal(RecoveryMaterial.blockedUsages(f.l,recovery.purchase_id)[0].mg,2000);
f.at(D2);const orderId=f.deliver(id,[{quantity:'1'},{quantity:'1'}],'2000'),after=f.l.priceLockDetail(id);assert.deepEqual(f.l.detail(orderId).lines.map(row=>row.costParts.material),[80000,85000]);assert.equal(after.delivery.leftover_cost,85000);assert.equal(RecoveryMaterial.blockedUsages(f.l,recovery.purchase_id)[0].mg,1500);assert.equal(f.l.rows('SELECT * FROM price_lock_pool_returns WHERE price_lock_id=?',id).length,2);
const cancel={revision:f.l.recoveryEdit(recovery.id,f.actors.owner).revision,reason:'合成取消录错回收',verified:true};f.run(cancel,()=>f.l.cancelRecovery(recovery.id,cancel,f.actors.owner));assert.deepEqual(RecoveryMaterial.blockedUsages(f.l,recovery.purchase_id),[]);assert.deepEqual(f.l.detail(orderId).lines.map(row=>row.costParts.material),[90000,90000]);assert.ok(!JSON.stringify(f.l.priceLockDetail(id).lines).includes(recovery.purchase_id));
f.at(D3);f.run({},()=>f.l.action(orderId,'return',{date:D3,verified:true,reason:'合成整单退回',returnPockets:['现货','现货']},f.actors.owner));assert.equal(f.l.rows("SELECT * FROM price_lock_pool_returns WHERE price_lock_id=? AND kind='goods'",id).length,2);assert.equal(f.l.materialPoolDetail(D3).remainingMg,3000);assert.ok(!JSON.stringify(f.l.materialPoolDetail(D3).remainingMaterialGroups??[]).includes(recovery.purchase_id));
test('多池行分别追溯个人先用与公共来源,短交回料按行释放,取消回收后不复活私料批次', t => {
const f = fixture(t);
f.buy('3', '2700');
f.enable();
const p = {
mode: 'direct',
date: D,
member: 'assistant',
customer: '合成回收客户',
salesperson: '合成经办',
old_lines: [{ name: '合成旧料', incoming_weight: '2', melted_weight: '2', purity: '100' }],
buy_rate: '800',
buy_total: '1600',
payer: 'assistant2',
payment_account: '助理2微信',
verified: true,
},
recovery = f.run(p, () => f.l.createRecovery(p, f.actors.owner));
const pool = f.l.materialPoolDetail(D),
material = { source: 'pool', poolId: D, revision: pool.revision },
id = f.create(
[f.line('合成私料第一件', '1.5', '2000', '0', material), f.line('合成混料第二件', '1.5', '2000', '0', material)],
'6000',
),
before = f.l.priceLockDetail(id);
assert.deepEqual(
before.lines.map(row => row.material_amount),
[120000, 130000],
);
assert.deepEqual(
before.lines[0].materialPool.materialSources.map(row => [row.kind, row.quantity]),
[['personal_recovery', 1500]],
);
assert.deepEqual(
before.lines[1].materialPool.materialSources.map(row => [row.kind, row.quantity]),
[
['personal_recovery', 500],
['public', 1000],
],
);
assert.equal(RecoveryMaterial.blockedUsages(f.l, recovery.purchase_id)[0].mg, 2000);
f.at(D2);
const orderId = f.deliver(id, [{ quantity: '1' }, { quantity: '1' }], '2000'),
after = f.l.priceLockDetail(id);
assert.deepEqual(
f.l.detail(orderId).lines.map(row => row.costParts.material),
[80000, 85000],
);
assert.equal(after.delivery.leftover_cost, 85000);
assert.equal(RecoveryMaterial.blockedUsages(f.l, recovery.purchase_id)[0].mg, 1500);
assert.equal(f.l.rows('SELECT * FROM price_lock_pool_returns WHERE price_lock_id=?', id).length, 2);
const cancel = {
revision: f.l.recoveryEdit(recovery.id, f.actors.owner).revision,
reason: '合成取消录错回收',
verified: true,
};
f.run(cancel, () => f.l.cancelRecovery(recovery.id, cancel, f.actors.owner));
assert.deepEqual(RecoveryMaterial.blockedUsages(f.l, recovery.purchase_id), []);
assert.deepEqual(
f.l.detail(orderId).lines.map(row => row.costParts.material),
[90000, 90000],
);
assert.ok(!JSON.stringify(f.l.priceLockDetail(id).lines).includes(recovery.purchase_id));
f.at(D3);
f.run({}, () =>
f.l.action(
orderId,
'return',
{ date: D3, verified: true, reason: '合成整单退回', returnPockets: ['现货', '现货'] },
f.actors.owner,
),
);
assert.equal(f.l.rows("SELECT * FROM price_lock_pool_returns WHERE price_lock_id=? AND kind='goods'", id).length, 2);
assert.equal(f.l.materialPoolDetail(D3).remainingMg, 3000);
assert.ok(!JSON.stringify(f.l.materialPoolDetail(D3).remainingMaterialGroups ?? []).includes(recovery.purchase_id));
});
test('混合退货累加手填余料与两行助理货品垫付,原池料款不重复抵扣',t=>{
const f=fixture(t);f.buy();f.enable();const pool=f.l.materialPoolDetail(D),id=f.create([f.line('合成手填黄金','2','1000','0',{source:'manual',rate:'850',payer:'assistant',verified:true}),f.line('合成池锁黄金','1','1000','0',{source:'pool',poolId:D,revision:pool.revision})],'3000');
const orderId=f.deliver(id,[{quantity:'1.8',costParts:{labor:'10',accessories:'0',other:'0'}},{quantity:'1.2',costParts:{labor:'20',accessories:'0',other:'0'},extraMaterial:{rate:'900',payer:'assistant',verified:true}}],'0');assert.equal(f.l.detail(orderId).assistantInventoryCredit,17000);
f.run({},()=>f.l.action(orderId,'return',{date:D,verified:true,reason:'合成全部退回',returnPockets:['现货','现货']},f.actors.owner));const returned=f.l.detail(orderId);assert.equal(returned.assistantInventoryCredit,191000);assert.equal(returned.assistantInventoryCreditSources.reduce((sum,row)=>sum+row.amount,0),191000);assert.equal(f.l.rows('SELECT * FROM material_rolling_returns WHERE order_id=?',orderId).length,1);assert.equal(f.l.rows("SELECT * FROM price_lock_pool_returns WHERE price_lock_id=? AND kind IN ('goods','extra')",id).length,2);
test('混合退货累加手填余料与两行助理货品垫付,原池料款不重复抵扣', t => {
const f = fixture(t);
f.buy();
f.enable();
const pool = f.l.materialPoolDetail(D),
id = f.create(
[
f.line('合成手填黄金', '2', '1000', '0', { source: 'manual', rate: '850', payer: 'assistant', verified: true }),
f.line('合成池锁黄金', '1', '1000', '0', { source: 'pool', poolId: D, revision: pool.revision }),
],
'3000',
);
const orderId = f.deliver(
id,
[
{ quantity: '1.8', costParts: { labor: '10', accessories: '0', other: '0' } },
{
quantity: '1.2',
costParts: { labor: '20', accessories: '0', other: '0' },
extraMaterial: { rate: '900', payer: 'assistant', verified: true },
},
],
'0',
);
assert.equal(f.l.detail(orderId).assistantInventoryCredit, 17000);
f.run({}, () =>
f.l.action(
orderId,
'return',
{ date: D, verified: true, reason: '合成全部退回', returnPockets: ['现货', '现货'] },
f.actors.owner,
),
);
const returned = f.l.detail(orderId);
assert.equal(returned.assistantInventoryCredit, 191000);
assert.equal(
returned.assistantInventoryCreditSources.reduce((sum, row) => sum + row.amount, 0),
191000,
);
assert.equal(f.l.rows('SELECT * FROM material_rolling_returns WHERE order_id=?', orderId).length, 1);
assert.equal(
f.l.rows("SELECT * FROM price_lock_pool_returns WHERE price_lock_id=? AND kind IN ('goods','extra')", id).length,
2,
);
});
test('旧单行池预留与余料数据库自动迁移,来源ID及旧现金逐字段保留并可再次重启',t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'multi-lock-migration-')),filename=path.join(dir,'legacy.sqlite');t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));const f=fixture(t,{filename});f.buy();f.enable();const pool=f.l.materialPoolDetail(D),id=f.create([f.line('合成旧池黄金','2','1000','0',{source:'pool',poolId:D,revision:pool.revision})],'2000');f.at(D2);const orderId=f.deliver(id,[{quantity:'1.5'}],'500'),events=clone(f.l.rows('SELECT * FROM price_lock_events WHERE price_lock_id=?',id)),reservation=f.l.one('SELECT * FROM price_lock_pool_reservations WHERE price_lock_id=?',id),returned=f.l.one('SELECT * FROM price_lock_pool_returns WHERE price_lock_id=?',id);f.close();
const db=new DatabaseSync(filename);db.exec('PRAGMA foreign_keys=OFF');
const rebuild=(table,definition,removed=[])=>{const columns=db.prepare('PRAGMA table_info('+table+')').all().map(row=>row.name).filter(name=>!removed.includes(name));db.exec('CREATE TABLE '+table+'_old('+definition+')');db.exec('INSERT INTO '+table+'_old('+columns.join(',')+') SELECT '+columns.join(',')+' FROM '+table);db.exec('DROP TABLE '+table);db.exec('ALTER TABLE '+table+'_old RENAME TO '+table);};
rebuild('price_locks',"id TEXT PRIMARY KEY,number TEXT UNIQUE NOT NULL,date TEXT NOT NULL,customer TEXT NOT NULL,salesperson TEXT NOT NULL,note TEXT NOT NULL,line TEXT NOT NULL,locked_mg INTEGER NOT NULL,sell_rate INTEGER NOT NULL,buy_rate INTEGER NOT NULL,buy_payer TEXT NOT NULL,material_amount INTEGER NOT NULL,estimated_total INTEGER NOT NULL,discount INTEGER NOT NULL,status TEXT NOT NULL CHECK(status IN ('pending','delivered')),revision INTEGER NOT NULL,final_order_id TEXT UNIQUE REFERENCES orders(id),delivery TEXT,actor TEXT NOT NULL,created TEXT NOT NULL,updated TEXT NOT NULL",['lines','cancelled_at','cancelled_reason']);
rebuild('price_lock_pool_reservations',"id TEXT PRIMARY KEY,price_lock_id TEXT NOT NULL UNIQUE REFERENCES price_locks(id),pool_id TEXT NOT NULL,mg INTEGER NOT NULL CHECK(mg>0),amount INTEGER,allocations TEXT NOT NULL DEFAULT '[]',snapshot TEXT NOT NULL DEFAULT '{}',revision INTEGER NOT NULL DEFAULT 1,created TEXT NOT NULL,updated TEXT NOT NULL",['line_index']);
rebuild('price_lock_pool_returns',"id TEXT PRIMARY KEY,price_lock_id TEXT NOT NULL REFERENCES price_locks(id),kind TEXT NOT NULL,date TEXT NOT NULL,mg INTEGER NOT NULL,amount INTEGER,allocations TEXT NOT NULL,origin_pool_id TEXT NOT NULL,same_day INTEGER NOT NULL,actor TEXT NOT NULL,created TEXT NOT NULL,UNIQUE(price_lock_id,kind)",['line_index']);
const delivery=JSON.parse(db.prepare('SELECT delivery FROM price_locks WHERE id=?').get(id).delivery);delete delivery.lines;db.prepare('UPDATE price_locks SET delivery=? WHERE id=?').run(JSON.stringify(delivery),id);db.close();
const reopened=new Ledger(filename);try{const lock=reopened.priceLockDetail(id);assert.equal(lock.lines.length,1);assert.equal(lock.final_order_id,orderId);assert.equal(lock.delivery.leftover_mg,500);assert.equal(reopened.one('SELECT line_index FROM price_lock_pool_reservations WHERE id=?',reservation.id).line_index,0);assert.equal(reopened.one('SELECT line_index FROM price_lock_pool_returns WHERE id=?',returned.id).line_index,0);assert.deepEqual(clone(reopened.rows('SELECT * FROM price_lock_events WHERE price_lock_id=?',id)),events);assert.equal(reopened.one('PRAGMA integrity_check').integrity_check,'ok');assert.deepEqual(reopened.rows('PRAGMA foreign_key_check'),[]);assert.equal(reopened.one('PRAGMA foreign_keys').foreign_keys,1);}finally{reopened.close();}
const again=new Ledger(filename);try{assert.equal(again.priceLockDetail(id).netReceived,150000);assert.equal(again.detail(orderId).goodsCost,132000);assert.deepEqual(again.rows('PRAGMA foreign_key_check'),[]);}finally{again.close();}
test('旧单行池预留与余料数据库自动迁移,来源ID及旧现金逐字段保留并可再次重启', t => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'multi-lock-migration-')),
filename = path.join(dir, 'legacy.sqlite');
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
const f = fixture(t, { filename });
f.buy();
f.enable();
const pool = f.l.materialPoolDetail(D),
id = f.create(
[f.line('合成旧池黄金', '2', '1000', '0', { source: 'pool', poolId: D, revision: pool.revision })],
'2000',
);
f.at(D2);
const orderId = f.deliver(id, [{ quantity: '1.5' }], '500'),
events = clone(f.l.rows('SELECT * FROM price_lock_events WHERE price_lock_id=?', id)),
reservation = f.l.one('SELECT * FROM price_lock_pool_reservations WHERE price_lock_id=?', id),
returned = f.l.one('SELECT * FROM price_lock_pool_returns WHERE price_lock_id=?', id);
f.close();
const db = new DatabaseSync(filename);
db.exec('PRAGMA foreign_keys=OFF');
const rebuild = (table, definition, removed = []) => {
const columns = db
.prepare('PRAGMA table_info(' + table + ')')
.all()
.map(row => row.name)
.filter(name => !removed.includes(name));
db.exec('CREATE TABLE ' + table + '_old(' + definition + ')');
db.exec('INSERT INTO ' + table + '_old(' + columns.join(',') + ') SELECT ' + columns.join(',') + ' FROM ' + table);
db.exec('DROP TABLE ' + table);
db.exec('ALTER TABLE ' + table + '_old RENAME TO ' + table);
};
rebuild(
'price_locks',
"id TEXT PRIMARY KEY,number TEXT UNIQUE NOT NULL,date TEXT NOT NULL,customer TEXT NOT NULL,salesperson TEXT NOT NULL,note TEXT NOT NULL,line TEXT NOT NULL,locked_mg INTEGER NOT NULL,sell_rate INTEGER NOT NULL,buy_rate INTEGER NOT NULL,buy_payer TEXT NOT NULL,material_amount INTEGER NOT NULL,estimated_total INTEGER NOT NULL,discount INTEGER NOT NULL,status TEXT NOT NULL CHECK(status IN ('pending','delivered')),revision INTEGER NOT NULL,final_order_id TEXT UNIQUE REFERENCES orders(id),delivery TEXT,actor TEXT NOT NULL,created TEXT NOT NULL,updated TEXT NOT NULL",
['lines', 'cancelled_at', 'cancelled_reason'],
);
rebuild(
'price_lock_pool_reservations',
"id TEXT PRIMARY KEY,price_lock_id TEXT NOT NULL UNIQUE REFERENCES price_locks(id),pool_id TEXT NOT NULL,mg INTEGER NOT NULL CHECK(mg>0),amount INTEGER,allocations TEXT NOT NULL DEFAULT '[]',snapshot TEXT NOT NULL DEFAULT '{}',revision INTEGER NOT NULL DEFAULT 1,created TEXT NOT NULL,updated TEXT NOT NULL",
['line_index'],
);
rebuild(
'price_lock_pool_returns',
'id TEXT PRIMARY KEY,price_lock_id TEXT NOT NULL REFERENCES price_locks(id),kind TEXT NOT NULL,date TEXT NOT NULL,mg INTEGER NOT NULL,amount INTEGER,allocations TEXT NOT NULL,origin_pool_id TEXT NOT NULL,same_day INTEGER NOT NULL,actor TEXT NOT NULL,created TEXT NOT NULL,UNIQUE(price_lock_id,kind)',
['line_index'],
);
const delivery = JSON.parse(db.prepare('SELECT delivery FROM price_locks WHERE id=?').get(id).delivery);
delete delivery.lines;
db.prepare('UPDATE price_locks SET delivery=? WHERE id=?').run(JSON.stringify(delivery), id);
db.close();
const reopened = new Ledger(filename);
try {
const lock = reopened.priceLockDetail(id);
assert.equal(lock.lines.length, 1);
assert.equal(lock.final_order_id, orderId);
assert.equal(lock.delivery.leftover_mg, 500);
assert.equal(
reopened.one('SELECT line_index FROM price_lock_pool_reservations WHERE id=?', reservation.id).line_index,
0,
);
assert.equal(reopened.one('SELECT line_index FROM price_lock_pool_returns WHERE id=?', returned.id).line_index, 0);
assert.deepEqual(clone(reopened.rows('SELECT * FROM price_lock_events WHERE price_lock_id=?', id)), events);
assert.equal(reopened.one('PRAGMA integrity_check').integrity_check, 'ok');
assert.deepEqual(reopened.rows('PRAGMA foreign_key_check'), []);
assert.equal(reopened.one('PRAGMA foreign_keys').foreign_keys, 1);
} finally {
reopened.close();
}
const again = new Ledger(filename);
try {
assert.equal(again.priceLockDetail(id).netReceived, 150000);
assert.equal(again.detail(orderId).goodsCost, 132000);
assert.deepEqual(again.rows('PRAGMA foreign_key_check'), []);
} finally {
again.close();
}
});
test('混合整单退货保留手填原料与补重的不同付款人,不把补重垫资并到原料付款人',t=>{
const f=fixture(t);f.buy();f.enable();const pool=f.l.materialPoolDetail(D),id=f.create([f.line('合成手填补重','1','1000','0',{source:'manual',rate:'850',payer:'owner',verified:true}),f.line('合成日池黄金','1','1000','0',{source:'pool',poolId:D,revision:pool.revision})],'2000'),orderId=f.deliver(id,[{quantity:'1.2',extraMaterial:{rate:'900',payer:'assistant2',verified:true}},{quantity:'1'}],'200');
f.run({},()=>f.l.action(orderId,'return',{date:D,verified:true,reason:'合成退回原料',returnPockets:['现货','现货']},f.actors.owner));const returned=f.l.one('SELECT allocations,amount FROM material_rolling_returns WHERE order_id=? AND line_index=0',orderId);assert.equal(returned.amount,103000);assert.deepEqual(JSON.parse(returned.allocations),[{payer:'owner',amount:85000},{payer:'assistant2',amount:18000}]);
test('混合整单退货保留手填原料与补重的不同付款人,不把补重垫资并到原料付款人', t => {
const f = fixture(t);
f.buy();
f.enable();
const pool = f.l.materialPoolDetail(D),
id = f.create(
[
f.line('合成手填补重', '1', '1000', '0', { source: 'manual', rate: '850', payer: 'owner', verified: true }),
f.line('合成日池黄金', '1', '1000', '0', { source: 'pool', poolId: D, revision: pool.revision }),
],
'2000',
),
orderId = f.deliver(
id,
[{ quantity: '1.2', extraMaterial: { rate: '900', payer: 'assistant2', verified: true } }, { quantity: '1' }],
'200',
);
f.run({}, () =>
f.l.action(
orderId,
'return',
{ date: D, verified: true, reason: '合成退回原料', returnPockets: ['现货', '现货'] },
f.actors.owner,
),
);
const returned = f.l.one(
'SELECT allocations,amount FROM material_rolling_returns WHERE order_id=? AND line_index=0',
orderId,
);
assert.equal(returned.amount, 103000);
assert.deepEqual(JSON.parse(returned.allocations), [
{ payer: 'owner', amount: 85000 },
{ payer: 'assistant2', amount: 18000 },
]);
});
test('跨日多件补重仅用交付日池,原锁冻结,个人先用、公共补足,次日冻结并回池守恒',t=>{
const f=fixture(t);f.buy('4','4000');f.enable();const originalPool=f.l.materialPoolDetail(D);
const lockId=f.create([f.line('手填原锁','1','2000','0',{source:'manual',rate:'800',payer:'assistant',verified:true}),f.line('公共原锁','1','2000','0',{source:'pool',poolId:D,revision:originalPool.revision})],'4000');
f.at(D2);const p={mode:'direct',date:D2,member:'assistant',customer:'补重测试回收',salesperson:'测试',old_lines:[{name:'旧金',incoming_weight:'0.5',melted_weight:'0.5',purity:'100'}],buy_rate:'600',buy_total:'300',payer:'assistant2',payment_account:'助理2微信',verified:true};
f.run(p,()=>f.l.createRecovery(p,f.actors.owner));const pool=f.l.materialPoolDetail(D2),extra={source:'pool',poolId:D2,revision:pool.revision};
const id=f.deliver(lockId,[{quantity:'1.5',extraMaterial:extra,inventory:{pocket:'现货',original:'receive',extra:'stocked'}},{quantity:'1.5',extraMaterial:extra,inventory:{pocket:'现货',original:'stocked',extra:'stocked'}}],'2000');
let order=f.l.detail(id);assert.deepEqual(order.lines.map(line=>line.costParts.material),[110000,150000]);assert.deepEqual(order.lines.map(line=>line.priceLockExtraPool.materialSources[0].kind),['personal_recovery','public']);
assert.equal(f.l.materialPoolDetail(D2).usedMg,500);assert.equal(f.l.materialPoolDetail(D2).personalPools.assistant.usedMg,500);assert.equal(f.l.priceLockDetail(lockId).material_events.length,1);
f.buy('1','2000');order=f.l.detail(id);assert.deepEqual(order.lines.map(line=>line.costParts.material),[110000,162500]);assert.equal(f.l.priceLockDetail(lockId).lines[1].material_amount,100000);
const own=f.l.asActor(f.actors.assistant).reportFor({date:D2,basis:'orderDate'},f.actors.assistant).ownershipBusiness.assistant;
assert.equal(own.poolMaterial.mg,2000);assert.equal(own.poolMaterial.amount,192500);
f.at(D3);f.buy('1','3000');assert.deepEqual(f.l.detail(id).lines.map(line=>line.costParts.material),[110000,162500]);
f.run({},()=>f.l.action(id,'return',{date:D3,verified:true,reason:'补重退回',returnPockets:['现货','现货']},f.actors.owner));
assert.equal(f.l.materialPoolDetail(D3).remainingMg,7000);assert.equal(f.l.materialPoolDetail(D3).remainingCost,980000);
assert.equal(f.l.rows("SELECT * FROM price_lock_events WHERE source='extra'").length,0);
test('跨日多件补重仅用交付日池,原锁冻结,个人先用、公共补足,次日冻结并回池守恒', t => {
const f = fixture(t);
f.buy('4', '4000');
f.enable();
const originalPool = f.l.materialPoolDetail(D);
const lockId = f.create(
[
f.line('手填原锁', '1', '2000', '0', { source: 'manual', rate: '800', payer: 'assistant', verified: true }),
f.line('公共原锁', '1', '2000', '0', { source: 'pool', poolId: D, revision: originalPool.revision }),
],
'4000',
);
f.at(D2);
const p = {
mode: 'direct',
date: D2,
member: 'assistant',
customer: '补重测试回收',
salesperson: '测试',
old_lines: [{ name: '旧金', incoming_weight: '0.5', melted_weight: '0.5', purity: '100' }],
buy_rate: '600',
buy_total: '300',
payer: 'assistant2',
payment_account: '助理2微信',
verified: true,
};
f.run(p, () => f.l.createRecovery(p, f.actors.owner));
const pool = f.l.materialPoolDetail(D2),
extra = { source: 'pool', poolId: D2, revision: pool.revision };
const id = f.deliver(
lockId,
[
{ quantity: '1.5', extraMaterial: extra, inventory: { pocket: '现货', original: 'receive', extra: 'stocked' } },
{ quantity: '1.5', extraMaterial: extra, inventory: { pocket: '现货', original: 'stocked', extra: 'stocked' } },
],
'2000',
);
let order = f.l.detail(id);
assert.deepEqual(
order.lines.map(line => line.costParts.material),
[110000, 150000],
);
assert.deepEqual(
order.lines.map(line => line.priceLockExtraPool.materialSources[0].kind),
['personal_recovery', 'public'],
);
assert.equal(f.l.materialPoolDetail(D2).usedMg, 500);
assert.equal(f.l.materialPoolDetail(D2).personalPools.assistant.usedMg, 500);
assert.equal(f.l.priceLockDetail(lockId).material_events.length, 1);
f.buy('1', '2000');
order = f.l.detail(id);
assert.deepEqual(
order.lines.map(line => line.costParts.material),
[110000, 162500],
);
assert.equal(f.l.priceLockDetail(lockId).lines[1].material_amount, 100000);
const own = f.l.asActor(f.actors.assistant).reportFor({ date: D2, basis: 'orderDate' }, f.actors.assistant)
.ownershipBusiness.assistant;
assert.equal(own.poolMaterial.mg, 2000);
assert.equal(own.poolMaterial.amount, 192500);
f.at(D3);
f.buy('1', '3000');
assert.deepEqual(
f.l.detail(id).lines.map(line => line.costParts.material),
[110000, 162500],
);
f.run({}, () =>
f.l.action(
id,
'return',
{ date: D3, verified: true, reason: '补重退回', returnPockets: ['现货', '现货'] },
f.actors.owner,
),
);
assert.equal(f.l.materialPoolDetail(D3).remainingMg, 7000);
assert.equal(f.l.materialPoolDetail(D3).remainingCost, 980000);
assert.equal(f.l.rows("SELECT * FROM price_lock_events WHERE source='extra'").length, 0);
});
test('改交付日把补重占用移到新日而保留原锁,重新核算并保持收付不重复',t=>{
const f=fixture(t);f.buy('4','4000');f.enable();const lockId=f.create([f.line('补重移日测试','1','2000','0',{source:'manual',rate:'800',payer:'owner',verified:true})],'2000'),pool=f.l.materialPoolDetail(D);
const id=f.deliver(lockId,[{quantity:'2',extraMaterial:{source:'pool',poolId:D,revision:pool.revision},inventory:{pocket:'现货',original:'receive',extra:'stocked'}}],'2000');
f.at(D2);f.buy('4','8000');const cash=clone(f.l.rows('SELECT * FROM price_lock_events'));
const info=f.l.orderEdit(id,f.actors.owner),input={...info.inputs,date:D2,fees_date:D2,revision:info.revision,reason:'测试交付日期更正',verified:true};
f.run(input,()=>f.l.editOrder(id,input,f.actors.owner));
const order=f.l.detail(id);assert.equal(order.lines[0].priceLockExtraPool.poolId,D2);assert.equal(order.goodsCost,230000);assert.equal(order.profit,170000);assert.equal(f.l.materialPoolDetail(D).usedMg,0);assert.equal(f.l.materialPoolDetail(D2).usedMg,1000);assert.deepEqual(clone(f.l.rows('SELECT * FROM price_lock_events')),cash);
test('改交付日把补重占用移到新日而保留原锁,重新核算并保持收付不重复', t => {
const f = fixture(t);
f.buy('4', '4000');
f.enable();
const lockId = f.create(
[f.line('补重移日测试', '1', '2000', '0', { source: 'manual', rate: '800', payer: 'owner', verified: true })],
'2000',
),
pool = f.l.materialPoolDetail(D);
const id = f.deliver(
lockId,
[
{
quantity: '2',
extraMaterial: { source: 'pool', poolId: D, revision: pool.revision },
inventory: { pocket: '现货', original: 'receive', extra: 'stocked' },
},
],
'2000',
);
f.at(D2);
f.buy('4', '8000');
const cash = clone(f.l.rows('SELECT * FROM price_lock_events'));
const info = f.l.orderEdit(id, f.actors.owner),
input = {
...info.inputs,
date: D2,
fees_date: D2,
revision: info.revision,
reason: '测试交付日期更正',
verified: true,
};
f.run(input, () => f.l.editOrder(id, input, f.actors.owner));
const order = f.l.detail(id);
assert.equal(order.lines[0].priceLockExtraPool.poolId, D2);
assert.equal(order.goodsCost, 230000);
assert.equal(order.profit, 170000);
assert.equal(f.l.materialPoolDetail(D).usedMg, 0);
assert.equal(f.l.materialPoolDetail(D2).usedMg, 1000);
assert.deepEqual(clone(f.l.rows('SELECT * FROM price_lock_events')), cash);
});