'use strict'; // 金额以分、黄金以毫克储存。业务和流水一起提交,网络重试复用操作号。 const { DatabaseSync, backup } = require('node:sqlite'); const { randomUUID, createHash } = require('node:crypto'); 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 PriceLocks=require('./price-locks'); const MaterialPools=require('./material-pools'); const OrderTemplates=require('./order-templates'); const OrderEdit=require('./order-edit'); const FEE_LABELS={shipping:'快递费',box:'包装盒',certificate:'证书',braiding:'编绳',sticker:'手机贴',other:'其他直接费用'}; const POCKETS = ['现货','金料','找金','回收旧料','君宝汇','臻金汇','金金','定制工厂']; // 历史货盘仍参与原单、退货和完整库存核算;新登记只使用当前五个货盘。 const ACTIVE_POCKETS = ['现货','金料','找金','回收旧料','君宝汇']; const 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); 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 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():''; if(!/^\d+$/.test(raw))fail(`${name}须为0~1000000的整数`); const count=Number(raw);if(!Number.isSafeInteger(count)||count>1000000)fail(`${name}须为0~1000000的整数`); return count; } 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}位小数`); const sign=s.startsWith('-')?-1:1; const [a,b='']=s.replace('-','').split('.'); const n=sign*(Number(a)*10**places+Number(b.padEnd(places,'0'))); if(!Number.isSafeInteger(n)||Math.abs(n)>1e11) fail(`${name}超出支持范围`); return n; } const money=(v,n='金额')=>fixed(v,2,n); const weight=(v,n='克重')=>fixed(v,3,n); function day(value, minimum='2000-01-01') { const s=String(value||''); 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||stoday()) fail(`业务日期应在${minimum}至${today()}之间`); return s; } const owner=(actor)=>{if(actor.role!=='owner')fail('这项操作由麦麦账号完成',403);}; const pick=(v,opts,name)=>{if(!opts.includes(v)) fail(`${name}无效`);return v;}; const priceLockEnv={day,money,weight,text,fail,pick,today,now,pockets:ACTIVE_POCKETS,accounts:ACCOUNTS}; class Ledger { constructor(filename) { this.filename=filename; 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(` CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY,value TEXT NOT NULL); CREATE TABLE IF NOT EXISTS users(id TEXT PRIMARY KEY,name TEXT UNIQUE NOT NULL,role TEXT NOT NULL,salt TEXT NOT NULL,hash TEXT NOT NULL); CREATE TABLE IF NOT EXISTS sessions(hash TEXT PRIMARY KEY,user_id TEXT REFERENCES users(id),expires INTEGER NOT NULL); CREATE TABLE IF NOT EXISTS orders(id TEXT PRIMARY KEY,number TEXT UNIQUE NOT NULL,date TEXT NOT NULL,customer TEXT NOT NULL,salesperson TEXT NOT NULL,note TEXT NOT NULL,paper_number TEXT NOT NULL,status TEXT NOT NULL,lines TEXT NOT NULL,discount INTEGER NOT NULL,total INTEGER NOT NULL,revision INTEGER NOT NULL DEFAULT 1,reviewed_revision INTEGER NOT NULL DEFAULT 0,created TEXT NOT NULL,delivered_date TEXT,returned_date TEXT); CREATE TABLE IF NOT EXISTS payments(id TEXT PRIMARY KEY,order_id TEXT NOT NULL REFERENCES orders(id),date TEXT NOT NULL,kind TEXT NOT NULL,amount INTEGER NOT NULL,account TEXT NOT NULL,reference TEXT NOT NULL,actor TEXT NOT NULL,created TEXT NOT NULL); CREATE TABLE IF NOT EXISTS expenses(id TEXT PRIMARY KEY,order_id TEXT NOT NULL REFERENCES orders(id),date TEXT NOT NULL,amount INTEGER NOT NULL,payer TEXT NOT NULL,note TEXT NOT NULL,actor TEXT NOT NULL,created TEXT NOT NULL); CREATE TABLE IF NOT EXISTS after_sales(id TEXT PRIMARY KEY,date TEXT NOT NULL,project TEXT NOT NULL,customer TEXT NOT NULL,amount INTEGER NOT NULL CHECK(amount>=0),payer TEXT NOT NULL CHECK(payer IN ('owner','assistant')),actor TEXT NOT NULL,created TEXT NOT NULL); CREATE TABLE IF NOT EXISTS daily_people_counts(date TEXT PRIMARY KEY,count INTEGER NOT NULL CHECK(count>=0 AND count<=1000000),revision INTEGER NOT NULL,actor TEXT NOT NULL,created TEXT NOT NULL,updated TEXT NOT NULL); CREATE TABLE IF NOT EXISTS settlements(id TEXT PRIMARY KEY,order_id TEXT NOT NULL REFERENCES orders(id),date TEXT NOT NULL,bucket TEXT NOT NULL,amount INTEGER NOT NULL,note TEXT NOT NULL,actor TEXT NOT NULL,created TEXT NOT NULL); CREATE TABLE IF NOT EXISTS movements(id TEXT PRIMARY KEY,group_id TEXT NOT NULL,order_id TEXT REFERENCES orders(id),date TEXT NOT NULL,pocket TEXT NOT NULL,mg INTEGER NOT NULL,kind TEXT NOT NULL,note TEXT NOT NULL,purchase_cost INTEGER,actor TEXT NOT NULL,created TEXT NOT NULL); CREATE TABLE IF NOT EXISTS journal(id TEXT PRIMARY KEY,order_id TEXT NOT NULL REFERENCES orders(id),date TEXT NOT NULL,kind TEXT NOT NULL,sales INTEGER NOT NULL,goods INTEGER NOT NULL,expense INTEGER NOT NULL,profit INTEGER NOT NULL,created TEXT NOT NULL); CREATE TABLE IF NOT EXISTS audit(id INTEGER PRIMARY KEY AUTOINCREMENT,entity TEXT NOT NULL,action TEXT NOT NULL,actor TEXT NOT NULL,detail TEXT NOT NULL,created TEXT NOT NULL); CREATE TABLE IF NOT EXISTS operations(id TEXT PRIMARY KEY,hash TEXT NOT NULL,result TEXT NOT NULL); CREATE TABLE IF NOT EXISTS corrections(target TEXT PRIMARY KEY,type TEXT NOT NULL,reason TEXT NOT NULL,actor TEXT NOT NULL,created TEXT NOT NULL); CREATE TABLE IF NOT EXISTS sync(entity TEXT PRIMARY KEY,revision INTEGER NOT NULL,done_revision INTEGER NOT NULL DEFAULT 0,record_id TEXT,attempts INTEGER NOT NULL DEFAULT 0,error TEXT,updated TEXT NOT NULL); CREATE TABLE IF NOT EXISTS closes(date TEXT PRIMARY KEY,report TEXT NOT NULL,actor TEXT NOT NULL,created TEXT NOT NULL,stale INTEGER NOT NULL DEFAULT 0); CREATE TABLE IF NOT EXISTS inventory_snapshots(date TEXT PRIMARY KEY,inventory TEXT NOT NULL,actor TEXT NOT NULL,created TEXT NOT NULL,updated TEXT NOT NULL,stale INTEGER NOT NULL DEFAULT 0,revision TEXT NOT NULL); CREATE INDEX IF NOT EXISTS ix_movements_date ON movements(date,pocket); CREATE INDEX IF NOT EXISTS ix_payment_order ON payments(order_id); CREATE INDEX IF NOT EXISTS ix_journal_date ON journal(date); CREATE INDEX IF NOT EXISTS ix_after_sales_date ON after_sales(date); `); // 增量升级旧库,不改写历史订单金额、单号和成本。 const columns=this.rows('PRAGMA table_info(orders)').map(r=>r.name); for(const [name,definition] of Object.entries({paper_date:"TEXT NOT NULL DEFAULT ''",payment_account:"TEXT NOT NULL DEFAULT '助理微信'",fee_items:"TEXT NOT NULL DEFAULT '[]'",fees_date:"TEXT NOT NULL DEFAULT ''",rounding_mode:"TEXT NOT NULL DEFAULT 'cent'"})){ if(!columns.includes(name))this.db.exec(`ALTER TABLE orders ADD COLUMN ${name} ${definition}`); } // 只加可空分项,不把历史原人数归给任一助理,也不改历史版本及录入信息。 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))`); PriceLocks.initialize(this); MaterialPools.initialize(this); OrderTemplates.initialize(this); if(filename!==':memory:') fs.chmodSync(filename,0o600); } 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());} 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'); this.db.exec('BEGIN IMMEDIATE'); 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; }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);} enqueue(entity){ const revision=entity.startsWith('order:')?this.one('SELECT revision FROM orders WHERE id=?',entity.slice(6)).revision:Math.max(Date.now(),(this.one('SELECT revision FROM sync WHERE entity=?',entity)?.revision||0)+1); this.run('INSERT INTO sync(entity,revision,updated) VALUES (?,?,?) ON CONFLICT(entity) DO UPDATE SET revision=excluded.revision,updated=excluded.updated',entity,revision,now()); } 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;} orderEdit(id,actor){return OrderEdit.detail(this,id,actor,priceLockEnv);} editOrder(id,input,actor){return OrderEdit.edit(this,id,input,actor,priceLockEnv);} detail(id){ const o=this.rawOrder(id); o.payments=this.rows('SELECT * FROM payments WHERE order_id=? ORDER BY date,created',id); const priceLock=this.one('SELECT id,buy_payer,delivery FROM price_locks WHERE final_order_id=?',id); if(priceLock){o.price_lock_id=priceLock.id;o.payments.push(...PriceLocks.inheritedPayments(this,id));o.payments.sort((a,b)=>a.date.localeCompare(b.date)||a.created.localeCompare(b.created));} o.expenses=this.rows('SELECT * FROM expenses WHERE order_id=? ORDER BY date,created',id); o.settlements=this.rows('SELECT * FROM settlements WHERE order_id=? ORDER BY date,created',id); o.corrections=this.rows('SELECT * FROM corrections WHERE target IN (SELECT id FROM payments WHERE order_id=? UNION SELECT id FROM expenses WHERE order_id=? UNION SELECT id FROM settlements WHERE order_id=?)',id,id,id); o.received=sum(o.payments,r=>r.kind==='receipt'?r.amount:0);o.refunded=sum(o.payments,r=>r.kind==='refund'?r.amount:0); o.netReceived=o.received-o.refunded;o.balance=(['cancelled','returned'].includes(o.status)?-o.netReceived:o.total-o.netReceived)||0; o.rounding_adjustment=o.rounding_mode==='yuan'?o.total-(sum(o.lines,'sale')-o.discount):0; o.goodsCost=o.lines.some(l=>l.cost===null)?null:sum(o.lines,'cost');o.directCost=sum(o.expenses,'amount'); o.materialCostPending=!['returned','cancelled'].includes(o.status)&&o.lines.some(l=>l.costMaterial?.mode==='pool'&&l.costParts?.material==null); o.knownGoodsCost=sum(o.lines,l=>l.cost??sum(Object.values(l.costParts||{}).map(amount=>({amount:amount??0})),'amount')); o.pendingFees=['draft','confirmed'].includes(o.status)?o.fee_items.filter(f=>f.status!=='recorded'&&(o.status==='draft'||f.status==='estimated')):[]; o.draftFees=sum(o.pendingFees,f=>f.amount||0); o.estimatedProfit=o.goodsCost===null||o.pendingFees.some(f=>f.amount===null)?null:o.total-o.goodsCost-o.directCost-o.draftFees; const j=this.one('SELECT COALESCE(SUM(profit),0) AS profit FROM journal WHERE order_id=?',id);o.profit=o.materialCostPending&&o.status==='delivered'?null:j.profit;o.knownProfit=o.profit??0; o.ownerCost=o.status==='delivered'?Calc.orderCosts(o).byPayer.owner.goods:0; if(['delivered','returned','cancelled'].includes(o.status))o.ownerCost+=sum(o.expenses,e=>e.payer==='owner'?e.amount:0); if(priceLock){ const delivery=priceLock.delivery?JSON.parse(priceLock.delivery):null,sources=[]; const leftover=['delivered','returned'].includes(o.status)&&priceLock.buy_payer==='assistant'?(delivery?.leftover_cost??0):0; if(leftover)sources.push({kind:'leftover',amount:leftover,quantity:delivery.leftover_mg,explanation:'助理垫付的剩余金料进入自有货盘,按原采购成本抵扣货款待结'}); const returned=o.status==='returned'?Calc.orderCosts({...o,status:'delivered'}).byPayer.assistant.goods:0; if(returned)sources.push({kind:'returnedGoods',amount:returned,explanation:'退回自有货盘的商品由助理垫付的货品成本,抵扣货款待结'}); o.assistantInventoryCredit=leftover+returned;o.assistantInventoryCreditSources=sources; o.assistantInventoryCreditExplanation=sources.map(source=>source.explanation).join(';'); } if(!priceLock&&o.status==='returned'&&o.lines.some(line=>line.costMaterial?.mode==='pool')){ const pooled=o.lines.filter(line=>line.costMaterial?.mode==='pool'); const retained=Calc.orderCosts({...o,lines:pooled,status:'delivered'}).rows.filter(row=>row.kind==='goods'&&row.payer==='assistant'&&!row.materialPoolId); const amount=sum(retained,'amount'); if(amount){ o.assistantInventoryCredit=amount; o.assistantInventoryCreditSources=[{kind:'returnedGoods',amount,explanation:'日购料关联商品已退回自有货盘,助理垫付的进货工费、配件和其他货品成本抵扣货款待结;料费由日购料剩余垫款单独抵扣'}]; o.assistantInventoryCreditExplanation=o.assistantInventoryCreditSources[0].explanation; } } o.ownerDirect=sum(o.payments,p=>p.account.startsWith('麦麦')?(p.kind==='receipt'?p.amount:-p.amount):0); // 取消/退货后的麦麦直收款属于待退客户款,不能再算一次应返助理。 o.ownerCredit=o.status==='delivered'||(priceLock&&o.status==='returned'&&o.netReceived===0)?o.ownerDirect:0; o.costTransferred=sum(o.settlements,s=>s.bucket==='cost'?s.amount:0);o.profitTransferred=sum(o.settlements,s=>s.bucket==='profit'?s.amount:0); o.costDue=o.ownerCost-(o.assistantInventoryCredit||0)-o.costTransferred;o.profitDue=o.profit===null?null:o.profit-o.profitTransferred; o.settlementDue=o.materialCostPending&&o.status==='delivered'?null:['delivered','returned','cancelled'].includes(o.status)?o.costDue+o.profitDue-o.ownerCredit:0; o.knownSettlementDue=o.settlementDue??0; o.audit=this.rows('SELECT action,actor,detail,created FROM audit WHERE entity=? ORDER BY id DESC LIMIT 100',id).map(r=>({...r,detail:JSON.parse(r.detail)})); o.sync=this.one('SELECT revision,done_revision,error,updated FROM sync WHERE entity=?','order:'+id)||null; return o; } validateLines(lines,historicalLines=[],businessDate=null,{orderId=null}={}){ if(!Array.isArray(lines)||!lines.length||lines.length>60)fail('每单需要1~60行商品'); const prepared=lines.map((l,i)=>{ const unit=pick(l.unit,['g','件'],'单位');const qty=unit==='g'?weight(l.quantity,`第${i+1}行克重`):fixed(l.quantity,1,'件数')/10; if(qty<=0||(unit==='件'&&!Number.isInteger(qty)))fail('克重必须大于0,件数必须为正整数'); const pocket=l.pocket?pick(l.pocket,POCKETS,'货盘'):'';if(pocket&&unit!=='g')fail('货盘库存按克重管理,按件商品请选外配/不扣黄金'); if(pocket&&!ACTIVE_POCKETS.includes(pocket)&&historicalLines[i]?.pocket!==pocket)fail('这个货盘已停用,新商品请选择当前货盘'); const name=text(l.name,'商品名称',60); if(Calc.isSilver(name)&&pocket)fail('银饰不扣黄金货盘,请选择外配/不扣黄金'); const mode=pick(l.pricingMode||'manual',['auto','manual'],'计价方式'); const priced=Calc.sale({...l,pricingMode:mode}); const pricing=mode==='auto'?priced:null; if(l.costMaterial?.mode==='pool'&&!l.costParts)fail('日购料商品请填写分项成本;没有发生的成本填0'); const breakdown=l.costParts?Calc.purchaseCosts(l):null; const costPayers=Calc.costPayers(l.costPayers===undefined?historicalLines?.[i]?.costPayers:l.costPayers); const cost=breakdown?breakdown.total:(l.cost===''||l.cost==null?null:money(l.cost,'货品成本')); const priceNote=pricing?`金价 ${(pricing.goldPrice/100).toFixed(2)}元/克 + 工费 ${(pricing.laborRate/100).toFixed(2)}元/${pricing.laborMode==='gram'?'克':`件 × ${pricing.pieces}件`}`:text(l.priceNote,'客户单价说明',100,true); return {name,code:text(l.code,'商品编号',30,true),unit,quantity:qty,pocket,payer:pick(l.payer,['owner','assistant'],'成本垫资人'),...(costPayers?{costPayers}:{}),cost,...(breakdown?{costParts:breakdown.parts,costMaterial:breakdown.costMaterial,costLabor:breakdown.costLabor}:{}),sale:priced.sale,baseSale:priced.baseSale,charges:priced.charges,pricingMode:mode,...(pricing?{goldPrice:pricing.goldPrice,laborRate:pricing.laborRate,laborMode:pricing.laborMode,pieces:pricing.pieces}:{}),priceNote}; }); return MaterialPools.prepareLines(this,prepared,businessDate,priceLockEnv,{orderId}); } paperNumber(date,allocate=false){ day(date);const prefix=date.replaceAll('-','');let seq=this.meta('paper-sequence',0); // 接续已经使用过的最大序号,包括旧版按日计数器里不再显示的已占号码。 for(const r of this.rows("SELECT value FROM meta WHERE key LIKE 'paper-seq:%'"))seq=Math.max(seq,JSON.parse(r.value)); for(const r of this.rows('SELECT paper_number FROM orders')){ const match=r.paper_number.match(/^\d{8}-?(\d+)$/);if(match)seq=Math.max(seq,Number(match[1])); } seq++;if(!Number.isSafeInteger(seq))fail('纸单流水号超出范围'); if(allocate)this.setMeta('paper-sequence',seq); return prefix+String(seq).padStart(3,'0'); } validateFees(items){ if(items==null)return []; if(!Array.isArray(items)||items.length>6100)fail('直接费用项目无效'); const seen=new Set();return items.map(item=>{ const key=String(item.key||'');if(!Object.hasOwn(FEE_LABELS,key)&&! /^(charge|manual):[a-f0-9-]{36}$/.test(key))fail('费用项目无效'); if(seen.has(key))fail('同一费用项目不能重复填写');seen.add(key); 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)}:{})}; }).filter(item=>item.status==='estimated'||item.amount>0); } recordFees(o,items,date,actor){ 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){ let id=input.id; const prior=id?this.rawOrder(id):null; if(prior){if(prior.status!=='draft')fail('已确认订单不能直接改写。未交付可取消重开,已交付请办理退货',409);if(prior.revision!==input.revision)fail('订单已被更新,请重新打开',409);} const date=day(input.date), lines=this.validateLines(input.lines,prior?.lines,date), discount=money(input.discount||'0','整单优惠'); const roundingMode=input.rounding_mode===undefined?(prior?.rounding_mode??'yuan'):input.rounding_mode; const {total}=Calc.orderTotal(lines.map(line=>line.sale),discount,roundingMode); const fees=this.validateFees(input.fee_items??prior?.fee_items?.map(r=>({...r,amount:r.amount===null?'':(r.amount/100).toFixed(2)}))); const feesDate=fees.length?day(input.fees_date||date,date):''; const account=pick(input.payment_account||prior?.payment_account||'助理微信',ACCOUNTS,'收款账户'); 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; 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]; if(id){ 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('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}; } validateCompletedCosts(lines,fees){ const missingCosts=lines.flatMap((line,i)=>{ if(line.cost!=null)return []; const missing=line.costParts?Object.entries(Calc.costLabels).filter(([key])=>line.costParts[key]==null&&!(key==='material'&&line.costMaterial?.mode==='pool')).map(([,label])=>label):['货品成本']; return missing.length?[`商品${i+1}的${missing.join('、')}`]:[]; }); if(missingCosts.length)fail(`请补齐${missingCosts.join(';')};没有的成本填0,不能把空白当作0`); const missingFees=fees.filter(f=>f.amount==null).map(f=>f.note); for(const [i,line] of lines.entries())for(const charge of line.charges||[]){ if(!charge.id)continue; const shipping=['快递','快递费','运费'].includes(charge.name),key=shipping?'shipping':'charge:'+charge.id; if(!fees.some(f=>f.key===key))missingFees.push(`商品${i+1}的${charge.name}`); } if(missingFees.length)fail(`请补齐附加成本:${missingFees.join('、')};没有发生的费用填0`); } issueOrder(input,actor){ // 调用方用同一事务生成订单、收全款、记录实际费用并交付;任一步失败全部回滚。 // 旧定金单仍沿用原动作,仅经明确确认 complete 后完成交付,不自动补收款。 const prior=input.id?this.rawOrder(input.id):null; if(prior&&prior.status!=='draft')fail('已确认订单不能直接改写。未交付可取消重开,已交付请办理退货',409); const lines=this.validateLines(input.lines,prior?.lines,day(input.date)); const fees=input.fee_items??prior?.fee_items.map(f=>({...f,amount:f.amount===null?'':(f.amount/100).toFixed(2)}))??[]; if(!Array.isArray(fees))fail('直接费用项目无效'); // 保存时暂用 estimated 保留显式填写的0,随后确认实际费用时统一转为 recorded。 const feeInputs=fees.map(f=>({...f,status:'estimated'})); 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.audit(id,'生成已交付单据',actor,{amount:o.total,account:o.payment_account}); return {id}; } inventory(asOf=null){ const rows=this.rows('SELECT pocket,SUM(mg) AS mg FROM movements'+(asOf?' WHERE date<=?':'')+' GROUP BY pocket',...(asOf?[asOf]:[])); const reserved={};if(!asOf)for(const row of this.rows("SELECT lines FROM orders WHERE status='confirmed'"))for(const l of JSON.parse(row.lines))if(l.pocket)reserved[l.pocket]=(reserved[l.pocket]||0)+l.quantity; return POCKETS.map(p=>({pocket:p,mg:rows.find(r=>r.pocket===p)?.mg||0,reserved:reserved[p]||0,available:(rows.find(r=>r.pocket===p)?.mg||0)-(reserved[p]||0)})); } inventoryRevision(date){ // 流水只追加。计数使同日先增后减、净重不变的并发登记也能被发现。 const count=this.one('SELECT COUNT(*) AS count FROM movements WHERE date<=?',date).count; return createHash('sha256').update(JSON.stringify({date,count,inventory:this.inventory(date)})).digest('hex'); } inventorySnapshot(date){ const row=this.one('SELECT * FROM inventory_snapshots WHERE date=?',date); return row?{...row,inventory:JSON.parse(row.inventory),stale:!!row.stale}:null; } inventoryStatus(actor){ const date=today(),yesterdayDate=new Date(Date.parse(date+'T00:00:00Z')-86400000).toISOString().slice(0,10); 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'}; } inventorySnapshots(query={}){ const date=day(query.date||today()),from=day(query.from||'2000-01-01'); if(from>date)fail('开始日期不能晚于结束日期'); const snapshots=this.rows('SELECT * FROM inventory_snapshots WHERE date>=? AND date<=? ORDER BY date DESC',from,date).map(row=>({...row,inventory:JSON.parse(row.inventory),stale:!!row.stale})); return {from,date,snapshots}; } saveInventorySnapshot(date,actor){ owner(actor);day(date); const inventory=this.inventory(date),revision=this.inventoryRevision(date),timestamp=now(); this.run('INSERT INTO inventory_snapshots(date,inventory,actor,created,updated,stale,revision) VALUES (?,?,?,?,?,0,?) ON CONFLICT(date) DO UPDATE SET inventory=excluded.inventory,actor=excluded.actor,updated=excluded.updated,stale=0,revision=excluded.revision',date,JSON.stringify(inventory),actor.name,timestamp,timestamp,revision); this.audit('inventory:'+date,'复核并保存库存快照',actor,{date,revision,inventory}); return this.inventorySnapshot(date); } reviewInventory(input,actor){ owner(actor);const date=day(input.date||today()); if(input.verified!==true)fail('请先核对各货盘克重,再确认保存快照'); if(typeof input.revision!=='string'||input.revision!==this.inventoryRevision(date))fail('库存有新变动,请刷新后重新核对',409); return {date,snapshot:this.saveInventorySnapshot(date,actor)}; } 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()); // 回填历史日期也逐日检查,防止只看当前余额掩盖过去负库存。 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`); this.dirtyInventory(date); } stock(input,actor){ const kind=pick(input.kind,['increase','decrease','transfer','opening','purchase','adjustment'],'库存动作');const date=day(input.date);const pocket=pick(input.pocket,ACTIVE_POCKETS,'货盘');const note=text(input.note,'备注',200,true); let mg=fixed(input.grams,3,'克重',kind==='adjustment');if(!mg)fail('克重不能为0');if(kind==='opening'||kind==='adjustment')owner(actor); if(kind==='opening'&&this.one('SELECT id FROM movements WHERE pocket=? LIMIT 1',pocket))fail('该货盘已有流水,起始库存不能重复登记;差异请核查后调整'); const group=randomUUID();let cost=null;if(kind==='purchase'&&input.cost!=null&&input.cost!=='')cost=money(input.cost,'本次采购总成本(仅留档,不重复扣订单利润)'); const to=kind==='transfer'?pick(input.to,ACTIVE_POCKETS,'目标货盘'):null;if(to===pocket)fail('来源和目标货盘不能相同'); // 独立调用也保持两边一起提交,任何库存校验失败都不会留下半笔或过期标记。 this.db.exec('SAVEPOINT stock_movement'); try{ if(kind==='transfer'){ 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}); 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){ const o=this.detail(id);const date=day(input.date||today(),o.date); // 整单更正后旧错日期可能已全额冲零;审计行仍保留,但不能阻挡后续真实业务。 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&&datef.status!=='estimated')&&input.feesVerified!==true)fail('请核实开单所填快递、包装等费用已实际支付'); 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); } else if(action==='receipt'||action==='refund'){ if(input.verified!==true)fail('请核实微信/支付宝/现金实际到账或退款后再勾选确认'); 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,'收退款账户'); if(action==='refund'){ 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()); } 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()); 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); if(input.revision!==o.revision)fail('订单已更新,请重新打开成本核实',409); if(input.verified!==true)fail('请核实费用已实际支付,没有发生的填0'); 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); } else if(action==='cost'){ if(o.status!=='confirmed')fail('只能在交付前补齐成本;交付后成本已锁定'); if(!Array.isArray(input.costs)||input.costs.length!==o.lines.length)fail('请逐行填写成本'); o.lines.forEach((l,i)=>{ 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 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'){ if(['labor','accessories','other'].some(key=>l.costParts[key]==null))fail('请补齐每项成本;没有的项目填0'); }else delete l.materialPool; }else{if(l.costParts)fail('这行已拆分成本,请逐项填写');l.cost=money(value,'货品成本');} }); MaterialPools.prepareLines(this,o.lines,o.date,priceLockEnv,{orderId:id}); this.run('UPDATE orders SET lines=? WHERE id=?',JSON.stringify(o.lines),id); } else if(action==='complete'){ if(o.status!=='confirmed')fail('只有待交付订单可以完成交付',409); if(input.revision!=null&&input.revision!==o.revision)fail('订单有新变动,请重新打开后完成记账',409); if(input.verified!==true)fail('请确认已全额收款、核实费用并实际交付'); if(o.balance!==0)fail('未收齐客户款,不能确认交付'); 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); 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'); this.validateCompletedCosts(o.lines,o.fee_items); if(o.pendingFees.length)fail('请先核实附加成本,没有发生的费用填0,不能把预估当作实际费用'); if(input.verified!==true)fail('请确认已复称、收款核实并实际交给客户/快递'); if(o.payments.some(p=>p.date>date)||o.expenses.some(e=>e.date>date))fail('交付日期不能早于本单已登记的收款或费用日期'); this.run("UPDATE orders SET status='delivered',delivered_date=? WHERE id=?",date,id); const delivered=MaterialPools.deliver(this,o,date,actor,priceLockEnv); const group=randomUUID();for(const l of o.lines)if(l.pocket)this.move({group,order:id,date,pocket:l.pocket,mg:-l.quantity,kind:'sale',note:o.number},actor); const knownGoods=sum(delivered.lines,line=>line.cost??sum(Object.values(line.costParts||{}).map(amount=>({amount:amount??0})),'amount')); this.journal(id,date,'交付',o.total,knownGoods,o.directCost); } else if(action==='cancel'){ if(!['draft','confirmed'].includes(o.status))fail('已交付订单请登记退货'); if(o.payments.some(p=>p.date>date)||o.expenses.some(e=>e.date>date))fail('取消日期不能早于本单已登记流水日期'); this.run("UPDATE orders SET status='cancelled' WHERE id=?",id);this.journal(id,date,'取消预订',0,0,o.directCost);text(input.reason,'取消原因',200); } else if(action==='return'){ if(o.status!=='delivered')fail('只有已交付订单可以整单退货',409);if(input.verified!==true)fail('请先确认实物已收回或退回供应商'); text(input.reason,'退货原因',200);this.run("UPDATE orders SET status='returned',returned_date=? WHERE id=?",date,id); const group=randomUUID();o.lines.forEach((l,i)=>{ const destination=input.returnPockets?.[i]??l.pocket; if(l.costMaterial?.mode==='pool'&&!destination)fail('日购料黄金退货须退回自有货盘,请选择实物退回的货盘;退供应商请先核实购料退款'); if(l.pocket&&!destination)fail('原自有货盘商品须选择退回货盘'); if(destination){pick(destination,destination===l.pocket?POCKETS:ACTIVE_POCKETS,'退回货盘');if(l.unit!=='g')fail('按件商品不计黄金货盘');this.move({group,order:id,date,pocket:destination,mg:l.quantity,kind:'return',note:o.number},actor);} }); this.journal(id,date,'整单退货',-o.total,-o.knownGoodsCost,0); MaterialPools.release(this,o,date,actor,priceLockEnv); } else if(action==='settlement'){ if(!['delivered','returned','cancelled'].includes(o.status))fail('定金阶段不结算货款和利润'); if(o.materialCostPending)fail('日购料成本待补,补齐采购后再结算'); const amount=money(input.amount);if(amount<=0)fail('交款须大于0');const bucket=pick(input.bucket,['cost','profit'],'款项归属'); const sign=pick(input.direction,['toOwner','toAssistant'],'转款方向')==='toOwner'?1:-1; if(input.verified!==true)fail('请核实双方实际转账'); // 麦麦直收的订单不猜如何分配货款与利润,由实际转款记录抵减总应结金额。 const due=o.ownerCredit?o.settlementDue:(bucket==='cost'?o.costDue:o.profitDue); if(Math.sign(due)!==sign||amount>Math.abs(due))fail('转款方向或金额超过本单应结余额,请核对实际流水'); this.run('INSERT INTO settlements VALUES (?,?,?,?,?,?,?,?)',randomUUID(),id,date,bucket,sign*amount,text(input.note,'交款凭据/说明',150),actor.name,now()); } else if(action==='material'){ return MaterialPools.reassign(this,o,input,actor,priceLockEnv); } else if(action==='correct'){ owner(actor);const type=pick(input.type,['payment','expense','settlement'],'更正类型');const reason=text(input.reason,'更正原因',200); if(input.verified!==true)fail('请核实原凭据和更正内容'); if(type==='payment'&&o.payments.some(payment=>payment.id===input.target&&payment.price_lock_event_id))fail('锁价实际收退款为不可改写的原始记录,不能从普通订单更正'); const table={payment:'payments',expense:'expenses',settlement:'settlements'}[type];const row=this.one(`SELECT * FROM ${table} WHERE id=? AND order_id=?`,String(input.target),id); if(!row)fail('原流水不存在');if(dateupdated.total||updated.netReceived<0)fail('更正后收退款余额不合理,请核对金额'); if(o.status==='delivered'&&updated.netReceived!==o.total)fail('已交付订单须保持收齐;收款账户可更正,金额差异请先核实真实交付情况'); for(const acc of ACCOUNTS){ // 锁价交付可明确从另一账户退差额;后续更正不能扩大该既有负净额。 const inherited=o.price_lock_id?sum(updated.payments,p=>p.price_lock_event_id&&p.account===acc?(p.kind==='receipt'?p.amount:-p.amount):0):0; if(sum(updated.payments,p=>p.account===acc?(p.kind==='receipt'?p.amount:-p.amount):0)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}:{})}))}; } createPriceLock(input,actor){return PriceLocks.create(this,input,actor,priceLockEnv);} priceLocks(query={}){return PriceLocks.list(this,query,priceLockEnv);} priceLockDetail(id){return PriceLocks.detail(this,id,priceLockEnv);} deliverPriceLock(id,input,actor){return PriceLocks.deliver(this,id,input,actor,priceLockEnv);} priceLockReporting(query={}){return PriceLocks.reporting(this,query,priceLockEnv);} createMaterialPurchase(input,actor){return MaterialPools.purchase(this,input,actor,priceLockEnv);} materialPoolAllocationStatus(){return MaterialPools.allocationStatus(this);} 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);} deleteMaterialPurchase(id,input,actor){return MaterialPools.deletePurchase(this,id,input,actor,priceLockEnv);} materialPools(query={}){return MaterialPools.list(this,query,priceLockEnv);} materialPoolDetail(id){return MaterialPools.readPool(this,id,priceLockEnv);} materialPoolReporting(query={}){return MaterialPools.reporting(this,query,priceLockEnv);} materialPoolSettlement(){return MaterialPools.settlement(this,priceLockEnv);} settleMaterialPool(id,input,actor){return MaterialPools.settle(this,id,input,actor,priceLockEnv);} saveAfterSale(input,actor){ if(!actor||!['owner','assistant'].includes(actor.role))fail('请使用麦麦或助理账号登记售后',403); if(!input||typeof input!=='object'||Array.isArray(input))fail('售后记录格式无效'); 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(); 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.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}; } 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}}; } savePeopleCount(input,actor){ if(!actor||!['owner','assistant'].includes(actor.role))fail('请使用麦麦或助理账号登记人数',403); if(!input||typeof input!=='object'||Array.isArray(input))fail('人数记录格式无效'); const date=day(input.date),count=peopleNumber(input.count,'人数'); 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); if(input.revision!==(previous?.revision??0))fail('该日人数已被更新,请刷新后核对再保存',409); // 旧页面或旧中断操作只有 count;缺省时保留分项,显式 null/空白才清为未记录。 const assistant1Count=Object.hasOwn(input,'assistant1Count')?peopleNumber(input.assistant1Count,'助理1号人数',true):previous?.assistant1_count??null; const assistant2Count=Object.hasOwn(input,'assistant2Count')?peopleNumber(input.assistant2Count,'助理2号人数',true):previous?.assistant2_count??null; 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); 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}; } orderBook(query={}){return orderBook(this,query,{today:today(),validateDay:day,accounts:ACCOUNTS});} orderTemplates(){return OrderTemplates.list(this);} 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);} 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); payments.push(...this.priceLockReporting({from,to:date}).customerCash.map(event=>({...event,price_lock_event_id:event.id}))); const settles=this.rows('SELECT s.*,o.number FROM settlements s JOIN orders o ON o.id=s.order_id WHERE s.date>=? AND s.date<=? ORDER BY s.date,s.created',from,date); const afterSales=this.rows('SELECT * FROM after_sales WHERE date>=? AND date<=? ORDER BY date,created,id',from,date); const orders=this.rows('SELECT id FROM orders ORDER BY created DESC').map(r=>this.detail(r.id)); const accounts=ACCOUNTS.map(account=>({account,receipt:sum(payments,p=>p.account===account&&p.kind==='receipt'?p.amount:0),refund:sum(payments,p=>p.account===account&&p.kind==='refund'?p.amount:0)})); const warnings=[];for(const o of orders){ if(o.status==='confirmed'&&o.pendingFees.length)warnings.push({id:o.id,number:o.number,message:'附加成本待核实'}); if(o.status==='confirmed'&&o.goodsCost===null||o.status==='delivered'&&o.materialCostPending)warnings.push({id:o.id,number:o.number,message:o.materialCostPending?'日购料成本待补,利润与结算暂不确认':'成本待补'}); if(['returned','cancelled'].includes(o.status)&&o.netReceived>0)warnings.push({id:o.id,number:o.number,message:`客户退款待登记:${(o.netReceived/100).toFixed(2)}元`}); if(o.status!=='draft'&&o.reviewed_revision!==o.revision)warnings.push({id:o.id,number:o.number,message:'有记录待麦麦复核'}); if(o.ownerDirect!==0)warnings.push({id:o.id,number:o.number,message:o.status==='delivered'?'麦麦直接收客户款,已扣减总待结金额;货款/利润拆分需单独复核':o.status==='confirmed'?'定金由麦麦直接收取,预订阶段不结算':o.price_lock_id&&o.status==='returned'&&o.netReceived===0?'跨账户收退款差额已纳入双方结算':'麦麦原收款账户仍有待退客户款,不计为应返助理'}); } const check=this.one('SELECT COALESCE(SUM(sales-goods-expense-profit),0) AS delta FROM journal').delta; if(check)warnings.push({message:'利润流水计算不一致,需要维护者检查'}); const close=this.one('SELECT * FROM closes WHERE date=?',date),poolSettlement=this.materialPoolSettlement(),poolActivity=this.materialPoolReporting({from,to:date}); const pendingMaterialOrders=orders.filter(o=>o.status==='delivered'&&o.materialCostPending&&j.some(row=>row.order_id===o.id)); const hasPendingSettlement=orders.some(o=>o.settlementDue===null)||poolSettlement.pendingCount>0; const pendingIds=new Set(pendingMaterialOrders.map(order=>order.id)); const knownProfit=sum(j.filter(row=>!pendingIds.has(row.order_id)),'profit')-sum(afterSales,'amount'),knownSettlementDue=sum(orders,o=>o.knownSettlementDue)+poolSettlement.knownSettlementDue; return {date,from,sales:sum(j,'sales'),goods:pendingMaterialOrders.length?null:sum(j,'goods'),knownGoods:sum(j,'goods'),expense:sum(j,'expense')+sum(afterSales,'amount'),profit:pendingMaterialOrders.length?null:knownProfit,knownProfit,materialCostPending:pendingMaterialOrders.length>0,pendingMaterialCount:pendingMaterialOrders.length, materialPoolActivity:poolActivity,materialPoolSettlement:poolSettlement, delivered:orders.filter(o=>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}; } closeDay(date,actor,basis){ owner(actor);if(basis!==undefined&&basis!=='orderDate')fail('对账日期口径无效'); const report=basis==='orderDate'?this.reportByOrderDate(day(date)):this.report(day(date)); this.run('INSERT INTO closes VALUES (?,?,?,?,0) ON CONFLICT(date) DO UPDATE SET report=excluded.report,actor=excluded.actor,created=excluded.created,stale=0',date,JSON.stringify(report),actor.name,now()); const snapshot=this.saveInventorySnapshot(date,actor); this.audit('day:'+date,'保存核对快照',actor,{warnings:report.warnings.length,...(basis?{basis}:{}),notice:'有待核项不等于已封账;补录会标记快照过期'}); return {date,snapshot,...(basis?{basis,reportRevision:report.reportRevision}:{})}; } async backupTo(filename){fs.mkdirSync(path.dirname(filename),{recursive:true,mode:0o700});await backup(this.db,filename);fs.chmodSync(filename,0o600);return filename;} close(){this.db.close();} } module.exports={Ledger,POCKETS,ACTIVE_POCKETS,ACCOUNTS,today,day,money,weight,fail,text,owner,now};