保存同行基础版:店铺配置与员工管理
This commit is contained in:
1 parent
ecb8d6dec0
commit
b7b987064b
84 files changed
+1884
-573
No files matched your search
+77
-40
@@ -6,6 +6,7 @@ const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const Calc = require('./public/calculations');
|
||||
const CreditCardFees=require('./public/credit-card-fees');
|
||||
const CreditCardRates=require('./credit-card-rates');
|
||||
const {orderBook}=require('./order-book');
|
||||
const {reportByOrderDate,dailyFundsReceipts}=require('./daily-report');
|
||||
const DailyFunds=require('./daily-funds');
|
||||
@@ -20,6 +21,7 @@ const OrderEdit=require('./order-edit');
|
||||
const OrderCancellations=require('./order-cancellations');
|
||||
const OrderChanges=require('./order-changes');
|
||||
const TeamMembers=require('./team-members');
|
||||
const ShopSettings=require('./shop-settings');
|
||||
const TeamFunds=require('./team-funds');
|
||||
const TeamProfits=require('./team-profits');
|
||||
const OrderOwnership=require('./order-ownership');
|
||||
@@ -43,7 +45,6 @@ const POCKETS = ['现货','金料','找金','回收旧料','君宝汇','臻金
|
||||
const ACTIVE_POCKETS = ['现货','金料','找金','回收旧料','君宝汇'];
|
||||
const SELF_POCKETS = ['现货','金料','回收旧料'];
|
||||
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=CreditCardFees.amount;
|
||||
const paymentAccount=value=>pick(CreditCardFees.normalizeAccount(value),ACCOUNTS,'收付款账户');
|
||||
@@ -64,12 +65,16 @@ function peopleNumber(value,name,optional=false){
|
||||
}
|
||||
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 peopleParts(ledger,actor=ledger.actor){
|
||||
const members=ledger.teamMode?TeamMembers.keys(ledger).filter(member=>member!=='owner'):['assistant','assistant2'];
|
||||
const parts=members.map(member=>member==='assistant'?['assistant1','assistant1_count',member]:member==='assistant2'?['assistant2','assistant2_count',member]:[member,member+'_count',member]);
|
||||
return ledger.teamMode&&actor?.role==='assistant'?parts.filter(([, ,member])=>member===ledger.memberFor(actor)):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 peopleSaved(ledger,from,date,parts){
|
||||
// 一次读取范围及每位可见成员的最近有效基准,跨空日、跨月不逐日查询。
|
||||
const columns=parts.map(([,column])=>column),baselines=columns.map(column=>`date=(SELECT MAX(date) FROM daily_people_counts WHERE date<? AND ${column} IS NOT NULL)`);
|
||||
return new Map(ledger.rows(`SELECT date,count,revision,${columns.join(',')} FROM daily_people_counts WHERE (date>=? AND date<=?) OR ${baselines.join(' OR ')} ORDER BY date`,from,date,...columns.map(()=>from)).map(row=>[row.date,row]));
|
||||
const columns=parts.map(([key,column])=>key.startsWith('staff_')?"json_extract(member_counts,'$."+key+"')":column),baselines=columns.map(column=>`date=(SELECT MAX(date) FROM daily_people_counts WHERE date<? AND ${column} IS NOT NULL)`);
|
||||
const rows=ledger.rows(`SELECT date,count,revision,assistant1_count,assistant2_count,member_counts FROM daily_people_counts WHERE (date>=? AND date<=?)${baselines.length?' OR '+baselines.join(' OR '):''} ORDER BY date`,from,date,...columns.map(()=>from));
|
||||
return new Map(rows.map(row=>{const saved=JSON.parse(row.member_counts);for(const [key,column] of parts)if(key.startsWith('staff_'))row[column]=saved[key]??null;return [row.date,row];}));
|
||||
}
|
||||
function peopleBaselines(saved,from,parts){
|
||||
const previous=new Map();
|
||||
@@ -80,6 +85,7 @@ function peopleDay(date,record,previous,parts){
|
||||
// previousDate 保留自然日前边界,实际比较日期在 previousDates 中分别返回。
|
||||
const result={date,previousDate:previousPeopleDate(date),previous:{},previousDates:{},mode:'daily-total'};
|
||||
for(const [key,column] of parts){const total=record?.[column]??null,baseline=previous.get(key)?.total??null,difference=peopleDifference(total,baseline);result[key+'Count']=total;result.previous[key+'Count']=baseline;result.previousDates[key]=previous.get(key)?.date??null;result[key+'Change']=difference.change;result[key+'ChangeReason']=difference.reason;}
|
||||
if(parts.some(([key])=>key.startsWith('staff_')))result.memberCounts=Object.fromEntries(parts.map(([key,,member])=>[member,result[key+'Count']]));
|
||||
return result;
|
||||
}
|
||||
function peoplePeriod(date,from,saved,parts){
|
||||
@@ -104,7 +110,7 @@ function day(value, minimum='2000-01-01') {
|
||||
if(!/^\d{4}-\d{2}-\d{2}$/.test(s)||!Number.isFinite(Date.parse(s+'T00:00:00Z'))||new Date(s+'T00:00:00Z').toISOString().slice(0,10)!==s||s<minimum||s>today()) fail(`业务日期应在${minimum}至${today()}之间`);
|
||||
return s;
|
||||
}
|
||||
const owner=(actor)=>{if(actor.role!=='owner')fail('这项操作由麦麦账号完成',403);};
|
||||
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;
|
||||
@@ -157,11 +163,13 @@ class Ledger {
|
||||
const peopleColumns=this.rows('PRAGMA table_info(daily_people_counts)').map(row=>row.name);
|
||||
for(const name of ['assistant1_count','assistant2_count'])if(!peopleColumns.includes(name))
|
||||
this.db.exec(`ALTER TABLE daily_people_counts ADD COLUMN ${name} INTEGER CHECK(${name} IS NULL OR (typeof(${name})='integer' AND ${name}>=0 AND ${name}<=1000000))`);
|
||||
if(!peopleColumns.includes('member_counts'))this.db.exec("ALTER TABLE daily_people_counts ADD COLUMN member_counts TEXT NOT NULL DEFAULT '{}'");
|
||||
// 旧快照均来自人工保存,只增加来源字段,不重算或补造历史库存。
|
||||
const snapshotColumns=this.rows('PRAGMA table_info(inventory_snapshots)').map(row=>row.name);
|
||||
if(!snapshotColumns.includes('source'))this.db.exec("ALTER TABLE inventory_snapshots ADD COLUMN source TEXT NOT NULL DEFAULT 'manual' CHECK(source IN ('manual','automatic'))");
|
||||
if(!snapshotColumns.includes('scheduled_for'))this.db.exec('ALTER TABLE inventory_snapshots ADD COLUMN scheduled_for TEXT');
|
||||
PriceLocks.initialize(this);
|
||||
CreditCardRates.initialize(this);
|
||||
MaterialPools.initialize(this);
|
||||
PriceLockChanges.initialize(this);
|
||||
OrderTemplates.initialize(this);
|
||||
@@ -187,7 +195,10 @@ class Ledger {
|
||||
reverseMovementCount(original,id){return InventoryCounts.reverse(this,original,id);}
|
||||
validateCountInventory(deltas=[]){return InventoryCounts.assertInventory(this,deltas);}
|
||||
inventoryCountSnapshot(pockets){return InventoryCounts.snapshot(this,pockets);}
|
||||
businessEnv(){return {...priceLockEnv,pockets:this.activePocketKeys(),selfPockets:this.selfPocketKeys(),validatePocket:(key,options)=>this.validatePocket(key,options)};}
|
||||
paymentAccounts(options={}){return TeamFunds.accounts(this,options);}
|
||||
paymentAccount(value,{original=null,historical=false}={}){const account=CreditCardFees.normalizeAccount(value);const allowed=this.paymentAccounts({activeOnly:!historical});if(!allowed.includes(account)&&account!==CreditCardFees.normalizeAccount(original))fail('收付款账户无效或员工已停用');TeamFunds.accountMember(account,this);return account;}
|
||||
validateMember(value,name='付款人',{original=null,historical=false}={}){if(!TeamMembers.keys(this).includes(value)||!historical&&value!==original&&!TeamMembers.activeKeys(this).includes(value))fail(name+'无效或员工已停用');return value;}
|
||||
businessEnv(){return {...priceLockEnv,accounts:this.paymentAccounts({activeOnly:true}),memberKeys:TeamMembers.activeKeys(this),allMemberKeys:TeamMembers.keys(this),validateMember:(value,name,options)=>this.validateMember(value,name,options),paymentAccount:(value,options)=>this.paymentAccount(value,options),cardFee:(cents,rate=CreditCardRates.current(this))=>CreditCardFees.amount(cents,rate),pockets:this.activePocketKeys(),selfPockets:this.selfPocketKeys(),validatePocket:(key,options)=>this.validatePocket(key,options)};}
|
||||
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,this.businessEnv());this.db.exec('RELEASE enable_team_mode');return result;}
|
||||
@@ -205,6 +216,8 @@ class Ledger {
|
||||
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)};}
|
||||
shopSettings(){return ShopSettings.read(this);}
|
||||
updateShopSettings(input,actor=this.actor){return ShopSettings.update(this,input,actor);}
|
||||
migrateTeamMaterialFunding(actor,env=this.businessEnv()){return TeamFunds.migrateMaterialFunding(this,actor,env);}
|
||||
teamFunds(query={},actor=this.actor){return TeamFunds.report(this,query,actor,this.businessEnv());}
|
||||
teamProfits(query={},actor=this.actor){return TeamProfits.report(this,query,actor,this.businessEnv());}
|
||||
@@ -355,7 +368,7 @@ class Ledger {
|
||||
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;
|
||||
return {...o,credit_card_rate_permille:CreditCardRates.read(this,'order',id)};
|
||||
}
|
||||
validateLines(lines,historicalLines=[],businessDate=null,{orderId=null,member=null}={}){
|
||||
if(!Array.isArray(lines)||!lines.length||lines.length>60)fail('每单需要1~60行商品');
|
||||
@@ -377,9 +390,10 @@ class Ledger {
|
||||
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);
|
||||
for(const [part,payer] of Object.entries(costPayers??{}))this.validateMember(payer,'成本垫资人',{original:historicalLines?.[i]?.costPayers?.[part]});
|
||||
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,...(stockCount===null?{}:{stockCount}),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 {name,code:text(l.code,'商品编号',30,true),unit,quantity:qty,pocket,...(stockCount===null?{}:{stockCount}),payer:this.validateMember(l.payer,'成本垫资人',{original:historicalLines?.[i]?.payer}),...(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};
|
||||
});
|
||||
const materialMember=member??(orderId?this.entityMember('order',orderId):null)??(this.actor?this.memberFor(this.actor):null);
|
||||
OrderAfterSales.prepareLines(this,prepared,lines,businessDate,this.businessEnv(),{orderId,member:materialMember});
|
||||
@@ -396,7 +410,7 @@ class Ledger {
|
||||
if(allocate)this.setMeta('paper-sequence',seq);
|
||||
return prefix+String(seq).padStart(3,'0');
|
||||
}
|
||||
validateFees(items){
|
||||
validateFees(items,{historicalFees=[],historicalExpenses=[]}={}){
|
||||
if(items==null)return [];
|
||||
if(!Array.isArray(items)||items.length>6100)fail('直接费用项目无效');
|
||||
const seen=new Set();return items.map(item=>{
|
||||
@@ -405,7 +419,8 @@ 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,...(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)}:{})};
|
||||
const original=historicalFees.find(fee=>fee.key===key)??historicalExpenses.find(fee=>fee.id===item.expense_id);
|
||||
return {key,amount,...(item.funding===undefined?{}:{funding:fundingReference(item.funding)}),payer:this.validateMember(item.payer,'费用付款人',{original:original?.payer}),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){
|
||||
@@ -417,15 +432,16 @@ class Ledger {
|
||||
}
|
||||
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','assistant2'],'信用卡手续费付款人');
|
||||
payer=this.validateMember(payer,'信用卡手续费付款人',{original:sourceKind==='price_lock'?payment.card_fee_payer:recordedFee?.payer});
|
||||
const order=this.rawOrder(id),key='card_fee:'+payment.id,existing=order.fee_items.find(fee=>fee.key===key);
|
||||
if(existing)return existing;
|
||||
// 锁价交付继承原事件已发生费用,旧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;
|
||||
const rate=recordedFee?recordedFee.rate_permille??null:inherited?payment.card_fee_rate??null:CreditCardRates.read(this,'order',id);
|
||||
const amount=recordedFee?.amount??(inherited?payment.card_fee_amount:cardFeeAmount(payment.amount,rate));
|
||||
const note=recordedFee?.note??(inherited?payment.card_fee_note||(rate!==null?CreditCardFees.note(rate):'已记录信用卡手续费'):CreditCardFees.note(rate)),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}:{})};
|
||||
const fee={key,system:'credit_card',source_kind:sourceKind,source_id:payment.id,date:payment.date,amount,payer,note,...(rate!==null?{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;
|
||||
@@ -447,27 +463,28 @@ class Ledger {
|
||||
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);
|
||||
for(const key of ['system','source_kind','source_id','expense_id','date','note','rate_permille'])if((item[key]??'')!==(original[key]??''))fail('信用卡手续费金额、日期及原流水由系统维护,不能手工改写',409);
|
||||
if(money(item.amount,'信用卡手续费')!==original.amount)fail('信用卡手续费金额由实收自动计算,不能手工改写');
|
||||
return {...original,payer:pick(item.payer,['owner','assistant','assistant2'],'信用卡手续费付款人')};
|
||||
return {...original,payer:this.validateMember(item.payer,'信用卡手续费付款人',{original:original.payer})};
|
||||
});
|
||||
}
|
||||
saveOrder(input,actor,context=null){
|
||||
saveOrder(input,actor,context=null,historicalLock=null){
|
||||
let id=input.id;
|
||||
const prior=id?this.rawOrder(id,actor):null;
|
||||
const member=this.selectedMember(input,actor,prior?this.entityMember('order',id):null);
|
||||
const inheritedLock=context===PRICE_LOCK_DELIVERY&&historicalLock?historicalLock:null;
|
||||
const member=this.selectedMember(input,actor,prior?this.entityMember('order',id):inheritedLock?this.entityMember('price_lock',inheritedLock.id):null);
|
||||
if(prior){this.guardRecoveryOrder(id);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;
|
||||
const customer=identity(input.customer,'客户称呼/代号',60),salesperson=identity(input.salesperson,'开单人',30);
|
||||
const date=day(input.date), lines=this.validateLines(input.lines,prior?.lines,date,{orderId:prior?.id??null,member}), discount=money(input.discount||'0','整单优惠');
|
||||
const date=day(input.date), lines=this.validateLines(input.lines,prior?.lines??inheritedLock?.lines.map(entry=>entry.line),date,{orderId:prior?.id??null,member}), discount=money(input.discount||'0','整单优惠');
|
||||
const roundingMode=input.rounding_mode===undefined?(prior?.rounding_mode??'yuan'):input.rounding_mode;
|
||||
const subtotal=sum(lines,'sale');
|
||||
const {total}=context===RECOVERY_ORDER&&subtotal===discount?{total:0}: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 fees=this.validateFees(input.fee_items??prior?.fee_items?.map(r=>({...r,amount:r.amount===null?'':(r.amount/100).toFixed(2)})),{historicalFees:prior?.fee_items??[]});
|
||||
const feesDate=fees.length?day(input.fees_date||date,date):'';
|
||||
const account=paymentAccount(input.payment_account||prior?.payment_account||'助理微信');
|
||||
const account=this.paymentAccount(input.payment_account||prior?.payment_account||(String(member).startsWith('staff_')?member+'微信':'助理微信'),{original:prior?.payment_account??inheritedLock?.cash_events.find(event=>event.kind==='receipt')?.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;
|
||||
@@ -479,6 +496,7 @@ class Ledger {
|
||||
} else {
|
||||
id=randomUUID();const number='MM'+today().replaceAll('-','')+'-'+randomUUID().slice(0,8).toUpperCase();
|
||||
this.run('INSERT INTO orders(id,number,date,customer,salesperson,note,internal_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);
|
||||
CreditCardRates.capture(this,'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};
|
||||
@@ -709,18 +727,19 @@ 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=paymentAccount(input.account);
|
||||
const account=this.paymentAccount(input.account);
|
||||
if(action==='refund'){
|
||||
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','assistant2'],'信用卡手续费付款人'):'owner',paymentId=randomUUID();
|
||||
const feePayer=action==='receipt'&&account.endsWith('信用卡')?this.validateMember(input.credit_card_fee_payer??'owner','信用卡手续费付款人'):'owner',paymentId=randomUUID();
|
||||
if(action==='receipt')CreditCardRates.capture(this,'order',id,o.credit_card_rate_permille);
|
||||
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');
|
||||
const expenseId=randomUUID(),payer=pick(input.payer,['owner','assistant','assistant2'],'费用付款人'),note=text(input.note,'费用项目及原因',150),funding=input.funding===undefined?undefined:fundingReference(input.funding);
|
||||
const expenseId=randomUUID(),payer=this.validateMember(input.payer,'费用付款人'),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);
|
||||
@@ -739,7 +758,8 @@ 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','assistant2'],'成本垫资人');
|
||||
for(const [part,payer] of Object.entries(costPayers??{}))this.validateMember(payer,'成本垫资人',{original:l.costPayers?.[part]});
|
||||
const payer=value.payer===undefined?l.payer:this.validateMember(value.payer,'成本垫资人',{original:l.payer});
|
||||
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'){
|
||||
@@ -827,10 +847,11 @@ class Ledger {
|
||||
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,'更正后金额');
|
||||
if(type==='payment')CreditCardRates.capture(this,'order',id,o.credit_card_rate_permille);
|
||||
this.run('INSERT INTO corrections VALUES (?,?,?,?,?)',row.id,type,reason,actor.name,now());
|
||||
if(type==='payment'){
|
||||
const account=paymentAccount(input.account);
|
||||
const feePayer=account.endsWith('信用卡')&&row.kind==='receipt'?pick(input.credit_card_fee_payer??'owner',['owner','assistant','assistant2'],'信用卡手续费付款人'):'owner';
|
||||
const account=this.paymentAccount(input.account);
|
||||
const feePayer=account.endsWith('信用卡')&&row.kind==='receipt'?this.validateMember(input.credit_card_fee_payer??'owner','信用卡手续费付款人'):'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);
|
||||
@@ -846,7 +867,7 @@ class Ledger {
|
||||
}
|
||||
}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','assistant2'],'更正后付款人'),'更正补记:'+reason,actor.name,now());
|
||||
if(amount)this.run('INSERT INTO expenses VALUES (?,?,?,?,?,?,?,?)',randomUUID(),id,date,amount,this.validateMember(input.payer,'更正后付款人'),'更正补记:'+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());
|
||||
@@ -866,7 +887,7 @@ 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(/^(助理2|助理1|助理|麦麦)/,'')))];
|
||||
const paymentMethods=[...new Set((receiptAccounts.length?receiptAccounts:[o.payment_account]).map(account=>TeamFunds.accountChannel(account)))];
|
||||
return {id:o.id,...(this.teamMode?{member:o.member}:{}),...(o.recovery_id?{recovery_id:o.recovery_id,recovery_mode:'exchange',nonCashOffset:o.nonCashOffset,cashPaid:o.cashPaid,netSettlement:o.netSettlement}:{}),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:o.recovery_id&&!o.netReceived?[]: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}:{})}))};
|
||||
}
|
||||
priceLockEdit(id,actor){return PriceLockChanges.detail(this,id,actor,this.businessEnv());}
|
||||
@@ -881,7 +902,7 @@ class Ledger {
|
||||
priceLocks(query={}){return PriceLocks.list(this,query,this.businessEnv());}
|
||||
priceLockDetail(id){return PriceLocks.detail(this,id,this.businessEnv());}
|
||||
deliverPriceLock(id,input,actor){
|
||||
return PriceLocks.deliver(this,id,input,actor,{...this.businessEnv(),saveDeliveryOrder:input=>this.saveOrder({...input,member:this.entityMember('price_lock',id)||this.memberFor(actor)},actor,PRICE_LOCK_DELIVERY),completeNewOrder:(orderId,date)=>{
|
||||
return PriceLocks.deliver(this,id,input,actor,{...this.businessEnv(),saveDeliveryOrder:input=>this.saveOrder({...input,member:this.entityMember('price_lock',id)||this.memberFor(actor)},actor,PRICE_LOCK_DELIVERY,this.priceLockDetail(id)),completeNewOrder:(orderId,date)=>{
|
||||
this.action(orderId,'confirm',{date},actor,NEW_ORDER_ACTION);
|
||||
this.action(orderId,'complete',{date,verified:true},actor,NEW_ORDER_ACTION);
|
||||
}});
|
||||
@@ -903,7 +924,7 @@ class Ledger {
|
||||
materialPools(query={}){return MaterialPools.list(this,query,this.businessEnv());}
|
||||
materialPoolQuote(input,actor=this.actor){return MaterialPools.quote(this,input,actor,this.businessEnv());}
|
||||
materialPoolDetail(id,query={},actor=this.actor){
|
||||
const member=actor?this.selectedMember(query,actor):query.member??null;
|
||||
const member=TeamMembers.queryMember(this,query,actor)??(actor?this.memberFor(actor):null);
|
||||
return MaterialPools.readPool(this,id,this.businessEnv(),{member});
|
||||
}
|
||||
materialPoolReporting(query={}){return MaterialPools.reporting(this,query,this.businessEnv());}
|
||||
@@ -920,7 +941,7 @@ 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','assistant2'],'费用付款人'),id=randomUUID();
|
||||
const amount=money(input.amount,'售后金额'),payer=this.validateMember(input.payer,'费用付款人'),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});
|
||||
@@ -929,6 +950,7 @@ class Ledger {
|
||||
this.audit('after-sale:'+id,'登记售后',actor,{date,project,customer,amount,payer});
|
||||
return {after_sale_id:id,kind:'afterSale'};
|
||||
}
|
||||
peopleCountParts(actor=this.actor){return peopleParts(this,actor);}
|
||||
peopleCount(date,actor=this.actor){
|
||||
day(date);const parts=peopleParts(this,actor),saved=peopleSaved(this,date,date,parts),record=saved.get(date);
|
||||
const result={...peopleDay(date,record,peopleBaselines(saved,date,parts),parts),revision:record?.revision??0};
|
||||
@@ -954,23 +976,38 @@ class Ledger {
|
||||
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 self=this.teamMode?this.memberFor(actor):null;
|
||||
if(input.memberCounts!==undefined&&(!input.memberCounts||typeof input.memberCounts!=='object'||Array.isArray(input.memberCounts)))fail('成员人数格式无效');
|
||||
if(this.teamMode&&actor.role==='assistant'){
|
||||
const ownKey=self==='assistant'?'assistant1':self;
|
||||
if(Object.hasOwn(input,'count')||['assistant1','assistant2'].some(key=>key!==ownKey&&Object.hasOwn(input,key+'Count'))||Object.keys(input.memberCounts??{}).some(member=>member!==self)||Object.keys(input).some(key=>/^staff_.*Count$/.test(key)&&key!==self+'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);
|
||||
const previous=this.one('SELECT count,assistant1_count,assistant2_count,member_counts,revision FROM daily_people_counts WHERE date=?',date);
|
||||
if(input.revision!==(previous?.revision??0))fail('该日人数已被更新,请刷新后核对再保存',409);
|
||||
// 新页面只填写两位助理;原人数保留旧值,新行用0满足旧表约束,不由分项求和。
|
||||
const count=submittedCount??previous?.count??0;
|
||||
// 旧页面或中断操作缺省的助理项仍保留,显式 null/空白才清为未记录。
|
||||
const assistant1Count=Object.hasOwn(input,'assistant1Count')?peopleNumber(input.assistant1Count,'娜娜人数',true):previous?.assistant1_count??null;
|
||||
const assistant2Count=Object.hasOwn(input,'assistant2Count')?peopleNumber(input.assistant2Count,'小昊人数',true):previous?.assistant2_count??null;
|
||||
const memberCounts=JSON.parse(previous?.member_counts??'{}'),incoming={...(input.memberCounts??{})};
|
||||
for(const key of Object.keys(input))if(/^staff_.*Count$/.test(key)){const member=key.slice(0,-5);if(Object.hasOwn(incoming,member)&&peopleNumber(incoming[member],'人数',true)!==peopleNumber(input[key],'人数',true))fail('同一成员人数填写不一致');incoming[member]=input[key];}
|
||||
for(const [member,key] of [['assistant','assistant1Count'],['assistant2','assistant2Count']])if(Object.hasOwn(incoming,member)){if(Object.hasOwn(input,key)&&peopleNumber(input[key],'人数',true)!==peopleNumber(incoming[member],'人数',true))fail('同一成员人数填写不一致');input={...input,[key]:incoming[member]};}
|
||||
for(const [member,value] of Object.entries(incoming)){
|
||||
if(!TeamMembers.keys(this).includes(member)||member==='owner')fail('成员人数归属无效');
|
||||
const normalized=peopleNumber(value,TeamMembers.label(this,member)+'人数',true),original=member==='assistant'?previous?.assistant1_count??null:member==='assistant2'?previous?.assistant2_count??null:memberCounts[member]??null;
|
||||
if(!TeamMembers.activeKeys(this).includes(member)&&normalized!==original)fail('员工已停用,不能登记新人数');
|
||||
if(member.startsWith('staff_'))memberCounts[member]=normalized;
|
||||
}
|
||||
const assistant1Count=Object.hasOwn(input,'assistant1Count')?peopleNumber(input.assistant1Count,TeamMembers.label(this,'assistant')+'人数',true):previous?.assistant1_count??null;
|
||||
const assistant2Count=Object.hasOwn(input,'assistant2Count')?peopleNumber(input.assistant2Count,TeamMembers.label(this,'assistant2')+'人数',true):previous?.assistant2_count??null;
|
||||
for(const [member,key,value,original] of [['assistant','assistant1Count',assistant1Count,previous?.assistant1_count??null],['assistant2','assistant2Count',assistant2Count,previous?.assistant2_count??null]])if(Object.hasOwn(input,key)&&!TeamMembers.activeKeys(this).includes(member)&&value!==original)fail('员工已停用,不能登记新人数');
|
||||
const revision=input.revision+1,timestamp=now();
|
||||
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);
|
||||
const changed=this.run('INSERT INTO daily_people_counts(date,count,assistant1_count,assistant2_count,member_counts,revision,actor,created,updated) VALUES (?,?,?,?,?,?,?,?,?) ON CONFLICT(date) DO UPDATE SET count=excluded.count,assistant1_count=excluded.assistant1_count,assistant2_count=excluded.assistant2_count,member_counts=excluded.member_counts,revision=excluded.revision,actor=excluded.actor,updated=excluded.updated WHERE daily_people_counts.revision=?',date,count,assistant1Count,assistant2Count,JSON.stringify(memberCounts),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});
|
||||
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,...(Object.keys(memberCounts).length?{memberCounts,previousMemberCounts:JSON.parse(previous?.member_counts??'{}')}:{}),revision});
|
||||
return this.peopleCount(date,actor);
|
||||
}
|
||||
orderBook(query={}){const member=TeamMembers.queryMember(this,query,this.actor)||this.memberFilter;return this.scope(this.actor,()=>orderBook(this,query,{today:today(),validateDay:day,pockets:this.pocketCatalog().map(row=>row.key),accounts:this.teamMode?ACCOUNTS:ACCOUNTS.filter(account=>!account.startsWith('助理2'))}),member);}
|
||||
orderBook(query={}){const member=TeamMembers.queryMember(this,query,this.actor)||this.memberFilter;return this.scope(this.actor,()=>orderBook(this,query,{today:today(),validateDay:day,pockets:this.pocketCatalog().map(row=>row.key),accounts:this.teamMode?[...new Set([...ACCOUNTS,...this.paymentAccounts()])]: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);}
|
||||
|
||||
Reference in new issue
Block a user