完善订单审批、每日对账与信用卡手续费
加入助理订单变更复核、收款人汇总、每日报销和应转金额;优化库存筛选、订单明细与连续浏览。开单身份必填,信用卡手续费按实收4‰自动计算并默认由麦麦承担,打印优惠显示在人民币大写旁。 验证:484项测试通过;独立HTTP与浏览器覆盖普通订单、锁价、修改审批、断线恢复和打印隔离。旧报表兼容,本机升级原29表295行数据保持一致。
This commit is contained in:
1 parent
27a11e9b35
commit
a506fb1228
68 files changed
+3591
-259
No files matched your search
+112
-21
@@ -6,22 +6,31 @@ const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const Calc = require('./public/calculations');
|
||||
const {orderBook}=require('./order-book');
|
||||
const {reportByOrderDate}=require('./daily-report');
|
||||
const {reportByOrderDate,dailyFundsReceipts}=require('./daily-report');
|
||||
const DailyFunds=require('./daily-funds');
|
||||
const PriceLocks=require('./price-locks');
|
||||
const MaterialPools=require('./material-pools');
|
||||
const OrderTemplates=require('./order-templates');
|
||||
const OrderEdit=require('./order-edit');
|
||||
const OrderCancellations=require('./order-cancellations');
|
||||
const OrderChanges=require('./order-changes');
|
||||
// 仅服务器的新单生成流程能传入,客户端字段不能取得这个权限。
|
||||
const NEW_ORDER_ACTION=Symbol('newOrderAction');
|
||||
const PRICE_LOCK_DELIVERY=Symbol('priceLockDelivery');
|
||||
const FEE_LABELS={shipping:'快递费',box:'包装盒',certificate:'证书',braiding:'编绳',sticker:'手机贴',other:'其他直接费用'};
|
||||
const POCKETS = ['现货','金料','找金','回收旧料','君宝汇','臻金汇','金金','定制工厂'];
|
||||
// 历史货盘仍参与原单、退货和完整库存核算;新登记只使用当前五个货盘。
|
||||
const ACTIVE_POCKETS = ['现货','金料','找金','回收旧料','君宝汇'];
|
||||
const ACCOUNTS = ['助理微信','助理支付宝','助理现金','麦麦微信','麦麦支付宝','麦麦现金'];
|
||||
const ACCOUNTS = ['助理微信','助理支付宝','助理现金','麦麦微信','麦麦支付宝','麦麦现金','助理信用卡','麦麦信用卡'];
|
||||
const CARD_FEE_NOTE='信用卡手续费(4‰)';
|
||||
const isCardFee=item=>item?.system==='credit_card'||String(item?.key||'').startsWith('card_fee:');
|
||||
const cardFeeAmount=amount=>Math.floor((amount*4+500)/1000);
|
||||
const today = () => new Intl.DateTimeFormat('sv-SE',{timeZone:'Asia/Shanghai'}).format(new Date());
|
||||
const now = () => new Date().toISOString();
|
||||
const sum = (rows, key) => rows.reduce((s,r)=>s+(typeof key==='function'?key(r):r[key]),0);
|
||||
function fail(message, status=400) { const e=new Error(message); e.status=status; throw e; }
|
||||
function text(value, name, max=100, optional=false) { const s=String(value??'').trim(); if ((!s&&!optional)||s.length>max) fail(`${name}请填写${optional?'不超过':'1~'}${max}字`); return s; }
|
||||
function orderIdentity(value,name,max){if(typeof value!=='string')fail(`${name}须填写文字`);return text(value,name,max);}
|
||||
function peopleNumber(value,name,optional=false){
|
||||
if(optional&&(value===null||typeof value==='string'&&!value.trim()))return null;
|
||||
const raw=['number','string'].includes(typeof value)?String(value).trim():'';
|
||||
@@ -45,7 +54,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};
|
||||
const priceLockEnv={day,money,weight,text,orderIdentity,fail,pick,today,now,pockets:ACTIVE_POCKETS,accounts:ACCOUNTS};
|
||||
class Ledger {
|
||||
constructor(filename) {
|
||||
this.filename=filename;
|
||||
@@ -87,6 +96,8 @@ class Ledger {
|
||||
MaterialPools.initialize(this);
|
||||
OrderTemplates.initialize(this);
|
||||
OrderCancellations.initialize(this);
|
||||
OrderChanges.initialize(this);
|
||||
DailyFunds.initialize(this);
|
||||
if(filename!==':memory:') fs.chmodSync(filename,0o600);
|
||||
}
|
||||
rows(sql,...args){return this.db.prepare(sql).all(...args);}
|
||||
@@ -115,6 +126,14 @@ class Ledger {
|
||||
rawOrder(id){const o=this.one('SELECT * FROM orders WHERE id=?',id);if(!o)fail('订单不存在',404);o.lines=JSON.parse(o.lines);o.fee_items=JSON.parse(o.fee_items);return o;}
|
||||
orderEdit(id,actor){return OrderEdit.detail(this,id,actor,priceLockEnv);}
|
||||
editOrder(id,input,actor){return OrderEdit.edit(this,id,input,actor,priceLockEnv);}
|
||||
orderChange(id,actor){return OrderChanges.detail(this,id,actor,priceLockEnv);}
|
||||
orderChanges(query={},actor){return OrderChanges.list(this,query,actor,priceLockEnv);}
|
||||
orderChangeRequest(id,actor){return OrderChanges.read(this,id,actor,priceLockEnv);}
|
||||
requestOrderChange(id,input,actor){return OrderChanges.request(this,id,input,actor,priceLockEnv);}
|
||||
approveOrderChange(id,input,actor){return OrderChanges.approve(this,id,input,actor,priceLockEnv);}
|
||||
rejectOrderChange(id,input,actor){return OrderChanges.reject(this,id,input,actor,priceLockEnv);}
|
||||
pendingOrderChange(id){return OrderChanges.pending(this,id);}
|
||||
guardOrderChange(id,options){return OrderChanges.guard(this,id,options,priceLockEnv);}
|
||||
orderCancellation(id,actor){return OrderCancellations.detail(this,id,actor,priceLockEnv);}
|
||||
orderCancellations(query={},actor){return OrderCancellations.list(this,query,actor,priceLockEnv);}
|
||||
orderCancellationRequest(id,actor){return OrderCancellations.read(this,id,actor,priceLockEnv);}
|
||||
@@ -124,7 +143,7 @@ class Ledger {
|
||||
guardOrderCancellation(id,options){return OrderCancellations.guard(this,id,options,priceLockEnv);}
|
||||
detail(id){
|
||||
const o=this.rawOrder(id);
|
||||
Object.assign(o,OrderCancellations.projection(this,id));
|
||||
Object.assign(o,OrderCancellations.projection(this,id),OrderChanges.projection(this,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));}
|
||||
@@ -217,17 +236,55 @@ class Ledger {
|
||||
return {key,amount,payer:pick(item.payer,['owner','assistant'],'费用付款人'),note,...(estimated?{status:'estimated',edited:item.edited===true}:{}),...(item.sourceName?{sourceName:text(item.sourceName,'附加项目名称',40)}:{})};
|
||||
}).filter(item=>item.status==='estimated'||item.amount>0);
|
||||
}
|
||||
recordFees(o,items,date,actor){
|
||||
recordFees(o,items,date,actor,context=null){
|
||||
if(actor.role!=='owner'&&context!==NEW_ORDER_ACTION)fail('已开订单的费用须先提交复核申请,由麦麦批准后入账',403);
|
||||
if(items.some(f=>f.amount===null))fail('请补齐附加成本;没有发生的费用填0');
|
||||
for(const f of items){if(f.amount>0)this.run('INSERT INTO expenses VALUES (?,?,?,?,?,?,?,?)',randomUUID(),o.id,date,f.amount,f.payer,f.note,actor.name,now());}
|
||||
const keys=new Set(items.map(f=>f.key));this.run('UPDATE orders SET fee_items=?,fees_date=? WHERE id=?',JSON.stringify(o.fee_items.map(f=>keys.has(f.key)?{...items.find(item=>item.key===f.key),status:'recorded'}:f)),date,o.id);
|
||||
if(items.some(f=>f.amount>0))this.dirty(date);
|
||||
}
|
||||
saveOrder(input,actor){
|
||||
recordCardFee(id,payment,actor,{payer='owner',sourceKind='payment',journal=true}={}){
|
||||
if(payment.kind!=='receipt'||payment.amount<=0||!payment.account.endsWith('信用卡'))return null;
|
||||
payer=pick(payer,['owner','assistant'],'信用卡手续费付款人');
|
||||
const order=this.rawOrder(id),key='card_fee:'+payment.id,existing=order.fee_items.find(fee=>fee.key===key);
|
||||
if(existing)return existing;
|
||||
const amount=cardFeeAmount(payment.amount),expenseId=amount?randomUUID():null;
|
||||
if(amount)this.run('INSERT INTO expenses VALUES (?,?,?,?,?,?,?,?)',expenseId,id,payment.date,amount,payer,CARD_FEE_NOTE,actor.name,now());
|
||||
const fee={key,system:'credit_card',source_kind:sourceKind,source_id:payment.id,date:payment.date,amount,payer,note:CARD_FEE_NOTE,status:'recorded',...(expenseId?{expense_id:expenseId}:{})};
|
||||
this.run('UPDATE orders SET fee_items=? WHERE id=?',JSON.stringify([...order.fee_items,fee]),id);
|
||||
if(amount&&journal&&['delivered','returned','cancelled'].includes(order.status))this.journal(id,payment.date,'信用卡手续费',0,0,amount);
|
||||
return fee;
|
||||
}
|
||||
reverseCardFee(id,sourceId,date,actor,reason,{journal=true}={}){
|
||||
const order=this.rawOrder(id),fee=order.fee_items.find(item=>isCardFee(item)&&item.source_id===sourceId);
|
||||
if(!fee)return;
|
||||
const row=fee.expense_id?this.one('SELECT * FROM expenses WHERE id=? AND order_id=?',fee.expense_id,id):null;
|
||||
if(row&&!this.one('SELECT target FROM corrections WHERE target=?',row.id)){
|
||||
this.run('INSERT INTO corrections VALUES (?,?,?,?,?)',row.id,'expense',reason,actor.name,now());
|
||||
this.run('INSERT INTO expenses VALUES (?,?,?,?,?,?,?,?)',randomUUID(),id,date,-row.amount,row.payer,'更正冲回:'+reason,actor.name,now());
|
||||
if(journal&&['delivered','returned','cancelled'].includes(order.status))this.journal(id,date,'信用卡手续费更正',0,0,-row.amount);
|
||||
}
|
||||
this.run('UPDATE orders SET fee_items=? WHERE id=?',JSON.stringify(order.fee_items.filter(item=>item.key!==fee.key)),id);
|
||||
}
|
||||
cardFeeInputs(order,items){
|
||||
const current=order.fee_items.filter(isCardFee),submitted=items.filter(isCardFee);
|
||||
if(current.length!==submitted.length)fail('信用卡手续费由原收款自动维护,请保留全部原费用后重新打开核对',409);
|
||||
const seen=new Set();return submitted.map(item=>{
|
||||
const original=current.find(fee=>fee.key===item.key);
|
||||
if(!original||seen.has(item.key))fail('信用卡手续费来源无效,请重新打开订单',409);seen.add(item.key);
|
||||
for(const key of ['system','source_kind','source_id','expense_id','date','note'])if((item[key]??'')!==(original[key]??''))fail('信用卡手续费金额、日期及原流水由系统维护,不能手工改写',409);
|
||||
if(money(item.amount,'信用卡手续费')!==original.amount)fail('信用卡手续费金额由实收自动计算,不能手工改写');
|
||||
return {...original,payer:pick(item.payer,['owner','assistant'],'信用卡手续费付款人')};
|
||||
});
|
||||
}
|
||||
saveOrder(input,actor,context=null){
|
||||
let id=input.id;
|
||||
const prior=id?this.rawOrder(id):null;
|
||||
if(prior)this.guardOrderCancellation(id);
|
||||
if(prior){this.guardOrderCancellation(id);this.guardOrderChange(id);owner(actor);}
|
||||
if(prior){if(prior.status!=='draft')fail('已确认订单不能直接改写。未交付可取消重开,已交付请办理退货',409);if(prior.revision!==input.revision)fail('订单已被更新,请重新打开',409);}
|
||||
// 历史锁价交付只是内部转换,不强迫改写旧资料;所有实际新建、修改保存必须填写。
|
||||
const identity=context===PRICE_LOCK_DELIVERY?(value,name,max)=>text(value,name,max,true):orderIdentity;
|
||||
const customer=identity(input.customer,'客户称呼/代号',60),salesperson=identity(input.salesperson,'开单人',30);
|
||||
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);
|
||||
@@ -238,7 +295,7 @@ class Ledger {
|
||||
const autoNumber=prior?.paper_date&&prior.paper_number.match(/^\d{8}-?(\d+)$/);
|
||||
const paper=newNumber?this.paperNumber(date,true):autoNumber?date.replaceAll('-','')+autoNumber[1]:prior.paper_number;
|
||||
if(this.one("SELECT id FROM orders WHERE REPLACE(paper_number,'-','')=? AND id<>?",paper.replaceAll('-',''),id||''))fail('该日期已有相同纸单号,请保留原日期或取消后重开',409);
|
||||
const common=[date,text(input.customer,'客户称呼',60,true),text(input.salesperson||actor.name,'开单人',30),text(input.note,'客户单备注',240,true),paper,JSON.stringify(lines),discount,total];
|
||||
const common=[date,customer,salesperson,text(input.note,'客户单备注',240,true),paper,JSON.stringify(lines),discount,total];
|
||||
if(id){
|
||||
this.run('UPDATE orders SET date=?,customer=?,salesperson=?,note=?,paper_number=?,lines=?,discount=?,total=? WHERE id=?',...common,id);this.touch(id);
|
||||
} else {
|
||||
@@ -267,7 +324,7 @@ class Ledger {
|
||||
// 调用方用同一事务生成订单、收全款、记录实际费用并交付;任一步失败全部回滚。
|
||||
// 旧定金单仍沿用原动作,仅经明确确认 complete 后完成交付,不自动补收款。
|
||||
const prior=input.id?this.rawOrder(input.id):null;
|
||||
if(prior)this.guardOrderCancellation(prior.id);
|
||||
if(prior){this.guardOrderCancellation(prior.id);this.guardOrderChange(prior.id);owner(actor);}
|
||||
if(prior&&prior.status!=='draft')fail('已确认订单不能直接改写。未交付可取消重开,已交付请办理退货',409);
|
||||
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)}))??[];
|
||||
@@ -277,9 +334,9 @@ class Ledger {
|
||||
this.validateCompletedCosts(lines,this.validateFees(feeInputs));
|
||||
const {id}=this.saveOrder({...input,fee_items:feeInputs},actor);
|
||||
const o=this.rawOrder(id);
|
||||
this.action(id,'confirm',{date:o.date},actor);
|
||||
this.action(id,'receipt',{date:o.date,amount:(o.total/100).toFixed(2),account:o.payment_account,verified:true,reference:'开单时已全额收款'},actor);
|
||||
this.action(id,'complete',{date:o.date,verified:true},actor);
|
||||
this.action(id,'confirm',{date:o.date},actor,NEW_ORDER_ACTION);
|
||||
this.action(id,'receipt',{date:o.date,amount:(o.total/100).toFixed(2),account:o.payment_account,credit_card_fee_payer:input.credit_card_fee_payer??'owner',verified:true,reference:'开单时已全额收款'},actor,NEW_ORDER_ACTION);
|
||||
this.action(id,'complete',{date:o.date,verified:true},actor,NEW_ORDER_ACTION);
|
||||
this.audit(id,'生成已交付单据',actor,{amount:o.total,account:o.payment_account});
|
||||
return {id};
|
||||
}
|
||||
@@ -302,6 +359,17 @@ class Ledger {
|
||||
const inventory=this.inventory();
|
||||
return {date,yesterdayDate,pockets:ACTIVE_POCKETS,current:inventory.filter(r=>ACTIVE_POCKETS.includes(r.pocket)),yesterday:this.inventorySnapshot(yesterdayDate),todaySnapshot:this.inventorySnapshot(date),revision:this.inventoryRevision(date),legacyInventory:inventory.filter(r=>!ACTIVE_POCKETS.includes(r.pocket)&&(r.mg!==0||r.reserved!==0)),canReview:actor?.role==='owner'};
|
||||
}
|
||||
inventoryMovements(query={}){
|
||||
const historical=new Set(this.rows('SELECT DISTINCT pocket FROM movements').map(r=>r.pocket));
|
||||
const pockets=POCKETS.filter(pocket=>ACTIVE_POCKETS.includes(pocket)||historical.has(pocket)).map(pocket=>({pocket,active:ACTIVE_POCKETS.includes(pocket)}));
|
||||
const pocket=query.pocket??'';
|
||||
if(typeof pocket!=='string'||pocket&&!pockets.some(p=>p.pocket===pocket))fail('筛选货盘无效');
|
||||
const where=pocket?' WHERE pocket=?':'',args=pocket?[pocket]:[];
|
||||
const total=this.one('SELECT COUNT(*) AS total FROM movements'+where,...args).total;
|
||||
// 先筛选再限条数;同一毫秒的流水按实际录入顺序稳定排列。
|
||||
const movements=this.rows('SELECT * FROM movements'+where+' ORDER BY created DESC,rowid DESC LIMIT 100',...args);
|
||||
return {pocket,pockets,total,shown:movements.length,limit:100,movements};
|
||||
}
|
||||
inventorySnapshots(query={}){
|
||||
const date=day(query.date||today()),from=day(query.from||'2000-01-01');
|
||||
if(from>date)fail('开始日期不能晚于结束日期');
|
||||
@@ -345,10 +413,16 @@ class Ledger {
|
||||
}catch(e){this.db.exec('ROLLBACK TO stock_movement');this.db.exec('RELEASE stock_movement');throw e;}
|
||||
}
|
||||
journal(id,date,kind,sales,goods,expense){this.run('INSERT INTO journal VALUES (?,?,?,?,?,?,?,?,?)',randomUUID(),id,date,kind,sales,goods,expense,sales-goods-expense,now());this.dirty(date);}
|
||||
action(id,action,input,actor){
|
||||
action(id,action,input,actor,context=null){
|
||||
const o=this.detail(id);const date=day(input.date||today(),o.date);
|
||||
if(action==='cancel')fail('取消订单须先提交取消申请,并由麦麦账号审批;旧取消接口不能直接作废订单',409);
|
||||
this.guardOrderCancellation(id,{action,type:input.type});
|
||||
this.guardOrderChange(id,{action});
|
||||
if(action==='material')owner(actor);
|
||||
if(actor.role!=='owner'&&context!==NEW_ORDER_ACTION){
|
||||
if(['expense','fees','refund','return','cost'].includes(action))fail('这项订单变更须先提交复核申请,由麦麦批准后入账',403);
|
||||
if(o.pendingFees.length&&(action==='complete'||action==='confirm'&&input.feesVerified===true))fail('本单还有待记费用,请先提交旧费用核实申请,由麦麦批准后继续交付',403);
|
||||
}
|
||||
// 整单更正后旧错日期可能已全额冲零;审计行仍保留,但不能阻挡后续真实业务。
|
||||
const financialDate=this.one('SELECT MAX(date) AS date FROM (SELECT date FROM journal WHERE order_id=? GROUP BY date HAVING SUM(sales)<>0 OR SUM(goods)<>0 OR SUM(expense)<>0)',id)?.date;
|
||||
if(['return','expense','refund','settlement','correct'].includes(action)&&financialDate&&date<financialDate)fail(`该动作日期不能早于本单最近记账日${financialDate}`);
|
||||
@@ -360,7 +434,7 @@ class Ledger {
|
||||
if(input.feesVerified===true&&o.pendingFees.some(f=>f.amount===null))fail('请补齐附加成本;没有发生的费用填0');
|
||||
for(const p of POCKETS){const need=sum(o.lines,l=>l.pocket===p?l.quantity:0);if(need>this.inventory().find(r=>r.pocket===p).available)fail(`${p}可用库存不足,请先登记入库`);}
|
||||
this.run("UPDATE orders SET status='confirmed' WHERE id=?",id);
|
||||
if(input.feesVerified===true&&o.pendingFees.length)this.recordFees(o,o.pendingFees,o.fees_date||date,actor);
|
||||
if(input.feesVerified===true&&o.pendingFees.length)this.recordFees(o,o.pendingFees,o.fees_date||date,actor,context);
|
||||
} else if(action==='receipt'||action==='refund'){
|
||||
if(input.verified!==true)fail('请核实微信/支付宝/现金实际到账或退款后再勾选确认');
|
||||
if(action==='receipt'&&!['confirmed'].includes(o.status))fail('仅待交付订单可以补收款');
|
||||
@@ -371,7 +445,9 @@ class Ledger {
|
||||
const available=sum(o.payments,p=>p.account===account?(p.kind==='receipt'?p.amount:-p.amount):0);
|
||||
if(amount>available)fail('原收款账户可退余额不足;请从原收款账户退款并按账户拆笔登记');
|
||||
}
|
||||
this.run('INSERT INTO payments VALUES (?,?,?,?,?,?,?,?,?)',randomUUID(),id,date,action,amount,account,text(input.reference,'收退款凭据备注',100,true),actor.name,now());
|
||||
const feePayer=action==='receipt'&&account.endsWith('信用卡')?pick(input.credit_card_fee_payer??'owner',['owner','assistant'],'信用卡手续费付款人'):'owner',paymentId=randomUUID();
|
||||
this.run('INSERT INTO payments VALUES (?,?,?,?,?,?,?,?,?)',paymentId,id,date,action,amount,account,text(input.reference,'收退款凭据备注',100,true),actor.name,now());
|
||||
this.recordCardFee(id,{id:paymentId,date,kind:action,amount,account},actor,{payer:feePayer});
|
||||
} else if(action==='expense'){
|
||||
if(o.status==='draft')fail('请先确认订单,再登记实际费用');
|
||||
const amount=money(input.amount);if(amount<=0)fail('费用须大于0');
|
||||
@@ -384,7 +460,7 @@ class Ledger {
|
||||
const fees=this.validateFees(input.fee_items);
|
||||
const keys=new Set(o.pendingFees.map(f=>f.key));
|
||||
if(fees.length!==keys.size||fees.some(f=>!keys.has(f.key)))fail('请逐项核实本单预估成本,不要遗漏');
|
||||
this.recordFees(o,fees,date,actor);
|
||||
this.recordFees(o,fees,date,actor,context);
|
||||
} else if(action==='cost'){
|
||||
if(o.status!=='confirmed')fail('只能在交付前补齐成本;交付后成本已锁定');
|
||||
if(!Array.isArray(input.costs)||input.costs.length!==o.lines.length)fail('请逐行填写成本');
|
||||
@@ -410,8 +486,8 @@ class Ledger {
|
||||
this.validateCompletedCosts(o.lines,o.fee_items);
|
||||
// 老版本无 status 的费用可能已经入账,只有明确待核实的项目才能在此新增支出。
|
||||
const fees=o.pendingFees;
|
||||
if(fees.length)this.recordFees(o,fees,o.fees_date||date,actor);
|
||||
this.action(id,'deliver',{date,verified:true},actor);
|
||||
if(fees.length)this.recordFees(o,fees,o.fees_date||date,actor,context);
|
||||
this.action(id,'deliver',{date,verified:true},actor,context);
|
||||
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&&!o.materialCostPending)fail('请先补齐货品成本,不能把空白当作0');
|
||||
@@ -453,13 +529,16 @@ class Ledger {
|
||||
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(type==='expense'&&o.fee_items.some(fee=>isCardFee(fee)&&fee.expense_id===row.id))fail('信用卡手续费由原收款自动计算;请更正收款或在整单修改中调整手续费付款人');
|
||||
if(this.one('SELECT target FROM corrections WHERE target=?',row.id)||row.amount===0||row.reference?.startsWith('更正冲回:')||row.note?.startsWith('更正冲回:'))fail('这条流水已冲回,请更正最新有效记录');
|
||||
const amount=money(input.amount,'更正后金额');
|
||||
this.run('INSERT INTO corrections VALUES (?,?,?,?,?)',row.id,type,reason,actor.name,now());
|
||||
if(type==='payment'){
|
||||
const account=pick(input.account,ACCOUNTS,'更正后账户');
|
||||
const feePayer=account.endsWith('信用卡')&&row.kind==='receipt'?pick(input.credit_card_fee_payer??'owner',['owner','assistant'],'信用卡手续费付款人'):'owner';
|
||||
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());
|
||||
if(row.kind==='receipt')this.reverseCardFee(id,row.id,date,actor,reason);
|
||||
if(amount){const paymentId=randomUUID();this.run('INSERT INTO payments VALUES (?,?,?,?,?,?,?,?,?)',paymentId,id,date,row.kind,amount,account,'更正补记:'+reason,actor.name,now());this.recordCardFee(id,{id:paymentId,date,kind:row.kind,amount,account},actor,{payer:feePayer});}
|
||||
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){
|
||||
@@ -494,7 +573,12 @@ class Ledger {
|
||||
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);}
|
||||
deliverPriceLock(id,input,actor){
|
||||
return PriceLocks.deliver(this,id,input,actor,{...priceLockEnv,saveDeliveryOrder:input=>this.saveOrder(input,actor,PRICE_LOCK_DELIVERY),completeNewOrder:(orderId,date)=>{
|
||||
this.action(orderId,'confirm',{date},actor,NEW_ORDER_ACTION);
|
||||
this.action(orderId,'complete',{date,verified:true},actor,NEW_ORDER_ACTION);
|
||||
}});
|
||||
}
|
||||
priceLockReporting(query={}){return PriceLocks.reporting(this,query,priceLockEnv);}
|
||||
createMaterialPurchase(input,actor){return MaterialPools.purchase(this,input,actor,priceLockEnv);}
|
||||
materialPoolAllocationStatus(){return MaterialPools.allocationStatus(this);}
|
||||
@@ -553,7 +637,14 @@ class Ledger {
|
||||
orderTemplate(id){return OrderTemplates.detail(this,id);}
|
||||
saveOrderTemplate(id,input,actor){return OrderTemplates.save(this,id,input,actor);}
|
||||
deleteOrderTemplate(id,input,actor){return OrderTemplates.remove(this,id,input,actor);}
|
||||
reportByOrderDate(date,from=date){return reportByOrderDate(this,date,from);}
|
||||
reimbursements(query={},actor){return DailyFunds.list(this,query,actor,priceLockEnv);}
|
||||
createReimbursement(input,actor){return DailyFunds.create(this,input,actor,priceLockEnv);}
|
||||
updateReimbursement(id,input,actor){return DailyFunds.update(this,id,input,actor,priceLockEnv);}
|
||||
approveReimbursement(id,input,actor){return DailyFunds.approve(this,id,input,actor,priceLockEnv);}
|
||||
rejectReimbursement(id,input,actor){return DailyFunds.reject(this,id,input,actor,priceLockEnv);}
|
||||
confirmDailyOutlay(input,actor){return DailyFunds.confirm(this,input,actor,priceLockEnv);}
|
||||
dailyFunds(query={},actor){return DailyFunds.report(this,query,actor,priceLockEnv,date=>dailyFundsReceipts(this,date));}
|
||||
reportByOrderDate(date,from=date,actor=null){return reportByOrderDate(this,date,from,actor,priceLockEnv);}
|
||||
report(date,from=date){
|
||||
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);
|
||||
|
||||
Reference in new issue
Block a user