普通订单取消须麦麦审批并按录错作废冲回
This commit is contained in:
1 parent
46530c29b8
commit
27a11e9b35
28 files changed
+759
-60
No files matched your search
@@ -17,7 +17,7 @@ function paidSource(item,order){
|
||||
function costSummaries(ledger,rows,{excludePoolMaterial=false}={}){
|
||||
const payers={assistant:payerSummary('assistant','助理'),owner:payerSummary('owner','麦麦')};
|
||||
for(const row of rows){
|
||||
const pooled=excludePoolMaterial&&row.materialPoolIds?.length&&row.status!=='draft';
|
||||
const pooled=excludePoolMaterial&&row.materialPoolIds?.length&&row.status!=='draft'&&!row.cancellationApproved;
|
||||
const order=pooled||row.costItems.some(item=>item.kind==='paid')?ledger.rawOrder(row.id):null;
|
||||
let items=row.costItems;
|
||||
if(pooled){
|
||||
|
||||
+15
-5
@@ -11,6 +11,7 @@ const PriceLocks=require('./price-locks');
|
||||
const MaterialPools=require('./material-pools');
|
||||
const OrderTemplates=require('./order-templates');
|
||||
const OrderEdit=require('./order-edit');
|
||||
const OrderCancellations=require('./order-cancellations');
|
||||
const FEE_LABELS={shipping:'快递费',box:'包装盒',certificate:'证书',braiding:'编绳',sticker:'手机贴',other:'其他直接费用'};
|
||||
const POCKETS = ['现货','金料','找金','回收旧料','君宝汇','臻金汇','金金','定制工厂'];
|
||||
// 历史货盘仍参与原单、退货和完整库存核算;新登记只使用当前五个货盘。
|
||||
@@ -85,6 +86,7 @@ class Ledger {
|
||||
PriceLocks.initialize(this);
|
||||
MaterialPools.initialize(this);
|
||||
OrderTemplates.initialize(this);
|
||||
OrderCancellations.initialize(this);
|
||||
if(filename!==':memory:') fs.chmodSync(filename,0o600);
|
||||
}
|
||||
rows(sql,...args){return this.db.prepare(sql).all(...args);}
|
||||
@@ -113,8 +115,16 @@ class Ledger {
|
||||
rawOrder(id){const o=this.one('SELECT * FROM orders WHERE id=?',id);if(!o)fail('订单不存在',404);o.lines=JSON.parse(o.lines);o.fee_items=JSON.parse(o.fee_items);return o;}
|
||||
orderEdit(id,actor){return OrderEdit.detail(this,id,actor,priceLockEnv);}
|
||||
editOrder(id,input,actor){return OrderEdit.edit(this,id,input,actor,priceLockEnv);}
|
||||
orderCancellation(id,actor){return OrderCancellations.detail(this,id,actor,priceLockEnv);}
|
||||
orderCancellations(query={},actor){return OrderCancellations.list(this,query,actor,priceLockEnv);}
|
||||
orderCancellationRequest(id,actor){return OrderCancellations.read(this,id,actor,priceLockEnv);}
|
||||
requestOrderCancellation(id,input,actor){return OrderCancellations.request(this,id,input,actor,priceLockEnv);}
|
||||
approveOrderCancellation(id,input,actor){return OrderCancellations.approve(this,id,input,actor,priceLockEnv);}
|
||||
rejectOrderCancellation(id,input,actor){return OrderCancellations.reject(this,id,input,actor,priceLockEnv);}
|
||||
guardOrderCancellation(id,options){return OrderCancellations.guard(this,id,options,priceLockEnv);}
|
||||
detail(id){
|
||||
const o=this.rawOrder(id);
|
||||
Object.assign(o,OrderCancellations.projection(this,id));
|
||||
o.payments=this.rows('SELECT * FROM payments WHERE order_id=? ORDER BY date,created',id);
|
||||
const priceLock=this.one('SELECT id,buy_payer,delivery FROM price_locks WHERE final_order_id=?',id);
|
||||
if(priceLock){o.price_lock_id=priceLock.id;o.payments.push(...PriceLocks.inheritedPayments(this,id));o.payments.sort((a,b)=>a.date.localeCompare(b.date)||a.created.localeCompare(b.created));}
|
||||
@@ -216,6 +226,7 @@ class Ledger {
|
||||
saveOrder(input,actor){
|
||||
let id=input.id;
|
||||
const prior=id?this.rawOrder(id):null;
|
||||
if(prior)this.guardOrderCancellation(id);
|
||||
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;
|
||||
@@ -256,6 +267,7 @@ class Ledger {
|
||||
// 调用方用同一事务生成订单、收全款、记录实际费用并交付;任一步失败全部回滚。
|
||||
// 旧定金单仍沿用原动作,仅经明确确认 complete 后完成交付,不自动补收款。
|
||||
const prior=input.id?this.rawOrder(input.id):null;
|
||||
if(prior)this.guardOrderCancellation(prior.id);
|
||||
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)}))??[];
|
||||
@@ -335,6 +347,8 @@ class Ledger {
|
||||
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);
|
||||
if(action==='cancel')fail('取消订单须先提交取消申请,并由麦麦账号审批;旧取消接口不能直接作废订单',409);
|
||||
this.guardOrderCancellation(id,{action,type:input.type});
|
||||
// 整单更正后旧错日期可能已全额冲零;审计行仍保留,但不能阻挡后续真实业务。
|
||||
const financialDate=this.one('SELECT MAX(date) AS date FROM (SELECT date FROM journal WHERE order_id=? GROUP BY date HAVING SUM(sales)<>0 OR SUM(goods)<>0 OR SUM(expense)<>0)',id)?.date;
|
||||
if(['return','expense','refund','settlement','correct'].includes(action)&&financialDate&&date<financialDate)fail(`该动作日期不能早于本单最近记账日${financialDate}`);
|
||||
@@ -410,10 +424,6 @@ class Ledger {
|
||||
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);
|
||||
@@ -569,7 +579,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.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?{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('对账日期口径无效');
|
||||
|
||||
@@ -319,12 +319,12 @@ function deliver(ledger,order,date,actor,env){
|
||||
for(const id of pools)reconcile(ledger,id,date,actor,env,{skipJournalOrder:order.id});
|
||||
return ledger.rawOrder(order.id);
|
||||
}
|
||||
function release(ledger,order,date,actor,env){
|
||||
function release(ledger,order,date,actor,env,{kind='实物退回释放'}={}){
|
||||
const usages=ledger.rows('SELECT * FROM material_pool_usages WHERE order_id=? AND active=1',order.id),pools=new Set();
|
||||
for(const usage of usages){
|
||||
const next={...usage,active:0,revision:usage.revision+1};
|
||||
ledger.run('UPDATE material_pool_usages SET active=0,revision=revision+1,updated=? WHERE id=?',env.now(),usage.id);
|
||||
usageEvent(ledger,usage,usageValue(usage),usageValue(next),'实物退回释放',date,actor,env);pools.add(usage.pool_id);
|
||||
usageEvent(ledger,usage,usageValue(usage),usageValue(next),kind,date,actor,env);pools.add(usage.pool_id);
|
||||
}
|
||||
for(const id of pools)reconcile(ledger,id,date,actor,env);
|
||||
}
|
||||
|
||||
+3
-1
@@ -57,11 +57,13 @@ function orderRow(order){
|
||||
if(order.status==='confirmed')hints.push('旧单账务未补齐,利润尚未记账');
|
||||
if(legacyUnallocated)hints.push('原单货品成本未分项,计入未分项成本');
|
||||
if(profitMismatch)hints.push('成本与利润流水不一致,待复核');
|
||||
if(excluded)hints.push('原售价与货品成本已冲回,实际费用保留');
|
||||
if(excluded)hints.push(order.cancellationApproved?'录错作废已获麦麦批准,本单销售、成本与收款记账已撤销,原单和审批记录保留':'原售价与货品成本已冲回,实际费用保留');
|
||||
}
|
||||
return {
|
||||
id:order.id,number:order.number,paper_number:order.paper_number,date:order.date,created:order.created,
|
||||
...(order.price_lock_id?{price_lock_id:order.price_lock_id}:{}),
|
||||
...(order.cancellationPending?{cancellationPending:order.cancellationPending}:{}),
|
||||
...(order.cancellationApproved?{cancellationApproved:order.cancellationApproved}:{}),
|
||||
...(materialPoolIds.length?{materialPoolIds,materialCostPending}:{}),
|
||||
customer:order.customer,salesperson:order.salesperson,status:order.status,note:order.note,
|
||||
types:[...new Set(order.lines.map(lineType))],
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
'use strict';
|
||||
// 录错订单的作废审批。原单、原流水和真实双方转账保留,批准时只追加更正。
|
||||
const {randomUUID,createHash}=require('node:crypto');
|
||||
const MaterialPools=require('./material-pools');
|
||||
const hash=value=>createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
||||
function activeActor(actor,env){if(!actor||!['owner','assistant'].includes(actor.role))env.fail('请使用麦麦或助理账号处理取消申请',403);}
|
||||
function owner(actor,env){activeActor(actor,env);if(actor.role!=='owner')env.fail('取消申请必须由麦麦账号审批',403);}
|
||||
function inputObject(input,env){if(!input||typeof input!=='object'||Array.isArray(input))env.fail('取消申请内容无效');}
|
||||
function atomic(ledger,fn){
|
||||
ledger.db.exec('SAVEPOINT order_cancellation_action');
|
||||
try{const result=fn();ledger.db.exec('RELEASE order_cancellation_action');return result;}
|
||||
catch(error){ledger.db.exec('ROLLBACK TO order_cancellation_action');ledger.db.exec('RELEASE order_cancellation_action');throw error;}
|
||||
}
|
||||
function initialize(ledger){ledger.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS order_cancellations(
|
||||
id TEXT PRIMARY KEY,order_id TEXT NOT NULL REFERENCES orders(id),order_revision INTEGER NOT NULL,
|
||||
reason TEXT NOT NULL,snapshot TEXT NOT NULL,snapshot_hash TEXT NOT NULL,
|
||||
status TEXT NOT NULL CHECK(status IN ('pending','approved','rejected')),
|
||||
requester_id TEXT NOT NULL,requester_name TEXT NOT NULL,requester_role TEXT NOT NULL,created TEXT NOT NULL,
|
||||
reviewer_id TEXT,reviewer_name TEXT,reviewed TEXT,note TEXT NOT NULL DEFAULT '');
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS ix_order_cancellation_pending ON order_cancellations(order_id) WHERE status='pending';
|
||||
CREATE INDEX IF NOT EXISTS ix_order_cancellation_status ON order_cancellations(status,created);
|
||||
`);}
|
||||
function pending(ledger,id){return ledger.one("SELECT * FROM order_cancellations WHERE order_id=? AND status='pending'",id)||null;}
|
||||
function approved(ledger,id){return ledger.one("SELECT * FROM order_cancellations WHERE order_id=? AND status='approved' ORDER BY created DESC LIMIT 1",id)||null;}
|
||||
function eligibility(ledger,order){
|
||||
if(ledger.one('SELECT id FROM price_locks WHERE final_order_id=?',order.id)||order.lines.some(line=>line.materialAllocations))return '锁价关联订单本次不支持取消申请,请保留原采购与收退款记录';
|
||||
if(!['draft','confirmed','delivered'].includes(order.status))return '已取消或已退货订单不能重复申请取消';
|
||||
return '';
|
||||
}
|
||||
function snapshot(ledger,id){
|
||||
const order=ledger.rawOrder(id),tables={};
|
||||
for(const table of ['payments','expenses','settlements','journal','movements'])tables[table]=ledger.rows('SELECT * FROM '+table+' WHERE order_id=? ORDER BY rowid',id);
|
||||
tables.corrections=ledger.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=?) ORDER BY rowid',id,id,id);
|
||||
tables.materialUsages=ledger.rows('SELECT * FROM material_pool_usages WHERE order_id=? ORDER BY rowid',id);
|
||||
const priceLock=ledger.one('SELECT id FROM price_locks WHERE final_order_id=?',id)?.id||null;
|
||||
return {order,...tables,priceLock};
|
||||
}
|
||||
function inventoryReversal(ledger,id){return ledger.rows('SELECT date,pocket,-SUM(mg) AS mg FROM movements WHERE order_id=? GROUP BY date,pocket HAVING SUM(mg)<>0 ORDER BY date,pocket',id);}
|
||||
function summary(ledger,order){return {total:order.total,netReceived:order.netReceived,goodsCost:order.goodsCost,directCost:order.directCost,profit:order.profit,settlementDue:order.settlementDue,inventory:inventoryReversal(ledger,order.id)};}
|
||||
function rowDetail(ledger,row,actor){
|
||||
const saved=JSON.parse(row.snapshot),order=ledger.rawOrder(row.order_id);
|
||||
const stale=row.status==='pending'&&(order.revision!==row.order_revision||hash(snapshot(ledger,row.order_id))!==row.snapshot_hash);
|
||||
const {snapshot:stored,snapshot_hash:storedHash,...fields}=row;
|
||||
return {...fields,order_number:saved.data.order.number,order_date:saved.data.order.date,order_status:saved.data.order.status,
|
||||
stale,canApprove:actor?.role==='owner'&&row.status==='pending'&&!stale&&!eligibility(ledger,order),summary:saved.summary};
|
||||
}
|
||||
function projection(ledger,id){
|
||||
const request=pending(ledger,id),accepted=approved(ledger,id);
|
||||
const compact=row=>row?{id:row.id,status:row.status,order_revision:row.order_revision,reason:row.reason,requester_name:row.requester_name,created:row.created,reviewer_name:row.reviewer_name,reviewed:row.reviewed,note:row.note}:null;
|
||||
return {cancellationPending:request?{...compact(request),stale:ledger.rawOrder(id).revision!==request.order_revision||hash(snapshot(ledger,id))!==request.snapshot_hash}:null,cancellationApproved:compact(accepted)};
|
||||
}
|
||||
function detail(ledger,id,actor,env){
|
||||
activeActor(actor,env);const order=ledger.rawOrder(id),reason=eligibility(ledger,order);
|
||||
const requests=ledger.rows('SELECT * FROM order_cancellations WHERE order_id=? ORDER BY created DESC,rowid DESC',id).map(row=>rowDetail(ledger,row,actor));
|
||||
return {eligible:!reason&&!requests.some(row=>row.status==='pending'),reason:reason||(requests.some(row=>row.status==='pending')?'本单已有取消申请,请先由麦麦审批':''),revision:order.revision,
|
||||
pending:requests.find(row=>row.status==='pending')||null,requests,canApprove:actor.role==='owner'};
|
||||
}
|
||||
function list(ledger,query,actor,env){
|
||||
activeActor(actor,env);const status=env.pick(query.status??'pending',['pending','approved','rejected','all'],'取消审批状态');
|
||||
const rows=ledger.rows('SELECT * FROM order_cancellations'+(status==='all'?'':' WHERE status=?')+' ORDER BY created DESC,rowid DESC',...(status==='all'?[]:[status]));
|
||||
const counts={pending:0,approved:0,rejected:0};for(const row of ledger.rows('SELECT status,COUNT(*) AS count FROM order_cancellations GROUP BY status'))counts[row.status]=row.count;
|
||||
return {requests:rows.map(row=>rowDetail(ledger,row,actor)),counts,canApprove:actor.role==='owner'};
|
||||
}
|
||||
function read(ledger,id,actor,env){
|
||||
activeActor(actor,env);const row=ledger.one('SELECT * FROM order_cancellations WHERE id=?',id);if(!row)env.fail('取消申请不存在',404);
|
||||
return rowDetail(ledger,row,actor);
|
||||
}
|
||||
function request(ledger,id,input,actor,env){return atomic(ledger,()=>{
|
||||
activeActor(actor,env);inputObject(input,env);const order=ledger.detail(id),reason=eligibility(ledger,order);
|
||||
if(reason)env.fail(reason,409);
|
||||
if(pending(ledger,id))env.fail('本单已有待审批取消申请,请先由麦麦处理',409);
|
||||
if(!Number.isSafeInteger(input.revision)||input.revision!==order.revision)env.fail('订单有新变动,请重新打开核对后申请取消',409);
|
||||
const explanation=env.text(input.reason,'录错作废原因',200),requestId=randomUUID(),created=env.now(),data=snapshot(ledger,id),saved={data,summary:summary(ledger,order)};
|
||||
ledger.run("INSERT INTO order_cancellations(id,order_id,order_revision,reason,snapshot,snapshot_hash,status,requester_id,requester_name,requester_role,created) VALUES (?,?,?,?,?,?,'pending',?,?,?,?)",requestId,id,order.revision,explanation,JSON.stringify(saved),hash(data),actor.id,actor.name,actor.role,created);
|
||||
ledger.audit(id,'申请取消订单',actor,{requestId,reason:explanation,revision:order.revision,summary:saved.summary,notice:'申请不改变原订单状态、财务与库存;按录错作废提交麦麦审批'});
|
||||
return {id,requestId,request:read(ledger,requestId,actor,env),order:ledger.detail(id)};
|
||||
});}
|
||||
function pendingDecision(ledger,id,actor,env){
|
||||
owner(actor,env);const row=ledger.one('SELECT * FROM order_cancellations WHERE id=?',id);if(!row)env.fail('取消申请不存在',404);
|
||||
if(row.status!=='pending')env.fail('这份取消申请已经处理,请刷新查看',409);return row;
|
||||
}
|
||||
function reversePayments(ledger,order,reason,actor,env){
|
||||
const corrected=new Set(order.corrections.filter(row=>row.type==='payment').map(row=>row.target));
|
||||
for(const row of order.payments)if(row.amount>0&&!corrected.has(row.id)&&!row.reference.startsWith('更正冲回:'))ledger.run('INSERT INTO corrections VALUES (?,?,?,?,?)',row.id,'payment',reason,actor.name,env.now());
|
||||
// 跨日更正的旧日正数与更正日负数也逐日归零,不能残留虚构收款。
|
||||
for(const row of ledger.rows('SELECT date,kind,account,SUM(amount) AS amount FROM payments WHERE order_id=? GROUP BY date,kind,account HAVING SUM(amount)<>0 ORDER BY date,kind,account',order.id)){
|
||||
const id=randomUUID();ledger.run('INSERT INTO payments VALUES (?,?,?,?,?,?,?,?,?)',id,order.id,row.date,row.kind,-row.amount,row.account,'更正冲回:取消审批作废;'+reason,actor.name,env.now());
|
||||
if(row.amount<0)ledger.run('INSERT INTO corrections VALUES (?,?,?,?,?)',id,'payment','作废更正的对冲记录,不是新增客户收付款',actor.name,env.now());
|
||||
}
|
||||
}
|
||||
function reverseExpenses(ledger,order,reason,actor,env){
|
||||
const corrected=new Set(order.corrections.filter(row=>row.type==='expense').map(row=>row.target));
|
||||
for(const row of order.expenses)if(row.amount>0&&!corrected.has(row.id)&&!row.note.startsWith('更正冲回:'))ledger.run('INSERT INTO corrections VALUES (?,?,?,?,?)',row.id,'expense',reason,actor.name,env.now());
|
||||
for(const row of ledger.rows('SELECT date,payer,SUM(amount) AS amount FROM expenses WHERE order_id=? GROUP BY date,payer HAVING SUM(amount)<>0 ORDER BY date,payer',order.id)){
|
||||
const id=randomUUID();ledger.run('INSERT INTO expenses VALUES (?,?,?,?,?,?,?,?)',id,order.id,row.date,-row.amount,row.payer,'更正冲回:取消审批作废;'+reason,actor.name,env.now());
|
||||
// 跨日更正原先留下的负数需要正数对冲;该正数仍是更正,不是实际支出。
|
||||
if(row.amount<0)ledger.run('INSERT INTO corrections VALUES (?,?,?,?,?)',id,'expense','作废更正的对冲记录,不是新增费用',actor.name,env.now());
|
||||
}
|
||||
}
|
||||
function approve(ledger,id,input,actor,env){return atomic(ledger,()=>{
|
||||
inputObject(input,env);const row=pendingDecision(ledger,id,actor,env),order=ledger.detail(row.order_id),reason=eligibility(ledger,order);
|
||||
if(reason)env.fail(reason,409);
|
||||
if(!Number.isSafeInteger(input.revision)||input.revision!==row.order_revision||order.revision!==row.order_revision||hash(snapshot(ledger,order.id))!==row.snapshot_hash)
|
||||
env.fail('订单或记账已有新变动,这份取消申请已过期,请驳回后重新申请',409);
|
||||
if(input.verified!==true)env.fail('请核实这是录错作废,并确认撤销本单记账及恢复库存');
|
||||
const note=env.text(input.note,'审批意见',200,true),date=env.today(),reviewed=env.now(),before=snapshot(ledger,order.id),inventory=inventoryReversal(ledger,order.id);
|
||||
ledger.run("UPDATE order_cancellations SET status='approved',reviewer_id=?,reviewer_name=?,reviewed=?,note=? WHERE id=? AND status='pending'",actor.id,actor.name,reviewed,note,id);
|
||||
ledger.run("UPDATE orders SET status='cancelled',reviewed_revision=0 WHERE id=?",order.id);
|
||||
reversePayments(ledger,order,row.reason,actor,env);reverseExpenses(ledger,order,row.reason,actor,env);
|
||||
for(const entry of ledger.rows('SELECT date,SUM(sales) AS sales,SUM(goods) AS goods,SUM(expense) AS expense FROM journal WHERE order_id=? GROUP BY date ORDER BY date',order.id))
|
||||
if(entry.sales||entry.goods||entry.expense)ledger.journal(order.id,entry.date,'订单录错作废冲回',-entry.sales,-entry.goods,-entry.expense);
|
||||
const group=randomUUID();for(const movement of inventory)ledger.move({group,order:order.id,date:movement.date,pocket:movement.pocket,mg:movement.mg,kind:'order_cancel_reverse',note:order.number+';审批作废:'+row.reason},actor);
|
||||
MaterialPools.release(ledger,order,date,actor,env,{kind:'订单录错作废释放'});
|
||||
ledger.touch(order.id);
|
||||
const dates=[order.date,order.delivered_date,...before.payments.map(r=>r.date),...before.expenses.map(r=>r.date),...before.journal.map(r=>r.date),...before.movements.map(r=>r.date),...before.materialUsages.map(r=>r.pool_id)].filter(Boolean);
|
||||
ledger.dirtyInventory(dates.sort()[0]||date);
|
||||
const after=ledger.detail(order.id);
|
||||
if(after.netReceived!==0||after.directCost!==0||after.profit!==0||inventoryReversal(ledger,order.id).length||ledger.one('SELECT id FROM material_pool_usages WHERE order_id=? AND active=1',order.id))env.fail('作废后的财务、库存或用料校验未通过,本次审批已撤回',409);
|
||||
ledger.audit(order.id,'同意取消订单(录错作废)',actor,{requestId:id,reason:row.reason,note,requestedBy:row.requester_name,requestedAt:row.created,reviewed,before,
|
||||
after:{revision:after.revision,status:after.status,netReceived:after.netReceived,directCost:after.directCost,profit:after.profit,settlementDue:after.settlementDue},inventory,
|
||||
notice:'原订单、审批、收支与库存流水保留;不是客户退货退款;原采购和双方实际交款不变,原已交款按作废后的应结余额处理'});
|
||||
return {id:order.id,requestId:id,request:read(ledger,id,actor,env),order:ledger.detail(order.id)};
|
||||
});}
|
||||
function reject(ledger,id,input,actor,env){return atomic(ledger,()=>{
|
||||
inputObject(input,env);const row=pendingDecision(ledger,id,actor,env),note=env.text(input.note,'驳回意见',200),reviewed=env.now();
|
||||
ledger.run("UPDATE order_cancellations SET status='rejected',reviewer_id=?,reviewer_name=?,reviewed=?,note=? WHERE id=? AND status='pending'",actor.id,actor.name,reviewed,note,id);
|
||||
ledger.audit(row.order_id,'驳回取消申请',actor,{requestId:id,reason:row.reason,note,requestedBy:row.requester_name,requestedAt:row.created,reviewed});
|
||||
return {id:row.order_id,requestId:id,request:read(ledger,id,actor,env),order:ledger.detail(row.order_id)};
|
||||
});}
|
||||
function guard(ledger,id,{action='',metadata=false,type=''}={},env){
|
||||
if(pending(ledger,id)&&!metadata&&!['print','review'].includes(action))env.fail('本单有待审批取消申请,请先由麦麦同意或驳回后再改动账务',409);
|
||||
if(approved(ledger,id)&&!metadata&&!['print','review','settlement'].includes(action)&&!(action==='correct'&&type==='settlement'))env.fail('本单已审批作废,不能新增收退款、费用、材料或交付;真实双方交款余额可继续处理',409);
|
||||
}
|
||||
module.exports={initialize,pending,approved,projection,detail,list,read,request,approve,reject,guard};
|
||||
+3
-2
@@ -51,8 +51,9 @@ function inputFor(order){
|
||||
lines:converted.lines.map(line=>Object.fromEntries(allowed.filter(key=>Object.hasOwn(line,key)).map(key=>[key,line[key]]))),fee_items:feeInputs(order)};
|
||||
}
|
||||
function detail(ledger,id,actor,env){
|
||||
activeActor(actor,env);const order=ledger.detail(id),financialEditable=order.status==='delivered'&&!order.price_lock_id;
|
||||
const reason=order.price_lock_id?'锁价单本次仅支持修改客户、开单人和备注;原采购、收退款、克重与成本保留。':
|
||||
activeActor(actor,env);const order=ledger.detail(id),financialEditable=order.status==='delivered'&&!order.price_lock_id&&!order.cancellationPending;
|
||||
const reason=order.cancellationPending?'本单有待审批取消申请,仅可更正客户、开单人和备注;修改后原申请将过期,请由麦麦驳回后重申。':
|
||||
order.price_lock_id?'锁价单本次仅支持修改客户、开单人和备注;原采购、收退款、克重与成本保留。':
|
||||
['cancelled','returned'].includes(order.status)?'已取消或已退货订单仅支持修改客户、开单人和备注,不能恢复销售。':
|
||||
!financialEditable?'整单账务修改仅支持已交付普通订单;旧草稿或预订单继续使用原保存、收款及交付流程。':'';
|
||||
const inputs=inputFor(order);
|
||||
|
||||
@@ -86,3 +86,7 @@ button.order-copy-button:focus-visible{outline:3px solid var(--gold);outline-off
|
||||
|
||||
/* 修改原单时,费用金额、付款人、支付日期与移除入口保持同一横行。 */
|
||||
#order-form[data-order-edit="true"] .fee-row{grid-template-columns:minmax(160px,1.5fr) minmax(120px,1fr) minmax(100px,.8fr) minmax(145px,1fr) minmax(100px,.8fr);min-width:760px;gap:14px}#order-form[data-order-edit="true"] .fee-row>button{white-space:nowrap}#order-edit-conflict details{margin-bottom:18px}#order-edit-meta-form textarea{min-height:90px}
|
||||
|
||||
/* 普通订单取消:申请期间仍计账,麦麦核对撤销摘要后才作废。 */
|
||||
#order-cancellations-entry{white-space:nowrap}.order-cancellation-panel{margin-top:20px;border-color:#d2c5a8}.order-cancellation-panel>.panel-title{margin-bottom:14px}.order-cancellation-panel>p{margin-bottom:12px}.order-cancellation-panel>details:last-child{margin-bottom:0}.cancellation-record-title{display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin-bottom:5px}.cancellation-reason{white-space:pre-wrap;overflow-wrap:anywhere;margin:7px 0}.cancellation-history{margin-bottom:0}.cancellation-history li{padding-bottom:18px}.cancellation-history li:last-child{padding-bottom:0}.order-cancellation-form>label{margin-top:18px}.order-cancellation-form .check{align-items:flex-start}.order-cancellation-form .check input{flex:0 0 18px;margin-top:2px}.cancellation-summary{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:18px;margin:20px 0 24px}.cancellation-summary dt{font-size:12px;color:var(--muted)}.cancellation-summary dd{font-size:19px;font-weight:600;font-variant-numeric:tabular-nums;margin:4px 0 0;overflow-wrap:anywhere}.cancellation-summary-note{margin-top:15px}.order-cancellation-form th.number{text-align:right}#order-cancellations-dialog{width:min(1100px,96vw)}#order-cancellations-title{padding-right:35px}.cancellation-list-tabs{display:flex;gap:7px;flex-wrap:wrap;margin-bottom:20px}.cancellation-list-table{min-width:780px}.cancellation-list-table td:nth-child(3),.cancellation-list-table td:nth-child(4){max-width:240px;overflow-wrap:anywhere}.cancellation-list-table button{white-space:nowrap}.cancellation-list-table .small{margin-top:5px}
|
||||
@media(max-width:650px){.cancellation-summary{grid-template-columns:repeat(2,minmax(0,1fr));gap:16px}.cancellation-summary dd{font-size:17px}.cancellation-list-tabs{gap:6px}.cancellation-list-tabs button{padding:8px 12px;font-size:12px}.order-cancellation-panel>.panel-title{flex-wrap:wrap;gap:8px}}
|
||||
+49
-26
@@ -9,7 +9,7 @@ let state,session,tab='create',currentOrder=null,editDraft=null,busy=false,repor
|
||||
let reportRequest=0,reportDateInitialized=false,reportLoadedUser='';
|
||||
let peopleRequest=0,peopleEntry=null,peopleEntryUser='';
|
||||
let printSettingsSaving=false;
|
||||
let orderCopyLoading=false;
|
||||
let orderCopyLoading=false,orderDetailRequest=0;
|
||||
const showOrderCopyEntry=false; // 复制新增入口暂时隐藏;需要恢复时改为 true。
|
||||
let orderBookFilters=null,orderBookUser='',orderBookRequest=0,orderBookTimer=null,orderBookDayChecking=false;
|
||||
let inventoryPage=null,inventoryRequest=0,inventoryHistoryOpen=false,inventoryHistoryMode='month',inventoryHistoryDate='',inventoryHistoryRequest=0;
|
||||
@@ -35,7 +35,7 @@ async function mutate(url,data,existing){
|
||||
document.querySelectorAll('button').forEach(b=>b.disabled=true);
|
||||
try{const r=await api(job.url,job.data,job.key);localStorage.removeItem(pendingKey());return r;}
|
||||
catch(err){if(err.confirmed&&[400,403,404,409,413].includes(err.status))localStorage.removeItem(pendingKey());else if(err.status===401)err.message='登录已过期,请刷新并登录,再恢复原操作。';else err.message='连接中断,提交结果待确认。请点“恢复原操作”,不要重新开单。';throw err;}
|
||||
finally{busy=false;document.querySelectorAll('button').forEach(b=>b.disabled=false);showPending();}
|
||||
finally{busy=false;document.querySelectorAll('button').forEach(b=>b.disabled=false);showPending();if(typeof applyOrderCancellationRestrictions==='function')applyOrderCancellationRestrictions();}
|
||||
}
|
||||
async function init(){
|
||||
try{session=await api('/api/session');if(!session.user)return login();$('#login').innerHTML='';$('#shell').hidden=false;restoreOrderEditTab();await refresh();showPending();}catch(err){$('#login').innerHTML=`<div class="login-wrap"><h1>系统暂时没有连接上</h1><p>${e(err.message)}</p><p>请保持启动窗口打开,再刷新页面。</p></div>`;}
|
||||
@@ -386,8 +386,8 @@ function orderBookIdentity(row){
|
||||
}
|
||||
async function renderOrders(){
|
||||
const f=getOrderBookFilters();let range;try{range=orderBookRange();}catch{}
|
||||
$('#main').innerHTML=heading('ORDER BOOK','订单','按日期查看销售订单与售后,点击销售单查看明细。',button('新增售后','new-after-sale')+button('记录人数','people-count')+button('刷新','refresh'))+`<div class="order-book-dates"><div class="order-period-buttons" role="group" aria-label="订单日期">${[['today','今天'],['yesterday','昨天'],['month','本月']].map(([value,name])=>button(name,'order-period','',`data-period="${value}" aria-pressed="false"`)).join('')}</div><label class="order-date-field">指定日期<input type="date" id="order-date" value="${e(f.mode==='date'?f.date:(range?.date||state.today))}" max="${e(state.today)}" aria-label="指定订单日期"></label><span class="small muted" id="order-period-caption"></span></div><div id="order-book-people" class="order-people-strip" aria-live="polite"></div><div class="cards order-book-cards" id="order-book-summary" aria-live="polite"></div><div id="order-lock-activity"></div><p class="small muted order-book-scope" id="order-book-scope">${orderBookScope()}</p><section class="panel order-book-panel"><div class="filters order-book-filters"><input id="order-search" aria-label="搜索订单" value="${e(f.q)}" placeholder="搜索单号、客户、商品或售后项目" maxlength="100"><select id="order-filter" aria-label="筛选状态">${opts([['','全部状态'],...Object.entries(label)],f.status)}</select><span class="small muted" id="order-book-count"></span></div><div id="order-list" aria-live="polite"></div><p class="small muted order-book-footnote">订单成本和利润为当前累计结果;售后费用按售后记录日期扣减利润。已取消订单不计汇总,其实际收退款及费用保留在每日对账。克重合计不含银饰,单行仍显示实际克重;件数照常合计。旧草稿报价不计入合计。</p></section>`;
|
||||
updateOrderBookDateControls(range);await loadOrderBook();
|
||||
$('#main').innerHTML=heading('ORDER BOOK','订单','按日期查看销售订单与售后,点击销售单查看明细。',button('待取消复核(…)','open-order-cancellations','', 'id="order-cancellations-entry"')+button('新增售后','new-after-sale')+button('记录人数','people-count')+button('刷新','refresh'))+`<div class="order-book-dates"><div class="order-period-buttons" role="group" aria-label="订单日期">${[['today','今天'],['yesterday','昨天'],['month','本月']].map(([value,name])=>button(name,'order-period','',`data-period="${value}" aria-pressed="false"`)).join('')}</div><label class="order-date-field">指定日期<input type="date" id="order-date" value="${e(f.mode==='date'?f.date:(range?.date||state.today))}" max="${e(state.today)}" aria-label="指定订单日期"></label><span class="small muted" id="order-period-caption"></span></div><div id="order-book-people" class="order-people-strip" aria-live="polite"></div><div class="cards order-book-cards" id="order-book-summary" aria-live="polite"></div><div id="order-lock-activity"></div><p class="small muted order-book-scope" id="order-book-scope">${orderBookScope()}</p><section class="panel order-book-panel"><div class="filters order-book-filters"><input id="order-search" aria-label="搜索订单" value="${e(f.q)}" placeholder="搜索单号、客户、商品或售后项目" maxlength="100"><select id="order-filter" aria-label="筛选状态">${opts([['','全部状态'],...Object.entries(label)],f.status)}</select><span class="small muted" id="order-book-count"></span></div><div id="order-list" aria-live="polite"></div><p class="small muted order-book-footnote">订单成本和利润为当前累计结果;售后费用按售后记录日期扣减利润。已取消订单不计汇总,原收退款、费用和作废冲回明细保留在每日对账。克重合计不含银饰,单行仍显示实际克重;件数照常合计。旧草稿报价不计入合计。</p></section>`;
|
||||
updateOrderBookDateControls(range);await Promise.all([loadOrderBook(),typeof loadOrderCancellationCount==='function'?loadOrderCancellationCount():Promise.resolve()]);
|
||||
}
|
||||
function orderBookLoading(range){
|
||||
if($('#order-lock-activity'))$('#order-lock-activity').innerHTML='';
|
||||
@@ -479,7 +479,15 @@ async function checkOrderBookDay(){
|
||||
}
|
||||
setInterval(checkOrderBookDay,60000);
|
||||
document.addEventListener('visibilitychange',()=>{if(!document.hidden)checkOrderBookDay();});
|
||||
async function openOrder(id){currentOrder=await api('/api/orders/'+id);renderDetail();if(!$('#order-dialog').open)$('#order-dialog').showModal();}
|
||||
async function openOrder(id){
|
||||
const request=++orderDetailRequest,user=session.user.id,originTab=tab;
|
||||
const [orderResult,cancellationResult]=await Promise.allSettled([api('/api/orders/'+encodeURIComponent(id)),api('/api/orders/'+encodeURIComponent(id)+'/cancellation')]);
|
||||
if(request!==orderDetailRequest||session.user.id!==user||tab!==originTab)return;
|
||||
if(orderResult.status==='rejected')throw orderResult.reason;
|
||||
currentOrder=orderResult.value;
|
||||
if(typeof useOrderCancellationDetail==='function')useOrderCancellationDetail(currentOrder,cancellationResult.status==='fulfilled'?cancellationResult.value:null,cancellationResult.status==='rejected'?cancellationResult.reason:null);
|
||||
renderDetail();if(!$('#order-dialog').open)$('#order-dialog').showModal();
|
||||
}
|
||||
async function copyOrder(id,source){
|
||||
if(tab==='order-edit')throw new Error('请先保存或取消订单修改,再复制新增。');
|
||||
if(busy||orderCopyLoading)throw new Error('正在处理订单,请稍候再复制。');
|
||||
@@ -509,7 +517,7 @@ function orderCostsHTML(o){
|
||||
<div class="table-wrap"><table aria-label="按付款人汇总成本"><thead><tr><th>付款人</th><th class="number">货品垫资</th><th class="number">已付费用</th><th class="number">合计</th></tr></thead><tbody>${Object.entries(names).map(([payer,name])=>summaryRow(name,c.byPayer[payer])).join('')}</tbody><tfoot>${summaryRow('合计',c.total)}</tfoot></table></div>
|
||||
${c.total.goodsMissing?`<p class="small danger-text">${o.materialCostPending?'本批料费尚未补齐,当前合计仅包含已知金额;补足购料后自动更新。':'旧单货品成本尚未补齐,当前合计仅包含已填金额。'}</p>`:''}
|
||||
${c.pendingCount?`<p class="small danger-text">旧单另有 ${c.pendingCount} 项费用尚未入账,未计入上述已付费用和合计。请按实际付款情况补齐旧单账务。</p>`:''}
|
||||
${c.goodsExcluded?'<p class="small muted">本单已'+(o.status==='returned'?'退货':'取消')+',原货品成本保留供查阅,不计入上方合计;实际发生的费用仍保留。</p>':''}
|
||||
${c.goodsExcluded?(o.cancellationApproved?'<p class="small muted">本单已按录错作废,原货品成本和费用保留供查阅,已撤销的金额不计入本单成本。</p>':'<p class="small muted">本单已'+(o.status==='returned'?'退货':'取消')+',原货品成本保留供查阅,不计入上方合计;实际发生的费用仍保留。</p>'):''}
|
||||
<div class="table-wrap cost-item-list"><table aria-label="逐项成本明细"><thead><tr><th>成本项目</th><th class="number">成本金额</th><th>付款人</th></tr></thead><tbody>${actualRows.map(row=>`<tr${row.excluded?' class="muted"':''}><td>${e(row.name)}<div class="small muted">${e(row.source)}${row.excluded?' · 原记录,不计本单成本':''}</div>${row.calculation?`<div class="small muted">${grams(row.calculation.quantity)}g × ${row.calculation.rate==null?(row.name===LedgerCalc.costLabels.material?'每克料价未补齐':'每克工费未补齐'):yuan(row.calculation.rate)+'元/克'}${row.amount==null?'':' = '+yuan(row.amount)+'元'}</div>`:''}</td><td class="number">${row.amount==null?'未补齐':'¥'+yuan(row.amount)}</td><td>${row.poolPending?'待补采购后分摊':names[row.payer]}</td></tr>`).join('')||'<tr><td colspan="3">暂无已记账成本。</td></tr>'}</tbody></table></div>
|
||||
<p class="small muted cost-footer">付款人合计用于核对成本;双方实际交款与待结金额见下方“与助理的结算”。</p></section>`;
|
||||
}
|
||||
@@ -522,34 +530,37 @@ function lineCostPayersHTML(line){
|
||||
}
|
||||
function renderDetail(){
|
||||
const o=currentOrder,done=['delivered','returned','cancelled'].includes(o.status),profit=profitSummary(o);
|
||||
const cancellationPending=typeof orderCancellationPending==='function'?orderCancellationPending(o):o.cancellationPending,voided=typeof orderCancellationApproved==='function'?orderCancellationApproved(o):o.cancellationApproved,financialBlocked=!!cancellationPending||!!voided;
|
||||
let actions=button('客户预览/打印','print','primary',`data-id="${o.id}"`)+(showOrderCopyEntry?button('<span aria-hidden="true">+</span>复制新增','copy-order','order-copy-button',`data-id="${e(o.id)}"`):'');
|
||||
if(o.status!=='draft')actions=button('修改订单','edit-order','primary',`data-id="${e(o.id)}"`)+actions;
|
||||
if(o.status==='draft')actions+=button('继续填写并开单','edit');
|
||||
if(o.status==='confirmed'){if(o.pendingFees.length)actions+=button('补记旧单费用','show-fees');if(o.balance>0)actions+=button('登记收款','show-receipt');actions+=button('补齐/核对货品成本','show-cost')+button('补齐旧单账务','show-complete');}
|
||||
if(o.status!=='draft')actions+=button('记额外费用','show-expense');
|
||||
if(['draft','confirmed'].includes(o.status))actions+=button('取消此单','show-cancel','danger');
|
||||
if(o.status==='delivered')actions+=button('整单退货','show-return','danger');
|
||||
if(['cancelled','returned'].includes(o.status)&&o.netReceived>0)actions+=button('登记实际退款','show-refund');
|
||||
if(done&&o.settlementDue!=null&&o.settlementDue!==0&&!o.materialCostPending)actions+=button('登记实际交款/返款','show-settlement');
|
||||
if(state.user.role==='owner'&&(o.payments.some(p=>!p.price_lock_event_id)||o.expenses.length||o.settlements.length))actions+=button('更正记错的流水','show-correct');
|
||||
if(state.user.role==='owner'&&o.reviewed_revision!==o.revision)actions+=button('麦麦复核','show-review');
|
||||
$('#order-content').innerHTML=`<div class="order-header"><div class="eyebrow">ORDER DETAIL</div><h2>${e(o.paper_number||o.number)}</h2><p class="small muted">系统单号 ${e(o.number)} · 收款账户 ${e(o.payment_account)}</p>${badge(o)}<span class="muted small">${e(o.customer||'未填客户称呼')} · ${o.date} · ${e(o.salesperson)}</span></div>${materialPoolOrderNoticeHTML(o)}${!done?`<div class="note">${o.status==='draft'?'这是尚未开单的旧草稿,继续填写后生成销售单据。':'这张旧单尚未完成销售记账。请按实际情况补齐款项、货品成本和费用,再点“补齐旧单账务”;保存时一并记费用、扣库存和计算利润。'}</div>`:''}<div class="cards order-totals">${card('成交金额',orderAmount(o.total,o.rounding_mode),e(savedOrderRoundingHint(o)))}${card(profit.title,profit.value,e(profit.hint),true)}</div><div class="actions">${actions}</div><div id="detail-form" class="detail-form"></div><div id="detail-error"></div>${orderCostsHTML(o)}<section class="panel" style="margin-top:20px"><h2>商品与成本 <span class="small muted">内部页面,客户请看“客户预览”</span></h2><div class="table-wrap"><table><thead><tr><th>商品</th><th>数量</th><th>成交金额</th><th>原货盘</th><th>货品成本</th><th>分项付款人</th></tr></thead><tbody>${o.lines.map(l=>`<tr><td>${e(l.name)}<div class="small muted">${e(l.priceNote)}</div>${l.charges?.length?`<div class="small">客户附加:${l.charges.map(c=>e(c.name)+(c.amount===null?'(未填收费)':' ¥'+yuan(c.amount))).join(';')}</div>`:''}</td><td>${l.unit==='g'?grams(l.quantity)+'g':l.quantity+'件'}</td><td>¥${yuan(l.sale)}</td><td>${e(l.pocket||'外配/不扣黄金')}</td><td>${l.cost==null?(l.costMaterial?.mode==='pool'?'料费待补':'成本未补齐'):'¥'+yuan(l.cost)}${materialPoolLineCostHTML(l)}${l.costMaterial?.mode==='gram'?`<div class="small muted">进货料价:${grams(l.quantity)}g × ${yuan(l.costMaterial.rate)}元/克 = ${yuan(l.costParts?.material)}元</div>`:''}${l.costLabor?.mode==='gram'?`<div class="small muted">进货工费:${yuan(l.costLabor.rate)}元/克 × ${grams(l.quantity)}g</div>`:''}${l.costParts?`<div class="small muted">${Object.entries(l.costParts).map(([k,v])=>e(LedgerCalc.costLabels[k])+' '+yuan(v)).join(' · ')}</div>`:''}</td><td>${lineCostPayersHTML(l)}</td></tr>`).join('')}</tbody></table></div><p class="small muted" style="margin-top:14px">整单优惠 ¥${yuan(o.discount)} · 直接费用 ¥${yuan(o.directCost)}${o.pendingFees.length?' · 旧单费用尚未入账 '+o.pendingFees.length+' 项':''}。货品成本已经包含的费用,不要再登记。</p><p>${e(o.note)}</p></section><details class="panel" ${done?'open':''}><summary>与助理的结算</summary><div class="grid three"><div>麦麦垫资应回收 <strong>¥${yuan(o.ownerCost)}</strong><br><small class="muted">实际已交净额 ¥${yuan(o.costTransferred)}</small></div><div>已记账订单利润 <strong>${done?(o.profit==null?(o.materialCostPending?'料费待补':'成本未补齐'):'¥'+yuan(o.profit)):'旧单待补齐'}</strong><br><small class="muted">实际已交净额 ¥${yuan(o.profitTransferred)}</small></div><div>${o.settlementDue<0?'麦麦待转回助理':'助理待交麦麦'} <strong>${o.settlementDue==null?'料费待补':'¥'+yuan(Math.abs(o.settlementDue))}</strong><br><small class="muted">${o.materialCostPending?'补足购料后自动计算;当前不能登记交款':done?'含本单货款与利润,该日购料结算另行核对':'旧单完成销售记账后形成应交款'}</small></div></div>${priceLockInventoryCreditHTML(o)}${o.ownerDirect?`<div class="note">麦麦直接收客户净额 ¥${yuan(o.ownerDirect)},${o.status==='delivered'?'已从总待结金额扣除,货款/利润拆分需单独复核。':o.price_lock_id&&o.status==='returned'&&o.netReceived===0?'客户已退清;跨账户收退款形成的差额已计入双方结算。':'这部分属于客户款,取消/退货后须从原账户退客户,不算应返助理。'}</div>`:''}<p class="small muted" style="margin:14px 0 0">开单后按单交货款,利润月底交。退货返款单独记录,不抵下一笔。这里记录实际转账,不会发起付款。</p></details><details class="panel"><summary>收退款与费用记录</summary>${transactionTable(o)}<details><summary>操作记录</summary><ul class="timeline">${o.audit.map(a=>`<li>${e(actionName[a.action]||a.action)} · ${e(a.actor)}<small>${e(new Date(a.created).toLocaleString('zh-CN'))}</small>${a.detail.reason?e(a.detail.reason):''}</li>`).join('')}</ul></details></details>`;
|
||||
if(o.status!=='draft'&&!cancellationPending)actions=button('修改订单','edit-order','primary',`data-id="${e(o.id)}"`)+actions;
|
||||
if(o.status==='draft'&&!financialBlocked)actions+=button('继续填写并开单','edit');
|
||||
if(o.status==='confirmed'&&!financialBlocked){if(o.pendingFees.length)actions+=button('补记旧单费用','show-fees');if(o.balance>0)actions+=button('登记收款','show-receipt');actions+=button('补齐/核对货品成本','show-cost')+button('补齐旧单账务','show-complete');}
|
||||
if(o.status!=='draft'&&!financialBlocked)actions+=button('记额外费用','show-expense');
|
||||
if(typeof orderCancellationActionHTML==='function')actions+=orderCancellationActionHTML(o);
|
||||
if(o.status==='delivered'&&!financialBlocked)actions+=button('整单退货','show-return','danger');
|
||||
if(['cancelled','returned'].includes(o.status)&&o.netReceived>0&&!financialBlocked)actions+=button('登记实际退款','show-refund');
|
||||
if(done&&!cancellationPending&&o.settlementDue!=null&&o.settlementDue!==0&&!o.materialCostPending)actions+=button('登记实际交款/返款','show-settlement');
|
||||
if(state.user.role==='owner'&&!cancellationPending&&((!voided&&(o.payments.some(p=>!p.price_lock_event_id)||o.expenses.length))||o.settlements.length))actions+=button('更正记错的流水','show-correct');
|
||||
if(state.user.role==='owner'&&!cancellationPending&&o.reviewed_revision!==o.revision)actions+=button('麦麦复核','show-review');
|
||||
$('#order-content').innerHTML=`<div class="order-header"><div class="eyebrow">ORDER DETAIL</div><h2>${e(o.paper_number||o.number)}</h2><p class="small muted">系统单号 ${e(o.number)} · 收款账户 ${e(o.payment_account)}</p>${badge(o)}<span class="muted small">${e(o.customer||'未填客户称呼')} · ${o.date} · ${e(o.salesperson)}</span></div>${materialPoolOrderNoticeHTML(o)}${!done?`<div class="note">${o.status==='draft'?'这是尚未开单的旧草稿,继续填写后生成销售单据。':'这张旧单尚未完成销售记账。请按实际情况补齐款项、货品成本和费用,再点“补齐旧单账务”;保存时一并记费用、扣库存和计算利润。'}</div>`:''}<div class="cards order-totals">${card(voided?'原成交金额(已作废)':'成交金额',orderAmount(o.total,o.rounding_mode),e(savedOrderRoundingHint(o)))}${card(profit.title,profit.value,e(profit.hint),true)}</div><div class="actions">${actions}</div>${typeof orderCancellationDetailHTML==='function'?orderCancellationDetailHTML(o):''}<div id="detail-form" class="detail-form"></div><div id="detail-error"></div>${orderCostsHTML(o)}<section class="panel" style="margin-top:20px"><h2>商品与成本 <span class="small muted">内部页面,客户请看“客户预览”</span></h2><div class="table-wrap"><table><thead><tr><th>商品</th><th>数量</th><th>成交金额</th><th>原货盘</th><th>货品成本</th><th>分项付款人</th></tr></thead><tbody>${o.lines.map(l=>`<tr><td>${e(l.name)}<div class="small muted">${e(l.priceNote)}</div>${l.charges?.length?`<div class="small">客户附加:${l.charges.map(c=>e(c.name)+(c.amount===null?'(未填收费)':' ¥'+yuan(c.amount))).join(';')}</div>`:''}</td><td>${l.unit==='g'?grams(l.quantity)+'g':l.quantity+'件'}</td><td>¥${yuan(l.sale)}</td><td>${e(l.pocket||'外配/不扣黄金')}</td><td>${l.cost==null?(l.costMaterial?.mode==='pool'?'料费待补':'成本未补齐'):'¥'+yuan(l.cost)}${materialPoolLineCostHTML(l)}${l.costMaterial?.mode==='gram'?`<div class="small muted">进货料价:${grams(l.quantity)}g × ${yuan(l.costMaterial.rate)}元/克 = ${yuan(l.costParts?.material)}元</div>`:''}${l.costLabor?.mode==='gram'?`<div class="small muted">进货工费:${yuan(l.costLabor.rate)}元/克 × ${grams(l.quantity)}g</div>`:''}${l.costParts?`<div class="small muted">${Object.entries(l.costParts).map(([k,v])=>e(LedgerCalc.costLabels[k])+' '+yuan(v)).join(' · ')}</div>`:''}</td><td>${lineCostPayersHTML(l)}</td></tr>`).join('')}</tbody></table></div><p class="small muted" style="margin-top:14px">整单优惠 ¥${yuan(o.discount)} · 直接费用 ¥${yuan(o.directCost)}${o.pendingFees.length?' · 旧单费用尚未入账 '+o.pendingFees.length+' 项':''}。货品成本已经包含的费用,不要再登记。</p><p>${e(o.note)}</p></section><details class="panel" ${done?'open':''}><summary>与助理的结算</summary><div class="grid three"><div>麦麦垫资应回收 <strong>¥${yuan(o.ownerCost)}</strong><br><small class="muted">实际已交净额 ¥${yuan(o.costTransferred)}</small></div><div>已记账订单利润 <strong>${done?(o.profit==null?(o.materialCostPending?'料费待补':'成本未补齐'):'¥'+yuan(o.profit)):'旧单待补齐'}</strong><br><small class="muted">实际已交净额 ¥${yuan(o.profitTransferred)}</small></div><div>${o.settlementDue<0?'麦麦待转回助理':'助理待交麦麦'} <strong>${o.settlementDue==null?'料费待补':'¥'+yuan(Math.abs(o.settlementDue))}</strong><br><small class="muted">${o.materialCostPending?'补足购料后自动计算;当前不能登记交款':done?'含本单货款与利润,该日购料结算另行核对':'旧单完成销售记账后形成应交款'}</small></div></div>${priceLockInventoryCreditHTML(o)}${o.ownerDirect?`<div class="note">麦麦直接收客户净额 ¥${yuan(o.ownerDirect)},${o.status==='delivered'?'已从总待结金额扣除,货款/利润拆分需单独复核。':o.price_lock_id&&o.status==='returned'&&o.netReceived===0?'客户已退清;跨账户收退款形成的差额已计入双方结算。':'这部分属于客户款,取消/退货后须从原账户退客户,不算应返助理。'}</div>`:''}<p class="small muted" style="margin:14px 0 0">开单后按单交货款,利润月底交。退货返款单独记录,不抵下一笔。这里记录实际转账,不会发起付款。</p></details><details class="panel"><summary>收退款与费用记录</summary>${transactionTable(o)}<details><summary>操作记录</summary><ul class="timeline">${o.audit.map(a=>`<li>${e(actionName[a.action]||a.action)} · ${e(a.actor)}<small>${e(new Date(a.created).toLocaleString('zh-CN'))}</small>${a.detail.reason?e(a.detail.reason):''}</li>`).join('')}</ul></details></details>`;
|
||||
}
|
||||
function transactionTable(o){const rows=[...o.payments.map(p=>({date:p.date,type:p.kind==='receipt'?'客户收款':'客户退款',amount:p.amount,who:p.account,note:p.reference})),...o.expenses.map(x=>({date:x.date,type:'直接费用',amount:x.amount,who:x.payer==='owner'?'麦麦支付':'助理支付',note:x.note})),...o.settlements.map(s=>({date:s.date,type:(s.amount<0?'麦麦返助理':'助理交麦麦')+' · '+(s.bucket==='cost'?'货款':'利润'),amount:Math.abs(s.amount),who:s.actor,note:s.note}))].sort((a,b)=>a.date.localeCompare(b.date));return rows.length?`<div class="table-wrap"><table><thead><tr><th>日期</th><th>业务</th><th>金额</th><th>账户/经办人</th><th>说明</th></tr></thead><tbody>${rows.map(r=>`<tr><td>${r.date}</td><td>${r.type}</td><td>¥${yuan(r.amount)}</td><td>${e(r.who)}</td><td>${e(r.note)}</td></tr>`).join('')}</tbody></table></div>`:'<p class="muted">还没有收退款、费用或交款记录。</p>';}
|
||||
function transactionTable(o){const rows=[...o.payments.map(p=>({date:p.date,type:String(p.reference||'').startsWith('更正冲回:取消审批作废;')?'作废冲回'+(p.kind==='receipt'?'收款':'退款'):p.kind==='receipt'?'客户收款':'客户退款',amount:p.amount,who:p.account,note:p.reference})),...o.expenses.map(x=>({date:x.date,type:String(x.note||'').startsWith('更正冲回:取消审批作废;')?'作废冲回费用':'直接费用',amount:x.amount,who:x.payer==='owner'?'麦麦支付':'助理支付',note:x.note})),...o.settlements.map(s=>({date:s.date,type:(s.amount<0?'麦麦返助理':'助理交麦麦')+' · '+(s.bucket==='cost'?'货款':'利润'),amount:Math.abs(s.amount),who:s.actor,note:s.note}))].sort((a,b)=>a.date.localeCompare(b.date));return rows.length?`<div class="table-wrap"><table><thead><tr><th>日期</th><th>业务</th><th>金额</th><th>账户/经办人</th><th>说明</th></tr></thead><tbody>${rows.map(r=>`<tr><td>${r.date}</td><td>${r.type}</td><td>¥${yuan(r.amount)}</td><td>${e(r.who)}</td><td>${e(r.note)}</td></tr>`).join('')}</tbody></table></div>`:'<p class="muted">还没有收退款、费用或交款记录。</p>';}
|
||||
function showAction(action){
|
||||
const o=currentOrder;let html='';const dt=dateField();
|
||||
if(action==='cancel')throw new Error('订单取消需要先申请,再由麦麦同意。请重新读取订单后点击“申请取消”。');
|
||||
if(o.cancellationPending||typeof orderCancellationPending==='function'&&orderCancellationPending(o))throw new Error('取消申请待麦麦复核,当前暂停本单修改和退货。');
|
||||
if(o.cancellationApproved&&!['settlement','correct','review'].includes(action))throw new Error('本单已按录错作废,不能继续登记销售、费用或退款。');
|
||||
if(action==='fees')html=`<p>补齐旧单实际已付费用,没有发生的填0。保存后只记一次实际费用;完成旧单账务后计算完整利润。</p>${dt}<div class="fee-grid" id="verify-fees">${o.pendingFees.map(f=>`<div class="fee-verify-row" data-key="${e(f.key)}"><h3>${e(f.note)}</h3>${moneyField('实际成本(元)','verifiedAmount',f.amount===null?'':(f.amount/100).toFixed(2))}${choice('实际付款人','verifiedPayer',[['assistant','助理'],['owner','麦麦']],f.payer)}</div>`).join('')}</div><label class="check"><input type="checkbox" name="verified" required>已核实实际支付,没有发生的费用已填0。</label>`;
|
||||
if(['receipt','refund'].includes(action))html=`<div class="grid three">${dt}${moneyField(action==='receipt'?'本次实收金额':'本次实退金额','amount',((action==='receipt'?o.balance:o.netReceived)/100).toFixed(2))}${accountFields(action==='refund'?(o.payments.find(p=>p.kind==='receipt'&&o.payments.filter(r=>r.account===p.account).reduce((n,r)=>n+(r.kind==='receipt'?r.amount:-r.amount),0)>0)?.account||o.payment_account):o.payment_account)}</div>${field('凭据备注(选填)','reference','','text','maxlength="100" placeholder="交易凭据末几位或说明"')}<label class="check"><input type="checkbox" name="verified" required>已在实际账户核实${action==='receipt'?'到账':'退款成功'},不是仅收到客户截图。</label>`;
|
||||
if(action==='expense')html=`${o.pendingFees.length?'<div class="note">本旧单还有费用尚未入账,请从“补记旧单费用”补齐,或完成旧单账务时一并入账。这里仅记额外发生的费用。</div>':''}<p class="small muted">记录额外已支付的费用;已包含在货品成本或已记账费用中的不要重复登记。</p><div class="grid three">${dt}${moneyField('本次费用','amount')}${choice('实际付款人','payer',[['assistant','助理'],['owner','麦麦']],'assistant')}</div>${field('费用项目与说明','note','','text','required maxlength="150"')}`;
|
||||
if(action==='cost')html=`<div class="note">进货料价和克工费按该行克重自动计算;原单合计金额保留,改按克录入时需填写实际单价。没有的成本填0,完成销售记账后锁定。快递和附加费用可从“补记旧单费用”填写。</div>${o.lines.map((l,i)=>`<div class="internal cost-editor"><h3>${e(l.name)} · ${l.unit==='g'?grams(l.quantity)+'g':l.quantity+'件'}</h3><div class="cost-fallback-payer">${choice('配件及其他成本付款人','goodsPayer',[['owner','麦麦'],['assistant','助理']],l.payer||'owner')}</div>${!l.costParts&&l.cost!==null?`<p class="small">原记录未分项,总额 ¥${yuan(l.cost)};请按凭据拆分,不要把总额再填入每个项目。</p>`:''}<div class="cost-fields grid">${costFields(l.costParts?Object.fromEntries(Object.entries(l.costParts).map(([k,v])=>[k,v===null?'':(v/100).toFixed(2)])):{material:'',labor:'',accessories:'0',other:'0'},'cost-'+i+'-',true,{mode:l.costLabor?.mode||'total',rate:l.costLabor?.rate==null?'':(l.costLabor.rate/100).toFixed(2)},{...materialCostInput(l),...(l.costMaterial?.mode==='gram'?{rate:l.costMaterial.rate==null?'':(l.costMaterial.rate/100).toFixed(2)}:{})},{},l.unit,costPayerInput(l))}</div><div class="cost-summary small"></div></div>`).join('')}`;
|
||||
if(action==='complete')html=`${dt}<p>补齐这张旧单的销售记账:按填写金额记录实际费用、从原货盘扣减黄金并计入销售与利润。款项未收齐或成本金额有空白时,请先补齐。</p><label class="check"><input type="checkbox" name="verified" required>已核实全额收款、商品已交付,所填费用为实际已付金额,没有发生的已填0。</label>`;
|
||||
if(action==='cancel')html=`${dt}${field('取消原因','reason','','text','required maxlength="200"')}<p class="small muted">释放占用,不制造退货入库。已付款项须另外登记实际退款。</p>`;
|
||||
if(action==='return')html=`${dt}${field('退货原因','reason','','text','required maxlength="200"')}<div class="grid two">${o.lines.map((l,i)=>choice(l.name+' · 实物去向','return-'+i,l.unit==='g'?[...(l.pocket||l.costMaterial?.mode==='pool'?[]:[['','已退供应商,不留店内']]),...state.pockets]:[['','按件商品,不记黄金货盘']],l.pocket||(l.costMaterial?.mode==='pool'?state.pockets[0]:''))).join('')}</div><div class="note">本入口办理整单退货,原销售额与货品成本在退货日冲回。已花费的运费等仍保留。换货先退原单,再开新单;部分退货暂未开放。</div><label class="check"><input type="checkbox" name="verified" required>已核实本单全部商品退回,所选去向与实际一致。</label>`;
|
||||
if(action==='settlement'&&(o.materialCostPending||o.settlementDue==null))throw new Error('本批料费尚未补齐,补足采购后再核对实际交款。');
|
||||
if(action==='settlement')html=`<div class="grid three">${dt}${choice('转款方向','direction',[['toOwner','助理 → 麦麦'],['toAssistant','麦麦 → 助理']],o.settlementDue<0?'toAssistant':'toOwner')}${choice('本笔归属','bucket',[['cost','货款'],['profit','利润']],'cost')}</div><div class="grid two">${moneyField('实际转账金额','amount')}${field('转账凭据/说明','note','','text','required maxlength="150"')}</div><p class="small muted">${o.ownerCredit?'麦麦已直接收到部分客户款,先按实际情况核清归属。':`货款待结 ¥${yuan(o.costDue)};利润待结 ¥${yuan(o.profitDue)}(负数为麦麦需转回)。`}</p><label class="check"><input type="checkbox" name="verified" required>已核实双方实际转账,不是仅记录计划交款。</label>`;
|
||||
if(action==='correct'){
|
||||
const valid=(r)=>!r.price_lock_event_id&&!o.corrections.some(c=>c.target===r.id)&&!String(r.note||r.reference||'').startsWith('更正冲回:');
|
||||
const entries=[...o.payments.filter(valid).map(r=>['payment:'+r.id,r.date+' '+(r.kind==='receipt'?'客户收款':'客户退款')+' '+yuan(r.amount)+'元 '+r.account]),...o.expenses.filter(valid).map(r=>['expense:'+r.id,r.date+' 直接费用 '+yuan(r.amount)+'元 '+r.note]),...o.settlements.filter(valid).map(r=>['settlement:'+r.id,r.date+' '+(r.amount<0?'麦麦返款':'助理交款')+' '+yuan(Math.abs(r.amount))+'元'])];
|
||||
const entries=[...(o.cancellationApproved?[]:o.payments.filter(valid)).map(r=>['payment:'+r.id,r.date+' '+(r.kind==='receipt'?'客户收款':'客户退款')+' '+yuan(r.amount)+'元 '+r.account]),...(o.cancellationApproved?[]:o.expenses.filter(valid)).map(r=>['expense:'+r.id,r.date+' 直接费用 '+yuan(r.amount)+'元 '+r.note]),...o.settlements.filter(valid).map(r=>['settlement:'+r.id,r.date+' '+(r.amount<0?'麦麦返款':'助理交款')+' '+yuan(Math.abs(r.amount))+'元'])];
|
||||
html=`<div class="note">更正录错的流水,保留原记录。填0表示撤回误记。真实客户退货请用退货入口,不要用更正代替。更正发生在所选日期,不覆盖原日记录。</div>${choice('选择原流水','entry',entries,entries[0]?.[0])}<div class="grid three">${dt}${moneyField('更正后金额(元)','amount')}${choice('更正后收退款账户(仅收退款)','account',state.accounts,'助理微信')}${choice('更正后付款人(仅费用)','payer',[['assistant','助理'],['owner','麦麦']],'assistant')}${choice('更正后转款方向(仅交款)','direction',[['toOwner','助理 → 麦麦'],['toAssistant','麦麦 → 助理']],'toOwner')}${choice('更正后款项归属(仅交款)','bucket',[['cost','货款'],['profit','利润']],'cost')}</div>${field('更正原因','reason','','text','required maxlength="200"')}<label class="check"><input type="checkbox" name="verified" required>已核实原凭据,这次是修正登记错误。</label>`;
|
||||
}
|
||||
if(action==='review')html='<p>确认已查看商品、克重、成本、收退款与交款凭据。复核后再有变动,会重新提示待复核。</p>';
|
||||
@@ -778,9 +789,19 @@ document.addEventListener('input',ev=>{if(ev.target.id==='people-count-date')loa
|
||||
document.addEventListener('input',ev=>{if(ev.target.closest('#order-form,#price-lock-create-form,#price-lock-delivery-form')){markFeeEdited(ev.target);syncChargePrice(ev.target);updateTotal();}if(ev.target.closest('#action-form[data-kind="cost"]'))syncCostEditor();if(ev.target.id==='order-search')filterOrders(180);if(ev.target.id==='order-date'){const f=getOrderBookFilters();f.mode='date';f.date=ev.target.value;saveOrderBookFilters();loadOrderBook();}});
|
||||
document.addEventListener('change',async ev=>{try{if(ev.target.closest('#price-lock-create-form,#price-lock-delivery-form')){markFeeEdited(ev.target);syncChargePrice(ev.target);updateTotal();}if(ev.target.closest('#order-form')){markFeeEdited(ev.target);syncChargePrice(ev.target);const row=ev.target.closest('.line-item');if(row&&ev.target.name==='nameType'&&['足银999','纯银925'].includes(ev.target.value))row.querySelector('[name="pocket"]').value='';if(row&&ev.target.name==='unit'&&ev.target.value==='件'){row.querySelector('[name="pricingMode"]').value='manual';row.querySelector('[name="pocket"]').value='';}updateTotal();if(ev.target.name==='date')updatePaperNumber();}if(ev.target.closest('#action-form[data-kind="cost"]'))syncCostEditor();if(ev.target.closest('#stock-form')&&ev.target.name==='kind')syncStockForm();if(ev.target.id==='inventory-history-date'){inventoryHistoryMode='date';inventoryHistoryDate=ev.target.value;await loadInventorySnapshots();}if(ev.target.id==='order-filter')filterOrders();if(ev.target.id==='report-month'){reportMonth=ev.target.checked;await renderReport();}if(ev.target.id==='report-date'){reportDate=ev.target.value;await renderReport();}}catch(err){toast(err.message,true);}});
|
||||
document.addEventListener('click',async ev=>{
|
||||
const b=ev.target.closest('button');if(!b)return;if(b.dataset.tab){if(tab==='order-edit')leaveOrderEdit();invalidateReport();invalidatePriceLockViews();tab=b.dataset.tab;priceLockDeliveryId='';editDraft=null;if(tab==='report'&&$('#report-content')){let range;try{range=reportRange();}catch{}if(range)reportQueryState(range);}try{await refresh();}catch(err){if(tab==='report'&&$('#report-content'))reportQueryState(null,err.message);toast(err.message,true);}return;}
|
||||
const b=ev.target.closest('button');if(!b)return;if(b.dataset.tab){++orderDetailRequest;if(typeof invalidateOrderCancellationViews==='function')invalidateOrderCancellationViews();if(tab==='order-edit')leaveOrderEdit();invalidateReport();invalidatePriceLockViews();tab=b.dataset.tab;priceLockDeliveryId='';editDraft=null;if(tab==='report'&&$('#report-content')){let range;try{range=reportRange();}catch{}if(range)reportQueryState(range);}try{await refresh();}catch(err){if(tab==='report'&&$('#report-content'))reportQueryState(null,err.message);toast(err.message,true);}return;}
|
||||
const a=b.dataset.action;if(!a)return;
|
||||
try{
|
||||
if(a==='open-order-cancellations')return await openOrderCancellations();
|
||||
if(a==='close-order-cancellations'){closeOrderCancellations();return;}
|
||||
if(a==='filter-order-cancellations'){orderCancellationListStatus=b.dataset.status;return await loadOrderCancellations();}
|
||||
if(a==='retry-order-cancellations')return await loadOrderCancellations();
|
||||
if(a==='open-cancellation-order'){closeOrderCancellations();return await openOrder(b.dataset.id);}
|
||||
if(a==='request-order-cancellation')return showOrderCancellationForm('request');
|
||||
if(a==='approve-order-cancellation')return showOrderCancellationForm('approve');
|
||||
if(a==='reject-order-cancellation')return showOrderCancellationForm('reject');
|
||||
if(a==='close-order-cancellation-form'){closeOrderCancellationForm();return;}
|
||||
if(a==='reload-order-cancellation')return await openOrder(b.dataset.id);
|
||||
if(a==='refresh-material-pools'){await refresh(false);return await renderMaterialPools();}
|
||||
if(a==='new-material-purchase'){$('#main').innerHTML=materialPoolsPageHTML(materialPoolsCache);return;}
|
||||
if(a==='toggle-material-pool'){materialPoolsOpenDate=materialPoolsOpenDate===b.dataset.id?'':b.dataset.id;if(materialPoolsCache&&$('#material-pools-content'))$('#material-pools-content').innerHTML=materialPoolListHTML(materialPoolsCache);return;}
|
||||
@@ -807,7 +828,7 @@ document.addEventListener('click',async ev=>{
|
||||
if(a==='deliver-price-lock'){if(pending())throw new Error('请先恢复上次未确认的操作,再办理交付。');$('#price-lock-dialog')?.close();invalidateReport();priceLockDeliveryId=b.dataset.id;tab='price-locks';return await refresh();}
|
||||
if(a==='open-lock-order'){$('#price-lock-dialog')?.close();return await openOrder(b.dataset.id);}
|
||||
if(a.startsWith('demo-')){await api('/api/demo-login',{role:a==='demo-owner'?'owner':'assistant'});return init();}
|
||||
if(a==='logout'){invalidatePriceLockViews();if(pending())throw new Error('请先恢复上次未确认的操作,再退出');if(tab==='order-edit')leaveOrderEdit();invalidateReport();invalidateMaterialPools();await api('/api/logout',{});resetOrderTemplates();localStorage.removeItem('mm-draft-'+session.user.id);return init();}
|
||||
if(a==='logout'){++orderDetailRequest;if(typeof invalidateOrderCancellationViews==='function')invalidateOrderCancellationViews();invalidatePriceLockViews();if(pending())throw new Error('请先恢复上次未确认的操作,再退出');if(tab==='order-edit')leaveOrderEdit();invalidateReport();invalidateMaterialPools();await api('/api/logout',{});resetOrderTemplates();localStorage.removeItem('mm-draft-'+session.user.id);return init();}
|
||||
if(a==='refresh'){
|
||||
if(tab==='orders'){clearTimeout(orderBookTimer);++orderBookRequest;let range;try{range=orderBookRange();}catch{}orderBookLoading(range);try{return await refresh();}catch(err){orderBookError(err.message);throw err;}}
|
||||
return refresh();
|
||||
@@ -836,8 +857,9 @@ document.addEventListener('click',async ev=>{
|
||||
await refresh();return toast('今日库存复核快照已保存');
|
||||
}
|
||||
if(a==='retry'){
|
||||
const p=pending();if(!p)return;let r;const orderEdit=p.url.match(/^\/api\/orders\/([^/]+)\/edit$/);const materialChange=p.url.match(/^\/api\/material-purchases\/([^/]+)\/(edit|delete)$/);
|
||||
try{r=await mutate(p.url,p.data,p);}catch(err){if(orderEdit)return orderEditError(err,decodeURIComponent(orderEdit[1]));if(materialChange)return materialPurchaseChangeError($('#material-purchase-'+materialChange[2]+'-form'),err,{id:decodeURIComponent(materialChange[1]),kind:materialChange[2]});if(p.url==='/api/people-count'&&err.status===409){await refresh(false);await showPeopleCountForm(p.data.date,'人数已被更新,已显示当前值,请核对后再保存。');return toast('人数已被更新,请核对当前值后再保存。',true);}throw err;}
|
||||
const p=pending();if(!p)return;let r;const orderEdit=p.url.match(/^\/api\/orders\/([^/]+)\/edit$/);const cancellation=typeof orderCancellationOperation==='function'?orderCancellationOperation(p.url):null;const materialChange=p.url.match(/^\/api\/material-purchases\/([^/]+)\/(edit|delete)$/);
|
||||
try{r=await mutate(p.url,p.data,p);}catch(err){if(cancellation)return orderCancellationError(err);if(orderEdit)return orderEditError(err,decodeURIComponent(orderEdit[1]));if(materialChange)return materialPurchaseChangeError($('#material-purchase-'+materialChange[2]+'-form'),err,{id:decodeURIComponent(materialChange[1]),kind:materialChange[2]});if(p.url==='/api/people-count'&&err.status===409){await refresh(false);await showPeopleCountForm(p.data.date,'人数已被更新,已显示当前值,请核对后再保存。');return toast('人数已被更新,请核对当前值后再保存。',true);}throw err;}
|
||||
if(cancellation)return await finishOrderCancellationSave(p.url,p.data,r);
|
||||
if(orderEdit)return await finishOrderEditSave(p.data,r,decodeURIComponent(orderEdit[1]));
|
||||
if(p.url==='/api/price-locks'||/^\/api\/price-locks\/[^/]+\/deliver$/.test(p.url))return await finishPriceLockSave(p.url,p.data,r);
|
||||
if(p.url==='/api/material-purchases')return await finishMaterialPurchaseSave(p.data,r);
|
||||
@@ -860,7 +882,7 @@ document.addEventListener('click',async ev=>{
|
||||
if(a==='clear-draft'){if(tab==='order-edit')throw new Error('请用“取消修改”退出订单修改。');editDraft=null;orderTemplateSelection='';localStorage.removeItem('mm-draft-'+session.user.id);return renderCreate();}
|
||||
if(a==='copy-order')return await copyOrder(b.dataset.id,b);
|
||||
if(a==='open-order')return await openOrder(b.dataset.id);
|
||||
if(a==='close-dialog'){$('#order-dialog').close();currentOrder=null;return;}
|
||||
if(a==='close-dialog'){++orderDetailRequest;if(typeof closeOrderCancellationForm==='function')closeOrderCancellationForm();$('#order-dialog').close();currentOrder=null;return;}
|
||||
if(a==='edit'){createMode='direct';orderTemplateSelection='';editDraft=draftInputs(currentOrder);$('#order-dialog').close();tab='create';return render();}
|
||||
if(a.startsWith('show-'))return showAction(a.slice(5));
|
||||
if(a==='hide-action'){$('#detail-form').innerHTML='';return;}
|
||||
@@ -883,6 +905,7 @@ document.addEventListener('click',async ev=>{
|
||||
document.addEventListener('submit',async ev=>{
|
||||
ev.preventDefault();const form=ev.target;const data=Object.fromEntries(new FormData(form));
|
||||
try{
|
||||
if(form.id==='order-cancellation-form')return await submitOrderCancellation(form);
|
||||
if(form.id==='setup-form'||form.id==='login-form'){await api(form.id==='setup-form'?'/api/setup':'/api/login',data);return init();}
|
||||
if(form.id==='material-purchase-form')return await submitMaterialPurchase(form);
|
||||
if(form.id==='material-purchase-edit-form'||form.id==='material-purchase-delete-form')return await submitMaterialPurchaseChange(form);
|
||||
@@ -923,6 +946,6 @@ document.addEventListener('submit',async ev=>{
|
||||
if(['review','complete'].includes(kind))input.revision=currentOrder.revision;
|
||||
const id=currentOrder.id;await mutate('/api/orders/'+id+'/'+kind,input);invalidateMaterialPools();await refresh();await openOrder(id);return toast(actionName[kind]+'已保存');
|
||||
}
|
||||
}catch(err){if(form.id==='order-edit-meta-form'||form.id==='order-form'&&form.dataset.orderEdit==='true')return orderEditError(err);if(form.id==='material-purchase-edit-form'||form.id==='material-purchase-delete-form')return materialPurchaseChangeError(form,err);if(form.id.startsWith('material-')){err.message=err.message.replace('不要重新开单','不要重复登记');toast(err.message,true);const target=form.id==='material-purchase-form'?$('#material-purchase-error'):$('#material-settlement-error');if(target)target.innerHTML=`<div class="error">${e(err.message)}${err.status===409?' '+button('关闭并重新读取该日购料','reload-material-settlement','quiet'):''}</div>`;return;}if(form.id==='people-count-form'&&err.status===409){await loadPeopleCount('人数已被更新,已显示当前值,请核对后再保存。');return toast('人数已被更新,请核对当前值后再保存。',true);}if(form.id==='people-count-form')err.message=err.message.replace('不要重新开单','不要重复记录人数');if(form.id==='after-sale-form')err.message=err.message.replace('不要重新开单','不要重复新增售后');if(form.id.startsWith('price-lock-'))err.message=err.message.replace('不要重新开单','不要重复锁价或交付');toast(err.message,true);if(form.id.startsWith('price-lock-')&&$('#price-lock-error'))$('#price-lock-error').innerHTML=`<div class="error">${e(err.message)}${err.status===409&&form.dataset.id?' '+button('重新读取锁价单','deliver-price-lock','',`data-id="${e(form.dataset.id)}"`):''}</div>`;else if(form.id==='people-count-form'&&$('#people-count-error'))$('#people-count-error').innerHTML=`<div class="error">${e(err.message)}</div>`;else if(form.id==='after-sale-form'&&$('#after-sale-error'))$('#after-sale-error').innerHTML=`<div class="error">${e(err.message)}</div>`;else if(form.id==='print-settings'&&$('#print-settings-error'))$('#print-settings-error').innerHTML=`<div class="error">${e(err.message)}</div>`;else if(form.id.endsWith('login-form')||form.id==='setup-form')$('#login-error').innerHTML=`<div class="error">${e(err.message)}</div>`;else if(form.id==='order-form')$('#order-error').innerHTML=`<div class="error">${e(err.message)}</div>`;else if(form.id==='stock-form'&&$('#stock-error'))$('#stock-error').innerHTML=`<div class="error">${e(err.message)}</div>`;else if($('#detail-error')&&form.id==='action-form')$('#detail-error').innerHTML=`<div class="error">${e(err.message)}</div>`;}
|
||||
}catch(err){if(form.id==='order-cancellation-form')return orderCancellationError(err);if(form.id==='order-edit-meta-form'||form.id==='order-form'&&form.dataset.orderEdit==='true')return orderEditError(err);if(form.id==='material-purchase-edit-form'||form.id==='material-purchase-delete-form')return materialPurchaseChangeError(form,err);if(form.id.startsWith('material-')){err.message=err.message.replace('不要重新开单','不要重复登记');toast(err.message,true);const target=form.id==='material-purchase-form'?$('#material-purchase-error'):$('#material-settlement-error');if(target)target.innerHTML=`<div class="error">${e(err.message)}${err.status===409?' '+button('关闭并重新读取该日购料','reload-material-settlement','quiet'):''}</div>`;return;}if(form.id==='people-count-form'&&err.status===409){await loadPeopleCount('人数已被更新,已显示当前值,请核对后再保存。');return toast('人数已被更新,请核对当前值后再保存。',true);}if(form.id==='people-count-form')err.message=err.message.replace('不要重新开单','不要重复记录人数');if(form.id==='after-sale-form')err.message=err.message.replace('不要重新开单','不要重复新增售后');if(form.id.startsWith('price-lock-'))err.message=err.message.replace('不要重新开单','不要重复锁价或交付');toast(err.message,true);if(form.id.startsWith('price-lock-')&&$('#price-lock-error'))$('#price-lock-error').innerHTML=`<div class="error">${e(err.message)}${err.status===409&&form.dataset.id?' '+button('重新读取锁价单','deliver-price-lock','',`data-id="${e(form.dataset.id)}"`):''}</div>`;else if(form.id==='people-count-form'&&$('#people-count-error'))$('#people-count-error').innerHTML=`<div class="error">${e(err.message)}</div>`;else if(form.id==='after-sale-form'&&$('#after-sale-error'))$('#after-sale-error').innerHTML=`<div class="error">${e(err.message)}</div>`;else if(form.id==='print-settings'&&$('#print-settings-error'))$('#print-settings-error').innerHTML=`<div class="error">${e(err.message)}</div>`;else if(form.id.endsWith('login-form')||form.id==='setup-form')$('#login-error').innerHTML=`<div class="error">${e(err.message)}</div>`;else if(form.id==='order-form')$('#order-error').innerHTML=`<div class="error">${e(err.message)}</div>`;else if(form.id==='stock-form'&&$('#stock-error'))$('#stock-error').innerHTML=`<div class="error">${e(err.message)}</div>`;else if($('#detail-error')&&form.id==='action-form')$('#detail-error').innerHTML=`<div class="error">${e(err.message)}</div>`;}
|
||||
});
|
||||
init();
|
||||
@@ -1,5 +1,5 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>麦麦珠宝 · 新账系统</title><link rel="stylesheet" href="/app.css"><script src="/calculations.js" defer></script><script src="/fee-estimates.js" defer></script><script src="/order-copy.js" defer></script><script src="/order-templates.js" defer></script><script src="/order-templates-ui.js" defer></script><script src="/price-locks-ui.js" defer></script><script src="/material-pools-ui.js" defer></script><script src="/order-edit-ui.js" defer></script><script src="/app.js" defer></script></head>
|
||||
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>麦麦珠宝 · 新账系统</title><link rel="stylesheet" href="/app.css"><script src="/calculations.js" defer></script><script src="/fee-estimates.js" defer></script><script src="/order-copy.js" defer></script><script src="/order-templates.js" defer></script><script src="/order-templates-ui.js" defer></script><script src="/price-locks-ui.js" defer></script><script src="/material-pools-ui.js" defer></script><script src="/order-edit-ui.js" defer></script><script src="/order-cancellations-ui.js" defer></script><script src="/app.js" defer></script></head>
|
||||
<body><div id="toast" role="status" hidden></div><div id="login"></div><div id="shell" hidden>
|
||||
<header class="app-header"><div class="brand"><span class="brand-mark">麦</span><div><strong>麦麦珠宝</strong><small>开单 · 库存 · 订单利润</small></div></div><div class="header-right"><span id="mode" class="badge"></span><span id="identity"></span><button class="quiet" data-action="logout">退出</button></div></header>
|
||||
<div id="notice" class="notice"></div><div id="pending" class="pending" hidden></div>
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
'use strict';
|
||||
// 取消是录错作废,申请与复核均沿用原操作号,不产生真实退款。
|
||||
let orderCancellationDetail=null,orderCancellationFormEntry=null;
|
||||
let orderCancellationCountRequest=0,orderCancellationListRequest=0,orderCancellationListStatus='pending';
|
||||
const orderCancellationStatus={pending:'待麦麦复核',approved:'已同意取消',rejected:'已驳回'};
|
||||
function orderCancellationUser(){return session?.user?.id||'';}
|
||||
function orderCancellationTime(value){const date=new Date(value);return Number.isNaN(date.getTime())?'时间未提供':date.toLocaleString('zh-CN');}
|
||||
function validateOrderCancellationRequest(request,orderId){
|
||||
const summary=request?.summary,nullable=value=>value===null||Number.isSafeInteger(value);
|
||||
if(!request||typeof request.id!=='string'||!request.id||typeof request.order_id!=='string'||orderId&&request.order_id!==orderId||
|
||||
!Object.hasOwn(orderCancellationStatus,request.status)||!Number.isSafeInteger(request.order_revision)||
|
||||
typeof request.reason!=='string'||typeof request.requester_name!=='string'||typeof request.created!=='string'||
|
||||
typeof request.stale!=='boolean'||typeof request.canApprove!=='boolean'||!summary||
|
||||
!['total','netReceived','directCost'].every(key=>Number.isSafeInteger(summary[key]))||!['goodsCost','profit','settlementDue'].every(key=>nullable(summary[key]))||
|
||||
!Array.isArray(summary.inventory)||!summary.inventory.every(item=>typeof item.date==='string'&&typeof item.pocket==='string'&&Number.isSafeInteger(item.mg)))throw new Error('取消申请资料未完整返回,请重新读取订单后复核。');
|
||||
return request;
|
||||
}
|
||||
function useOrderCancellationDetail(order,result,error){
|
||||
orderCancellationFormEntry=null;
|
||||
const entry={id:order.id,user:orderCancellationUser(),revision:order.revision,data:null,error:''};
|
||||
try{
|
||||
if(error)throw error;
|
||||
if(!result||typeof result.eligible!=='boolean'||typeof result.canApprove!=='boolean'||!Number.isSafeInteger(result.revision)||!Array.isArray(result.requests)||
|
||||
result.pending!==null&&typeof result.pending!=='object')throw new Error('取消复核资料尚未完整返回,请重新读取。');
|
||||
if(result.revision!==order.revision)throw new Error('订单已有新记录,请重新读取订单后复核取消申请。');
|
||||
result.requests.forEach(request=>validateOrderCancellationRequest(request,order.id));
|
||||
if(result.pending)validateOrderCancellationRequest(result.pending,order.id);
|
||||
entry.data=result;
|
||||
}catch(err){entry.error=err.name==='AbortError'?'取消申请读取超时,请重新读取。':err.message;}
|
||||
orderCancellationDetail=entry;return entry;
|
||||
}
|
||||
function currentOrderCancellation(order=currentOrder){
|
||||
return order&&orderCancellationDetail?.id===order.id&&orderCancellationDetail.user===orderCancellationUser()&&orderCancellationDetail.revision===order.revision?orderCancellationDetail:null;
|
||||
}
|
||||
function orderCancellationPending(order){return currentOrderCancellation(order)?.data?.pending||order.cancellationPending||null;}
|
||||
function orderCancellationApproved(order){return order.cancellationApproved||currentOrderCancellation(order)?.data?.requests.find(request=>request.status==='approved')||null;}
|
||||
function orderCancellationActionHTML(order){
|
||||
const entry=currentOrderCancellation(order),data=entry?.data;
|
||||
if(order.price_lock_id||!['draft','confirmed','delivered'].includes(order.status)||orderCancellationPending(order)||!data?.eligible)return '';
|
||||
return button('申请取消','request-order-cancellation','danger',`data-id="${e(order.id)}"`);
|
||||
}
|
||||
function orderCancellationHistoryHTML(request){
|
||||
return `<li><div class="cancellation-record-title"><strong>${e(orderCancellationStatus[request.status])}</strong>${request.stale&&request.status==='pending'?'<span class="badge danger">订单已有变动</span>':''}</div><div>申请人:${e(request.requester_name)} · ${e(orderCancellationTime(request.created))}</div><p class="cancellation-reason">${e(request.reason)}</p>${request.status!=='pending'?`<div class="small muted">复核人:${e(request.reviewer_name||'未提供')} · ${e(orderCancellationTime(request.reviewed))}${request.note?`<p class="cancellation-reason">${request.status==='rejected'?'驳回意见':'复核备注'}:${e(request.note)}</p>`:''}</div>`:''}</li>`;
|
||||
}
|
||||
function orderCancellationDetailHTML(order){
|
||||
if(order.price_lock_id)return '';
|
||||
const entry=currentOrderCancellation(order),data=entry?.data,request=orderCancellationPending(order),approved=orderCancellationApproved(order);
|
||||
if(!data)return `<section class="panel order-cancellation-panel"><h2>取消申请与复核</h2><p class="${entry?.error?'danger-text':'muted'}" role="status">${e(entry?.error||'取消申请资料尚未读取,请先重新读取订单。')}</p>${button('重新读取订单','reload-order-cancellation','',`data-id="${e(order.id)}"`)}</section>`;
|
||||
if(!request&&!data.requests.length)return '';
|
||||
const canReview=state.user.role==='owner'&&data.canApprove&&request?.status==='pending';
|
||||
return `<section class="panel order-cancellation-panel" id="order-cancellation-panel"><div class="panel-title"><h2>${approved?'已取消 · 录错作废':'取消申请与复核'}</h2>${request?'<span class="badge warn">待麦麦复核</span>':''}</div>${request?`<p>申请期间仍按原订单计账,尚未取消。复核完成前暂停本单财务修改和退货。</p>${request.stale?'<div class="error" role="status">订单在申请后已有变动,原申请不能同意。请麦麦驳回后重新申请,再按最新资料核对。</div>':''}${canReview?`<div class="actions">${!request.stale?button('同意取消','approve-order-cancellation','danger',`data-id="${e(request.id)}"`):''}${button('驳回','reject-order-cancellation','',`data-id="${e(request.id)}"`)}</div>`:'<p class="small muted">由麦麦账号查看撤销摘要并复核。</p>'}`:''}${approved?'<p>本单为录错作废:销售、成本、收款及费用已撤销,原有库存出入已冲回。原单、原流水与复核记录保留;本次没有登记真实退货或发起退款。</p><p class="small muted">双方已登记的实际交款保留,请继续核对下方待结金额。</p>':''}<details ${request?'open':''}><summary>取消申请与复核记录(${data.requests.length})</summary><ul class="timeline cancellation-history">${data.requests.map(orderCancellationHistoryHTML).join('')}</ul></details></section>`;
|
||||
}
|
||||
function orderCancellationSummaryHTML(request){
|
||||
const summary=validateOrderCancellationRequest(request).summary,amount=value=>value===null?'待补齐':'¥'+yuan(value);
|
||||
return `<div class="note">同意后按“录错作废”撤销本单记账,不是实际退货退款。原单和冲回明细保留,不会向客户付款。</div><dl class="cancellation-summary"><div><dt>撤销原成交金额</dt><dd>${amount(summary.total)}</dd></div><div><dt>撤销收款净额</dt><dd>${amount(summary.netReceived)}</dd></div><div><dt>撤销货品成本</dt><dd>${amount(summary.goodsCost)}</dd></div><div><dt>撤销已记费用</dt><dd>${amount(summary.directCost)}</dd></div><div><dt>撤销原记账利润</dt><dd>${amount(summary.profit)}</dd></div><div><dt>申请时双方待结净额</dt><dd>${amount(summary.settlementDue)}</dd></div></dl><h3>库存冲回摘要</h3>${summary.inventory.length?`<div class="table-wrap"><table aria-label="取消后库存冲回摘要"><thead><tr><th>原日期</th><th>货盘</th><th class="number">恢复/冲回克重</th></tr></thead><tbody>${summary.inventory.map(item=>`<tr><td>${e(item.date)}</td><td>${e(item.pocket)}</td><td class="number">${item.mg>0?'+':''}${grams(item.mg)}g</td></tr>`).join('')}</tbody></table></div>`:'<p class="small muted">本单没有需要冲回的库存出入。</p>'}<p class="small muted cancellation-summary-note">按原日期、原货盘冲回库存。收款与费用撤回后仍能查看原记录和冲回行;双方实际交款保留,不会自动抹掉或转账。日购料真实采购付款保留,本单耗用将释放并重算相关成本与待结金额。</p>`;
|
||||
}
|
||||
function requireOrderCancellationDetail(){
|
||||
if(busy)throw new Error('正在保存,请稍候。');
|
||||
if(pending())throw new Error('请先点击顶部“恢复原操作”,确认上次提交结果后再处理取消申请。');
|
||||
const order=currentOrder,entry=currentOrderCancellation(order);
|
||||
if(!order||!entry?.data||entry.error)throw new Error('请重新读取订单并核对取消申请。');
|
||||
if(order.price_lock_id)throw new Error('锁价单暂不支持取消。');
|
||||
return {order,entry,data:entry.data};
|
||||
}
|
||||
function showOrderCancellationForm(kind){
|
||||
const {order,data}=requireOrderCancellationDetail(),request=data.pending;
|
||||
if(kind==='request'&&(!data.eligible||request||!['draft','confirmed','delivered'].includes(order.status)))throw new Error(data.reason||'这张订单当前不能申请取消。');
|
||||
if(kind!=='request'&&(state.user.role!=='owner'||!data.canApprove||request?.status!=='pending'))throw new Error('取消申请由麦麦账号复核。');
|
||||
if(kind==='approve'&&(!request.canApprove||request.stale||request.order_revision!==order.revision))throw new Error('订单已有变动,请重新读取后复核;过期申请需驳回后重新申请。');
|
||||
orderCancellationFormEntry={kind,id:order.id,user:orderCancellationUser(),revision:order.revision,requestId:request?.id||'',requestRevision:request?.order_revision};
|
||||
let html='',title='',submit='';
|
||||
if(kind==='request'){
|
||||
title='申请取消这张订单';submit='提交取消申请';
|
||||
html='<p>仅用于开错、重复录入等需要整单作废的登记错误。提交后仍按原单计账,麦麦同意后才取消、恢复库存并撤销本单销售、成本、收款和费用记账。</p><p class="small muted">真实退货请从“整单退货”办理;这里不会发起真实退款。</p><label>取消原因<textarea name="reason" rows="3" required maxlength="200" placeholder="写清这张单录错的原因,例如:同一笔销售重复录入。"></textarea></label>';
|
||||
}else if(kind==='approve'){
|
||||
title='复核并同意取消';submit='同意取消并作废';
|
||||
html=`<p>申请人:${e(request.requester_name)} · ${e(orderCancellationTime(request.created))}</p><p class="cancellation-reason">取消原因:${e(request.reason)}</p>${orderCancellationSummaryHTML(request)}<label>复核备注(选填)<textarea name="note" maxlength="200" rows="2"></textarea></label><label class="check"><input type="checkbox" name="verified" required>已核实这是录错作废,并确认撤销上述记账和冲回库存;本次不登记真实退货退款。</label>`;
|
||||
}else if(kind==='reject'){
|
||||
title='驳回取消申请';submit='确认驳回';
|
||||
html=`<p class="cancellation-reason">取消原因:${e(request.reason)}</p><p class="small muted">驳回后原订单继续计账,申请人可核对后重新申请。</p><label>驳回意见<textarea name="note" rows="3" required maxlength="200" placeholder="写清需要补充或重新核对的地方。"></textarea></label>`;
|
||||
}else throw new Error('取消操作无效,请重新读取订单。');
|
||||
$('#detail-error').innerHTML='';$('#detail-form').innerHTML=`<form class="panel order-cancellation-form" id="order-cancellation-form" data-kind="${kind}"><h2>${title}</h2>${html}<div id="order-cancellation-error" aria-live="polite"></div><div class="form-actions"><button type="submit" class="${kind==='approve'?'danger':'primary'}">${submit}</button>${button('收起','close-order-cancellation-form','quiet')}</div></form>`;
|
||||
$('#detail-form').scrollIntoView({block:'nearest',behavior:'smooth'});$('#order-cancellation-form textarea')?.focus();
|
||||
}
|
||||
function closeOrderCancellationForm(){orderCancellationFormEntry=null;if($('#order-cancellation-form'))$('#detail-form').innerHTML='';}
|
||||
function orderCancellationOperation(url){
|
||||
const application=url.match(/^\/api\/orders\/([^/]+)\/cancellation$/),decision=url.match(/^\/api\/order-cancellations\/([^/]+)\/(approve|reject)$/);
|
||||
return application?{kind:'request',orderId:decodeURIComponent(application[1])}:decision?{kind:decision[2],requestId:decodeURIComponent(decision[1])}:null;
|
||||
}
|
||||
function applyOrderCancellationRestrictions(){
|
||||
const form=$('#order-cancellation-form');if(!form)return;
|
||||
const blocked=busy||!!pending()||!orderCancellationFormEntry;
|
||||
form.querySelectorAll('input,textarea,button').forEach(control=>{const action=control.dataset.action;control.disabled=action==='close-order-cancellation-form'?false:['reload-order-cancellation','retry'].includes(action)?busy:blocked;});
|
||||
}
|
||||
function orderCancellationError(err){
|
||||
err.message=err.message.replace('不要重新开单','不要重复提交取消申请或复核');
|
||||
const entry=orderCancellationFormEntry,id=entry?.id||currentOrder?.id;
|
||||
if(err.status===409||err.status===403||err.status===404){
|
||||
orderCancellationFormEntry=null;if(orderCancellationDetail)orderCancellationDetail={...orderCancellationDetail,data:null,error:'取消申请或订单已有新记录,请重新读取后复核。'};
|
||||
const checkbox=$('#order-cancellation-form [name="verified"]');if(checkbox)checkbox.checked=false;
|
||||
if($('#order-cancellation-panel'))$('#order-cancellation-panel').innerHTML='<h2>请重新读取后复核</h2><p>取消申请或订单已有变动,当前页面不能继续复核。</p>';
|
||||
}
|
||||
const target=$('#order-cancellation-error')||$('#detail-error');
|
||||
if(target)target.innerHTML=`<div class="error">${e(err.message)}${pending()?' '+button('恢复原操作','retry','danger'):id?' '+button('重新读取订单并复核','reload-order-cancellation','',`data-id="${e(id)}"`):''}</div>`;
|
||||
applyOrderCancellationRestrictions();toast(err.message,true);
|
||||
}
|
||||
async function submitOrderCancellation(form){
|
||||
const {order,data}=requireOrderCancellationDetail(),entry=orderCancellationFormEntry;
|
||||
if(form!==$('#order-cancellation-form')||!entry||entry.id!==order.id||entry.user!==orderCancellationUser()||entry.revision!==order.revision)throw new Error('请重新读取订单后核对取消申请。');
|
||||
const get=name=>form.querySelector(`[name="${name}"]`),text=name=>String(get(name)?.value||'').trim();let input,url;
|
||||
if(entry.kind==='request'){
|
||||
if(!data.eligible||data.pending)throw new Error('这张订单当前不能重复申请取消。');
|
||||
const reason=text('reason');if(!reason||reason.length>200)throw new Error('取消原因请填写1~200字。');
|
||||
input={revision:entry.revision,reason};url='/api/orders/'+encodeURIComponent(order.id)+'/cancellation';
|
||||
}else{
|
||||
const request=data.pending;if(state.user.role!=='owner'||!data.canApprove||request?.status!=='pending'||request.id!==entry.requestId)throw new Error('取消申请由麦麦账号复核,请重新读取。');
|
||||
const note=text('note');if(note.length>200||entry.kind==='reject'&&!note)throw new Error(entry.kind==='reject'?'驳回意见请填写1~200字。':'复核备注最多200字。');
|
||||
if(entry.kind==='approve'){
|
||||
if(!request.canApprove||request.stale||entry.requestRevision!==order.revision)throw new Error('订单已有变动,请重新读取后复核,不能同意旧申请。');
|
||||
if(!get('verified')?.checked)throw new Error('请先核对撤销金额、成本和库存,并勾选录错作废确认。');
|
||||
input={revision:entry.requestRevision,verified:true,note};
|
||||
}else input={note};
|
||||
url='/api/order-cancellations/'+encodeURIComponent(entry.requestId)+'/'+entry.kind;
|
||||
}
|
||||
$('#order-cancellation-error').innerHTML='';
|
||||
try{const result=await mutate(url,input);return await finishOrderCancellationSave(url,input,result);}
|
||||
catch(err){orderCancellationError(err);}
|
||||
}
|
||||
async function finishOrderCancellationSave(url,input,result){
|
||||
const operation=orderCancellationOperation(url),id=result.id||result.order?.id||operation?.orderId,title=operation?.kind==='approve'?'已同意取消,原订单已作废':operation?.kind==='reject'?'取消申请已驳回':'取消申请已提交,等待麦麦复核';
|
||||
orderCancellationFormEntry=null;orderCancellationDetail=null;currentOrder=null;
|
||||
invalidateMaterialPools();invalidateReport();invalidatePriceLockViews();inventoryPage=null;++orderBookRequest;
|
||||
if($('#order-content'))$('#order-content').innerHTML=`<div class="order-header"><h2>${title}</h2><p>操作已经保存。${operation?.kind==='request'?'复核期间仍按原单计账。':operation?.kind==='approve'?'没有发起真实退款,原单和复核记录已保留。':'原订单继续计账。'}</p><div id="order-cancellation-saved-status" aria-live="polite"></div><div class="actions">${button('重新读取原订单','reload-order-cancellation','primary',`data-id="${e(id)}"`)}</div></div>`;
|
||||
try{await refresh();await openOrder(id);toast(title);}
|
||||
catch{if($('#order-cancellation-saved-status'))$('#order-cancellation-saved-status').textContent='保存已成功,最新资料暂未读到。请重新读取原订单查看。';toast('操作已经保存,请重新读取原订单查看,不要重复提交。',true);}
|
||||
}
|
||||
function validateOrderCancellationList(result){
|
||||
if(!result||!Array.isArray(result.requests)||typeof result.canApprove!=='boolean'||!['pending','approved','rejected'].every(key=>Number.isSafeInteger(result.counts?.[key])&&result.counts[key]>=0))throw new Error('取消复核列表未完整返回,请重新读取。');
|
||||
result.requests.forEach(request=>validateOrderCancellationRequest(request));return result;
|
||||
}
|
||||
async function loadOrderCancellationCount(){
|
||||
const request=++orderCancellationCountRequest,user=orderCancellationUser();
|
||||
try{
|
||||
const result=validateOrderCancellationList(await api('/api/order-cancellations?status=pending'));
|
||||
const entry=$('#order-cancellations-entry');if(request!==orderCancellationCountRequest||user!==orderCancellationUser()||tab!=='orders'||!entry)return;
|
||||
entry.textContent='待取消复核('+result.counts.pending+')';entry.classList.toggle('danger',result.counts.pending>0);entry.title='所有日期的取消申请,不受订单筛选影响';
|
||||
}catch{const entry=$('#order-cancellations-entry');if(request===orderCancellationCountRequest&&user===orderCancellationUser()&&tab==='orders'&&entry){entry.textContent='待取消复核(读取失败)';entry.title='点击重新读取全部日期的取消申请';}}
|
||||
}
|
||||
function orderCancellationListHTML(result){
|
||||
const owner=state.user.role==='owner'&&result.canApprove;
|
||||
return `<div class="cancellation-list-tabs" role="group" aria-label="取消申请状态">${[['pending','待复核'],['approved','已同意'],['rejected','已驳回'],['all','全部']].map(([value,name])=>button(name+(value==='all'?'':'('+result.counts[value]+')'),'filter-order-cancellations',orderCancellationListStatus===value?'primary':'',`data-status="${value}" aria-pressed="${orderCancellationListStatus===value}"`)).join('')}</div>${result.requests.length?`<div class="table-wrap"><table class="cancellation-list-table" aria-label="全部日期的取消申请"><thead><tr><th>原订单/日期</th><th>申请人/申请时间</th><th>取消原因</th><th>状态/复核意见</th><th>查看</th></tr></thead><tbody>${result.requests.map(request=>`<tr><td><strong>${e(request.order_number)}</strong><div class="small muted">${e(request.order_date)}</div><div class="small">原成交 ¥${yuan(request.summary.total)}</div></td><td>${e(request.requester_name)}<div class="small muted">${e(orderCancellationTime(request.created))}</div></td><td class="cancellation-reason">${e(request.reason)}</td><td>${e(orderCancellationStatus[request.status])}${request.stale&&request.status==='pending'?'<div class="small danger-text">原单已有变动,需驳回后重新申请</div>':''}${request.note?`<div class="small cancellation-reason">${e(request.note)}</div>`:''}${request.reviewer_name?`<div class="small muted">${e(request.reviewer_name)} · ${e(orderCancellationTime(request.reviewed))}</div>`:''}</td><td>${button(owner&&request.status==='pending'?'查看并复核':'查看订单','open-cancellation-order','',`data-id="${e(request.order_id)}"`)}</td></tr>`).join('')}</tbody></table></div>`:'<p class="empty">全部日期均无此状态的取消申请。</p>'}`;
|
||||
}
|
||||
async function openOrderCancellations(status='pending'){
|
||||
orderCancellationListStatus=Object.hasOwn(orderCancellationStatus,status)||status==='all'?status:'pending';
|
||||
let dialog=$('#order-cancellations-dialog');
|
||||
if(!dialog){dialog=document.createElement('dialog');dialog.id='order-cancellations-dialog';dialog.setAttribute('aria-labelledby','order-cancellations-title');dialog.addEventListener('cancel',()=>{++orderCancellationListRequest;});document.body.append(dialog);}
|
||||
dialog.innerHTML=`<button class="dialog-close" data-action="close-order-cancellations" aria-label="关闭取消申请列表">×</button><h2 id="order-cancellations-title">取消申请与复核</h2><p class="small muted">全部日期,不受订单页的日期、搜索或状态筛选影响。申请期间仍按原订单计账;麦麦同意后才按录错作废。</p><div id="order-cancellations-list" aria-live="polite" aria-busy="true">正在读取…</div>`;
|
||||
if(!dialog.open)dialog.showModal();return await loadOrderCancellations();
|
||||
}
|
||||
async function loadOrderCancellations(){
|
||||
const dialog=$('#order-cancellations-dialog'),target=$('#order-cancellations-list');if(!dialog?.open||!target)return;
|
||||
const request=++orderCancellationListRequest,user=orderCancellationUser(),status=orderCancellationListStatus;
|
||||
target.setAttribute('aria-busy','true');target.innerHTML='正在读取全部日期的取消申请…';
|
||||
try{
|
||||
const result=validateOrderCancellationList(await api('/api/order-cancellations?'+new URLSearchParams({status})));
|
||||
if(request!==orderCancellationListRequest||user!==orderCancellationUser()||!dialog.open||status!==orderCancellationListStatus)return;
|
||||
target.innerHTML=orderCancellationListHTML(result);target.setAttribute('aria-busy','false');
|
||||
const entry=$('#order-cancellations-entry');if(entry)entry.textContent='待取消复核('+result.counts.pending+')';
|
||||
}catch(err){if(request!==orderCancellationListRequest||user!==orderCancellationUser()||!dialog.open)return;target.setAttribute('aria-busy','false');target.innerHTML=`<div class="error">${e(err.name==='AbortError'?'读取超时,请重新读取。':err.message)} ${button('重新读取','retry-order-cancellations')}</div>`;}
|
||||
}
|
||||
function closeOrderCancellations(){++orderCancellationListRequest;$('#order-cancellations-dialog')?.close();}
|
||||
function invalidateOrderCancellationViews(){
|
||||
++orderCancellationCountRequest;closeOrderCancellations();orderCancellationDetail=null;orderCancellationFormEntry=null;
|
||||
}
|
||||
+8
-2
@@ -76,6 +76,9 @@ function createApp(options={}){
|
||||
const materialPoolMatch=route.match(/^\/api\/material-pools\/(\d{4}-\d{2}-\d{2})(?:\/(settlement))?$/);
|
||||
if(materialPoolMatch&&!isPost){if(materialPoolMatch[2])fail('地址不存在',404);return send(res,200,ledger.materialPoolDetail(materialPoolMatch[1]));}
|
||||
if(route==='/api/price-locks'&&!isPost)return send(res,200,ledger.priceLocks(Object.fromEntries(url.searchParams)));
|
||||
if(route==='/api/order-cancellations'&&!isPost)return send(res,200,ledger.orderCancellations(Object.fromEntries(url.searchParams),actor));
|
||||
const cancellationMatch=route.match(/^\/api\/order-cancellations\/([a-f0-9-]{36})(?:\/(approve|reject))?$/);
|
||||
if(cancellationMatch&&!isPost){if(cancellationMatch[2])fail('地址不存在',404);return send(res,200,ledger.orderCancellationRequest(cancellationMatch[1],actor));}
|
||||
const lockMatch=route.match(/^\/api\/price-locks\/([a-f0-9-]+)(?:\/(deliver))?$/);
|
||||
if(lockMatch&&!isPost){if(lockMatch[2])fail('地址不存在',404);return send(res,200,ledger.priceLockDetail(lockMatch[1]));}
|
||||
if(route==='/api/inventory'&&!isPost)return send(res,200,ledger.inventoryStatus(actor));
|
||||
@@ -87,7 +90,7 @@ function createApp(options={}){
|
||||
if(route==='/api/people-count'&&!isPost)return send(res,200,ledger.peopleCount(url.searchParams.get('date')??today()));
|
||||
if(route==='/api/paper-number'&&!isPost)return send(res,200,{number:ledger.paperNumber(url.searchParams.get('date')||today())});
|
||||
const match=route.match(/^\/api\/orders\/([a-f0-9-]+)(?:\/([a-z]+))?$/);
|
||||
if(match&&!isPost){if(match[2]==='public')return send(res,200,ledger.publicOrder(match[1]));if(match[2]==='edit')return send(res,200,ledger.orderEdit(match[1],actor));if(!match[2])return send(res,200,ledger.detail(match[1]));fail('地址不存在',404);}
|
||||
if(match&&!isPost){if(match[2]==='public')return send(res,200,ledger.publicOrder(match[1]));if(match[2]==='edit')return send(res,200,ledger.orderEdit(match[1],actor));if(match[2]==='cancellation')return send(res,200,ledger.orderCancellation(match[1],actor));if(!match[2])return send(res,200,ledger.detail(match[1]));fail('地址不存在',404);}
|
||||
if(route.startsWith('/print/')&&!isPost){const id=route.slice(7);return send(res,200,receipt(ledger.publicOrder(id),ledger.meta('printing',defaults),url.searchParams.get('mode')),'text/html; charset=utf-8');}
|
||||
if(route==='/api/report'&&!isPost){
|
||||
const basis=url.searchParams.get('basis');if(basis!==null&&basis!=='orderDate')fail('对账日期口径无效');
|
||||
@@ -113,6 +116,9 @@ function createApp(options={}){
|
||||
if(route==='/api/price-locks')return ledger.createPriceLock(b,actor);
|
||||
if(lockMatch&&lockMatch[2]==='deliver')return ledger.deliverPriceLock(lockMatch[1],b,actor);
|
||||
if(route==='/api/after-sales')return ledger.saveAfterSale(b,actor);
|
||||
if(cancellationMatch&&cancellationMatch[2]==='approve')return ledger.approveOrderCancellation(cancellationMatch[1],b,actor);
|
||||
if(cancellationMatch&&cancellationMatch[2]==='reject')return ledger.rejectOrderCancellation(cancellationMatch[1],b,actor);
|
||||
if(match&&match[2]==='cancellation')return ledger.requestOrderCancellation(match[1],b,actor);
|
||||
if(route==='/api/people-count')return ledger.savePeopleCount(b,actor);
|
||||
if(match&&match[2]==='edit')return ledger.editOrder(match[1],b,actor);
|
||||
if(match&&match[2])return ledger.action(match[1],match[2],b,actor);
|
||||
@@ -124,7 +130,7 @@ function createApp(options={}){
|
||||
fail('地址不存在',404);
|
||||
});return send(res,200,result);
|
||||
}
|
||||
const assets={'/':'index.html','/app.js':'app.js','/order-copy.js':'order-copy.js','/order-templates.js':'order-templates.js','/order-templates-ui.js':'order-templates-ui.js','/order-edit-ui.js':'order-edit-ui.js','/price-locks-ui.js':'price-locks-ui.js','/material-pools-ui.js':'material-pools-ui.js','/calculations.js':'calculations.js','/fee-estimates.js':'fee-estimates.js','/app.css':'app.css','/print.js':'print.js'};const file=assets[route];if(!file||isPost)fail('地址不存在',404);
|
||||
const assets={'/':'index.html','/app.js':'app.js','/order-copy.js':'order-copy.js','/order-templates.js':'order-templates.js','/order-templates-ui.js':'order-templates-ui.js','/order-edit-ui.js':'order-edit-ui.js','/order-cancellations-ui.js':'order-cancellations-ui.js','/price-locks-ui.js':'price-locks-ui.js','/material-pools-ui.js':'material-pools-ui.js','/calculations.js':'calculations.js','/fee-estimates.js':'fee-estimates.js','/app.css':'app.css','/print.js':'print.js'};const file=assets[route];if(!file||isPost)fail('地址不存在',404);
|
||||
send(res,200,fs.readFileSync(path.join(__dirname,'public',file)),file.endsWith('.js')?'application/javascript; charset=utf-8':file.endsWith('.css')?'text/css; charset=utf-8':'text/html; charset=utf-8');
|
||||
}catch(e){if(!res.headersSent)send(res,e.status||400,{error:e.status||e.message?.startsWith('打印')?e.message:(e.code?.startsWith('SQLITE')?'保存失败,请保留操作内容并联系维护者':e.message||'操作失败')});else res.end();}
|
||||
});
|
||||
|
||||
+1
-1
@@ -28,7 +28,7 @@ class FeishuSync {
|
||||
fields(entity,revision){
|
||||
if(entity==='inventory')return {'系统键':entity,'类型':'库存快照','单号':'','状态':'从主账流水重算','日期':now().slice(0,10),'销售金额':0,'订单利润':0,'已收净额':0,'待结算':0,'数据版本':revision,'明细':JSON.stringify(this.ledger.inventory())};
|
||||
const o=this.ledger.detail(entity.slice(6));const {audit,sync,...details}=o;
|
||||
return {'系统键':entity,'类型':'订单','单号':o.number,'状态':o.status,'日期':o.date,'销售金额':o.total/100,'订单利润':o.profit/100,'已收净额':o.netReceived/100,'待结算':o.settlementDue/100,'数据版本':revision,'明细':JSON.stringify(details)};
|
||||
return {'系统键':entity,'类型':'订单','单号':o.number,'状态':o.status,'日期':o.date,'销售金额':o.cancellationApproved?0:o.total/100,'订单利润':o.profit/100,'已收净额':o.netReceived/100,'待结算':o.settlementDue/100,'数据版本':revision,'明细':JSON.stringify(details)};
|
||||
}
|
||||
async tick(){
|
||||
if(!this.enabled||this.busy)return;this.busy=true;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
'use strict';
|
||||
const {historicalAction}=require('./fixtures/legacy-cancellation.cjs');
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict');
|
||||
const {randomUUID}=require('node:crypto'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
|
||||
const {Ledger}=require('../ledger'),Calc=require('../public/calculations'),{createApp}=require('../server'),{FeishuSync}=require('../sync');
|
||||
@@ -12,7 +13,7 @@ function fixture(t){
|
||||
const run=(input,fn,key=randomUUID())=>ledger.transact(key,owner,input,fn);
|
||||
run({stock:true},()=>ledger.stock({kind:'opening',date:D,pocket:'现货',grams:'20',note:'合成库存'},owner));
|
||||
const save=(input=payload(),issue=false)=>run(input,()=>issue?ledger.issueOrder(input,owner):ledger.saveOrder(input,owner)).id;
|
||||
const action=(id,kind,extra={})=>{const input={date:D,...extra};return run({id,kind,input},()=>ledger.action(id,kind,input,owner));};
|
||||
const action=(id,kind,extra={})=>{const input={date:D,...extra};return run({id,kind,input},()=>historicalAction(ledger,id,kind,input,owner));};
|
||||
return {ledger,run,save,action};
|
||||
}
|
||||
const snapshot=ledger=>JSON.stringify(ledger.rows("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").map(({name})=>[name,ledger.rows('SELECT * FROM "'+name+'"')]));
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
'use strict';
|
||||
const {historicalAction}=require('./fixtures/legacy-cancellation.cjs');
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict');
|
||||
const {randomUUID}=require('node:crypto'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
|
||||
const {Ledger,today}=require('../ledger'),{createApp}=require('../server');
|
||||
@@ -13,7 +14,7 @@ function fixture(t){
|
||||
return run(input,()=>issue?ledger.issueOrder(input,actor):ledger.saveOrder(input,actor)).id;
|
||||
};
|
||||
const action=(id,kind,extra={},key=randomUUID())=>{
|
||||
const input={date:D,...extra};return run({id,kind,input},()=>ledger.action(id,kind,input,actor),key);
|
||||
const input={date:D,...extra};return run({id,kind,input},()=>historicalAction(ledger,id,kind,input,actor),key);
|
||||
};
|
||||
const report=(date=D,from=date)=>ledger.reportByOrderDate(date,from);
|
||||
const close=(date=D,basis='orderDate')=>run({date,basis},()=>ledger.closeDay(date,actor,basis));
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
'use strict';
|
||||
const {historicalAction}=require('./fixtures/legacy-cancellation.cjs');
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),{randomUUID}=require('node:crypto');
|
||||
const Estimates=require('../public/fee-estimates'),Calc=require('../public/calculations'),{Ledger}=require('../ledger');
|
||||
const actor={id:'fee-test',name:'测试麦麦',role:'owner'},date='2026-10-17';
|
||||
const charge=(name,amount='10')=>({id:randomUUID(),name,amount});
|
||||
const product=charges=>({name:'足金999',unit:'g',quantity:'2',pocket:'',payer:'owner',cost:'1000',pricingMode:'manual',baseSale:'1200',charges});
|
||||
function fixture(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'maimai-fees-'));const l=new Ledger(path.join(dir,'ledger.sqlite'));t.after(()=>{l.close();fs.rmSync(dir,{recursive:true,force:true});});const run=(data,fn,key=randomUUID())=>l.transact(key,actor,data,fn);const save=input=>run(input,()=>l.saveOrder({date,discount:'0',...input},actor)).id;const act=(id,action,input={})=>run({id,action,input},()=>l.action(id,action,{date,...input},actor));return {l,run,save,act};}
|
||||
function fixture(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'maimai-fees-'));const l=new Ledger(path.join(dir,'ledger.sqlite'));t.after(()=>{l.close();fs.rmSync(dir,{recursive:true,force:true});});const run=(data,fn,key=randomUUID())=>l.transact(key,actor,data,fn);const save=input=>run(input,()=>l.saveOrder({date,discount:'0',...input},actor)).id;const act=(id,action,input={})=>run({id,action,input},()=>historicalAction(l,id,action,{date,...input},actor));return {l,run,save,act};}
|
||||
test('选入附加项目自动带入成本:证书4、包装3、快递整单6;未知不猜数',()=>{
|
||||
const charges=[charge('附加费'),charge('编绳'),charge('证书'),charge('包装'),charge('物料','')];
|
||||
const rows=Estimates.sync([],[product(charges)],{addShipping:true});assert.deepEqual(rows.map(r=>[r.note,r.amount]),[['快递费','6'],['附加费',''],['编绳',''],['证书','4'],['包装','3'],['物料','']]);assert.ok(rows.every(r=>r.status==='estimated'));
|
||||
@@ -30,7 +31,7 @@ test('预估保存与确认订单不造支出;交付前核实真实费用,
|
||||
save({id,revision:l.detail(id).revision,lines,fee_items:fees});assert.equal(l.detail(id).fee_items.length,3);act(id,'confirm');assert.equal(l.detail(id).expenses.length,0);assert.equal(l.detail(id).pendingFees.length,3);assert.equal(l.report(date).expense,0);assert.ok(l.report(date).warnings.some(w=>w.message==='附加成本待核实'));
|
||||
act(id,'receipt',{amount:'1220',account:'助理微信',verified:true});assert.throws(()=>act(id,'deliver',{verified:true}),/附加成本/);
|
||||
const payload={date,revision:l.detail(id).revision,verified:true,fee_items:fees.map(f=>({...f,amount:f.note==='证书'?'4.5':f.note==='包装'?'0':'6'}))},key=randomUUID();
|
||||
run(payload,()=>l.action(id,'fees',payload,actor),key);run(payload,()=>l.action(id,'fees',payload,actor),key);assert.equal(l.detail(id).expenses.length,2);assert.equal(l.detail(id).directCost,1050);assert.equal(l.detail(id).pendingFees.length,0);assert.equal(l.detail(id).draftFees,0);assert.throws(()=>act(id,'fees',payload),/没有待核实/);
|
||||
run(payload,()=>historicalAction(l,id,'fees',payload,actor),key);run(payload,()=>historicalAction(l,id,'fees',payload,actor),key);assert.equal(l.detail(id).expenses.length,2);assert.equal(l.detail(id).directCost,1050);assert.equal(l.detail(id).pendingFees.length,0);assert.equal(l.detail(id).draftFees,0);assert.throws(()=>act(id,'fees',payload),/没有待核实/);
|
||||
act(id,'deliver',{verified:true});assert.equal(l.detail(id).profit,20950);assert.equal(l.report(date).expense,1050);
|
||||
const publicJson=JSON.stringify(l.publicOrder(id));for(const privateKey of ['pendingFees','fee_items','sourceName','estimated','payer','4.5'])assert.ok(!publicJson.includes(privateKey));
|
||||
});
|
||||
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
'use strict';
|
||||
// 仅用于旧库兼容测试:构造上线前已有的客户取消记录,生产入口不再提供旧取消动作。
|
||||
const {day,today,text,fail}=require('../../ledger');
|
||||
function historicalAction(ledger,id,action,input,actor){
|
||||
if(action!=='cancel')return ledger.action(id,action,input,actor);
|
||||
const order=ledger.detail(id),date=day(input.date||today(),order.date);
|
||||
if(!['draft','confirmed'].includes(order.status))fail('已交付订单请登记退货');
|
||||
if(order.payments.some(row=>row.date>date)||order.expenses.some(row=>row.date>date))fail('取消日期不能早于本单已登记流水日期');
|
||||
text(input.reason,'取消原因',200);
|
||||
ledger.run("UPDATE orders SET status='cancelled' WHERE id=?",id);
|
||||
ledger.journal(id,date,'取消预订',0,0,order.directCost);
|
||||
ledger.touch(id);ledger.dirty(date);ledger.audit(id,'cancel',actor,{...input,revision:ledger.rawOrder(id).revision});
|
||||
return {id};
|
||||
}
|
||||
module.exports={historicalAction};
|
||||
@@ -1,13 +1,14 @@
|
||||
'use strict';
|
||||
const {historicalAction}=require('./fixtures/legacy-cancellation.cjs');
|
||||
const test=require('node:test'),assert=require('node:assert/strict');
|
||||
const {randomUUID}=require('node:crypto');const fs=require('node:fs'),os=require('node:os'),path=require('node:path');
|
||||
const {Ledger,today,money,weight}=require('../ledger');const {receipt}=require('../printing');
|
||||
const actor={id:'owner-test',name:'测试麦麦',role:'owner'},assistant={id:'assistant-test',name:'测试助理',role:'assistant'};
|
||||
const D='2026-09-30',D2='2026-10-01';
|
||||
function fixture(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'maimai-ledger-test-'));const l=new Ledger(path.join(dir,'ledger.sqlite'));t.after(()=>{try{l.close();}catch{}fs.rmSync(dir,{recursive:true,force:true});});const run=(payload,fn,a=actor,key=randomUUID())=>l.transact(key,a,payload,fn);const stock=(p={},a=actor)=>run(p,()=>l.stock({kind:'opening',date:D,pocket:'现货',grams:'10.000',note:'合成测试',...p},a),a);const save=(p={})=>run(p,()=>l.saveOrder({date:D,customer:'测试客户',discount:'0',lines:[{name:'测试黄金',unit:'g',quantity:'1.200',pocket:'现货',payer:'owner',cost:'1000',sale:'1200',priceNote:'销售单价'}],...p},actor)).id;const act=(id,a,p={},who=actor)=>run({id,a,...p},()=>l.action(id,a,{date:D,...p},who),who);const fulfill=id=>{act(id,'confirm');act(id,'receipt',{amount:'1200',account:'助理微信',verified:true});act(id,'deliver',{verified:true});};return {l,dir,run,stock,save,act,fulfill};}
|
||||
function fixture(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'maimai-ledger-test-'));const l=new Ledger(path.join(dir,'ledger.sqlite'));t.after(()=>{try{l.close();}catch{}fs.rmSync(dir,{recursive:true,force:true});});const run=(payload,fn,a=actor,key=randomUUID())=>l.transact(key,a,payload,fn);const stock=(p={},a=actor)=>run(p,()=>l.stock({kind:'opening',date:D,pocket:'现货',grams:'10.000',note:'合成测试',...p},a),a);const save=(p={})=>run(p,()=>l.saveOrder({date:D,customer:'测试客户',discount:'0',lines:[{name:'测试黄金',unit:'g',quantity:'1.200',pocket:'现货',payer:'owner',cost:'1000',sale:'1200',priceNote:'销售单价'}],...p},actor)).id;const act=(id,a,p={},who=actor)=>run({id,a,...p},()=>historicalAction(l,id,a,{date:D,...p},who),who);const fulfill=id=>{act(id,'confirm');act(id,'receipt',{amount:'1200',account:'助理微信',verified:true});act(id,'deliver',{verified:true});};return {l,dir,run,stock,save,act,fulfill};}
|
||||
test('金额与克重整数化,拒绝空值、指数、超精度、NaN',()=>{assert.equal(money('0.29'),29);assert.equal(weight('0.001'),1);for(const v of ['',null,'NaN','1e2','-1','1.005'])assert.throws(()=>money(v));assert.throws(()=>weight('0.0001'));});
|
||||
test('定金、跨天尾款、交付是三个独立事实',t=>{const {l,stock,save,act}=fixture(t);stock();const id=save();act(id,'confirm');act(id,'receipt',{amount:'300',account:'助理微信',verified:true});assert.equal(l.detail(id).settlementDue,0);assert.equal(l.detail(id).profit,0);assert.equal(l.inventory()[0].mg,10000);assert.equal(l.inventory()[0].reserved,1200);assert.throws(()=>act(id,'deliver',{verified:true}),/未收齐/);act(id,'receipt',{date:D2,amount:'900',account:'助理支付宝',verified:true});act(id,'deliver',{date:D2,verified:true});assert.equal(l.inventory()[0].mg,8800);assert.equal(l.detail(id).profit,20000);assert.equal(l.detail(id).costDue,100000);assert.equal(l.report(D).sales,0);assert.equal(l.report(D2).accounts.find(a=>a.account==='助理支付宝').receipt,90000);assert.equal(l.report(D2).sales,120000);});
|
||||
test('同一操作号重试不多记款,内容改变报冲突',t=>{const {l,stock,save,act}=fixture(t);stock();const id=save();act(id,'confirm');const key=randomUUID(),payload={amount:'300',account:'助理微信',verified:true,date:D};const run=()=>l.transact(key,actor,payload,()=>l.action(id,'receipt',payload,actor));run();run();assert.equal(l.detail(id).received,30000);assert.equal(l.detail(id).payments.length,1);assert.throws(()=>l.transact(key,actor,{different:true},()=>({})),/其他内容/);});
|
||||
test('同一操作号重试不多记款,内容改变报冲突',t=>{const {l,stock,save,act}=fixture(t);stock();const id=save();act(id,'confirm');const key=randomUUID(),payload={amount:'300',account:'助理微信',verified:true,date:D};const run=()=>l.transact(key,actor,payload,()=>historicalAction(l,id,'receipt',payload,actor));run();run();assert.equal(l.detail(id).received,30000);assert.equal(l.detail(id).payments.length,1);assert.throws(()=>l.transact(key,actor,{different:true},()=>({})),/其他内容/);});
|
||||
test('同一次交付、补打及重新补打不重复扣库存',t=>{const {l,stock,save,act,fulfill}=fixture(t);stock();const id=save();fulfill(id);assert.throws(()=>act(id,'deliver',{verified:true}),/待交付/);for(let i=0;i<3;i++)act(id,'print');assert.equal(l.inventory()[0].mg,8800);assert.equal(l.detail(id).received,120000);assert.equal(l.report(D).sales,120000);});
|
||||
test('三位克重、混合货盘、调拨守恒',t=>{const {l,stock,save,act}=fixture(t);stock({grams:'0.003'});stock({kind:'transfer',grams:'0.001',to:'金料'});assert.equal(l.inventory()[0].mg,2);assert.equal(l.inventory()[1].mg,1);assert.equal(l.inventory().reduce((s,r)=>s+r.mg,0),3);const id=save({lines:[{name:'测试',unit:'g',quantity:'0.001',pocket:'金料',payer:'owner',cost:'1',sale:'2'}]});act(id,'confirm');act(id,'receipt',{amount:'2',account:'助理微信',verified:true});act(id,'deliver',{verified:true});assert.equal(l.inventory()[1].mg,0);});
|
||||
test('库存被订单占用后,调拨不能消耗占用;失败事务不留下半笔',t=>{const {l,stock,save,act}=fixture(t);stock({grams:'1.200'});const id=save();act(id,'confirm');assert.throws(()=>stock({kind:'transfer',grams:'0.001',to:'金料'}),/可用库存不足/);assert.equal(l.inventory()[0].mg,1200);assert.equal(l.inventory()[1].mg,0);assert.equal(l.rows('SELECT * FROM movements').length,1);});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
'use strict';
|
||||
const {historicalAction}=require('./fixtures/legacy-cancellation.cjs');
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict'),{randomUUID}=require('node:crypto');
|
||||
const fs=require('node:fs'),os=require('node:os'),path=require('node:path');
|
||||
const {Ledger}=require('../ledger'),{createApp}=require('../server'),Calc=require('../public/calculations');
|
||||
@@ -14,7 +15,7 @@ function fixture(t){
|
||||
const buy=(grams='10',total='9000',payer='owner',date=D,key=randomUUID())=>run({grams,total,payer,date},()=>l.createMaterialPurchase({date,grams,total,payer,note:'原始采购凭据'},assistant),key);
|
||||
const issue=(p=input(),key=randomUUID())=>run(p,()=>l.issueOrder(p,assistant),key).id;
|
||||
const save=(p=input())=>run(p,()=>l.saveOrder(p,assistant)).id;
|
||||
const act=(id,action,p={})=>run({id,action,p},()=>l.action(id,action,{date:D,...p},assistant));
|
||||
const act=(id,action,p={})=>run({id,action,p},()=>historicalAction(l,id,action,{date:D,...p},assistant));
|
||||
const settle=(id,amount,direction,extra={})=>{
|
||||
const p={date:D,amount,direction,verified:true,revision:l.materialPoolDetail(id).revision,...extra};
|
||||
return run({id,p},()=>l.settleMaterialPool(id,p,assistant));
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
'use strict';
|
||||
const {historicalAction}=require('./fixtures/legacy-cancellation.cjs');
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict');
|
||||
const {randomUUID}=require('node:crypto'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
|
||||
const {Ledger,today}=require('../ledger'),{createApp}=require('../server');
|
||||
@@ -13,7 +14,7 @@ function fixture(t){
|
||||
return run(input,()=>issue?ledger.issueOrder(input,actor):ledger.saveOrder(input,actor)).id;
|
||||
};
|
||||
const action=(id,kind,extra={},key=randomUUID())=>{
|
||||
const input={date:D,...extra};return run({id,kind,input},()=>ledger.action(id,kind,input,actor),key);
|
||||
const input={date:D,...extra};return run({id,kind,input},()=>historicalAction(ledger,id,kind,input,actor),key);
|
||||
};
|
||||
const book=(query={})=>ledger.orderBook({date:D,...query});
|
||||
return {ledger,save,action,book,run};
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path'),vm=require('node:vm');
|
||||
const {randomUUID}=require('node:crypto'),Calc=require('../public/calculations');
|
||||
const ID='11111111-1111-4111-8111-111111111111',RID='22222222-2222-4222-8222-222222222222',D='2026-10-22';
|
||||
function order(extra={}){return {id:ID,revision:7,number:'XS20261022001',paper_number:'20261022001',date:D,status:'delivered',customer:'客户代号',salesperson:'助理',payment_account:'助理微信',total:210000,rounding_mode:'cent',discount:0,profit:28000,directCost:2000,goodsCost:180000,ownerCost:180000,netReceived:210000,balance:0,settlementDue:208000,costDue:180000,profitDue:28000,costTransferred:0,profitTransferred:0,ownerDirect:0,reviewed_revision:0,lines:[],payments:[],expenses:[],settlements:[],corrections:[],pendingFees:[],fee_items:[],audit:[],note:'',...extra};}
|
||||
function request(extra={}){return {id:RID,order_id:ID,order_number:'XS20261022001',order_date:D,order_status:'delivered',order_revision:7,reason:'同一笔销售重复录入',status:'pending',requester_name:'助理',requester_role:'assistant',requester_id:'assistant-id',created:D+'T08:00:00.000Z',reviewer_name:null,reviewed:null,note:'',stale:false,canApprove:true,summary:{total:210000,netReceived:210000,goodsCost:180000,directCost:2000,profit:28000,settlementDue:208000,inventory:[{date:D,pocket:'现货',mg:2000}]},...extra};}
|
||||
function detail(pending=null,extra={}){return {eligible:!pending,reason:pending?'已有待审申请':'',revision:7,pending,requests:pending?[pending]:[],canApprove:true,...extra};}
|
||||
function node(extra={}){return {innerHTML:'',textContent:'',hidden:false,disabled:false,dataset:{},classList:{toggle(){}},setAttribute(){},scrollIntoView(){},focus(){},...extra};}
|
||||
function harness(role='owner'){
|
||||
const saved=new Map(),nodes=new Map(),calls=[],handlers={},toasts=[];
|
||||
for(const selector of ['#main','#order-content','#detail-form','#detail-error','#order-cancellation-error','#pending','#order-cancellations-entry'])nodes.set(selector,node());
|
||||
nodes.set('#order-dialog',node({open:true,showModal(){this.open=true;},close(){this.open=false;}}));
|
||||
const context=vm.createContext({LedgerCalc:Calc,crypto:{randomUUID},console,setInterval(){},setTimeout(){},clearTimeout(){},
|
||||
document:{querySelector:selector=>nodes.get(selector)||null,querySelectorAll(){return [];},addEventListener(type,handler){(handlers[type]??=[]).push(handler);}},
|
||||
window:{scrollTo(){}},localStorage:{getItem:key=>saved.get(key)??null,setItem:(key,value)=>saved.set(key,String(value)),removeItem:key=>saved.delete(key)},sessionStorage:{getItem(){return null;},setItem(){}},
|
||||
__calls:calls,__toasts:toasts,__order:order(),__detail:detail(),__request:request(),__form:null,__finished:null});
|
||||
const run=code=>vm.runInContext(code,context),json=code=>JSON.parse(JSON.stringify(run(code)));
|
||||
for(const file of ['order-cancellations-ui.js','app.js'])run(fs.readFileSync(path.join(__dirname,'../public',file),'utf8').replace(/\ninit\(\);\s*$/,''));
|
||||
run(`session={user:{id:'cancel-user',name:'${role==='owner'?'麦麦':'助理'}',role:'${role}'}};state={user:session.user,today:'2026-10-23',pockets:['现货','金料'],accounts:['助理微信','麦麦微信']};tab='orders';currentOrder=__order;
|
||||
api=async function(url,data,key){__calls.push({url,data,key});return __detail;};toast=function(message,error){__toasts.push({message,error});};
|
||||
invalidateMaterialPools=function(){};invalidateReport=function(){};invalidatePriceLockViews=function(){};materialPoolOrderNoticeHTML=function(){return '';};priceLockInventoryCreditHTML=function(){return '';};
|
||||
profitSummary=function(){return {title:'利润',value:'¥280.00',hint:''};};useOrderCancellationDetail(currentOrder,__detail);`);
|
||||
function prepare(pending=null,extra={}){context.__detail=detail(pending,extra);run('useOrderCancellationDetail(currentOrder,__detail)');}
|
||||
function form(kind,values={}){
|
||||
run(`showOrderCancellationForm('${kind}')`);
|
||||
const fields=Object.fromEntries(Object.entries({reason:'重复开单',note:'',verified:false,...values}).map(([name,value])=>[name,node({name,value:typeof value==='boolean'?'on':value,checked:value===true})]));
|
||||
const submit=node({type:'submit'}),close=node({dataset:{action:'close-order-cancellation-form'}}),reload=node({dataset:{action:'reload-order-cancellation'}}),retry=node({dataset:{action:'retry'}}),controls=[...Object.values(fields),submit,close,reload,retry];
|
||||
const form=node({id:'order-cancellation-form',dataset:{kind},querySelector(selector){const name=selector.match(/\[name="([^"]+)"\]/)?.[1];return fields[name]||null;},querySelectorAll(){return controls;}});
|
||||
nodes.set('#order-cancellation-form',form);nodes.set('#order-cancellation-form [name="verified"]',fields.verified);context.__form=form;return {form,fields,submit,close,reload,retry};
|
||||
}
|
||||
async function click(action,attrs={}){const b=node({dataset:{action,...attrs},closest(){return null;}});for(const handler of handlers.click)await handler({target:{closest(){return b;}}});}
|
||||
return {context,run,json,nodes,calls,saved,toasts,prepare,form,click};
|
||||
}
|
||||
test('普通订单直接显示申请取消,锁价、退货、作废和待审单没有重复申请入口',()=>{
|
||||
const h=harness();assert.match(h.run('orderCancellationActionHTML(currentOrder)'),/申请取消/);
|
||||
for(const extra of [{price_lock_id:'lock-id'},{status:'returned'},{status:'cancelled'},{cancellationPending:{id:RID,status:'pending'}}]){
|
||||
h.context.__order=order(extra);h.run('currentOrder=__order;useOrderCancellationDetail(currentOrder,__detail)');assert.equal(h.run('orderCancellationActionHTML(currentOrder)'),'');
|
||||
}
|
||||
assert.equal(h.calls.length,0);
|
||||
});
|
||||
test('取消原因必填,申请仅提交原版本与原因,申请成功走原单结果处理',async()=>{
|
||||
const h=harness(),{fields}=h.form('request',{reason:' '});h.run('finishOrderCancellationSave=async function(url,input,result){__finished={url,input,result};};');
|
||||
await assert.rejects(h.run('submitOrderCancellation(__form)'),/取消原因/);assert.equal(h.calls.length,0);
|
||||
fields.reason.value=' 一笔交易重复录入 ';await h.run('submitOrderCancellation(__form)');
|
||||
assert.equal(h.calls.length,1);assert.equal(h.calls[0].url,'/api/orders/'+ID+'/cancellation');assert.deepEqual(JSON.parse(JSON.stringify(h.calls[0].data)),{revision:7,reason:'一笔交易重复录入'});assert.equal(h.json('__finished.input.revision'),7);
|
||||
});
|
||||
test('麦麦核对金额成本库存并勾选才能同意;助理没有审批按钮且无法调用审批表单',async()=>{
|
||||
const h=harness();h.prepare(request());const html=h.run('orderCancellationDetailHTML(currentOrder)');assert.match(html,/申请期间仍按原订单计账/);assert.match(html,/approve-order-cancellation/);assert.match(html,/reject-order-cancellation/);assert.match(html,/助理/);
|
||||
const {fields}=h.form('approve');h.run('finishOrderCancellationSave=async function(){};');await assert.rejects(h.run('submitOrderCancellation(__form)'),/勾选/);assert.equal(h.calls.length,0);
|
||||
const preview=h.nodes.get('#detail-form').innerHTML;for(const text of ['撤销收款净额','2,100.00','1,800.00','20.00','+2.000g','真实采购付款保留','双方实际交款保留'])assert.ok(preview.includes(text),text);
|
||||
fields.verified.checked=true;fields.note.value='核对原单后确认';await h.run('submitOrderCancellation(__form)');assert.equal(h.calls[0].url,'/api/order-cancellations/'+RID+'/approve');assert.deepEqual(JSON.parse(JSON.stringify(h.calls[0].data)),{revision:7,verified:true,note:'核对原单后确认'});
|
||||
const assistant=harness('assistant');assistant.prepare(request(),{canApprove:true});const assistantHTML=assistant.run('orderCancellationDetailHTML(currentOrder)');assert.ok(!assistantHTML.includes('approve-order-cancellation'));assert.ok(!assistantHTML.includes('reject-order-cancellation'));assert.throws(()=>assistant.run("showOrderCancellationForm('approve')"),/麦麦账号/);assert.equal(assistant.calls.length,0);
|
||||
});
|
||||
test('过期申请隐藏同意、仍允许麦麦填意见驳回;驳回记录后可重新申请',async()=>{
|
||||
const h=harness(),stale=request({stale:true,canApprove:false});h.prepare(stale);const html=h.run('orderCancellationDetailHTML(currentOrder)');assert.ok(!html.includes('approve-order-cancellation'));assert.match(html,/reject-order-cancellation/);assert.match(html,/原申请不能同意/);
|
||||
assert.throws(()=>h.run("showOrderCancellationForm('approve')"),/已有变动/);const {fields}=h.form('reject');h.run('finishOrderCancellationSave=async function(){};');await assert.rejects(h.run('submitOrderCancellation(__form)'),/驳回意见/);fields.note.value='金额已有修正,请按最新单据重新申请';await h.run('submitOrderCancellation(__form)');assert.deepEqual(JSON.parse(JSON.stringify(h.calls[0].data)),{note:fields.note.value});
|
||||
const rejected=request({status:'rejected',reviewer_name:'麦麦',reviewed:D+'T09:00:00Z',note:'请重新核对',canApprove:false});h.prepare(null,{requests:[rejected]});assert.match(h.run('orderCancellationDetailHTML(currentOrder)'),/已驳回/);assert.match(h.run('orderCancellationActionHTML(currentOrder)'),/申请取消/);
|
||||
});
|
||||
test('pending投影在独立读取失败时仍阻止财务、退货、交款和普通复核,保留打印',()=>{
|
||||
const h=harness();h.context.__order=order({cancellationPending:{id:RID,status:'pending'},payments:[{id:'p',date:D,kind:'receipt',amount:210000}],expenses:[{id:'e',date:D,amount:2000,payer:'assistant'}]});h.run('currentOrder=__order;useOrderCancellationDetail(currentOrder,null,new Error("暂未连接"));renderDetail()');const html=h.nodes.get('#order-content').innerHTML;
|
||||
for(const action of ['edit-order','show-expense','show-return','show-settlement','show-correct','show-review'])assert.ok(!html.includes('data-action="'+action+'"'),action);
|
||||
assert.ok(html.includes('data-action="print"'));assert.match(html,/暂未连接/);assert.throws(()=>h.run("showAction('return')"),/待麦麦复核/);
|
||||
});
|
||||
test('审批作废保留收款费用冲回与双方交款明细,不能再登记销售退款或费用',()=>{
|
||||
const h=harness(),approved=request({status:'approved',canApprove:false,reviewer_name:'麦麦',reviewed:D+'T09:00:00Z'});
|
||||
h.context.__order=order({status:'cancelled',cancellationApproved:approved,netReceived:100,expenses:[{date:D,amount:-2000,payer:'assistant',note:'更正冲回:取消审批作废;重复开单'}],payments:[{date:D,kind:'receipt',amount:-210000,account:'助理微信',reference:'更正冲回:取消审批作废;重复开单'}],settlements:[{id:'s',date:D,bucket:'cost',amount:1000,actor:'助理',note:'原实际交款'}]});
|
||||
h.run('currentOrder=__order');h.prepare(null,{eligible:false,requests:[approved]});h.run('renderDetail()');const html=h.nodes.get('#order-content').innerHTML;
|
||||
for(const text of ['已取消 · 录错作废','原成交金额(已作废)','作废冲回收款','作废冲回费用','原实际交款','已撤销的金额不计入本单成本'])assert.ok(html.includes(text),text);
|
||||
assert.ok(!html.includes('实际发生的费用仍保留'));for(const action of ['request-order-cancellation','show-refund','show-expense','show-return'])assert.ok(!html.includes('data-action="'+action+'"'),action);
|
||||
h.run("showAction('correct')");const correction=h.nodes.get('#detail-form').innerHTML;assert.match(correction,/settlement:s/);assert.ok(!correction.includes('payment:'));assert.ok(!correction.includes('expense:'));
|
||||
});
|
||||
test('撤销摘要的缺失成本不冒充0,原因、意见及货盘转义,负库存冲回保留符号',()=>{
|
||||
const h=harness(),r=request({reason:'<img src=x onerror=1>',note:'<script>错误</script>',summary:{...request().summary,goodsCost:null,profit:null,inventory:[{date:D,pocket:'<现货>',mg:-1000}]}});h.context.__request=r;
|
||||
const summary=h.run('orderCancellationSummaryHTML(__request)');assert.match(summary,/待补齐/);assert.match(summary,/-1.000g/);assert.match(summary,/<现货>/);assert.ok(!summary.includes('<现货>'));
|
||||
const history=h.run('orderCancellationHistoryHTML(__request)');assert.ok(!history.includes('<img'));assert.match(history,/<img/);
|
||||
});
|
||||
test('待取消数量从全局接口读取,与今日日期和搜索无关,读取失败不能显示0',async()=>{
|
||||
const h=harness();h.run("orderBookFilters={mode:'today',date:'2026-10-23',q:'只看这个客户',status:'delivered'};api=async function(url){__calls.push({url});return {requests:[__request],counts:{pending:1,approved:3,rejected:2},canApprove:true};};");await h.run('loadOrderCancellationCount()');assert.equal(h.calls[0].url,'/api/order-cancellations?status=pending');assert.equal(h.nodes.get('#order-cancellations-entry').textContent,'待取消复核(1)');
|
||||
h.run("api=async function(){throw new Error('断线');}");await h.run('loadOrderCancellationCount()');assert.equal(h.nodes.get('#order-cancellations-entry').textContent,'待取消复核(读取失败)');
|
||||
h.context.__late={requests:[],counts:{pending:0,approved:0,rejected:0},canApprove:true};h.run("api=async function(){session.user={id:'another-user',role:'owner'};return __late;}");await h.run('loadOrderCancellationCount()');assert.equal(h.nodes.get('#order-cancellations-entry').textContent,'待取消复核(读取失败)');
|
||||
});
|
||||
test('全局列表保留跨日期原单、申请人原因和状态,助理只有查看入口',()=>{
|
||||
const h=harness(),r=request({order_date:'2026-09-01',created:'2026-09-02T08:00:00Z'});h.context.__list={requests:[r],counts:{pending:1,approved:0,rejected:0},canApprove:true};const html=h.run('orderCancellationListHTML(__list)');for(const text of ['2026-09-01','2026/9/2','同一笔销售重复录入','查看并复核'])assert.ok(html.includes(text),text);
|
||||
h.run("state.user.role='assistant'");const assistant=h.run('orderCancellationListHTML(__list)');assert.match(assistant,/查看订单/);assert.ok(!assistant.includes('查看并复核'));
|
||||
});
|
||||
test('409清空录错确认并阻止批准旧页面,必须重新读取复核',async()=>{
|
||||
const h=harness();h.prepare(request());const {fields,submit,reload,retry}=h.form('approve',{verified:true});h.run("api=async function(){const err=new Error('订单或记账已有新变动');err.status=409;err.confirmed=true;throw err;};");await h.run('submitOrderCancellation(__form)');
|
||||
assert.equal(h.run('orderCancellationFormEntry'),null);assert.equal(fields.verified.checked,false);assert.equal(submit.disabled,true);assert.equal(reload.disabled,false);assert.equal(retry.disabled,false);assert.match(h.nodes.get('#order-cancellation-error').innerHTML,/重新读取订单并复核/);assert.equal(h.saved.get('mm-pending-cancel-user'),undefined);await assert.rejects(h.run('submitOrderCancellation(__form)'),/重新读取/);
|
||||
});
|
||||
test('断线恢复批准复用原操作号及旧版本,不重复生成新单或批准请求',async()=>{
|
||||
const h=harness();h.prepare(request());h.form('approve',{verified:true});h.run("api=async function(url,data,key){__calls.push({url,data,key});throw new Error('响应丢失');};");await h.run('submitOrderCancellation(__form)');const saved=JSON.parse(h.saved.get('mm-pending-cancel-user'));assert.equal(saved.url,'/api/order-cancellations/'+RID+'/approve');
|
||||
h.run("api=async function(url,data,key){__calls.push({url,data,key});return {id:currentOrder.id};};finishOrderCancellationSave=async function(url,input,result){__finished={url,input,result};};");await h.click('retry');assert.equal(h.calls.length,2);assert.equal(h.calls[1].key,saved.key);assert.deepEqual(JSON.parse(JSON.stringify(h.calls[1].data)),saved.data);assert.equal(h.calls[1].data.revision,7);assert.equal(h.json('__finished.result.id'),ID);assert.equal(h.saved.get('mm-pending-cancel-user'),undefined);assert.ok(h.calls.every(call=>!call.url.includes('/issue')));
|
||||
});
|
||||
test('保存已成功但刷新失败时只留只读重读入口,不再显示提交表单',async()=>{
|
||||
const h=harness();h.prepare(request());h.form('approve',{verified:true});h.context.__savedResult={id:ID};h.run("refresh=async function(){throw new Error('刷新失败');};");await h.run(`finishOrderCancellationSave('/api/order-cancellations/${RID}/approve',{},__savedResult)`);
|
||||
assert.equal(h.run('currentOrder'),null);assert.equal(h.run('orderCancellationFormEntry'),null);const html=h.nodes.get('#order-content').innerHTML;assert.match(html,/已同意取消/);assert.match(html,/重新读取原订单/);assert.ok(!html.includes('type="submit"'));assert.equal(h.calls.length,0);assert.match(h.nodes.get('#order-cancellation-saved-status')?.textContent||h.toasts.at(-1).message,/保存|重新读取/);
|
||||
});
|
||||
test('详情版本不一致拒绝审批;晚到的旧订单和换账号响应不能覆盖当前单',async()=>{
|
||||
const h=harness();h.prepare(request(),{revision:8});assert.equal(h.run('currentOrderCancellation().data'),null);assert.match(h.run('orderCancellationDetailHTML(currentOrder)'),/已有新记录/);assert.throws(()=>h.run("showOrderCancellationForm('approve')"),/重新读取/);
|
||||
const second='33333333-3333-4333-8333-333333333333',resolvers=new Map();h.context.__api=url=>new Promise(resolve=>resolvers.set(url,resolve));h.run('api=__api');const first=h.run(`openOrder('${ID}')`),next=h.run(`openOrder('${second}')`);
|
||||
resolvers.get('/api/orders/'+second)(order({id:second,number:'后打开的订单'}));resolvers.get('/api/orders/'+second+'/cancellation')(detail());await next;assert.equal(h.run('currentOrder.id'),second);
|
||||
resolvers.get('/api/orders/'+ID)(order());resolvers.get('/api/orders/'+ID+'/cancellation')(detail(request()));await first;assert.equal(h.run('currentOrder.id'),second);
|
||||
h.context.__api=async url=>{h.run("session.user={id:'changed-user',role:'owner'}");return url.endsWith('/cancellation')?detail():order();};h.run('api=__api');await h.run(`openOrder('${ID}')`);assert.equal(h.run('currentOrder.id'),second);
|
||||
});
|
||||
@@ -0,0 +1,183 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict'),{randomUUID}=require('node:crypto');
|
||||
const fs=require('node:fs'),os=require('node:os'),path=require('node:path');
|
||||
const {Ledger}=require('../ledger'),{createApp,createUser}=require('../server'),Calc=require('../public/calculations');
|
||||
const {FeishuSync}=require('../sync');
|
||||
const D0='2026-10-15',D='2026-10-16',D2='2026-10-17',D3='2026-10-18';
|
||||
const owner={id:'cancel-owner',name:'测试麦麦',role:'owner'},assistant={id:'cancel-assistant',name:'测试助理',role:'assistant'};
|
||||
const line=(extra={})=>({name:'足金999',unit:'g',quantity:'2',pocket:'现货',payer:'owner',sale:'2000',costParts:{material:'1700',labor:'20',accessories:'0',other:'0'},...extra});
|
||||
const input=(extra={})=>({date:D,customer:'测试客户',salesperson:'测试开单人',note:'原备注',rounding_mode:'cent',payment_account:'助理微信',lines:[line()],fee_items:[{key:'shipping',note:'快递费',amount:'6',payer:'assistant'}],...extra});
|
||||
const all=ledger=>ledger.rows("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").map(({name})=>[name,ledger.rows('SELECT * FROM "'+name+'"')]);
|
||||
const business=ledger=>Object.fromEntries(['orders','payments','expenses','settlements','movements','journal','corrections','closes','inventory_snapshots','sync','material_purchases','material_pool_usages','material_pool_settlements'].map(table=>[table,ledger.rows('SELECT * FROM '+table)]));
|
||||
function fixture(t){
|
||||
const l=new Ledger(':memory:');t.after(()=>l.close());
|
||||
const run=(payload,fn,actor=assistant,key=randomUUID())=>l.transact(key,actor,payload,fn);
|
||||
for(const pocket of ['现货','金料'])run({pocket},()=>l.stock({kind:'opening',date:D0,pocket,grams:'20',note:'合成库存'},owner),owner);
|
||||
const issue=(p=input())=>run(p,()=>l.issueOrder(p,assistant)).id;
|
||||
const save=(p=input())=>run(p,()=>l.saveOrder(p,assistant)).id;
|
||||
const act=(id,kind,extra={},actor=owner)=>run({id,kind,extra},()=>l.action(id,kind,{date:D,...extra},actor),actor);
|
||||
const request=(id,extra={},actor=assistant,key=randomUUID())=>{const p={revision:l.detail(id).revision,reason:'原订单重复录入,应作废',...extra};return run({request:id,p},()=>l.requestOrderCancellation(id,p,actor),actor,key);};
|
||||
const approve=(request,extra={},actor=owner,key=randomUUID())=>{const p={revision:request.request.order_revision,verified:true,note:'已核实原始订单',...extra};return run({approve:request.requestId,p},()=>l.approveOrderCancellation(request.requestId,p,actor),actor,key);};
|
||||
const reject=(request,note='原订单有效,请继续交付',actor=owner)=>run({reject:request.requestId,note},()=>l.rejectOrderCancellation(request.requestId,{note},actor),actor);
|
||||
const edit=(id,change={})=>{const p={...l.orderEdit(id,assistant).inputs,revision:l.detail(id).revision,reason:'核对后更正',verified:true,...change};return run({edit:id,p},()=>l.editOrder(id,p,assistant));};
|
||||
const buy=(grams='10',total='9000',payer='owner')=>{const p={date:D,grams,total,payer,note:'真实购料原凭据'};return run(p,()=>l.createMaterialPurchase(p,assistant));};
|
||||
return {l,run,issue,save,act,request,approve,reject,edit,buy};
|
||||
}
|
||||
|
||||
test('申请与驳回不改原状态财务库存汇总;每单仅一待审,可全局跨日查看并重新申请',t=>{
|
||||
const f=fixture(t),id=f.issue(),original=business(f.l),report=f.l.reportByOrderDate(D),key=randomUUID();
|
||||
const application=f.request(id,{},assistant,key),same=f.request(id,{},assistant,key);
|
||||
assert.equal(JSON.stringify(same),JSON.stringify(application));assert.deepEqual(business(f.l),original);assert.equal(f.l.detail(id).status,'delivered');
|
||||
assert.equal(f.l.reportByOrderDate(D).sales,report.sales);assert.equal(f.l.orderCancellation(id,assistant).pending.id,application.requestId);
|
||||
assert.equal(f.l.orderCancellations({},owner).requests[0].order_date,D);assert.equal(f.l.orderCancellations({},owner).counts.pending,1);
|
||||
assert.throws(()=>f.request(id),error=>error.status===409&&/待审批/.test(error.message));
|
||||
assert.throws(()=>f.reject(application,'不同意',assistant),error=>error.status===403);
|
||||
assert.throws(()=>f.approve(application,{},assistant),error=>error.status===403);assert.deepEqual(business(f.l),original);
|
||||
f.reject(application);assert.deepEqual(business(f.l),original);assert.equal(f.l.detail(id).cancellationPending,null);
|
||||
const next=f.request(id);assert.notEqual(next.requestId,application.requestId);assert.equal(f.l.orderCancellation(id,owner).requests.length,2);
|
||||
assert.equal(f.l.orderCancellations({status:'all'},owner).counts.rejected,1);
|
||||
});
|
||||
|
||||
test('批准录错作废原日撤销销售成本收款并恢复库存,原单原流水真实交款与审计完整保留',t=>{
|
||||
const f=fixture(t),id=f.issue(),original=f.l.detail(id);
|
||||
f.act(id,'settlement',{bucket:'cost',amount:'1000',direction:'toOwner',verified:true,note:'已实际转款'});
|
||||
for(const date of [D,D2])f.run({close:date},()=>f.l.closeDay(date,owner,'orderDate'),owner);
|
||||
const before=business(f.l),request=f.request(id),key=randomUUID(),result=f.approve(request,{},owner,key);
|
||||
assert.equal(JSON.stringify(f.approve(request,{},owner,key)),JSON.stringify(result));const order=f.l.detail(id);
|
||||
for(const field of ['id','number','paper_number','created','lines','total','date'])assert.deepEqual(order[field],original[field]);
|
||||
assert.equal(order.status,'cancelled');assert.equal(order.netReceived,0);assert.equal(order.directCost,0);assert.equal(order.profit,0);assert.equal(order.settlementDue,-100000);
|
||||
assert.equal(order.reviewed_revision,0);assert.equal(order.cancellationApproved.id,request.requestId);assert.equal(order.cancellationPending,null);
|
||||
assert.equal(f.l.inventory(D).find(row=>row.pocket==='现货').mg,20000);assert.equal(f.l.inventory().find(row=>row.pocket==='现货').reserved,0);
|
||||
assert.deepEqual(f.l.rows('SELECT * FROM settlements'),before.settlements);
|
||||
for(const table of ['payments','expenses','movements','journal'])for(const row of before[table])assert.deepEqual(f.l.one('SELECT * FROM '+table+' WHERE id=?',row.id),row);
|
||||
assert.ok(order.payments.every(row=>row.kind==='receipt'));assert.equal(f.l.report(D).returns,0);assert.equal(f.l.report(D).delivered,0);
|
||||
const report=f.l.reportByOrderDate(D);for(const key of ['sales','goods','expense','profit','outlayTotal'])assert.equal(report[key],0,key);
|
||||
assert.equal(report.receiptsByOrderDate.net,0);assert.equal(report.orderRows[0].cancellationApproved.id,request.requestId);
|
||||
for(const date of [D,D2]){assert.equal(f.l.inventorySnapshot(date).stale,true);assert.equal(f.l.one('SELECT stale FROM closes WHERE date=?',date).stale,1);}
|
||||
assert.equal(f.l.one('SELECT revision FROM sync WHERE entity=?','order:'+id).revision,order.revision);
|
||||
const mirror=new FeishuSync(f.l,null).fields('order:'+id,order.revision);assert.equal(mirror['销售金额'],0);assert.equal(mirror['订单利润'],0);assert.equal(mirror['已收净额'],0);assert.equal(JSON.parse(mirror['明细']).total,original.total);
|
||||
assert.ok(order.audit.some(row=>row.action==='同意取消订单(录错作废)'&&row.detail.requestId===request.requestId));
|
||||
f.act(id,'settlement',{date:D2,bucket:'cost',amount:'1000',direction:'toAssistant',verified:true,note:'退回原已交款'});assert.equal(f.l.detail(id).settlementDue,0);
|
||||
assert.throws(()=>f.approve(request),error=>error.status===409&&/已经处理/.test(error.message));
|
||||
});
|
||||
|
||||
test('多次改克重货盘日期后按本单有效库存冲回;跨日更正的收支各日期账户付款人净额均归零',t=>{
|
||||
const f=fixture(t),id=f.issue();
|
||||
f.act(id,'correct',{date:D2,type:'payment',target:f.l.detail(id).payments[0].id,amount:'2000',account:'麦麦支付宝',verified:true,reason:'收款渠道录错'});
|
||||
f.act(id,'correct',{date:D2,type:'expense',target:f.l.detail(id).expenses[0].id,amount:'8',payer:'owner',verified:true,reason:'原费用录错'});
|
||||
f.act(id,'correct',{date:D3,type:'expense',target:f.l.detail(id).expenses.find(row=>row.amount===800).id,amount:'5',payer:'assistant',verified:true,reason:'最终费用核实'});
|
||||
f.edit(id,{date:D2,lines:[line({quantity:'3',pocket:'金料',sale:'3000',costParts:{material:'2600',labor:'25',accessories:'0',other:'0'}})]});
|
||||
f.edit(id,{date:D3,lines:[line({quantity:'1.123',pocket:'现货',sale:'1800',costParts:{material:'1500',labor:'11',accessories:'0',other:'0'}})]});
|
||||
const before=business(f.l),application=f.request(id);assert.deepEqual(application.request.summary.inventory,[{date:D3,pocket:'现货',mg:1123}]);
|
||||
f.approve(application);
|
||||
for(const table of ['payments','expenses','movements','journal'])for(const row of before[table])assert.deepEqual(f.l.one('SELECT * FROM '+table+' WHERE id=?',row.id),row);
|
||||
assert.deepEqual(f.l.rows('SELECT date,kind,account,SUM(amount) AS amount FROM payments WHERE order_id=? GROUP BY date,kind,account HAVING SUM(amount)<>0',id),[]);
|
||||
assert.deepEqual(f.l.rows('SELECT date,payer,SUM(amount) AS amount FROM expenses WHERE order_id=? GROUP BY date,payer HAVING SUM(amount)<>0',id),[]);
|
||||
assert.deepEqual(f.l.rows('SELECT date,pocket,SUM(mg) AS mg FROM movements WHERE order_id=? GROUP BY date,pocket HAVING SUM(mg)<>0',id),[]);
|
||||
for(const date of [D,D2,D3]){const r=f.l.report(date);for(const key of ['sales','goods','expense','profit'])assert.equal(r[key],0,date+key);assert.equal(f.l.inventory(date).find(row=>row.pocket==='现货').mg,20000);assert.equal(f.l.inventory(date).find(row=>row.pocket==='金料').mg,20000);}
|
||||
const costs=Calc.orderCosts(f.l.detail(id));assert.equal(costs.total.total,0);assert.equal(costs.rows.filter(row=>row.kind==='paid').length,0);
|
||||
const report=f.l.reportByOrderDate(D3);assert.equal(report.payerCosts.owner.total,0);assert.equal(report.payerCosts.assistant.total,0);assert.equal(report.outlayTotal,0);
|
||||
});
|
||||
|
||||
test('日购料作废释放有效占用并重排后续FIFO,原采购和料池实际交款不变,也不产生虚构退货入库',t=>{
|
||||
const f=fixture(t);f.buy('4','3600','owner');f.buy('6','5400','assistant');
|
||||
const pooled=quantity=>line({quantity,pocket:'',costMaterial:{mode:'pool',poolId:D},costParts:{material:'',labor:'10',accessories:'5',other:'0'}});
|
||||
const id=f.issue(input({lines:[pooled('6')],fee_items:[]})),later=f.issue(input({lines:[pooled('3')],fee_items:[]}));
|
||||
const transfer={date:D,revision:f.l.materialPoolDetail(D).revision,amount:'900',direction:'toAssistant',verified:true};
|
||||
f.run(transfer,()=>f.l.settleMaterialPool(D,transfer,assistant));
|
||||
assert.equal(Calc.orderCosts(f.l.detail(later)).byPayer.assistant.goods,270000);
|
||||
const before=business(f.l),application=f.request(id);assert.deepEqual(application.request.summary.inventory,[]);f.approve(application);
|
||||
assert.deepEqual(f.l.rows('SELECT * FROM material_purchases'),before.material_purchases);assert.deepEqual(f.l.rows('SELECT * FROM material_pool_settlements'),before.material_pool_settlements);
|
||||
assert.deepEqual(f.l.rows('SELECT * FROM movements'),before.movements);assert.equal(f.l.materialPoolDetail(D).usedMg,3000);
|
||||
assert.equal(Calc.orderCosts(f.l.detail(later)).byPayer.owner.goods,271500);assert.equal(Calc.orderCosts(f.l.detail(later)).byPayer.assistant.goods,0);
|
||||
assert.ok(f.l.rows('SELECT * FROM material_pool_usages WHERE order_id=?',id).every(row=>row.active===0));
|
||||
assert.deepEqual(f.l.rows('SELECT kind FROM material_pool_events WHERE order_id=? AND kind LIKE ? ORDER BY rowid',id,'%释放').map(row=>row.kind),['订单录错作废释放']);
|
||||
const r=f.l.reportByOrderDate(D);assert.equal(r.outlayGoods,901500);assert.equal(r.outlayExpense,0);assert.equal(r.orderRows.find(row=>row.id===id).totalCost,0);
|
||||
assert.equal(r.orderRows.find(row=>row.id===id).costItems.filter(row=>row.kind==='paid').length,0);assert.equal(f.l.detail(id).profit,0);
|
||||
});
|
||||
|
||||
test('待审批统一阻止财务改单交付退货和交款;metadata或购料重算使申请过期,可驳回后重申',t=>{
|
||||
const f=fixture(t),id=f.issue(),application=f.request(id),before=all(f.l);
|
||||
for(const [kind,p] of [['return',{verified:true,reason:'不得混成退货'}],['expense',{amount:'1',payer:'owner',note:'新费用'}],['receipt',{}],['refund',{}],['fees',{}],['cost',{}],['complete',{}],['deliver',{}],['material',{}],['settlement',{}],['correct',{type:'expense'}]]){
|
||||
assert.throws(()=>f.act(id,kind,p),error=>error.status===409&&/待审批/.test(error.message));assert.deepEqual(all(f.l),before);
|
||||
}
|
||||
assert.throws(()=>f.edit(id,{lines:[line({sale:'9999'})]}),/待审批/);assert.deepEqual(all(f.l),before);
|
||||
f.edit(id,{customer:'仅更正称呼'});assert.equal(f.l.orderCancellation(id,owner).pending.stale,true);
|
||||
assert.throws(()=>f.approve(application),error=>error.status===409&&/已过期/.test(error.message));f.reject(application,'资料已更新,核对新版本后重新申请');
|
||||
const next=f.request(id);f.approve(next);assert.equal(f.l.detail(id).status,'cancelled');
|
||||
f.buy();const pooled=f.issue(input({lines:[line({pocket:'',costMaterial:{mode:'pool',poolId:D}})],fee_items:[]})),old=f.request(pooled);
|
||||
f.buy('1','1000','assistant');assert.equal(f.l.orderCancellation(pooled,owner).pending.stale,true);
|
||||
assert.throws(()=>f.approve(old),error=>error.status===409&&/已过期/.test(error.message));f.reject(old,'购料已重算');f.approve(f.request(pooled));
|
||||
});
|
||||
|
||||
test('版本未touch但原凭据变化仍使审批过期;草稿和待交付可申请且申请期间不能保存或开单',t=>{
|
||||
const f=fixture(t),id=f.issue(),application=f.request(id),revision=f.l.detail(id).revision;
|
||||
f.l.run('UPDATE payments SET account=? WHERE order_id=?','麦麦现金',id);assert.equal(f.l.detail(id).revision,revision);
|
||||
const before=all(f.l);assert.throws(()=>f.approve(application),error=>error.status===409&&/已过期/.test(error.message));assert.deepEqual(all(f.l),before);f.reject(application,'原始凭据发生变化');
|
||||
for(const status of ['draft','confirmed']){
|
||||
const p=input({fee_items:[]}),draft=f.save(p);if(status==='confirmed'){f.act(draft,'confirm');f.act(draft,'receipt',{amount:'300',account:'助理微信',verified:true});}
|
||||
const requested=f.request(draft),state=all(f.l);
|
||||
for(const fn of [()=>f.l.saveOrder({...p,id:draft,revision:f.l.detail(draft).revision},assistant),()=>f.l.issueOrder({...p,id:draft,revision:f.l.detail(draft).revision},assistant)]){assert.throws(fn,/待审批/);assert.deepEqual(all(f.l),state);}
|
||||
f.approve(requested);assert.equal(f.l.detail(draft).netReceived,0);assert.equal(f.l.detail(draft).status,'cancelled');
|
||||
}
|
||||
});
|
||||
|
||||
test('批准后财务入口均拒绝恢复销售,metadata保持可改,真实双方转款余额可以处理',t=>{
|
||||
const f=fixture(t),id=f.issue();f.act(id,'settlement',{bucket:'cost',amount:'50',direction:'toOwner',verified:true,note:'原真实转账'});f.approve(f.request(id));
|
||||
const before=business(f.l);
|
||||
for(const [kind,p] of [['confirm',{}],['receipt',{}],['refund',{}],['expense',{}],['fees',{}],['cost',{}],['complete',{}],['deliver',{}],['return',{}],['material',{}],['correct',{type:'payment'}],['correct',{type:'expense'}]]){
|
||||
assert.throws(()=>f.act(id,kind,p),error=>error.status===409&&/已审批作废/.test(error.message));assert.deepEqual(business(f.l),before);
|
||||
}
|
||||
assert.throws(()=>f.edit(id,{lines:[line({sale:'9999'})]}),/仅支持修改/);assert.deepEqual(business(f.l),before);
|
||||
f.edit(id,{customer:'资料更正',salesperson:'麦麦',note:'保留审核后资料'});assert.equal(f.l.detail(id).customer,'资料更正');assert.equal(f.l.detail(id).status,'cancelled');
|
||||
for(const table of ['payments','expenses','settlements','movements','journal'])assert.deepEqual(f.l.rows('SELECT * FROM '+table),before[table]);
|
||||
f.act(id,'settlement',{date:D2,bucket:'cost',amount:'50',direction:'toAssistant',verified:true,note:'返还原交款'});assert.equal(f.l.detail(id).settlementDue,0);
|
||||
});
|
||||
|
||||
test('所有锁价关联单与已退货已取消不能申请;旧cancel动作不能绕过审批,输入校验无副作用',t=>{
|
||||
const f=fixture(t),id=f.issue(),returned=f.issue();f.act(returned,'return',{verified:true,reason:'真实退货'});
|
||||
const lockInput={date:D,customer:'锁价客户',line:{name:'足金999',quantity:'1',goldPrice:'1000',laborRate:'0',laborMode:'gram'},payment:{amount:'1000',account:'助理微信',verified:true},material:{rate:'900',payer:'assistant',verified:true}};
|
||||
const lock=f.run(lockInput,()=>f.l.createPriceLock(lockInput,assistant));
|
||||
const delivery={date:D2,revision:1,verified:true,line:{quantity:'1',laborRate:'0',laborMode:'gram',payer:'owner',costParts:{labor:'0',accessories:'0',other:'0'}},inventory:{pocket:'现货',original:'receive'},fee_items:[]};
|
||||
const locked=f.run(delivery,()=>f.l.deliverPriceLock(lock.id,delivery,assistant)).id;
|
||||
for(const order of [returned,locked]){assert.equal(f.l.orderCancellation(order,owner).eligible,false);const before=all(f.l);assert.throws(()=>f.request(order));assert.deepEqual(all(f.l),before);}
|
||||
for(const actor of [owner,assistant])assert.throws(()=>f.act(id,'cancel',{reason:'跳过审批'},actor),error=>error.status===409&&/须先提交取消申请/.test(error.message));
|
||||
for(const p of [{reason:''},{revision:0},{revision:String(f.l.detail(id).revision)},{reason:'长'.repeat(201)}]){const before=all(f.l);assert.throws(()=>f.request(id,p));assert.deepEqual(all(f.l),before);}
|
||||
const requested=f.request(id),before=all(f.l);assert.throws(()=>f.approve(requested,{verified:false}),/请核实/);assert.throws(()=>f.reject(requested,''),/驳回意见/);assert.deepEqual(all(f.l),before);
|
||||
f.approve(requested);assert.throws(()=>f.request(id),/不能重复/);
|
||||
});
|
||||
|
||||
test('审批后置失败原子回滚包含他单FIFO重算快照和操作号,直接调用同样不留下半笔',t=>{
|
||||
const f=fixture(t);f.buy('10','9000','assistant');const p=input({lines:[line({costMaterial:{mode:'pool',poolId:D}})]}),id=f.issue(p);f.issue(p);
|
||||
f.run({close:D},()=>f.l.closeDay(D,owner,'orderDate'),owner);const requested=f.request(id),before=all(f.l),audit=f.l.audit;
|
||||
f.l.audit=function(entity,action,...args){if(action==='同意取消订单(录错作废)')throw new Error('模拟审批末尾写入故障');return audit.call(this,entity,action,...args);};
|
||||
assert.throws(()=>f.approve(requested),/模拟审批末尾/);assert.deepEqual(all(f.l),before);
|
||||
assert.throws(()=>f.l.approveOrderCancellation(requested.requestId,{revision:requested.request.order_revision,verified:true},owner),/模拟审批末尾/);assert.deepEqual(all(f.l),before);
|
||||
f.l.audit=audit;f.approve(requested);assert.equal(f.l.detail(id).status,'cancelled');
|
||||
});
|
||||
|
||||
test('HTTP审批保护登录CSRF权限和版本,同key并发只审批一次,跨日全局待审不受订单筛选影响',async t=>{
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'maimai-cancellation-http-')),l=new Ledger(path.join(dir,'ledger.sqlite'));
|
||||
createUser(l,'麦麦','owner','synthetic-owner-password');createUser(l,'助理','assistant','synthetic-assistant-password');
|
||||
const app=createApp({mode:'trial',port:0,dataDir:dir,ledger:l});await new Promise(resolve=>app.server.listen(0,'127.0.0.1',resolve));
|
||||
t.after(async()=>{await new Promise(resolve=>app.server.close(resolve));l.close();fs.rmSync(dir,{recursive:true,force:true});});
|
||||
const base='http://127.0.0.1:'+app.server.address().port,cookies={};
|
||||
const call=(who,route,body,key=randomUUID(),extra={})=>fetch(base+route,{method:body===undefined?'GET':'POST',headers:{...(cookies[who]?{Cookie:cookies[who]}:{}),...(body===undefined?{}:{'Content-Type':'application/json','X-Requested-With':'maimai-ledger',Origin:base,'Idempotency-Key':key}),...extra},...(body===undefined?{}:{body:JSON.stringify(body)})});
|
||||
assert.equal((await call('none','/api/order-cancellations')).status,401);
|
||||
for(const [who,name] of [['owner','麦麦'],['assistant','助理']]){const response=await call(who,'/api/login',{name,password:who==='owner'?'synthetic-owner-password':'synthetic-assistant-password'});cookies[who]=response.headers.get('set-cookie').split(';')[0];}
|
||||
const payload=input({lines:[line({pocket:''})]}),issued=await(await call('assistant','/api/orders/issue',payload)).json(),id=issued.id;
|
||||
const info=await(await call('assistant','/api/orders/'+id+'/cancellation')).json(),body={revision:info.revision,reason:'重复录入'};
|
||||
assert.equal((await call('assistant','/api/orders/'+id+'/cancellation',body,undefined,{Origin:'https://evil.example'})).status,403);
|
||||
const key=randomUUID(),responses=await Promise.all([call('assistant','/api/orders/'+id+'/cancellation',body,key),call('assistant','/api/orders/'+id+'/cancellation',body,key)]);
|
||||
assert.deepEqual(responses.map(row=>row.status),[200,200]);const [application,retry]=await Promise.all(responses.map(row=>row.json()));assert.equal(application.requestId,retry.requestId);
|
||||
const requestPath='/api/order-cancellations/'+application.requestId,decision={revision:info.revision,verified:true,note:'核实后作废'};
|
||||
assert.equal((await call('assistant',requestPath+'/approve',decision)).status,403);assert.equal((await call('assistant',requestPath+'/reject',{note:'不允许助理审批'})).status,403);
|
||||
assert.equal((await call('owner','/api/orders/'+id+'/cancel',{reason:'旧客户端'})).status,409);
|
||||
const pending=await(await call('owner','/api/order-cancellations')).json();assert.equal(pending.counts.pending,1);assert.equal(pending.requests[0].order_date,D);
|
||||
const approveKey=randomUUID(),approved=await Promise.all([call('owner',requestPath+'/approve',decision,approveKey),call('owner',requestPath+'/approve',decision,approveKey)]);assert.deepEqual(approved.map(row=>row.status),[200,200]);
|
||||
assert.equal((await call('owner',requestPath+'/approve',decision)).status,409);assert.equal((await call('owner',requestPath+'/reject',{note:'已经同意不能驳回'})).status,409);
|
||||
assert.equal(l.rows("SELECT * FROM audit WHERE action='同意取消订单(录错作废)'").length,1);assert.equal(l.rows('SELECT * FROM orders').length,1);
|
||||
assert.equal((await(await call('owner','/api/orders/'+id)).json()).status,'cancelled');assert.equal((await(await call('owner','/api/order-cancellations?status=all')).json()).counts.approved,1);
|
||||
const printable=await(await call('assistant','/api/orders/'+id+'/public')).json();assert.equal(printable.status,'cancelled');assert.ok(!JSON.stringify(printable).includes('cancellationApproved'));
|
||||
const second=new Ledger(path.join(dir,'ledger.sqlite'));assert.equal(second.orderCancellation(id,owner).requests[0].status,'approved');second.close();
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
'use strict';
|
||||
const {historicalAction}=require('./fixtures/legacy-cancellation.cjs');
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict'),{randomUUID}=require('node:crypto');
|
||||
const {Ledger}=require('../ledger'),Calc=require('../public/calculations'),{receipt}=require('../printing');
|
||||
const date='2026-10-17',actor={id:'cost-owner',name:'测试麦麦',role:'owner'};
|
||||
@@ -10,7 +11,7 @@ function fixture(t,p=input(),legacy=false){
|
||||
const ledger=new Ledger(':memory:');t.after(()=>ledger.close());
|
||||
const run=(p,fn)=>ledger.transact(randomUUID(),actor,p,fn);
|
||||
const id=run(p,()=>legacy?ledger.saveOrder(p,actor):ledger.issueOrder(p,actor)).id;
|
||||
const action=(kind,p={})=>run({kind,p},()=>ledger.action(id,kind,{date,...p},actor));
|
||||
const action=(kind,p={})=>run({kind,p},()=>historicalAction(ledger,id,kind,{date,...p},actor));
|
||||
if(legacy)action('confirm');
|
||||
const detail=()=>ledger.detail(id),costs=()=>Calc.orderCosts(detail());
|
||||
return {ledger,id,action,detail,costs};
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
'use strict';
|
||||
const {historicalAction}=require('./fixtures/legacy-cancellation.cjs');
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict');
|
||||
const {randomUUID,createHash}=require('node:crypto');
|
||||
const {Ledger}=require('../ledger'),Calc=require('../public/calculations');
|
||||
@@ -12,7 +13,7 @@ function fixture(t){
|
||||
const input={date:D,customer:'合成客户',note:'仅用于测试',payment_account:'助理微信',lines:[line()],fee_items:[],...extra};
|
||||
return run(input,()=>issue?ledger.issueOrder(input,actor):ledger.saveOrder(input,actor)).id;
|
||||
};
|
||||
const action=(id,kind,extra={})=>{const input={date:D,...extra};return run({id,kind,input},()=>ledger.action(id,kind,input,actor));};
|
||||
const action=(id,kind,extra={})=>{const input={date:D,...extra};return run({id,kind,input},()=>historicalAction(ledger,id,kind,input,actor));};
|
||||
const after=(extra={})=>{const input={date:D,project:'合成售后',customer:'合成客户',amount:'20',payer:'assistant',...extra};return run(input,()=>ledger.saveAfterSale(input,actor)).after_sale_id;};
|
||||
const close=(date=D)=>run({date,basis:'orderDate'},()=>ledger.closeDay(date,actor,'orderDate'));
|
||||
const book=(query={})=>ledger.orderBook({date:D,...query});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
'use strict';
|
||||
const {historicalAction}=require('./fixtures/legacy-cancellation.cjs');
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict'),{randomUUID}=require('node:crypto');
|
||||
const fs=require('node:fs'),os=require('node:os'),path=require('node:path');
|
||||
const {Ledger}=require('../ledger'),{createApp}=require('../server'),Calc=require('../public/calculations');
|
||||
@@ -15,7 +16,7 @@ function fixture(t){
|
||||
const issue=(input=orderInput())=>run(input,()=>l.issueOrder(input,assistant)).id;
|
||||
const inputs=id=>({...l.orderEdit(id,assistant).inputs,revision:l.detail(id).revision,reason:'核实原凭据后更正录入',verified:true});
|
||||
const edit=(id,input=inputs(id),key=randomUUID(),actor=assistant)=>run({id,input},()=>l.editOrder(id,input,actor),actor,key);
|
||||
const act=(id,kind,input={},actor=owner)=>run({id,kind,input},()=>l.action(id,kind,{date:D,note:'测试实际交款',...input},actor),actor);
|
||||
const act=(id,kind,input={},actor=owner)=>run({id,kind,input},()=>historicalAction(l,id,kind,{date:D,note:'测试实际交款',...input},actor),actor);
|
||||
const buy=(date=D,grams='10',total='9000',payer='owner')=>run({date,grams,total,payer},()=>l.createMaterialPurchase({date,grams,total,payer,note:'原采购'},assistant));
|
||||
return {l,run,issue,inputs,edit,act,buy};
|
||||
}
|
||||
@@ -55,7 +56,7 @@ test('只改客户资料或原样重复保存不新增支付费用库存利润
|
||||
|
||||
test('旧单多渠道分笔实收在总额账户未改变时保留,明确换账户后只记所选渠道总额',t=>{
|
||||
const {l,run,inputs,edit}=fixture(t),p=orderInput({fee_items:[]}),id=run(p,()=>l.saveOrder(p,assistant)).id;
|
||||
for(const [kind,input] of [['confirm',{}],['receipt',{amount:'1200',account:'助理微信',verified:true}],['receipt',{amount:'800',account:'麦麦支付宝',verified:true}],['complete',{verified:true}]])run({kind,input},()=>l.action(id,kind,{date:D,...input},assistant));
|
||||
for(const [kind,input] of [['confirm',{}],['receipt',{amount:'1200',account:'助理微信',verified:true}],['receipt',{amount:'800',account:'麦麦支付宝',verified:true}],['complete',{verified:true}]])run({kind,input},()=>historicalAction(l,id,kind,{date:D,...input},assistant));
|
||||
const before=financialRows(l,id),input=inputs(id);input.lines[0].costParts.labor='21';edit(id,input);
|
||||
assert.deepEqual(financialRows(l,id).payments,before.payments);assert.equal(l.report(D).accounts.find(row=>row.account==='助理微信').receipt,120000);assert.equal(l.report(D).accounts.find(row=>row.account==='麦麦支付宝').receipt,80000);
|
||||
const financial=l.detail(id),dateOnly=inputs(id);dateOnly.date=D2;edit(id,dateOnly);assert.equal(l.detail(id).ownerDirect,financial.ownerDirect);assert.equal(l.detail(id).settlementDue,financial.settlementDue);
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
'use strict';
|
||||
const {historicalAction}=require('./fixtures/legacy-cancellation.cjs');
|
||||
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
|
||||
const {randomUUID}=require('node:crypto');
|
||||
const {Ledger}=require('../ledger'),Calc=require('../public/calculations'),{receipt}=require('../printing'),{createApp}=require('../server');
|
||||
const actor={id:'entry-owner',name:'测试麦麦',role:'owner'},D='2026-10-16',D2='2026-10-17';
|
||||
const line=(extra={})=>({name:'足金999',unit:'g',quantity:'2.2',pocket:'',payer:'owner',pricingMode:'auto',goldPrice:'940',laborRate:'45',laborMode:'gram',pieces:'1',costParts:{material:'1980',labor:'44',accessories:'0',other:'0'},...extra});
|
||||
function fixture(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'maimai-entry-'));const file=path.join(dir,'ledger.sqlite');const l=new Ledger(file);t.after(()=>{try{l.close();}catch{}fs.rmSync(dir,{recursive:true,force:true});});const run=(p,fn,key=randomUUID())=>l.transact(key,actor,p,fn);const save=(extra={})=>{const p={date:D,lines:[line()],discount:'0',...extra};return run(p,()=>l.saveOrder(p,actor)).id;};const act=(id,a,p={})=>run({id,a,p},()=>l.action(id,a,{date:D,...p},actor));return {dir,file,l,run,save,act};}
|
||||
function fixture(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'maimai-entry-'));const file=path.join(dir,'ledger.sqlite');const l=new Ledger(file);t.after(()=>{try{l.close();}catch{}fs.rmSync(dir,{recursive:true,force:true});});const run=(p,fn,key=randomUUID())=>l.transact(key,actor,p,fn);const save=(extra={})=>{const p={date:D,lines:[line()],discount:'0',...extra};return run(p,()=>l.saveOrder(p,actor)).id;};const act=(id,a,p={})=>run({id,a,p},()=>historicalAction(l,id,a,{date:D,...p},actor));return {dir,file,l,run,save,act};}
|
||||
test('克工费与件工费:用户给定案例、整数分舍入、件数及非法输入',()=>{
|
||||
assert.equal(Calc.calculate(line()).sale,216700);
|
||||
assert.equal(Calc.calculate(line({laborMode:'piece'})).sale,211300);
|
||||
@@ -77,7 +78,7 @@ test('接续旧版最大序号,跨月跨年不归零,超过999继续累计
|
||||
test('快递包装按整单登记一次;各付款人分开;退货保留实际已付费用',t=>{
|
||||
const {l,save,act,run}=fixture(t);const id=save({payment_account:'助理支付宝',fees_date:D,fee_items:[{key:'shipping',amount:'8',payer:'assistant'},{key:'box',amount:'3',payer:'owner'}]});
|
||||
assert.equal(l.detail(id).draftFees,1100);assert.equal(l.detail(id).estimatedProfit,13200);assert.equal(l.detail(id).expenses.length,0);
|
||||
assert.throws(()=>act(id,'confirm'),/实际支付/);const p={date:D,feesVerified:true},key=randomUUID();run(p,()=>l.action(id,'confirm',p,actor),key);run(p,()=>l.action(id,'confirm',p,actor),key);
|
||||
assert.throws(()=>act(id,'confirm'),/实际支付/);const p={date:D,feesVerified:true},key=randomUUID();run(p,()=>historicalAction(l,id,'confirm',p,actor),key);run(p,()=>historicalAction(l,id,'confirm',p,actor),key);
|
||||
assert.equal(l.detail(id).expenses.length,2);assert.equal(l.detail(id).draftFees,0);assert.equal(l.detail(id).directCost,1100);
|
||||
act(id,'receipt',{amount:'2167',account:'助理支付宝',verified:true});act(id,'deliver',{verified:true});assert.equal(l.detail(id).profit,13200);assert.equal(l.detail(id).ownerCost,202700);
|
||||
act(id,'return',{date:D2,reason:'合成退货',verified:true});assert.equal(l.detail(id).profit,-1100);assert.equal(l.report(D2).profit,-14300);
|
||||
|
||||
@@ -44,9 +44,9 @@ test('货品成本、克工费和附加成本缺项均不生成单据,未提
|
||||
assert.throws(()=>issue(p),error);assert.deepEqual(snapshot(l),before);assert.equal(l.paperNumber(date),number);
|
||||
}
|
||||
});
|
||||
test('交付后取消改走退货,退款从开单收款账户冲回,已发生费用保留',t=>{
|
||||
test('旧取消入口不能绕过审批,真实退货仍按原账户退款并保留实际费用',t=>{
|
||||
const {l,issue,act}=fixture(t),id=issue();
|
||||
assert.throws(()=>act(id,'cancel',{reason:'测试取消'}),/已交付/);
|
||||
assert.throws(()=>act(id,'cancel',{reason:'测试取消'}),/取消申请/);
|
||||
act(id,'return',{reason:'测试退货',verified:true});assert.equal(l.detail(id).balance,-216000);assert.equal(l.detail(id).profit,-600);assert.equal(l.inventory().find(r=>r.pocket==='现货').mg,10000);
|
||||
assert.throws(()=>act(id,'refund',{amount:'2160',account:'助理微信',verified:true}),/原收款账户/);
|
||||
act(id,'refund',{amount:'2160',account:'助理支付宝',verified:true});assert.equal(l.detail(id).netReceived,0);assert.equal(l.detail(id).expenses.length,1);
|
||||
|
||||
+19
-3
@@ -2,6 +2,8 @@
|
||||
|
||||
更新:2026-10-23。包含普通开单、原订单修改、锁价待交付、每日购料加权成本和打印模板。日购料垫付款按录入顺序扣减已在本机3100更新,历史有效用量已升级至v2;本次尚未向线上 `tz.summermai.top` 部署此项更新,线上版本和服务器配置以实际运维记录为准。打印机购买与实机校准后置。已经录入经营数据的本机账必须按真实账保管,不能因为启动入口名为“演示”就清空。
|
||||
|
||||
**普通订单取消审批已于2026-10-23更新本机3100,刷新页面即可使用;本次未部署到线上服务。** 更新前已备份,原有经营记录核对一致,没有取消任何真实订单。
|
||||
|
||||
## 先看成品
|
||||
|
||||
- Windows:双击上一级的「启动新账演示.bat」。
|
||||
@@ -40,6 +42,20 @@
|
||||
|
||||
修改内容与普通开单草稿分别暂存,刷新可以继续;「取消修改」回到原单详情,本次不写账。出现订单已有新记录时,填写内容仍保留,先读取并核对当前订单再继续;连接中断时点顶部「恢复原操作」。锁价单、已取消及已退货订单本次只开放客户称呼、开单人和备注,锁价关联与原采购收付款保留。
|
||||
|
||||
## 申请取消录错订单
|
||||
|
||||
普通订单录错、重复录入而需要整单作废时,打开原单点「申请取消」,填写取消原因后提交。普通旧草稿、旧单待补齐及已完成订单均可申请;锁价关联单暂不支持取消,已退货、已取消订单没有申请入口。
|
||||
|
||||
申请期间仍按原订单计账,不会提前恢复库存或撤销金额。详情显示申请人、原因和时间,并暂停本单修改、收退款、费用、补齐账务、退货、交款及流水更正;助理只能申请和查看进度,不能同意或驳回。
|
||||
|
||||
麦麦在「订单」页点「待取消复核(n)」,可查看所有日期的待审申请,不受「今天」、搜索及订单状态筛选影响。进入原单后,点「同意取消」先核对将撤销的成交金额、收款净额、货品成本、已记费用、利润及库存冲回摘要,勾选录错作废确认,再点「同意取消并作废」。也可填写驳回意见后驳回,原订单继续计账,申请人核对后可重新申请。
|
||||
|
||||
同意后原单标记「已取消 · 录错作废」,恢复本单原有库存出入,撤销该单销售、成本、收款及费用记账;日购料的本单耗用释放,相关成本和待结金额重新核算。原订单、原流水、冲回行、申请与复核记录保留,原单号不会复用。双方已经登记的实际交款不抹掉,后续按剩余待结金额核对。
|
||||
|
||||
这个入口处理的是登记错误,不是真实退货退款,不会发起客户退款或双方转账。真实退货仍从原单「整单退货」办理,退款按实际发生情况登记。如果申请后订单或关联购料数据发生变动,原申请会提示过期,不能直接同意;先驳回,再按最新订单重新申请和复核。
|
||||
|
||||
断网或响应丢失时,点顶部「恢复原操作」,沿用同一个操作号,不重复执行申请或批准。提示订单已有新记录时,先点「重新读取订单并复核」,不能继续批准旧页面。已经显示保存成功而暂未读到最新资料时,只重新读取原订单,不要重新提交。
|
||||
|
||||
## 复制新增订单(入口暂时隐藏)
|
||||
|
||||
目前使用开单模板,订单列表和详情中的「复制新增」入口已暂时隐藏。底层功能保留,以下说明供以后恢复入口时参考。
|
||||
@@ -140,7 +156,7 @@
|
||||
|
||||
## 退货和更正
|
||||
|
||||
- 旧草稿及尚未完成记账的历史单可以取消,释放占用;已收款另行登记真实退款。新流程开出的单据已完成出库,退货从原单办理。
|
||||
- 录错需要整单作废时,普通订单通过「申请取消」交由麦麦复核,同意后撤销本单记账,详见上节。真实退货从原单「整单退货」办理,不用取消申请代替。
|
||||
- 已开单:从原单办理整单退货,核实实物回到哪个货盘。外配退给供应商可选不入店内库存;外配留店须选实际货盘,后续出售仍按实际垫资人和成本录入。
|
||||
- 退货按原售价、原货品成本在退货日冲回。实际发生的运费等不自动消失;确实是登记错误的费用,用更正入口处理。
|
||||
- 客户退款从原收款账户登记;麦麦返给助理的原货款、已交利润分别登记,不抵下一单,不重复算经营费用。
|
||||
@@ -154,11 +170,11 @@
|
||||
|
||||
订单页上方显示当前筛选的订单数量、利润与成本,并把成本按麦麦、助理分开。收款区分别显示微信、支付宝,有现金时另列现金,退款另列。麦麦已确认全部按订单开单日期统计:收款、成本、利润都对应当前筛选出的这批订单,显示它们截至现在的累计账务结果;昨天的订单今天补款,仍归在昨天的订单中。搜索和状态筛选也会同步更新所有汇总。历史单成本缺失时会显示已知部分和缺项数量;草稿不算正式销售,旧单未分项成本保留原总额,不猜分成料费或工费。
|
||||
|
||||
已取消的销售单仍保留在订单列表,可查看原记录;订单页上方统计和列表底部合计都排除这些单的数量、克重/件数、收退款、成本及利润,并标明「未计入汇总」。只筛选已取消订单时,列表有记录,汇总为0。独立售后仍按所选日期计入,手工人数不受影响。「每日对账」继续保留实际发生的收退款和费用用于核对,取消记录的历史账务不会因订单页显示规则而删除。
|
||||
已取消的销售单仍保留在订单列表,可查看原记录;订单页上方统计和列表底部合计都排除这些单的数量、克重/件数、收退款、成本及利润,并标明「未计入汇总」。只筛选已取消订单时,列表有记录,汇总为0。独立售后仍按所选日期计入,手工人数不受影响。「每日对账」保留原流水与冲回明细;本次审批作废的收款、费用净额撤销,历史取消与真实退货仍按其原业务记录核对,历史账务不会删除。
|
||||
|
||||
「每日对账」选日期,先核对微信、支付宝、现金各账户累计收款、退款,再核对「助理支出成本」和「麦麦支出成本」。两人分别显示货品成本、已付费用与合计,可展开查看订单、料费、进货工费、配件、证书、包装、快递等逐项金额。料费使用克重乘进货料价后的合计,不能把每克单价当作总支出。勾选「汇总当月」查看该月1日至所选日开出的订单;下载报告也包含双方成本明细。
|
||||
|
||||
普通订单的收款、成本、利润都按所选订单截至现在的累计结果展示,跨天补款、补费用或退货会回到原开单日期更新结果。锁价单的现金按实际发生日期、销售和消耗成本按交付订单日期,详见上面的锁价说明。未入账的预估费用不计入实际成本,缺失金额显示待补;取消、退货后的货品成本已冲回,已发生的费用保留。全局未结事项是截至现在的状态,不受日期筛选;库存仍按截至所选日的库存流水计算。
|
||||
普通订单的收款、成本、利润都按所选订单截至现在的累计结果展示,跨天补款、补费用或退货会回到原开单日期更新结果。锁价单的现金按实际发生日期、销售和消耗成本按交付订单日期,详见上面的锁价说明。未入账的预估费用不计入实际成本,缺失金额显示待补;真实退货后的货品成本冲回,已发生的费用保留;本次审批取消属于录错作废,本单收款和费用也撤销,原始明细及双方实际交款保留。全局未结事项是截至现在的状态,不受日期筛选;库存仍按截至所选日的库存流水计算。
|
||||
|
||||
独立售后按售后记录的日期计入成本和利润,不追溯到客户原来买货的日期。补录历史售后会更新那一天的财务核对结果,库存快照不受售后费用影响。
|
||||
|
||||
|
||||
@@ -2,6 +2,22 @@
|
||||
|
||||
更新:2026-10-23。包含锁价待交付和每日购料加权;日购料垫付款按录入顺序扣减已在本机3100更新,历史有效用量已升级至v2。本次尚未向线上 `tz.summermai.top` 部署此项更新,线上版本和服务器配置以实际运维记录为准。无第三方包、无npm安装;业务模块使用Node内置SQLite、HTTP、crypto、fs。最小Node22.16,建议24 LTS。当前3100账本已有真实经营数据,维护时不得因其APP_MODE为demo而重新播种或清空。
|
||||
|
||||
**普通订单取消审批已于2026-10-23更新本机3100,本次未部署到线上。** Windows启动方式、纯Node零依赖保持原入口。
|
||||
|
||||
## 普通订单取消审批
|
||||
|
||||
- `public/order-cancellations-ui.js`提供申请、全部日期的待复核列表、金额与库存冲回摘要、同意/驳回及历史记录。`public/index.html`在`app.js`前加载该脚本,服务端静态白名单须包含此文件。
|
||||
- `GET /api/orders/:id/cancellation`返回当前资格、当前订单`revision`、待审`pending`、历史`requests`和角色权限`canApprove`;`POST`同路径接收`{revision,reason}`申请。普通`draft/confirmed/delivered`可申请;锁价关联、已退货和已取消订单拒绝。旧`cancel`动作拒绝绕过审批。
|
||||
- `GET /api/order-cancellations?status=pending|all|approved|rejected`按所有日期返回申请与各状态数量;`GET /api/order-cancellations/:id`读取单条。申请期间保持原账,不按订单页日期筛选隐藏旧日期申请。助理没有审批操作,后端也检查角色。
|
||||
- `POST /api/order-cancellations/:id/approve`接收`{revision:request.order_revision,verified:true,note}`,仅麦麦同意;`POST .../reject`接收必填驳回意见`{note}`。申请人、原因、时间、原版本、撤销摘要、复核人、意见及结果均保留。重复申请与重复同意受业务状态保护。
|
||||
- 同意按录错作废处理:冲回本单库存出入、销售及货品成本,撤回本单收款和费用,释放本单日购料耗用并重算。原始订单和流水保留;收退款`reference`、费用`note`中的冲回记录以「更正冲回:取消审批作废;」标识。页面明确标为作废冲回,不冒充真实退款。
|
||||
- 真实日购料采购付款及双方已经发生的实际交款保留,按重新计算的待结余额核对。批准后仅保留资料更正、实际交款及交款更正、复核和打印;不再登记销售收退款、费用或退货。客户打印保留取消标记及内部字段隔离。
|
||||
- 待审期间拦截本单财务动作、旧单补齐、退货、整单修改、草稿保存、实际交款和流水更正。后端允许客户、开单人、备注等资料修正,但会使申请过期;页面在待审期间隐藏修改和普通订单复核入口,减少无意变更。关联购料重价等使原版本过期时,只允许驳回后重新申请,不自动使用新金额批准。
|
||||
- 申请与复核写入均沿用现有登录、CSRF、`Idempotency-Key`和事务机制。浏览器先保存原操作号,断网从「恢复原操作」继续;响应已确认后只重新读取,不重新提交。409会清空确认勾选、关闭旧表单提交能力并要求重新读取复核。详情读取校验返回版本,旧异步响应不能覆盖后来打开的订单或其他账号。
|
||||
- 飞书镜像仅对本次审批作废订单将「销售金额」置0,明细保留原单金额和审批信息;历史取消语义不变。审批通过时沿用原同步队列,未启用新的真实飞书写入配置。
|
||||
|
||||
2026-10-23 验证:新旧系统完整回归352项通过,最后的409恢复按钮修正后13项前端回归复验通过;另有17项独立账本/HTTP/旧版兼容检查和完整浏览器流程通过。浏览器验收覆盖助理申请、麦麦驳回、重申、批准、过期资料重新读取及作废后的资料更正,测试只用隔离合成账本。本机3100停服后创建独立备份,再启动新版本;原25张表240条记录的旧列哈希全部一致,新增审批表为空,SQLite完整性为ok。健康接口与新增静态脚本均返回200,没有取消或修改真实订单。线上版本仍以实际部署记录为准。
|
||||
|
||||
## 每日购料数据与成本
|
||||
|
||||
- `material-pools.js`按真实采购日期建立共享成本余额,采购与双方实际转款分别保存在`material_purchases`、`material_pool_settlements`。采购支持修改及软删除,完整前后值、经办人和时间保留在审计中;双方实际转款仍保留原记录。`material_pool_usages`为订单商品行的当前用量,`material_pool_events`保留使用、释放、重新计价前后值。首次启用日购料时只增补表、索引和版本字段,不将旧手填成本订单自动转成日购料;本次已关联日购料的历史归属升级见下文。
|
||||
|
||||
Reference in new issue
Block a user