新增锁价与每日购料管理

支持锁价交付、每日加权成本、购料修改与软删除,完善付款归属、结算及利润重算。

244项测试和隔离浏览器验收通过;记录尚未实施的剩料跨日结转与当天资金结清需求。
This commit is contained in:
summer committed 2026-10-21 01:32:49 +08:00
1 parent 42d75a4968
commit 20bf6e7d24
23 files changed
+2330 -101

No files matched your search

+91 -19
View File
@@ -7,6 +7,8 @@ const path = require('node:path');
const Calc = require('./public/calculations');
const {orderBook}=require('./order-book');
const {reportByOrderDate}=require('./daily-report');
const PriceLocks=require('./price-locks');
const MaterialPools=require('./material-pools');
const FEE_LABELS={shipping:'快递费',box:'包装盒',certificate:'证书',braiding:'编绳',sticker:'手机贴',other:'其他直接费用'};
const POCKETS = ['现货','金料','找金','回收旧料','君宝汇','臻金汇','金金','定制工厂'];
// 历史货盘仍参与原单、退货和完整库存核算;新登记只使用当前五个货盘。
@@ -33,6 +35,7 @@ function day(value, minimum='2000-01-01') {
}
const owner=(actor)=>{if(actor.role!=='owner')fail('这项操作由麦麦账号完成',403);};
const pick=(v,opts,name)=>{if(!opts.includes(v)) fail(`${name}无效`);return v;};
const priceLockEnv={day,money,weight,text,fail,pick,today,now,pockets:ACTIVE_POCKETS,accounts:ACCOUNTS};
class Ledger {
constructor(filename) {
this.filename=filename;
@@ -66,6 +69,8 @@ class Ledger {
for(const [name,definition] of Object.entries({paper_date:"TEXT NOT NULL DEFAULT ''",payment_account:"TEXT NOT NULL DEFAULT '助理微信'",fee_items:"TEXT NOT NULL DEFAULT '[]'",fees_date:"TEXT NOT NULL DEFAULT ''",rounding_mode:"TEXT NOT NULL DEFAULT 'cent'"})){
if(!columns.includes(name))this.db.exec(`ALTER TABLE orders ADD COLUMN ${name} ${definition}`);
}
PriceLocks.initialize(this);
MaterialPools.initialize(this);
if(filename!==':memory:') fs.chmodSync(filename,0o600);
}
rows(sql,...args){return this.db.prepare(sql).all(...args);}
@@ -95,6 +100,8 @@ class Ledger {
detail(id){
const o=this.rawOrder(id);
o.payments=this.rows('SELECT * FROM payments WHERE order_id=? ORDER BY date,created',id);
const priceLock=this.one('SELECT id,buy_payer,delivery FROM price_locks WHERE final_order_id=?',id);
if(priceLock){o.price_lock_id=priceLock.id;o.payments.push(...PriceLocks.inheritedPayments(this,id));o.payments.sort((a,b)=>a.date.localeCompare(b.date)||a.created.localeCompare(b.created));}
o.expenses=this.rows('SELECT * FROM expenses WHERE order_id=? ORDER BY date,created',id);
o.settlements=this.rows('SELECT * FROM settlements WHERE order_id=? ORDER BY date,created',id);
o.corrections=this.rows('SELECT * FROM corrections WHERE target IN (SELECT id FROM payments WHERE order_id=? UNION SELECT id FROM expenses WHERE order_id=? UNION SELECT id FROM settlements WHERE order_id=?)',id,id,id);
@@ -102,23 +109,45 @@ class Ledger {
o.netReceived=o.received-o.refunded;o.balance=(['cancelled','returned'].includes(o.status)?-o.netReceived:o.total-o.netReceived)||0;
o.rounding_adjustment=o.rounding_mode==='yuan'?o.total-(sum(o.lines,'sale')-o.discount):0;
o.goodsCost=o.lines.some(l=>l.cost===null)?null:sum(o.lines,'cost');o.directCost=sum(o.expenses,'amount');
o.materialCostPending=!['returned','cancelled'].includes(o.status)&&o.lines.some(l=>l.costMaterial?.mode==='pool'&&l.costParts?.material==null);
o.knownGoodsCost=sum(o.lines,l=>l.cost??sum(Object.values(l.costParts||{}).map(amount=>({amount:amount??0})),'amount'));
o.pendingFees=['draft','confirmed'].includes(o.status)?o.fee_items.filter(f=>f.status!=='recorded'&&(o.status==='draft'||f.status==='estimated')):[];
o.draftFees=sum(o.pendingFees,f=>f.amount||0);
o.estimatedProfit=o.goodsCost===null||o.pendingFees.some(f=>f.amount===null)?null:o.total-o.goodsCost-o.directCost-o.draftFees;
const j=this.one('SELECT COALESCE(SUM(profit),0) AS profit FROM journal WHERE order_id=?',id);o.profit=j.profit;
const j=this.one('SELECT COALESCE(SUM(profit),0) AS profit FROM journal WHERE order_id=?',id);o.profit=o.materialCostPending&&o.status==='delivered'?null:j.profit;o.knownProfit=o.profit??0;
o.ownerCost=o.status==='delivered'?Calc.orderCosts(o).byPayer.owner.goods:0;
if(['delivered','returned','cancelled'].includes(o.status))o.ownerCost+=sum(o.expenses,e=>e.payer==='owner'?e.amount:0);
if(priceLock){
const delivery=priceLock.delivery?JSON.parse(priceLock.delivery):null,sources=[];
const leftover=['delivered','returned'].includes(o.status)&&priceLock.buy_payer==='assistant'?(delivery?.leftover_cost??0):0;
if(leftover)sources.push({kind:'leftover',amount:leftover,quantity:delivery.leftover_mg,explanation:'助理垫付的剩余金料进入自有货盘,按原采购成本抵扣货款待结'});
const returned=o.status==='returned'?Calc.orderCosts({...o,status:'delivered'}).byPayer.assistant.goods:0;
if(returned)sources.push({kind:'returnedGoods',amount:returned,explanation:'退回自有货盘的商品由助理垫付的货品成本,抵扣货款待结'});
o.assistantInventoryCredit=leftover+returned;o.assistantInventoryCreditSources=sources;
o.assistantInventoryCreditExplanation=sources.map(source=>source.explanation).join(';');
}
if(!priceLock&&o.status==='returned'&&o.lines.some(line=>line.costMaterial?.mode==='pool')){
const pooled=o.lines.filter(line=>line.costMaterial?.mode==='pool');
const retained=Calc.orderCosts({...o,lines:pooled,status:'delivered'}).rows.filter(row=>row.kind==='goods'&&row.payer==='assistant'&&!row.materialPoolId);
const amount=sum(retained,'amount');
if(amount){
o.assistantInventoryCredit=amount;
o.assistantInventoryCreditSources=[{kind:'returnedGoods',amount,explanation:'日购料关联商品已退回自有货盘,助理垫付的进货工费、配件和其他货品成本抵扣货款待结;料费由日购料剩余垫款单独抵扣'}];
o.assistantInventoryCreditExplanation=o.assistantInventoryCreditSources[0].explanation;
}
}
o.ownerDirect=sum(o.payments,p=>p.account.startsWith('麦麦')?(p.kind==='receipt'?p.amount:-p.amount):0);
// 取消/退货后的麦麦直收款属于待退客户款,不能再算一次应返助理。
o.ownerCredit=o.status==='delivered'?o.ownerDirect:0;
o.ownerCredit=o.status==='delivered'||(priceLock&&o.status==='returned'&&o.netReceived===0)?o.ownerDirect:0;
o.costTransferred=sum(o.settlements,s=>s.bucket==='cost'?s.amount:0);o.profitTransferred=sum(o.settlements,s=>s.bucket==='profit'?s.amount:0);
o.costDue=o.ownerCost-o.costTransferred;o.profitDue=o.profit-o.profitTransferred;
o.settlementDue=['delivered','returned','cancelled'].includes(o.status)?o.costDue+o.profitDue-o.ownerCredit:0;
o.costDue=o.ownerCost-(o.assistantInventoryCredit||0)-o.costTransferred;o.profitDue=o.profit===null?null:o.profit-o.profitTransferred;
o.settlementDue=o.materialCostPending&&o.status==='delivered'?null:['delivered','returned','cancelled'].includes(o.status)?o.costDue+o.profitDue-o.ownerCredit:0;
o.knownSettlementDue=o.settlementDue??0;
o.audit=this.rows('SELECT action,actor,detail,created FROM audit WHERE entity=? ORDER BY id DESC LIMIT 100',id).map(r=>({...r,detail:JSON.parse(r.detail)}));
o.sync=this.one('SELECT revision,done_revision,error,updated FROM sync WHERE entity=?','order:'+id)||null;
return o;
}
validateLines(lines,historicalLines=[]){
validateLines(lines,historicalLines=[],businessDate=null){
if(!Array.isArray(lines)||!lines.length||lines.length>60)fail('每单需要1~60行商品');
return lines.map((l,i)=>{
const unit=pick(l.unit,['g','件'],'单位');const qty=unit==='g'?weight(l.quantity,`第${i+1}行克重`):fixed(l.quantity,1,'件数')/10;
@@ -130,11 +159,12 @@ class Ledger {
const mode=pick(l.pricingMode||'manual',['auto','manual'],'计价方式');
const priced=Calc.sale({...l,pricingMode:mode});
const pricing=mode==='auto'?priced:null;
if(l.costMaterial?.mode==='pool'&&!l.costParts)fail('日购料商品请填写分项成本;没有发生的成本填0');
const breakdown=l.costParts?Calc.purchaseCosts(l):null;
const costPayers=Calc.costPayers(l.costPayers===undefined?historicalLines?.[i]?.costPayers:l.costPayers);
const cost=breakdown?breakdown.total:(l.cost===''||l.cost==null?null:money(l.cost,'货品成本'));
const priceNote=pricing?`金价 ${(pricing.goldPrice/100).toFixed(2)}元/克 + 工费 ${(pricing.laborRate/100).toFixed(2)}元/${pricing.laborMode==='gram'?'克':`件 × ${pricing.pieces}件`}`:text(l.priceNote,'客户单价说明',100,true);
return {name,code:text(l.code,'商品编号',30,true),unit,quantity:qty,pocket,payer:pick(l.payer,['owner','assistant'],'成本垫资人'),...(costPayers?{costPayers}:{}),cost,...(breakdown?{costParts:breakdown.parts,costMaterial:breakdown.costMaterial,costLabor:breakdown.costLabor}:{}),sale:priced.sale,baseSale:priced.baseSale,charges:priced.charges,pricingMode:mode,...(pricing?{goldPrice:pricing.goldPrice,laborRate:pricing.laborRate,laborMode:pricing.laborMode,pieces:pricing.pieces}:{}),priceNote};
return MaterialPools.prepareLine(this,{name,code:text(l.code,'商品编号',30,true),unit,quantity:qty,pocket,payer:pick(l.payer,['owner','assistant'],'成本垫资人'),...(costPayers?{costPayers}:{}),cost,...(breakdown?{costParts:breakdown.parts,costMaterial:breakdown.costMaterial,costLabor:breakdown.costLabor}:{}),sale:priced.sale,baseSale:priced.baseSale,charges:priced.charges,pricingMode:mode,...(pricing?{goldPrice:pricing.goldPrice,laborRate:pricing.laborRate,laborMode:pricing.laborMode,pieces:pricing.pieces}:{}),priceNote},businessDate,priceLockEnv);
});
}
paperNumber(date,allocate=false){
@@ -170,7 +200,7 @@ class Ledger {
let id=input.id;
const prior=id?this.rawOrder(id):null;
if(prior){if(prior.status!=='draft')fail('已确认订单不能直接改写。未交付可取消重开,已交付请办理退货',409);if(prior.revision!==input.revision)fail('订单已被更新,请重新打开',409);}
const date=day(input.date), lines=this.validateLines(input.lines,prior?.lines), discount=money(input.discount||'0','整单优惠');
const date=day(input.date), lines=this.validateLines(input.lines,prior?.lines,date), discount=money(input.discount||'0','整单优惠');
const roundingMode=input.rounding_mode===undefined?(prior?.rounding_mode??'yuan'):input.rounding_mode;
const {total}=Calc.orderTotal(lines.map(line=>line.sale),discount,roundingMode);
const fees=this.validateFees(input.fee_items??prior?.fee_items?.map(r=>({...r,amount:r.amount===null?'':(r.amount/100).toFixed(2)})));
@@ -191,7 +221,11 @@ class Ledger {
this.audit(id,'保存草稿',actor,{revision:this.rawOrder(id).revision});return {id};
}
validateCompletedCosts(lines,fees){
const missingCosts=lines.flatMap((line,i)=>line.cost==null?[`商品${i+1}的${line.costParts?Object.entries(Calc.costLabels).filter(([key])=>line.costParts[key]==null).map(([,label])=>label).join('、'):'货品成本'}`]:[]);
const missingCosts=lines.flatMap((line,i)=>{
if(line.cost!=null)return [];
const missing=line.costParts?Object.entries(Calc.costLabels).filter(([key])=>line.costParts[key]==null&&!(key==='material'&&line.costMaterial?.mode==='pool')).map(([,label])=>label):['货品成本'];
return missing.length?[`商品${i+1}的${missing.join('、')}`]:[];
});
if(missingCosts.length)fail(`请补齐${missingCosts.join(';')};没有的成本填0,不能把空白当作0`);
const missingFees=fees.filter(f=>f.amount==null).map(f=>f.note);
for(const [i,line] of lines.entries())for(const charge of line.charges||[]){
@@ -206,7 +240,7 @@ class Ledger {
// 旧定金单仍沿用原动作,仅经明确确认 complete 后完成交付,不自动补收款。
const prior=input.id?this.rawOrder(input.id):null;
if(prior&&prior.status!=='draft')fail('已确认订单不能直接改写。未交付可取消重开,已交付请办理退货',409);
const lines=this.validateLines(input.lines,prior?.lines);
const lines=this.validateLines(input.lines,prior?.lines,day(input.date));
const fees=input.fee_items??prior?.fee_items.map(f=>({...f,amount:f.amount===null?'':(f.amount/100).toFixed(2)}))??[];
if(!Array.isArray(fees))fail('直接费用项目无效');
// 保存时暂用 estimated 保留显式填写的0,随后确认实际费用时统一转为 recorded。
@@ -327,8 +361,12 @@ class Ledger {
if(value&&typeof value==='object'){
const costPayers=Calc.costPayers(value.costPayers===undefined?l.costPayers:value.costPayers);
const payer=value.payer===undefined?l.payer:pick(value.payer,['owner','assistant'],'成本垫资人');
const result=Calc.purchaseCosts({costParts:value.parts||value,costMaterial:value.costMaterial,costLabor:value.costLabor,unit:l.unit,quantity:l.unit==='g'?(l.quantity/1000).toFixed(3):l.quantity});if(result.total===null)fail('请补齐每项成本;没有的项目填0');
const result=Calc.purchaseCosts({name:l.name,costParts:value.parts||value,costMaterial:value.costMaterial,costLabor:value.costLabor,unit:l.unit,quantity:l.unit==='g'?(l.quantity/1000).toFixed(3):l.quantity});if(result.total===null&&result.costMaterial.mode!=='pool')fail('请补齐每项成本;没有的项目填0');
l.costParts=result.parts;l.cost=result.total;l.costMaterial=result.costMaterial;l.costLabor=result.costLabor;l.payer=payer;if(costPayers)l.costPayers=costPayers;
if(l.costMaterial.mode==='pool'){
MaterialPools.prepareLine(this,l,o.date,priceLockEnv);
if(['labor','accessories','other'].some(key=>l.costParts[key]==null))fail('请补齐每项成本;没有的项目填0');
}else delete l.materialPool;
}else{if(l.costParts)fail('这行已拆分成本,请逐项填写');l.cost=money(value,'货品成本');}
});
this.run('UPDATE orders SET lines=? WHERE id=?',JSON.stringify(o.lines),id);
@@ -344,13 +382,16 @@ class Ledger {
this.action(id,'deliver',{date,verified:true},actor);
this.audit(id,'complete',actor,{...input,revision:this.rawOrder(id).revision});return {id};
} else if(action==='deliver'){
if(o.status!=='confirmed')fail('订单不在待交付状态',409);if(o.balance!==0)fail('未收齐客户款,不能确认交付');if(o.goodsCost===null)fail('请先补齐货品成本,不能把空白当作0');
if(o.status!=='confirmed')fail('订单不在待交付状态',409);if(o.balance!==0)fail('未收齐客户款,不能确认交付');if(o.goodsCost===null&&!o.materialCostPending)fail('请先补齐货品成本,不能把空白当作0');
this.validateCompletedCosts(o.lines,o.fee_items);
if(o.pendingFees.length)fail('请先核实附加成本,没有发生的费用填0,不能把预估当作实际费用');
if(input.verified!==true)fail('请确认已复称、收款核实并实际交给客户/快递');
if(o.payments.some(p=>p.date>date)||o.expenses.some(e=>e.date>date))fail('交付日期不能早于本单已登记的收款或费用日期');
this.run("UPDATE orders SET status='delivered',delivered_date=? WHERE id=?",date,id);
const delivered=MaterialPools.deliver(this,o,date,actor,priceLockEnv);
const group=randomUUID();for(const l of o.lines)if(l.pocket)this.move({group,order:id,date,pocket:l.pocket,mg:-l.quantity,kind:'sale',note:o.number},actor);
this.journal(id,date,'交付',o.total,o.goodsCost,o.directCost);
const knownGoods=sum(delivered.lines,line=>line.cost??sum(Object.values(line.costParts||{}).map(amount=>({amount:amount??0})),'amount'));
this.journal(id,date,'交付',o.total,knownGoods,o.directCost);
} else if(action==='cancel'){
if(!['draft','confirmed'].includes(o.status))fail('已交付订单请登记退货');
if(o.payments.some(p=>p.date>date)||o.expenses.some(e=>e.date>date))fail('取消日期不能早于本单已登记流水日期');
@@ -360,12 +401,15 @@ class Ledger {
text(input.reason,'退货原因',200);this.run("UPDATE orders SET status='returned',returned_date=? WHERE id=?",date,id);
const group=randomUUID();o.lines.forEach((l,i)=>{
const destination=input.returnPockets?.[i]??l.pocket;
if(l.costMaterial?.mode==='pool'&&!destination)fail('日购料黄金退货须退回自有货盘,请选择实物退回的货盘;退供应商请先核实购料退款');
if(l.pocket&&!destination)fail('原自有货盘商品须选择退回货盘');
if(destination){pick(destination,destination===l.pocket?POCKETS:ACTIVE_POCKETS,'退回货盘');if(l.unit!=='g')fail('按件商品不计黄金货盘');this.move({group,order:id,date,pocket:destination,mg:l.quantity,kind:'return',note:o.number},actor);}
});
this.journal(id,date,'整单退货',-o.total,-o.goodsCost,0);
this.journal(id,date,'整单退货',-o.total,-o.knownGoodsCost,0);
MaterialPools.release(this,o,date,actor,priceLockEnv);
} else if(action==='settlement'){
if(!['delivered','returned','cancelled'].includes(o.status))fail('定金阶段不结算货款和利润');
if(o.materialCostPending)fail('日购料成本待补,补齐采购后再结算');
const amount=money(input.amount);if(amount<=0)fail('交款须大于0');const bucket=pick(input.bucket,['cost','profit'],'款项归属');
const sign=pick(input.direction,['toOwner','toAssistant'],'转款方向')==='toOwner'?1:-1;
if(input.verified!==true)fail('请核实双方实际转账');
@@ -373,9 +417,12 @@ class Ledger {
const due=o.ownerCredit?o.settlementDue:(bucket==='cost'?o.costDue:o.profitDue);
if(Math.sign(due)!==sign||amount>Math.abs(due))fail('转款方向或金额超过本单应结余额,请核对实际流水');
this.run('INSERT INTO settlements VALUES (?,?,?,?,?,?,?,?)',randomUUID(),id,date,bucket,sign*amount,text(input.note,'交款凭据/说明',150),actor.name,now());
} else if(action==='material'){
return MaterialPools.reassign(this,o,input,actor,priceLockEnv);
} else if(action==='correct'){
owner(actor);const type=pick(input.type,['payment','expense','settlement'],'更正类型');const reason=text(input.reason,'更正原因',200);
if(input.verified!==true)fail('请核实原凭据和更正内容');
if(type==='payment'&&o.payments.some(payment=>payment.id===input.target&&payment.price_lock_event_id))fail('锁价实际收退款为不可改写的原始记录,不能从普通订单更正');
const table={payment:'payments',expense:'expenses',settlement:'settlements'}[type];const row=this.one(`SELECT * FROM ${table} WHERE id=? AND order_id=?`,String(input.target),id);
if(!row)fail('原流水不存在');if(date<row.date)fail('更正日期不能早于原流水');
if(this.one('SELECT target FROM corrections WHERE target=?',row.id)||row.amount===0||row.reference?.startsWith('更正冲回:')||row.note?.startsWith('更正冲回:'))fail('这条流水已冲回,请更正最新有效记录');
@@ -385,9 +432,13 @@ class Ledger {
const account=pick(input.account,ACCOUNTS,'更正后账户');
this.run('INSERT INTO payments VALUES (?,?,?,?,?,?,?,?,?)',randomUUID(),id,date,row.kind,-row.amount,row.account,'更正冲回:'+reason,actor.name,now());
if(amount)this.run('INSERT INTO payments VALUES (?,?,?,?,?,?,?,?,?)',randomUUID(),id,date,row.kind,amount,account,'更正补记:'+reason,actor.name,now());
const updated=this.detail(id);if(updated.received>updated.total||updated.netReceived<0)fail('更正后收退款余额不合理,请核对金额');
const updated=this.detail(id);if((o.price_lock_id?updated.netReceived:updated.received)>updated.total||updated.netReceived<0)fail('更正后收退款余额不合理,请核对金额');
if(o.status==='delivered'&&updated.netReceived!==o.total)fail('已交付订单须保持收齐;收款账户可更正,金额差异请先核实真实交付情况');
for(const acc of ACCOUNTS)if(sum(updated.payments,p=>p.account===acc?(p.kind==='receipt'?p.amount:-p.amount):0)<0)fail('更正后原账户退款超过收款,请先核对关联退款记录');
for(const acc of ACCOUNTS){
// 锁价交付可明确从另一账户退差额;后续更正不能扩大该既有负净额。
const inherited=o.price_lock_id?sum(updated.payments,p=>p.price_lock_event_id&&p.account===acc?(p.kind==='receipt'?p.amount:-p.amount):0):0;
if(sum(updated.payments,p=>p.account===acc?(p.kind==='receipt'?p.amount:-p.amount):0)<Math.min(0,inherited))fail('更正后原账户退款超过收款,请先核对关联退款记录');
}
}else if(type==='expense'){
this.run('INSERT INTO expenses VALUES (?,?,?,?,?,?,?,?)',randomUUID(),id,date,-row.amount,row.payer,'更正冲回:'+reason,actor.name,now());
if(amount)this.run('INSERT INTO expenses VALUES (?,?,?,?,?,?,?,?)',randomUUID(),id,date,amount,pick(input.payer,['owner','assistant'],'更正后付款人'),'更正补记:'+reason,actor.name,now());
@@ -412,6 +463,20 @@ class Ledger {
const paymentMethods=[...new Set((receiptAccounts.length?receiptAccounts:[o.payment_account]).map(account=>account.replace(/^(助理|麦麦)/,'')))];
return {id:o.id,number:o.number,date:o.date,customer:o.customer,salesperson:o.salesperson,note:o.note,paper_number:o.paper_number,status:o.status,total:o.total,rounding_mode:o.rounding_mode,rounding_adjustment:o.rounding_adjustment,discount:o.discount,received:o.received,refunded:o.refunded,netReceived:o.netReceived,balance:o.balance,paymentMethods,lines:o.lines.map(l=>({name:l.name,code:l.code,unit:l.unit,quantity:l.quantity,sale:l.sale,baseSale:l.baseSale??l.sale,charges:(l.charges||[]).filter(c=>c.amount!==null).map(c=>({name:c.name,amount:c.amount})),priceNote:l.priceNote,...(l.pricingMode==='auto'?{pricingMode:'auto',goldPrice:l.goldPrice,laborRate:l.laborRate,laborMode:l.laborMode,pieces:l.pieces}:{})}))};
}
createPriceLock(input,actor){return PriceLocks.create(this,input,actor,priceLockEnv);}
priceLocks(query={}){return PriceLocks.list(this,query,priceLockEnv);}
priceLockDetail(id){return PriceLocks.detail(this,id,priceLockEnv);}
deliverPriceLock(id,input,actor){return PriceLocks.deliver(this,id,input,actor,priceLockEnv);}
priceLockReporting(query={}){return PriceLocks.reporting(this,query,priceLockEnv);}
createMaterialPurchase(input,actor){return MaterialPools.purchase(this,input,actor,priceLockEnv);}
materialPurchaseDetail(id){return MaterialPools.purchaseDetail(this,id,priceLockEnv);}
editMaterialPurchase(id,input,actor){return MaterialPools.editPurchase(this,id,input,actor,priceLockEnv);}
deleteMaterialPurchase(id,input,actor){return MaterialPools.deletePurchase(this,id,input,actor,priceLockEnv);}
materialPools(query={}){return MaterialPools.list(this,query,priceLockEnv);}
materialPoolDetail(id){return MaterialPools.readPool(this,id,priceLockEnv);}
materialPoolReporting(query={}){return MaterialPools.reporting(this,query,priceLockEnv);}
materialPoolSettlement(){return MaterialPools.settlement(this,priceLockEnv);}
settleMaterialPool(id,input,actor){return MaterialPools.settle(this,id,input,actor,priceLockEnv);}
saveAfterSale(input,actor){
if(!actor||!['owner','assistant'].includes(actor.role))fail('请使用麦麦或助理账号登记售后',403);
if(!input||typeof input!=='object'||Array.isArray(input))fail('售后记录格式无效');
@@ -454,21 +519,28 @@ class Ledger {
day(date);day(from);if(from>date)fail('开始日期不能晚于结束日期');
const j=this.rows('SELECT j.*,o.number FROM journal j JOIN orders o ON o.id=j.order_id WHERE j.date>=? AND j.date<=? ORDER BY j.date,j.created',from,date);
const payments=this.rows('SELECT p.*,o.number FROM payments p JOIN orders o ON o.id=p.order_id WHERE p.date>=? AND p.date<=? ORDER BY p.date,p.created',from,date);
payments.push(...this.priceLockReporting({from,to:date}).customerCash.map(event=>({...event,price_lock_event_id:event.id})));
const settles=this.rows('SELECT s.*,o.number FROM settlements s JOIN orders o ON o.id=s.order_id WHERE s.date>=? AND s.date<=? ORDER BY s.date,s.created',from,date);
const afterSales=this.rows('SELECT * FROM after_sales WHERE date>=? AND date<=? ORDER BY date,created,id',from,date);
const orders=this.rows('SELECT id FROM orders ORDER BY created DESC').map(r=>this.detail(r.id));
const accounts=ACCOUNTS.map(account=>({account,receipt:sum(payments,p=>p.account===account&&p.kind==='receipt'?p.amount:0),refund:sum(payments,p=>p.account===account&&p.kind==='refund'?p.amount:0)}));
const warnings=[];for(const o of orders){
if(o.status==='confirmed'&&o.pendingFees.length)warnings.push({id:o.id,number:o.number,message:'附加成本待核实'});
if(o.status==='confirmed'&&o.goodsCost===null)warnings.push({id:o.id,number:o.number,message:'成本待补'});
if(o.status==='confirmed'&&o.goodsCost===null||o.status==='delivered'&&o.materialCostPending)warnings.push({id:o.id,number:o.number,message:o.materialCostPending?'日购料成本待补,利润与结算暂不确认':'成本待补'});
if(['returned','cancelled'].includes(o.status)&&o.netReceived>0)warnings.push({id:o.id,number:o.number,message:`客户退款待登记:${(o.netReceived/100).toFixed(2)}元`});
if(o.status!=='draft'&&o.reviewed_revision!==o.revision)warnings.push({id:o.id,number:o.number,message:'有记录待麦麦复核'});
if(o.ownerDirect!==0)warnings.push({id:o.id,number:o.number,message:o.status==='delivered'?'麦麦直接收客户款,已扣减总待结金额;货款/利润拆分需单独复核':o.status==='confirmed'?'定金由麦麦直接收取,预订阶段不结算':'麦麦原收款账户仍有待退客户款,不计为应返助理'});
if(o.ownerDirect!==0)warnings.push({id:o.id,number:o.number,message:o.status==='delivered'?'麦麦直接收客户款,已扣减总待结金额;货款/利润拆分需单独复核':o.status==='confirmed'?'定金由麦麦直接收取,预订阶段不结算':o.price_lock_id&&o.status==='returned'&&o.netReceived===0?'跨账户收退款差额已纳入双方结算':'麦麦原收款账户仍有待退客户款,不计为应返助理'});
}
const check=this.one('SELECT COALESCE(SUM(sales-goods-expense-profit),0) AS delta FROM journal').delta;
if(check)warnings.push({message:'利润流水计算不一致,需要维护者检查'});
const close=this.one('SELECT * FROM closes WHERE date=?',date);
return {date,from,sales:sum(j,'sales'),goods:sum(j,'goods'),expense:sum(j,'expense')+sum(afterSales,'amount'),profit:sum(j,'profit')-sum(afterSales,'amount'),delivered:j.filter(r=>r.kind==='交付').length,returns:j.filter(r=>r.kind==='整单退货').length,accounts,payments,settlements:settles,journal:j,afterSales,afterSaleCount:afterSales.length,inventory:this.inventory(date),warnings,unsettled:orders.filter(o=>o.settlementDue!==0).map(o=>({id:o.id,number:o.number,date:o.delivered_date||o.date,status:o.status,costDue:o.costDue,profitDue:o.profitDue,ownerDirect:o.ownerDirect,total:o.settlementDue})),settlementDue:sum(orders,'settlementDue'),customerBalance:sum(orders,o=>o.status==='confirmed'?o.balance:0),close:close?{date:close.date,actor:close.actor,created:close.created,stale:!!close.stale}:null};
const close=this.one('SELECT * FROM closes WHERE date=?',date),poolSettlement=this.materialPoolSettlement(),poolActivity=this.materialPoolReporting({from,to:date});
const pendingMaterialOrders=orders.filter(o=>o.status==='delivered'&&o.materialCostPending&&j.some(row=>row.order_id===o.id));
const hasPendingSettlement=orders.some(o=>o.settlementDue===null)||poolSettlement.pendingCount>0;
const pendingIds=new Set(pendingMaterialOrders.map(order=>order.id));
const knownProfit=sum(j.filter(row=>!pendingIds.has(row.order_id)),'profit')-sum(afterSales,'amount'),knownSettlementDue=sum(orders,o=>o.knownSettlementDue)+poolSettlement.knownSettlementDue;
return {date,from,sales:sum(j,'sales'),goods:pendingMaterialOrders.length?null:sum(j,'goods'),knownGoods:sum(j,'goods'),expense:sum(j,'expense')+sum(afterSales,'amount'),profit:pendingMaterialOrders.length?null:knownProfit,knownProfit,materialCostPending:pendingMaterialOrders.length>0,pendingMaterialCount:pendingMaterialOrders.length,
materialPoolActivity:poolActivity,materialPoolSettlement:poolSettlement,
delivered:j.filter(r=>r.kind==='交付').length,returns:j.filter(r=>r.kind==='整单退货').length,accounts,payments,settlements:settles,journal:j.map(row=>pendingIds.has(row.order_id)?{...row,goods:null,profit:null,materialCostPending:true}:row),afterSales,afterSaleCount:afterSales.length,inventory:this.inventory(date),warnings,unsettled:orders.filter(o=>o.settlementDue!==0).map(o=>({id:o.id,number:o.number,date:o.delivered_date||o.date,status:o.status,costDue:o.costDue,profitDue:o.profitDue,ownerDirect:o.ownerDirect,total:o.settlementDue,materialCostPending:o.materialCostPending})),settlementDue:hasPendingSettlement?null:sum(orders,'settlementDue')+poolSettlement.settlementDue,knownSettlementDue,customerBalance:sum(orders,o=>o.status==='confirmed'?o.balance:0),close:close?{date:close.date,actor:close.actor,created:close.created,stale:!!close.stale}:null};
}
closeDay(date,actor,basis){
owner(actor);if(basis!==undefined&&basis!=='orderDate')fail('对账日期口径无效');