支持三人台账、库存更正审批与每日人数增量
This commit is contained in:
1 parent
8d9039aacf
commit
f6bdfcf10d
57 files changed
+2536
-564
No files matched your search
+147
-65
@@ -5,6 +5,7 @@ const { randomUUID, createHash } = require('node:crypto');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const Calc = require('./public/calculations');
|
||||
const CreditCardFees=require('./public/credit-card-fees');
|
||||
const {orderBook}=require('./order-book');
|
||||
const {reportByOrderDate,dailyFundsReceipts}=require('./daily-report');
|
||||
const DailyFunds=require('./daily-funds');
|
||||
@@ -14,6 +15,9 @@ const OrderTemplates=require('./order-templates');
|
||||
const OrderEdit=require('./order-edit');
|
||||
const OrderCancellations=require('./order-cancellations');
|
||||
const OrderChanges=require('./order-changes');
|
||||
const TeamMembers=require('./team-members');
|
||||
const TeamFunds=require('./team-funds');
|
||||
const InventoryChanges=require('./inventory-changes');
|
||||
// 仅服务器的新单生成流程能传入,客户端字段不能取得这个权限。
|
||||
const NEW_ORDER_ACTION=Symbol('newOrderAction');
|
||||
const SAME_DAY_ORDER_ACTION=Symbol('sameDayOrderAction');
|
||||
@@ -22,10 +26,11 @@ const FEE_LABELS={shipping:'快递费',box:'包装盒',certificate:'证书',brai
|
||||
const POCKETS = ['现货','金料','找金','回收旧料','君宝汇','臻金汇','金金','定制工厂'];
|
||||
// 历史货盘仍参与原单、退货和完整库存核算;新登记只使用当前五个货盘。
|
||||
const ACTIVE_POCKETS = ['现货','金料','找金','回收旧料','君宝汇'];
|
||||
const ACCOUNTS = ['助理微信','助理支付宝','助理现金','麦麦微信','麦麦支付宝','麦麦现金','助理信用卡','麦麦信用卡'];
|
||||
const CARD_FEE_NOTE='信用卡手续费(4‰)';
|
||||
const ACCOUNTS = ['助理微信','助理支付宝','助理现金','麦麦微信','麦麦支付宝','麦麦现金','助理信用卡','麦麦信用卡','助理2微信','助理2支付宝','助理2现金','助理2信用卡'];
|
||||
const CARD_FEE_NOTE=CreditCardFees.note();
|
||||
const isCardFee=item=>item?.system==='credit_card'||String(item?.key||'').startsWith('card_fee:');
|
||||
const cardFeeAmount=amount=>Math.floor((amount*4+500)/1000);
|
||||
const cardFeeAmount=CreditCardFees.amount;
|
||||
const paymentAccount=value=>pick(CreditCardFees.normalizeAccount(value),ACCOUNTS,'收付款账户');
|
||||
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);
|
||||
@@ -39,6 +44,23 @@ function peopleNumber(value,name,optional=false){
|
||||
const count=Number(raw);if(!Number.isSafeInteger(count)||count>1000000)fail(`${name}须为0~1000000的整数`);
|
||||
return count;
|
||||
}
|
||||
const PEOPLE_PARTS=[['assistant1','assistant1_count'],['assistant2','assistant2_count']];
|
||||
const previousPeopleDate=date=>new Date(Date.parse(date+'T00:00:00Z')-86400000).toISOString().slice(0,10);
|
||||
function peopleParts(ledger,actor=ledger.actor){return ledger.teamMode&&actor?.role==='assistant'?PEOPLE_PARTS.filter(([key])=>key===(ledger.memberFor(actor)==='assistant'?'assistant1':'assistant2')):PEOPLE_PARTS;}
|
||||
function peopleDifference(current,previous){return {change:current===null||previous===null?null:current-previous,reason:current===null?(previous===null?'missing-both':'missing-current'):previous===null?'missing-previous':null};}
|
||||
function peopleDay(date,record,previous,parts){
|
||||
const result={date,previousDate:previousPeopleDate(date),previous:{},mode:'daily-total'};
|
||||
for(const [key,column] of parts){const total=record?.[column]??null,baseline=previous?.[column]??null,difference=peopleDifference(total,baseline);result[key+'Count']=total;result.previous[key+'Count']=baseline;result[key+'Change']=difference.change;result[key+'ChangeReason']=difference.reason;}
|
||||
return result;
|
||||
}
|
||||
function peoplePeriod(date,from,saved,parts){
|
||||
const baselineDate=previousPeopleDate(from),end=saved.get(date),baseline=saved.get(baselineDate),result={};
|
||||
for(const [key,column] of parts){
|
||||
const endTotal=end?.[column]??null,baselineTotal=baseline?.[column]??null,difference=peopleDifference(endTotal,baselineTotal);
|
||||
result[key]={total:endTotal,endTotal,baselineTotal,netChange:difference.change,netChangeReason:difference.reason,recordedDays:[...saved.values()].filter(row=>row.date>=from&&row.date<=date&&row[column]!==null).length};
|
||||
}
|
||||
return result;
|
||||
}
|
||||
function fixed(value, places, name, negative=false) {
|
||||
const s=String(value??'').trim(); const re=new RegExp(`^${negative?'-?':''}\\d+(?:\\.\\d{1,${places}})?$`);
|
||||
if(!re.test(s)) fail(`${name}须为${negative?'可带负号的':''}数字,最多${places}位小数`);
|
||||
@@ -55,10 +77,23 @@ 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;};
|
||||
function fundingReference(value){
|
||||
if(value===undefined)return undefined;
|
||||
if(!value||typeof value!=='object'||Array.isArray(value))fail('报销来源格式无效');
|
||||
const {reimbursementId,itemId,amount,revision}=value;
|
||||
if(!/^[a-f0-9-]{36}$/.test(String(reimbursementId))||!/^[a-f0-9-]{36}$/.test(String(itemId)))fail('报销来源编号无效');
|
||||
if(amount!==undefined&&money(amount,'报销使用金额')<=0)fail('报销使用金额须大于0');
|
||||
if(revision!==undefined&&(!Number.isSafeInteger(revision)||revision<1))fail('报销来源版本无效');
|
||||
return {reimbursementId,itemId,...(amount!==undefined?{amount:String(amount)}:{}),...(revision!==undefined?{revision}:{})};
|
||||
}
|
||||
function costFundingReferences(value){
|
||||
if(value===undefined)return undefined;if(!value||typeof value!=='object'||Array.isArray(value))fail('货品报销来源格式无效');
|
||||
const result={};for(const [key,source] of Object.entries(value)){if(!['material','labor','accessories','other','total'].includes(key))fail('货品报销成本项目无效');if(source!==null)result[key]=fundingReference(source);}return result;
|
||||
}
|
||||
const priceLockEnv={day,money,weight,text,orderIdentity,fail,pick,today,now,pockets:ACTIVE_POCKETS,accounts:ACCOUNTS};
|
||||
class Ledger {
|
||||
constructor(filename) {
|
||||
this.filename=filename;
|
||||
this.filename=filename;this.teamMode=false;this.actor=null;this.memberFilter=null;
|
||||
if(filename!==':memory:') fs.mkdirSync(path.dirname(filename),{recursive:true,mode:0o700});
|
||||
this.db=new DatabaseSync(filename); this.db.exec('PRAGMA foreign_keys=ON; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=5000;');
|
||||
this.db.exec(`
|
||||
@@ -99,14 +134,36 @@ class Ledger {
|
||||
OrderCancellations.initialize(this);
|
||||
OrderChanges.initialize(this);
|
||||
DailyFunds.initialize(this);
|
||||
TeamMembers.initialize(this);TeamFunds.initialize(this);InventoryChanges.initialize(this);
|
||||
if(filename!==':memory:') fs.chmodSync(filename,0o600);
|
||||
}
|
||||
enableTeamMode(){
|
||||
const previousMode=this.teamMode;this.db.exec('SAVEPOINT enable_team_mode');
|
||||
try{const result=TeamMembers.migrate(this);this.teamMode=true;TeamFunds.migrateMaterialFunding(this,undefined,priceLockEnv);this.db.exec('RELEASE enable_team_mode');return result;}
|
||||
catch(error){this.teamMode=previousMode;this.db.exec('ROLLBACK TO enable_team_mode');this.db.exec('RELEASE enable_team_mode');throw error;}
|
||||
}
|
||||
scope(actor,fn,member=this.memberFilter){const previous=this.actor,filter=this.memberFilter;this.actor=actor;this.memberFilter=member;try{return fn();}finally{this.actor=previous;this.memberFilter=filter;}}
|
||||
asActor(actor){const ledger=this;return new Proxy(this,{get(target,key){const value=target[key];return typeof value==='function'?(...args)=>ledger.scope(actor,()=>value.apply(target,args)):value;}});}
|
||||
memberFor(actor=this.actor){return TeamMembers.memberFor(this,actor);}
|
||||
bindMemberUser(id,member,options){return TeamMembers.bindUser(this,id,member,options);}
|
||||
entityMember(kind,id){return TeamMembers.entityMember(this,kind,id);}
|
||||
assignMember(kind,id,member,{fresh=false}={}){const result=TeamMembers.assign(this,kind,id,member);if(fresh&&this.teamMode)TeamFunds.activate(this,kind,id,{legacy:false});return result;}
|
||||
selectedMember(input,actor=this.actor,existing=null){return TeamMembers.selected(this,input,actor,existing);}
|
||||
canAccess(kind,id,actor=this.actor){return TeamMembers.canAccess(this,kind,id,actor);}
|
||||
assertAccess(kind,id,actor=this.actor){return TeamMembers.assertAccess(this,kind,id,actor);}
|
||||
queryMember(query={},actor=this.actor){return this.memberFilter||TeamMembers.queryMember(this,query,actor);}
|
||||
visibleRows(kind,rows,idKey='id',actor=this.actor,member=this.memberFilter){return TeamMembers.visible(this,kind,rows,idKey,actor,member);}
|
||||
teamMembers(){owner(this.actor);return {members:TeamMembers.users(this)};}
|
||||
migrateTeamMaterialFunding(actor,env=priceLockEnv){return TeamFunds.migrateMaterialFunding(this,actor,env);}
|
||||
teamFunds(query={},actor=this.actor){return TeamFunds.report(this,query,actor,priceLockEnv);}
|
||||
transferTeamFunds(input,actor=this.actor){return TeamFunds.transfer(this,input,actor,priceLockEnv);}
|
||||
syncTeamFunds(actor=this.actor){if(this.teamMode)TeamFunds.syncTouchedOrders(this,actor,priceLockEnv);}
|
||||
rows(sql,...args){return this.db.prepare(sql).all(...args);}
|
||||
one(sql,...args){return this.db.prepare(sql).get(...args);}
|
||||
run(sql,...args){return this.db.prepare(sql).run(...args);}
|
||||
meta(key,fallback=null){const v=this.one('SELECT value FROM meta WHERE key=?',key);return v?JSON.parse(v.value):fallback;}
|
||||
setMeta(key,value){this.run('INSERT INTO meta VALUES (?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value',key,JSON.stringify(value));}
|
||||
audit(entity,action,actor,detail){this.run('INSERT INTO audit(entity,action,actor,detail,created) VALUES (?,?,?,?,?)',entity,action,actor.name,JSON.stringify(detail),now());}
|
||||
audit(entity,action,actor,detail){this.run('INSERT INTO audit(entity,action,actor,detail,created) VALUES (?,?,?,?,?)',entity,action,actor.name,JSON.stringify(this.teamMode?{...detail,actorIdentity:{id:actor.id,role:actor.role,member:this.memberFor(actor)}}:detail),now());}
|
||||
transact(key,actor,payload,fn){
|
||||
if(!/^[a-zA-Z0-9_-]{16,100}$/.test(String(key)))fail('缺少有效操作号,请刷新后重试');
|
||||
const hash=createHash('sha256').update(JSON.stringify({actor:actor.id,payload})).digest('hex');
|
||||
@@ -114,7 +171,7 @@ class Ledger {
|
||||
try {
|
||||
const prior=this.one('SELECT * FROM operations WHERE id=?',key);
|
||||
if(prior){if(prior.hash!==hash)fail('这个操作号已用于其他内容,请重新操作',409);this.db.exec('COMMIT');return JSON.parse(prior.result);}
|
||||
const result=fn();this.run('INSERT INTO operations VALUES (?,?,?)',key,hash,JSON.stringify(result));this.db.exec('COMMIT');return result;
|
||||
const result=fn();this.syncTeamFunds(actor);this.run('INSERT INTO operations VALUES (?,?,?)',key,hash,JSON.stringify(result));this.db.exec('COMMIT');return result;
|
||||
}catch(e){if(this.db.isTransaction)this.db.exec('ROLLBACK');throw e;}
|
||||
}
|
||||
touch(id){this.run('UPDATE orders SET revision=revision+1 WHERE id=?',id);this.enqueue('order:'+id);}
|
||||
@@ -124,7 +181,7 @@ class Ledger {
|
||||
}
|
||||
dirty(date){this.run('UPDATE closes SET stale=1 WHERE date>=?',date);this.enqueue('inventory');}
|
||||
dirtyInventory(date){this.run('UPDATE inventory_snapshots SET stale=1 WHERE date>=?',date);this.dirty(date);}
|
||||
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;}
|
||||
rawOrder(id,actor=this.actor){this.assertAccess('order',id,actor);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);if(this.teamMode)o.member=this.entityMember('order',id);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);}
|
||||
@@ -192,6 +249,7 @@ class Ledger {
|
||||
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;
|
||||
if(this.teamMode){o.funds_mode=this.one("SELECT source_id FROM team_fund_sources WHERE kind='order' AND source_id=?",id)?'team':'legacy';if(o.funds_mode==='team'){o.costDue=0;o.profitDue=0;o.settlementDue=0;o.knownSettlementDue=0;}}
|
||||
return o;
|
||||
}
|
||||
validateLines(lines,historicalLines=[],businessDate=null,{orderId=null}={}){
|
||||
@@ -211,7 +269,7 @@ class Ledger {
|
||||
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 {name,code:text(l.code,'商品编号',30,true),unit,quantity:qty,pocket,payer:pick(l.payer,['owner','assistant','assistant2'],'成本垫资人'),...(costPayers?{costPayers}:{}),...(l.costFundings===undefined?{}:{costFundings:costFundingReferences(l.costFundings)}),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.prepareLines(this,prepared,businessDate,priceLockEnv,{orderId});
|
||||
}
|
||||
@@ -235,24 +293,27 @@ class Ledger {
|
||||
const estimated=item.status==='estimated';
|
||||
const amount=estimated&&(item.amount==null||item.amount==='')?null:money(item.amount,FEE_LABELS[key]||'附加成本');
|
||||
const note=text(item.note||FEE_LABELS[key],'费用项目名称',150);
|
||||
return {key,amount,payer:pick(item.payer,['owner','assistant'],'费用付款人'),note,...(estimated?{status:'estimated',edited:item.edited===true}:{}),...(item.sourceName?{sourceName:text(item.sourceName,'附加项目名称',40)}:{})};
|
||||
return {key,amount,...(item.funding===undefined?{}:{funding:fundingReference(item.funding)}),payer:pick(item.payer,['owner','assistant','assistant2'],'费用付款人'),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,context=null){
|
||||
if(actor.role!=='owner'&&context!==NEW_ORDER_ACTION&&context!==SAME_DAY_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());}
|
||||
for(const f of items)if(f.amount>0){const expenseId=randomUUID();this.run('INSERT INTO expenses VALUES (?,?,?,?,?,?,?,?)',expenseId,o.id,date,f.amount,f.payer,f.note,actor.name,now());if(f.funding)f.expense_id=expenseId;}
|
||||
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);
|
||||
}
|
||||
recordCardFee(id,payment,actor,{payer='owner',sourceKind='payment',journal=true}={}){
|
||||
recordCardFee(id,payment,actor,{payer='owner',sourceKind='payment',journal=true,recordedFee=null}={}){
|
||||
if(payment.kind!=='receipt'||payment.amount<=0||!payment.account.endsWith('信用卡'))return null;
|
||||
payer=pick(payer,['owner','assistant'],'信用卡手续费付款人');
|
||||
payer=pick(payer,['owner','assistant','assistant2'],'信用卡手续费付款人');
|
||||
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}:{})};
|
||||
// 锁价交付继承原事件已发生费用,旧4‰实际费用与备注不能按今天费率重算。
|
||||
const inherited=sourceKind==='price_lock'&&payment.card_fee_amount!==null&&payment.card_fee_amount!==undefined;
|
||||
const amount=recordedFee?.amount??(inherited?payment.card_fee_amount:cardFeeAmount(payment.amount)),rate=recordedFee?recordedFee.rate_permille??null:inherited?payment.card_fee_rate??null:CreditCardFees.ratePermille;
|
||||
const note=recordedFee?.note??(inherited?payment.card_fee_note||(rate?CreditCardFees.note(rate):'已记录信用卡手续费'):CARD_FEE_NOTE),expenseId=amount?randomUUID():null;
|
||||
if(amount)this.run('INSERT INTO expenses VALUES (?,?,?,?,?,?,?,?)',expenseId,id,payment.date,amount,payer,note,actor.name,now());
|
||||
const fee={key,system:'credit_card',source_kind:sourceKind,source_id:payment.id,date:payment.date,amount,payer,note,...(rate?{rate_permille:rate}:{}),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;
|
||||
@@ -276,13 +337,14 @@ class Ledger {
|
||||
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'],'信用卡手续费付款人')};
|
||||
return {...original,payer:pick(item.payer,['owner','assistant','assistant2'],'信用卡手续费付款人')};
|
||||
});
|
||||
}
|
||||
saveOrder(input,actor,context=null){
|
||||
let id=input.id;
|
||||
const prior=id?this.rawOrder(id):null;
|
||||
if(prior){this.guardOrderCancellation(id);this.guardOrderChange(id);owner(actor);}
|
||||
const prior=id?this.rawOrder(id,actor):null;
|
||||
const member=this.selectedMember(input,actor,prior?this.entityMember('order',id):null);
|
||||
if(prior){this.guardOrderCancellation(id);this.guardOrderChange(id);if(!this.teamMode||actor.role!=='assistant'||prior.date!==today()||input.date!==today())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;
|
||||
@@ -292,7 +354,7 @@ class Ledger {
|
||||
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)})));
|
||||
const feesDate=fees.length?day(input.fees_date||date,date):'';
|
||||
const account=pick(input.payment_account||prior?.payment_account||'助理微信',ACCOUNTS,'收款账户');
|
||||
const account=paymentAccount(input.payment_account||prior?.payment_account||'助理微信');
|
||||
const newNumber=!prior?.paper_number;
|
||||
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;
|
||||
@@ -302,7 +364,7 @@ class Ledger {
|
||||
this.run('UPDATE orders SET date=?,customer=?,salesperson=?,note=?,paper_number=?,lines=?,discount=?,total=? WHERE id=?',...common,id);this.touch(id);
|
||||
} else {
|
||||
id=randomUUID();const number='MM'+today().replaceAll('-','')+'-'+randomUUID().slice(0,8).toUpperCase();
|
||||
this.run('INSERT INTO orders(id,number,date,customer,salesperson,note,paper_number,lines,discount,total,status,created) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)',id,number,...common,'draft',now());this.enqueue('order:'+id);
|
||||
this.run('INSERT INTO orders(id,number,date,customer,salesperson,note,paper_number,lines,discount,total,status,created) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)',id,number,...common,'draft',now());this.assignMember('order',id,member,{fresh:true});this.enqueue('order:'+id);
|
||||
}
|
||||
this.run('UPDATE orders SET paper_date=?,payment_account=?,fee_items=?,fees_date=?,rounding_mode=? WHERE id=?',newNumber||autoNumber?date:prior?.paper_date||'',account,JSON.stringify(fees),feesDate,roundingMode,id);
|
||||
this.audit(id,'保存草稿',actor,{revision:this.rawOrder(id).revision});return {id};
|
||||
@@ -325,9 +387,10 @@ class Ledger {
|
||||
issueOrder(input,actor){
|
||||
// 调用方用同一事务生成订单、收全款、记录实际费用并交付;任一步失败全部回滚。
|
||||
// 旧定金单仍沿用原动作,仅经明确确认 complete 后完成交付,不自动补收款。
|
||||
const prior=input.id?this.rawOrder(input.id):null;
|
||||
if(prior){this.guardOrderCancellation(prior.id);this.guardOrderChange(prior.id);owner(actor);}
|
||||
const prior=input.id?this.rawOrder(input.id,actor):null;
|
||||
if(prior){this.guardOrderCancellation(prior.id);this.guardOrderChange(prior.id);if(!this.teamMode||actor.role!=='assistant'||prior.date!==today()||input.date!==today())owner(actor);}
|
||||
if(prior&&prior.status!=='draft')fail('已确认订单不能直接改写。未交付可取消重开,已交付请办理退货',409);
|
||||
this.selectedMember(input,actor,prior?this.entityMember('order',prior.id):null);
|
||||
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('直接费用项目无效');
|
||||
@@ -361,15 +424,16 @@ 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={}){
|
||||
inventoryMovements(query={},actor=this.actor){
|
||||
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 all=this.rows('SELECT * FROM movements'+where+' ORDER BY created DESC,rowid DESC',...args).filter(row=>this.canAccess('movement',row.id,actor));
|
||||
const total=all.length;
|
||||
// 先筛选再限条数;同一毫秒的流水按实际录入顺序稳定排列。
|
||||
const movements=this.rows('SELECT * FROM movements'+where+' ORDER BY created DESC,rowid DESC LIMIT 100',...args);
|
||||
const movements=InventoryChanges.decorate(this,all.slice(0,100),actor,priceLockEnv);
|
||||
return {pocket,pockets,total,shown:movements.length,limit:100,movements};
|
||||
}
|
||||
inventorySnapshots(query={}){
|
||||
@@ -391,8 +455,16 @@ class Ledger {
|
||||
if(typeof input.revision!=='string'||input.revision!==this.inventoryRevision(date))fail('库存有新变动,请刷新后重新核对',409);
|
||||
return {date,snapshot:this.saveInventorySnapshot(date,actor)};
|
||||
}
|
||||
inventoryMovement(id,actor=this.actor){return InventoryChanges.detail(this,id,actor,priceLockEnv);}
|
||||
updateInventoryMovement(id,input,actor=this.actor){return InventoryChanges.change(this,id,'update',input,actor,priceLockEnv);}
|
||||
deleteInventoryMovement(id,input,actor=this.actor){return InventoryChanges.change(this,id,'delete',input,actor,priceLockEnv);}
|
||||
inventoryChanges(query={},actor=this.actor){return InventoryChanges.list(this,query,actor,priceLockEnv);}
|
||||
inventoryChange(id,actor=this.actor){return InventoryChanges.read(this,id,actor,priceLockEnv);}
|
||||
approveInventoryChange(id,input,actor=this.actor){return InventoryChanges.approve(this,id,input,actor,priceLockEnv);}
|
||||
rejectInventoryChange(id,input,actor=this.actor){return InventoryChanges.reject(this,id,input,actor,priceLockEnv);}
|
||||
move({group=randomUUID(),order=null,date,pocket,mg,kind,note,cost=null},actor){
|
||||
this.run('INSERT INTO movements VALUES (?,?,?,?,?,?,?,?,?,?,?)',randomUUID(),group,order,date,pocket,mg,kind,note,cost,actor.name,now());
|
||||
const movementId=randomUUID();this.run('INSERT INTO movements VALUES (?,?,?,?,?,?,?,?,?,?,?)',movementId,group,order,date,pocket,mg,kind,note,cost,actor.name,now());
|
||||
this.assignMember('movement',movementId,order?this.entityMember('order',order)||this.memberFor(actor):this.memberFor(actor));
|
||||
// 回填历史日期也逐日检查,防止只看当前余额掩盖过去负库存。
|
||||
let balance=0;for(const r of this.rows('SELECT date,SUM(mg) AS mg FROM movements WHERE pocket=? GROUP BY date ORDER BY date',pocket)){balance+=r.mg;if(balance<0)fail(`${pocket}在${r.date}库存不足,不能提交`);}
|
||||
const inv=this.inventory().find(r=>r.pocket===pocket);if(inv.available<0)fail(`${pocket}可用库存不足,已有订单占用${(inv.reserved/1000).toFixed(3)}g`);
|
||||
@@ -411,12 +483,15 @@ class Ledger {
|
||||
this.move({group,date,pocket,mg:-mg,kind,note},actor);this.move({group,date,pocket:to,mg,kind,note},actor);
|
||||
}else this.move({group,date,pocket,mg:kind==='decrease'?-mg:mg,kind,note,cost},actor);
|
||||
this.audit('inventory','库存变动',actor,{group,kind,date,pocket,...(to?{to}:{}),grams:input.grams,note});
|
||||
InventoryChanges.register(this,group,actor,priceLockEnv);
|
||||
this.db.exec('RELEASE stock_movement');return {group};
|
||||
}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,context=null){
|
||||
this.assertAccess('order',id,actor);if(Object.hasOwn(input,'member'))this.selectedMember(input,actor,this.entityMember('order',id));
|
||||
const o=this.detail(id);const date=day(input.date||today(),actor.role==='assistant'&&['expense','fees','refund','return'].includes(action)?'2000-01-01':o.date);
|
||||
if(o.funds_mode==='team'&&(action==='settlement'||action==='correct'&&input.type==='settlement'))fail('三人新单请在成员间转款中登记实际付款,旧双方交款入口仅保留历史单据');
|
||||
if(action==='cancel')fail('取消订单须先提交取消申请,并由麦麦账号审批;旧取消接口不能直接作废订单',409);
|
||||
this.guardOrderCancellation(id,{action,type:input.type});
|
||||
this.guardOrderChange(id,{action});
|
||||
@@ -448,18 +523,20 @@ class Ledger {
|
||||
if(action==='receipt'&&!['confirmed'].includes(o.status))fail('仅待交付订单可以补收款');
|
||||
if(action==='refund'&&!['cancelled','returned'].includes(o.status))fail('先取消预订或登记整单退货,再记录实际退款');
|
||||
const amount=money(input.amount);if(amount<=0||amount>(action==='receipt'?o.balance:o.netReceived))fail('金额超过本单待收/待退款余额');
|
||||
const account=pick(input.account,ACCOUNTS,'收退款账户');
|
||||
const account=paymentAccount(input.account);
|
||||
if(action==='refund'){
|
||||
const available=sum(o.payments,p=>p.account===account?(p.kind==='receipt'?p.amount:-p.amount):0);
|
||||
const available=sum(o.payments,p=>(CreditCardFees.isAccount(account)?CreditCardFees.isAccount(p.account):p.account===account)?(p.kind==='receipt'?p.amount:-p.amount):0);
|
||||
if(amount>available)fail('原收款账户可退余额不足;请从原收款账户退款并按账户拆笔登记');
|
||||
}
|
||||
const feePayer=action==='receipt'&&account.endsWith('信用卡')?pick(input.credit_card_fee_payer??'owner',['owner','assistant'],'信用卡手续费付款人'):'owner',paymentId=randomUUID();
|
||||
const feePayer=action==='receipt'&&account.endsWith('信用卡')?pick(input.credit_card_fee_payer??'owner',['owner','assistant','assistant2'],'信用卡手续费付款人'):'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');
|
||||
this.run('INSERT INTO expenses VALUES (?,?,?,?,?,?,?,?)',randomUUID(),id,date,amount,pick(input.payer,['owner','assistant'],'费用付款人'),text(input.note,'费用项目及原因',150),actor.name,now());
|
||||
const expenseId=randomUUID(),payer=pick(input.payer,['owner','assistant','assistant2'],'费用付款人'),note=text(input.note,'费用项目及原因',150),funding=input.funding===undefined?undefined:fundingReference(input.funding);
|
||||
this.run('INSERT INTO expenses VALUES (?,?,?,?,?,?,?,?)',expenseId,id,date,amount,payer,note,actor.name,now());
|
||||
if(funding)this.run('UPDATE orders SET fee_items=? WHERE id=?',JSON.stringify([...o.fee_items,{key:'manual:'+expenseId,amount,payer,note,status:'recorded',expense_id:expenseId,funding}]),id);
|
||||
if(['delivered','returned','cancelled'].includes(o.status))this.journal(id,date,'直接费用',0,0,amount);
|
||||
} else if(action==='fees'){
|
||||
if(o.status!=='confirmed'||!o.pendingFees.length)fail('本单没有待核实的附加成本',409);
|
||||
@@ -476,7 +553,7 @@ class Ledger {
|
||||
const value=input.costs[i];
|
||||
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 payer=value.payer===undefined?l.payer:pick(value.payer,['owner','assistant','assistant2'],'成本垫资人');
|
||||
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'){
|
||||
@@ -542,21 +619,24 @@ class Ledger {
|
||||
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';
|
||||
const account=paymentAccount(input.account);
|
||||
const feePayer=account.endsWith('信用卡')&&row.kind==='receipt'?pick(input.credit_card_fee_payer??'owner',['owner','assistant','assistant2'],'信用卡手续费付款人'):'owner';
|
||||
this.run('INSERT INTO payments VALUES (?,?,?,?,?,?,?,?,?)',randomUUID(),id,date,row.kind,-row.amount,row.account,'更正冲回:'+reason,actor.name,now());
|
||||
const originalFee=o.fee_items.find(fee=>isCardFee(fee)&&fee.source_id===row.id),unchangedCard=row.amount===amount&&row.account===account?originalFee:null;
|
||||
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});}
|
||||
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,recordedFee:unchangedCard});}
|
||||
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(CreditCardFees.isAccount(acc)&&acc!=='麦麦信用卡')continue;
|
||||
const sameAccount=p=>CreditCardFees.isAccount(acc)?CreditCardFees.isAccount(p.account):p.account===acc;
|
||||
// 锁价交付可明确从另一账户退差额;后续更正不能扩大该既有负净额。
|
||||
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('更正后原账户退款超过收款,请先核对关联退款记录');
|
||||
const inherited=o.price_lock_id?sum(updated.payments,p=>p.price_lock_event_id&&sameAccount(p)?(p.kind==='receipt'?p.amount:-p.amount):0):0;
|
||||
if(sum(updated.payments,p=>sameAccount(p)?(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());
|
||||
if(amount)this.run('INSERT INTO expenses VALUES (?,?,?,?,?,?,?,?)',randomUUID(),id,date,amount,pick(input.payer,['owner','assistant','assistant2'],'更正后付款人'),'更正补记:'+reason,actor.name,now());
|
||||
if(['delivered','returned','cancelled'].includes(o.status))this.journal(id,date,'费用更正',0,0,amount-row.amount);
|
||||
}else{
|
||||
this.run('INSERT INTO settlements VALUES (?,?,?,?,?,?,?,?)',randomUUID(),id,date,row.bucket,-row.amount,'更正冲回:'+reason,actor.name,now());
|
||||
@@ -576,21 +656,21 @@ class Ledger {
|
||||
// 打印展示收款渠道,不以此推定到账。旧单尚无收款流水时沿用开单选择。
|
||||
// 更正冲回的旧账户不再显示;实际分次使用不同方式时完整保留。
|
||||
const receiptAccounts=ACCOUNTS.filter(account=>sum(o.payments,p=>p.kind==='receipt'&&p.account===account?p.amount:0)>0);
|
||||
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}:{})}))};
|
||||
const paymentMethods=[...new Set((receiptAccounts.length?receiptAccounts:[o.payment_account]).map(account=>account.replace(/^(助理2|助理1|助理|麦麦)/,'')))];
|
||||
return {id:o.id,...(this.teamMode?{member:o.member}:{}),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,saveDeliveryOrder:input=>this.saveOrder(input,actor,PRICE_LOCK_DELIVERY),completeNewOrder:(orderId,date)=>{
|
||||
return PriceLocks.deliver(this,id,input,actor,{...priceLockEnv,saveDeliveryOrder:input=>this.saveOrder({...input,member:this.entityMember('price_lock',id)||this.memberFor(actor)},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);}
|
||||
materialPoolAllocationStatus(){const status=MaterialPools.allocationStatus(this);if(this.teamMode&&this.actor?.role==='assistant'){const usages=this.visibleRows('order',this.rows('SELECT order_id,active FROM material_pool_usages'),'order_id');return {...status,usageCount:usages.length,activeUsageCount:usages.filter(row=>row.active).length};}return status;}
|
||||
migrateMaterialPoolAllocation(actor,options={}){return MaterialPools.migrateAllocation(this,actor,priceLockEnv,options);}
|
||||
materialPurchaseDetail(id){return MaterialPools.purchaseDetail(this,id,priceLockEnv);}
|
||||
editMaterialPurchase(id,input,actor){return MaterialPools.editPurchase(this,id,input,actor,priceLockEnv);}
|
||||
@@ -605,41 +685,41 @@ class Ledger {
|
||||
if(!input||typeof input!=='object'||Array.isArray(input))fail('售后记录格式无效');
|
||||
if(typeof input.project!=='string'||typeof input.customer!=='string')fail('售后项目和客户称呼须填写文字');
|
||||
const date=day(input.date),project=text(input.project,'售后项目',100),customer=text(input.customer,'客户称呼',60);
|
||||
const amount=money(input.amount,'售后金额'),payer=pick(input.payer,['owner','assistant'],'费用付款人'),id=randomUUID();
|
||||
const amount=money(input.amount,'售后金额'),payer=pick(input.payer,['owner','assistant','assistant2'],'费用付款人'),id=randomUUID();
|
||||
const member=this.selectedMember(input,actor);
|
||||
this.run('INSERT INTO after_sales(id,date,project,customer,amount,payer,actor,created) VALUES (?,?,?,?,?,?,?,?)',id,date,project,customer,amount,payer,actor.name,now());
|
||||
this.assignMember('after_sale',id,member,{fresh:true});
|
||||
// 售后属于所选日期的费用,不能使库存或其他日期的核对状态过期。
|
||||
this.run('UPDATE closes SET stale=1 WHERE date=?',date);
|
||||
this.audit('after-sale:'+id,'登记售后',actor,{date,project,customer,amount,payer});
|
||||
return {after_sale_id:id,kind:'afterSale'};
|
||||
}
|
||||
peopleCount(date){
|
||||
day(date);const record=this.one('SELECT count,assistant1_count,assistant2_count,revision FROM daily_people_counts WHERE date=?',date);
|
||||
return {date,count:record?.count??null,assistant1Count:record?.assistant1_count??null,assistant2Count:record?.assistant2_count??null,revision:record?.revision??0};
|
||||
peopleCount(date,actor=this.actor){
|
||||
day(date);const previousDate=previousPeopleDate(date),saved=new Map(this.rows('SELECT date,count,assistant1_count,assistant2_count,revision FROM daily_people_counts WHERE date IN (?,?)',date,previousDate).map(row=>[row.date,row])),record=saved.get(date);
|
||||
const result={...peopleDay(date,record,saved.get(previousDate),peopleParts(this,actor)),revision:record?.revision??0};
|
||||
if(!this.teamMode)result.count=record?.count??null;return result;
|
||||
}
|
||||
peopleCountSummary(date,from=date){
|
||||
day(date);day(from);if(from>date)fail('开始日期不能晚于结束日期');
|
||||
const totals=this.one(`SELECT COALESCE(SUM(count),0) AS total,COUNT(*) AS recordedDays,
|
||||
COALESCE(SUM(assistant1_count),0) AS assistant1Total,COUNT(assistant1_count) AS assistant1Days,
|
||||
COALESCE(SUM(assistant2_count),0) AS assistant2Total,COUNT(assistant2_count) AS assistant2Days
|
||||
FROM daily_people_counts WHERE date>=? AND date<=?`,from,date);
|
||||
return {from,date,total:totals.total,recordedDays:totals.recordedDays,
|
||||
assistant1:{total:totals.assistant1Total,recordedDays:totals.assistant1Days},assistant2:{total:totals.assistant2Total,recordedDays:totals.assistant2Days}};
|
||||
const baselineDate=previousPeopleDate(from),saved=new Map(this.rows('SELECT date,count,assistant1_count,assistant2_count FROM daily_people_counts WHERE date>=? AND date<=? ORDER BY date',baselineDate,date).map(row=>[row.date,row]));
|
||||
const result={from,date,baselineDate,mode:'daily-total',...peoplePeriod(date,from,saved,peopleParts(this))};
|
||||
if(!this.teamMode){result.total=saved.get(date)?.count??null;result.recordedDays=[...saved.values()].filter(row=>row.date>=from).length;}return result;
|
||||
}
|
||||
peopleCountHistory(query={}){
|
||||
const current=today(),from=day(query.from??current.slice(0,7)+'-01'),date=day(query.date??current);
|
||||
const first=Date.parse(from+'T00:00:00Z'),last=Date.parse(date+'T00:00:00Z'),days=(last-first)/86400000+1;
|
||||
if(from>date)fail('开始日期不能晚于结束日期');if(days>366)fail('每次最多查看366天,请缩小日期范围');
|
||||
const saved=new Map(this.rows('SELECT date,assistant1_count,assistant2_count FROM daily_people_counts WHERE date>=? AND date<=? ORDER BY date',from,date).map(row=>[row.date,row]));
|
||||
const rows=[],summary={assistant1:{total:0,recordedDays:0},assistant2:{total:0,recordedDays:0}};
|
||||
const baselineDate=previousPeopleDate(from),saved=new Map(this.rows('SELECT date,assistant1_count,assistant2_count FROM daily_people_counts WHERE date>=? AND date<=? ORDER BY date',baselineDate,date).map(row=>[row.date,row]));
|
||||
const rows=[],parts=peopleParts(this);
|
||||
for(let i=0;i<days;i++){
|
||||
const date=new Date(first+i*86400000).toISOString().slice(0,10),record=saved.get(date),row={date,assistant1Count:record?.assistant1_count??null,assistant2Count:record?.assistant2_count??null};
|
||||
rows.push(row);for(const key of ['assistant1','assistant2'])if(row[key+'Count']!==null){summary[key].total+=row[key+'Count'];summary[key].recordedDays++;}
|
||||
const date=new Date(first+i*86400000).toISOString().slice(0,10);rows.push(peopleDay(date,saved.get(date),saved.get(previousPeopleDate(date)),parts));
|
||||
}
|
||||
return {from,date,today:current,rows,summary};
|
||||
return {from,date,today:current,baselineDate,mode:'daily-total',rows,summary:peoplePeriod(date,from,saved,parts)};
|
||||
}
|
||||
savePeopleCount(input,actor){
|
||||
if(!actor||!['owner','assistant'].includes(actor.role))fail('请使用麦麦或助理账号登记人数',403);
|
||||
if(!input||typeof input!=='object'||Array.isArray(input))fail('人数记录格式无效');
|
||||
if(this.teamMode&&actor.role==='assistant'){const other=this.memberFor(actor)==='assistant'?'assistant2Count':'assistant1Count';if(Object.hasOwn(input,other)||Object.hasOwn(input,'count'))fail('只能登记本人的人数',403);}
|
||||
const date=day(input.date),submittedCount=Object.hasOwn(input,'count')?peopleNumber(input.count,'人数'):undefined;
|
||||
if(!Number.isSafeInteger(input.revision)||input.revision<0)fail('人数记录版本无效,请刷新后再保存');
|
||||
const previous=this.one('SELECT count,assistant1_count,assistant2_count,revision FROM daily_people_counts WHERE date=?',date);
|
||||
@@ -653,13 +733,15 @@ class Ledger {
|
||||
const changed=this.run('INSERT INTO daily_people_counts(date,count,assistant1_count,assistant2_count,revision,actor,created,updated) VALUES (?,?,?,?,?,?,?,?) ON CONFLICT(date) DO UPDATE SET count=excluded.count,assistant1_count=excluded.assistant1_count,assistant2_count=excluded.assistant2_count,revision=excluded.revision,actor=excluded.actor,updated=excluded.updated WHERE daily_people_counts.revision=?',date,count,assistant1Count,assistant2Count,revision,actor.name,timestamp,timestamp,input.revision);
|
||||
if(changed.changes!==1)fail('该日人数已被更新,请刷新后核对再保存',409);
|
||||
this.audit('people-count:'+date,previous?'更新人数':'登记人数',actor,{date,count,assistant1Count,assistant2Count,previousCount:previous?.count??null,previousAssistant1Count:previous?.assistant1_count??null,previousAssistant2Count:previous?.assistant2_count??null,revision});
|
||||
return {date,count,assistant1Count,assistant2Count,revision};
|
||||
return this.peopleCount(date,actor);
|
||||
}
|
||||
orderBook(query={}){return orderBook(this,query,{today:today(),validateDay:day,accounts:ACCOUNTS});}
|
||||
orderTemplates(){return OrderTemplates.list(this);}
|
||||
orderBook(query={}){const member=TeamMembers.queryMember(this,query,this.actor)||this.memberFilter;return this.scope(this.actor,()=>orderBook(this,query,{today:today(),validateDay:day,accounts:this.teamMode?ACCOUNTS:ACCOUNTS.filter(account=>!account.startsWith('助理2'))}),member);}
|
||||
reportFor(query={},actor=this.actor){const date=query.date||today(),from=query.from||date,basis=query.basis;if(basis!==undefined&&basis!=='orderDate')fail('对账日期口径无效');const member=TeamMembers.queryMember(this,query,actor);return this.scope(actor,()=>basis==='orderDate'?this.reportByOrderDate(date,from,actor):this.report(date,from),member);}
|
||||
orderTemplates(query={}){return this.scope(this.actor,()=>OrderTemplates.list(this),TeamMembers.queryMember(this,query,this.actor));}
|
||||
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);}
|
||||
reimbursementFundingOptions(query={},actor=this.actor){return DailyFunds.fundingOptions(this,query,actor,priceLockEnv);}
|
||||
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);}
|
||||
@@ -670,12 +752,12 @@ class Ledger {
|
||||
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);
|
||||
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);
|
||||
const j=this.visibleRows('order',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),'order_id');
|
||||
const payments=this.visibleRows('order',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),'order_id');
|
||||
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 settles=this.visibleRows('order',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),'order_id');
|
||||
const afterSales=this.visibleRows('after_sale',this.rows('SELECT * FROM after_sales WHERE date>=? AND date<=? ORDER BY date,created,id',from,date));
|
||||
const orders=this.visibleRows('order',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:'附加成本待核实'});
|
||||
@@ -693,7 +775,7 @@ class Ledger {
|
||||
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:orders.filter(o=>!o.cancellationApproved&&o.delivered_date>=from&&o.delivered_date<=date).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};
|
||||
delivered:orders.filter(o=>!o.cancellationApproved&&o.delivered_date>=from&&o.delivered_date<=date).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&&(!this.teamMode||this.actor?.role!=='assistant')?{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('对账日期口径无效');
|
||||
|
||||
Reference in new issue
Block a user