2026-10-17 19:50:24 +08:00
'use strict' ;
// 金额以分、黄金以毫克储存。业务和流水一起提交,网络重试复用操作号。
const { DatabaseSync , backup } = require ( 'node:sqlite' );
const { randomUUID , createHash } = require ( 'node:crypto' );
const fs = require ( 'node:fs' );
const path = require ( 'node:path' );
const Calc = require ( './public/calculations' );
2026-10-25 14:19:24 +08:00
const CreditCardFees = require ( './public/credit-card-fees' );
2026-10-17 19:50:24 +08:00
const { orderBook } = require ( './order-book' );
2026-10-23 09:49:36 +08:00
const { reportByOrderDate , dailyFundsReceipts } = require ( './daily-report' );
const DailyFunds = require ( './daily-funds' );
2026-10-21 01:32:49 +08:00
const PriceLocks = require ( './price-locks' );
const MaterialPools = require ( './material-pools' );
2026-10-26 17:07:26 +08:00
const RollingMaterialPools = require ( './rolling-material-pools' );
const MaterialPurchaseChanges = require ( './material-purchase-changes' );
2026-10-22 04:21:26 +08:00
const OrderTemplates = require ( './order-templates' );
2026-10-22 17:06:32 +08:00
const OrderEdit = require ( './order-edit' );
2026-10-23 00:38:04 +08:00
const OrderCancellations = require ( './order-cancellations' );
2026-10-23 09:49:36 +08:00
const OrderChanges = require ( './order-changes' );
2026-10-25 14:19:24 +08:00
const TeamMembers = require ( './team-members' );
const TeamFunds = require ( './team-funds' );
const InventoryChanges = require ( './inventory-changes' );
2026-10-26 14:44:07 +08:00
const Recoveries = require ( './recoveries' );
2026-10-23 09:49:36 +08:00
// 仅服务器的新单生成流程能传入,客户端字段不能取得这个权限。
const NEW_ORDER_ACTION = Symbol ( 'newOrderAction' );
2026-10-23 11:58:19 +08:00
const SAME_DAY_ORDER_ACTION = Symbol ( 'sameDayOrderAction' );
2026-10-23 09:49:36 +08:00
const PRICE_LOCK_DELIVERY = Symbol ( 'priceLockDelivery' );
2026-10-26 14:44:07 +08:00
const RECOVERY_ORDER = Symbol ( 'recoveryOrder' );
2026-10-17 19:50:24 +08:00
const FEE_LABELS = { shipping : '快递费' , box : '包装盒' , certificate : '证书' , braiding : '编绳' , sticker : '手机贴' , other : '其他直接费用' };
const POCKETS = [ '现货' , '金料' , '找金' , '回收旧料' , '君宝汇' , '臻金汇' , '金金' , '定制工厂' ];
// 历史货盘仍参与原单、退货和完整库存核算;新登记只使用当前五个货盘。
const ACTIVE_POCKETS = [ '现货' , '金料' , '找金' , '回收旧料' , '君宝汇' ];
2026-10-26 17:07:26 +08:00
const SELF_POCKETS = [ '现货' , '金料' , '回收旧料' ];
2026-10-25 14:19:24 +08:00
const ACCOUNTS = [ '助理微信' , '助理支付宝' , '助理现金' , '麦麦微信' , '麦麦支付宝' , '麦麦现金' , '助理信用卡' , '麦麦信用卡' , '助理2微信' , '助理2支付宝' , '助理2现金' , '助理2信用卡' ];
const CARD_FEE_NOTE = CreditCardFees . note ();
2026-10-23 09:49:36 +08:00
const isCardFee = item => item ? . system === 'credit_card' || String ( item ? . key || '' ). startsWith ( 'card_fee:' );
2026-10-25 14:19:24 +08:00
const cardFeeAmount = CreditCardFees . amount ;
const paymentAccount = value => pick ( CreditCardFees . normalizeAccount ( value ), ACCOUNTS , '收付款账户' );
2026-10-17 19:50:24 +08:00
const today = () => new Intl . DateTimeFormat ( 'sv-SE' ,{ timeZone : 'Asia/Shanghai' }). format ( new Date ());
const now = () => new Date (). toISOString ();
const sum = ( rows , key ) => rows . reduce (( s , r )=> s + ( typeof key === 'function' ? key ( r ) : r [ key ]), 0 );
function fail ( message , status = 400 ) { const e = new Error ( message ); e . status = status ; throw e ; }
function text ( value , name , max = 100 , optional = false ) { const s = String ( value ?? '' ). trim (); if (( ! s &&! optional ) || s . length > max ) fail ( ` ${ name } 请填写 ${ optional ? '不超过' : '1~ ' }${ max } 字` ); return s ; }
2026-10-23 09:49:36 +08:00
function orderIdentity ( value , name , max ){ if ( typeof value !== 'string' ) fail ( ` ${ name } 须填写文字` ); return text ( value , name , max );}
2026-10-23 00:21:53 +08:00
function peopleNumber ( value , name , optional = false ){
if ( optional && ( value === null || typeof value === 'string' &&! value . trim ())) return null ;
const raw = [ 'number' , 'string' ]. includes ( typeof value ) ? String ( value ). trim () : '' ;
if ( ! /^\d+$/ . test ( raw )) fail ( ` ${ name } 须为0~ 1000000的整数` );
const count = Number ( raw ); if ( ! Number . isSafeInteger ( count ) || count > 1000000 ) fail ( ` ${ name } 须为0~ 1000000的整数` );
return count ;
}
2026-10-25 14:19:24 +08:00
const PEOPLE_PARTS = [[ 'assistant1' , 'assistant1_count' ],[ 'assistant2' , 'assistant2_count' ]];
const previousPeopleDate = date => new Date ( Date . parse ( date + 'T00:00:00Z' ) - 86400000 ). toISOString (). slice ( 0 , 10 );
function peopleParts ( ledger , actor = ledger . actor ){ return ledger . teamMode && actor ? . role === 'assistant' ? PEOPLE_PARTS . filter (([ key ])=> key === ( ledger . memberFor ( actor ) === 'assistant' ? 'assistant1' : 'assistant2' )) : PEOPLE_PARTS ;}
function peopleDifference ( current , previous ){ return { change : current === null || previous === null ? null : current - previous , reason : current === null ? ( previous === null ? 'missing-both' : 'missing-current' ) : previous === null ? 'missing-previous' : null };}
function peopleDay ( date , record , previous , parts ){
const result = { date , previousDate : previousPeopleDate ( date ), previous : {}, mode : 'daily-total' };
for ( const [ key , column ] of parts ){ const total = record ? .[ column ] ?? null , baseline = previous ? .[ column ] ?? null , difference = peopleDifference ( total , baseline ); result [ key + 'Count' ] = total ; result . previous [ key + 'Count' ] = baseline ; result [ key + 'Change' ] = difference . change ; result [ key + 'ChangeReason' ] = difference . reason ;}
return result ;
}
function peoplePeriod ( date , from , saved , parts ){
const baselineDate = previousPeopleDate ( from ), end = saved . get ( date ), baseline = saved . get ( baselineDate ), result = {};
for ( const [ key , column ] of parts ){
const endTotal = end ? .[ column ] ?? null , baselineTotal = baseline ? .[ column ] ?? null , difference = peopleDifference ( endTotal , baselineTotal );
result [ key ] = { total : endTotal , endTotal , baselineTotal , netChange : difference . change , netChangeReason : difference . reason , recordedDays : [... saved . values ()]. filter ( row => row . date >= from && row . date <= date && row [ column ] !== null ). length };
}
return result ;
}
2026-10-17 19:50:24 +08:00
function fixed ( value , places , name , negative = false ) {
const s = String ( value ?? '' ). trim (); const re = new RegExp ( `^ ${ negative ? '-?' : '' } \\d+(?:\\.\\d{1, ${ places } })?$` );
if ( ! re . test ( s )) fail ( ` ${ name } 须为 ${ negative ? '可带负号的' : '' } 数字,最多 ${ places } 位小数` );
const sign = s . startsWith ( '-' ) ?- 1 : 1 ; const [ a , b = '' ] = s . replace ( '-' , '' ). split ( '.' );
const n = sign * ( Number ( a ) * 10 ** places + Number ( b . padEnd ( places , '0' )));
if ( ! Number . isSafeInteger ( n ) || Math . abs ( n ) > 1e11 ) fail ( ` ${ name } 超出支持范围` ); return n ;
}
const money = ( v , n = '金额' )=> fixed ( v , 2 , n );
const weight = ( v , n = '克重' )=> fixed ( v , 3 , n );
function day ( value , minimum = '2000-01-01' ) {
const s = String ( value || '' );
if ( ! /^\d{4}-\d{2}-\d{2}$/ . test ( s ) ||! Number . isFinite ( Date . parse ( s + 'T00:00:00Z' )) || new Date ( s + 'T00:00:00Z' ). toISOString (). slice ( 0 , 10 ) !== s || s < minimum || s > today ()) fail ( `业务日期应在 ${ minimum } 至 ${ today () } 之间` );
return s ;
}
const owner = ( actor )=>{ if ( actor . role !== 'owner' ) fail ( '这项操作由麦麦账号完成' , 403 );};
const pick = ( v , opts , name )=>{ if ( ! opts . includes ( v )) fail ( ` ${ name } 无效` ); return v ;};
2026-10-25 14:19:24 +08:00
function fundingReference ( value ){
if ( value === undefined ) return undefined ;
if ( ! value || typeof value !== 'object' || Array . isArray ( value )) fail ( '报销来源格式无效' );
const { reimbursementId , itemId , amount , revision } = value ;
if ( ! /^[a-f0-9-]{36}$/ . test ( String ( reimbursementId )) ||! /^[a-f0-9-]{36}$/ . test ( String ( itemId ))) fail ( '报销来源编号无效' );
if ( amount !== undefined && money ( amount , '报销使用金额' ) <= 0 ) fail ( '报销使用金额须大于0' );
if ( revision !== undefined && ( ! Number . isSafeInteger ( revision ) || revision < 1 )) fail ( '报销来源版本无效' );
return { reimbursementId , itemId ,...( amount !== undefined ? { amount : String ( amount )} : {}),...( revision !== undefined ? { revision } : {})};
}
function costFundingReferences ( value ){
if ( value === undefined ) return undefined ; if ( ! value || typeof value !== 'object' || Array . isArray ( value )) fail ( '货品报销来源格式无效' );
const result = {}; for ( const [ key , source ] of Object . entries ( value )){ if ( ! [ 'material' , 'labor' , 'accessories' , 'other' , 'total' ]. includes ( key )) fail ( '货品报销成本项目无效' ); if ( source !== null ) result [ key ] = fundingReference ( source );} return result ;
}
2026-10-26 17:07:26 +08:00
const priceLockEnv = { day , money , weight , text , orderIdentity , fail , pick , today , now , pockets : ACTIVE_POCKETS , selfPockets : SELF_POCKETS , accounts : ACCOUNTS , paymentAccount , cardFee : cardFeeAmount };
2026-10-17 19:50:24 +08:00
class Ledger {
constructor ( filename ) {
2026-10-25 14:19:24 +08:00
this . filename = filename ; this . teamMode = false ; this . actor = null ; this . memberFilter = null ;
2026-10-17 19:50:24 +08:00
if ( filename !== ':memory:' ) fs . mkdirSync ( path . dirname ( filename ),{ recursive : true , mode : 0o700 });
this . db = new DatabaseSync ( filename ); this . db . exec ( 'PRAGMA foreign_keys=ON; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=5000;' );
this . db . exec ( `
CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY,value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS users(id TEXT PRIMARY KEY,name TEXT UNIQUE NOT NULL,role TEXT NOT NULL,salt TEXT NOT NULL,hash TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS sessions(hash TEXT PRIMARY KEY,user_id TEXT REFERENCES users(id),expires INTEGER NOT NULL);
CREATE TABLE IF NOT EXISTS orders(id TEXT PRIMARY KEY,number TEXT UNIQUE NOT NULL,date TEXT NOT NULL,customer TEXT NOT NULL,salesperson TEXT NOT NULL,note TEXT NOT NULL,paper_number TEXT NOT NULL,status TEXT NOT NULL,lines TEXT NOT NULL,discount INTEGER NOT NULL,total INTEGER NOT NULL,revision INTEGER NOT NULL DEFAULT 1,reviewed_revision INTEGER NOT NULL DEFAULT 0,created TEXT NOT NULL,delivered_date TEXT,returned_date TEXT);
CREATE TABLE IF NOT EXISTS payments(id TEXT PRIMARY KEY,order_id TEXT NOT NULL REFERENCES orders(id),date TEXT NOT NULL,kind TEXT NOT NULL,amount INTEGER NOT NULL,account TEXT NOT NULL,reference TEXT NOT NULL,actor TEXT NOT NULL,created TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS expenses(id TEXT PRIMARY KEY,order_id TEXT NOT NULL REFERENCES orders(id),date TEXT NOT NULL,amount INTEGER NOT NULL,payer TEXT NOT NULL,note TEXT NOT NULL,actor TEXT NOT NULL,created TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS after_sales(id TEXT PRIMARY KEY,date TEXT NOT NULL,project TEXT NOT NULL,customer TEXT NOT NULL,amount INTEGER NOT NULL CHECK(amount>=0),payer TEXT NOT NULL CHECK(payer IN ('owner','assistant')),actor TEXT NOT NULL,created TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS daily_people_counts(date TEXT PRIMARY KEY,count INTEGER NOT NULL CHECK(count>=0 AND count<=1000000),revision INTEGER NOT NULL,actor TEXT NOT NULL,created TEXT NOT NULL,updated TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS settlements(id TEXT PRIMARY KEY,order_id TEXT NOT NULL REFERENCES orders(id),date TEXT NOT NULL,bucket TEXT NOT NULL,amount INTEGER NOT NULL,note TEXT NOT NULL,actor TEXT NOT NULL,created TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS movements(id TEXT PRIMARY KEY,group_id TEXT NOT NULL,order_id TEXT REFERENCES orders(id),date TEXT NOT NULL,pocket TEXT NOT NULL,mg INTEGER NOT NULL,kind TEXT NOT NULL,note TEXT NOT NULL,purchase_cost INTEGER,actor TEXT NOT NULL,created TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS journal(id TEXT PRIMARY KEY,order_id TEXT NOT NULL REFERENCES orders(id),date TEXT NOT NULL,kind TEXT NOT NULL,sales INTEGER NOT NULL,goods INTEGER NOT NULL,expense INTEGER NOT NULL,profit INTEGER NOT NULL,created TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS audit(id INTEGER PRIMARY KEY AUTOINCREMENT,entity TEXT NOT NULL,action TEXT NOT NULL,actor TEXT NOT NULL,detail TEXT NOT NULL,created TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS operations(id TEXT PRIMARY KEY,hash TEXT NOT NULL,result TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS corrections(target TEXT PRIMARY KEY,type TEXT NOT NULL,reason TEXT NOT NULL,actor TEXT NOT NULL,created TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS sync(entity TEXT PRIMARY KEY,revision INTEGER NOT NULL,done_revision INTEGER NOT NULL DEFAULT 0,record_id TEXT,attempts INTEGER NOT NULL DEFAULT 0,error TEXT,updated TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS closes(date TEXT PRIMARY KEY,report TEXT NOT NULL,actor TEXT NOT NULL,created TEXT NOT NULL,stale INTEGER NOT NULL DEFAULT 0);
CREATE TABLE IF NOT EXISTS inventory_snapshots(date TEXT PRIMARY KEY,inventory TEXT NOT NULL,actor TEXT NOT NULL,created TEXT NOT NULL,updated TEXT NOT NULL,stale INTEGER NOT NULL DEFAULT 0,revision TEXT NOT NULL);
CREATE INDEX IF NOT EXISTS ix_movements_date ON movements(date,pocket);
CREATE INDEX IF NOT EXISTS ix_payment_order ON payments(order_id);
CREATE INDEX IF NOT EXISTS ix_journal_date ON journal(date);
CREATE INDEX IF NOT EXISTS ix_after_sales_date ON after_sales(date);
` );
// 增量升级旧库,不改写历史订单金额、单号和成本。
const columns = this . rows ( 'PRAGMA table_info(orders)' ). map ( r => r . name );
for ( const [ name , definition ] of Object . entries ({ paper_date : "TEXT NOT NULL DEFAULT ''" , payment_account : "TEXT NOT NULL DEFAULT '助理微信'" , fee_items : "TEXT NOT NULL DEFAULT '[]'" , fees_date : "TEXT NOT NULL DEFAULT ''" , rounding_mode : "TEXT NOT NULL DEFAULT 'cent'" })){
if ( ! columns . includes ( name )) this . db . exec ( `ALTER TABLE orders ADD COLUMN ${ name } ${ definition } ` );
}
2026-10-23 00:21:53 +08:00
// 只加可空分项,不把历史原人数归给任一助理,也不改历史版本及录入信息。
const peopleColumns = this . rows ( 'PRAGMA table_info(daily_people_counts)' ). map ( row => row . name );
for ( const name of [ 'assistant1_count' , 'assistant2_count' ]) if ( ! peopleColumns . includes ( name ))
this . db . exec ( `ALTER TABLE daily_people_counts ADD COLUMN ${ name } INTEGER CHECK( ${ name } IS NULL OR (typeof( ${ name } )='integer' AND ${ name } >=0 AND ${ name } <=1000000))` );
2026-10-21 01:32:49 +08:00
PriceLocks . initialize ( this );
MaterialPools . initialize ( this );
2026-10-22 04:21:26 +08:00
OrderTemplates . initialize ( this );
2026-10-23 00:38:04 +08:00
OrderCancellations . initialize ( this );
2026-10-23 09:49:36 +08:00
OrderChanges . initialize ( this );
DailyFunds . initialize ( this );
2026-10-26 17:07:26 +08:00
TeamMembers . initialize ( this ); TeamFunds . initialize ( this ); InventoryChanges . initialize ( this ); Recoveries . initialize ( this ); MaterialPurchaseChanges . initialize ( this );
2026-10-17 19:50:24 +08:00
if ( filename !== ':memory:' ) fs . chmodSync ( filename , 0o600 );
}
2026-10-25 14:19:24 +08:00
enableTeamMode (){
const previousMode = this . teamMode ; this . db . exec ( 'SAVEPOINT enable_team_mode' );
try { const result = TeamMembers . migrate ( this ); this . teamMode = true ; TeamFunds . migrateMaterialFunding ( this , undefined , priceLockEnv ); this . db . exec ( 'RELEASE enable_team_mode' ); return result ;}
catch ( error ){ this . teamMode = previousMode ; this . db . exec ( 'ROLLBACK TO enable_team_mode' ); this . db . exec ( 'RELEASE enable_team_mode' ); throw error ;}
}
scope ( actor , fn , member = this . memberFilter ){ const previous = this . actor , filter = this . memberFilter ; this . actor = actor ; this . memberFilter = member ; try { return fn ();} finally { this . actor = previous ; this . memberFilter = filter ;}}
asActor ( actor ){ const ledger = this ; return new Proxy ( this ,{ get ( target , key ){ const value = target [ key ]; return typeof value === 'function' ? (... args )=> ledger . scope ( actor ,()=> value . apply ( target , args )) : value ;}});}
memberFor ( actor = this . actor ){ return TeamMembers . memberFor ( this , actor );}
bindMemberUser ( id , member , options ){ return TeamMembers . bindUser ( this , id , member , options );}
entityMember ( kind , id ){ return TeamMembers . entityMember ( this , kind , id );}
assignMember ( kind , id , member ,{ fresh = false } = {}){ const result = TeamMembers . assign ( this , kind , id , member ); if ( fresh && this . teamMode ) TeamFunds . activate ( this , kind , id ,{ legacy : false }); return result ;}
selectedMember ( input , actor = this . actor , existing = null ){ return TeamMembers . selected ( this , input , actor , existing );}
canAccess ( kind , id , actor = this . actor ){ return TeamMembers . canAccess ( this , kind , id , actor );}
assertAccess ( kind , id , actor = this . actor ){ return TeamMembers . assertAccess ( this , kind , id , actor );}
queryMember ( query = {}, actor = this . actor ){ return this . memberFilter || TeamMembers . queryMember ( this , query , actor );}
visibleRows ( kind , rows , idKey = 'id' , actor = this . actor , member = this . memberFilter ){ return TeamMembers . visible ( this , kind , rows , idKey , actor , member );}
teamMembers (){ owner ( this . actor ); return { members : TeamMembers . users ( this )};}
migrateTeamMaterialFunding ( actor , env = priceLockEnv ){ return TeamFunds . migrateMaterialFunding ( this , actor , env );}
teamFunds ( query = {}, actor = this . actor ){ return TeamFunds . report ( this , query , actor , priceLockEnv );}
2026-10-26 14:44:07 +08:00
recoveryQuote ( input , actor = this . actor ){ return Recoveries . quote ( this , input , actor , priceLockEnv );}
createRecovery ( input , actor = this . actor ){ return Recoveries . create ( this , input , actor ,{... priceLockEnv , saveRecoveryOrder : input => this . saveOrder ( input , actor , RECOVERY_ORDER ), recoveryOrderAction : ( id , action , input )=> this . action ( id , action , input , actor , NEW_ORDER_ACTION )});}
recoveries ( query = {}, actor = this . actor ){ return Recoveries . list ( this , query , actor , priceLockEnv );}
recovery ( id , actor = this . actor ){ return Recoveries . detail ( this , id , actor , priceLockEnv );}
publicRecovery ( id , actor = this . actor ){ return Recoveries . publicDetail ( this , id , actor , priceLockEnv );}
guardRecoveryOrder ( id ){ return Recoveries . guardOrder ( this , id , priceLockEnv );}
2026-10-25 14:19:24 +08:00
transferTeamFunds ( input , actor = this . actor ){ return TeamFunds . transfer ( this , input , actor , priceLockEnv );}
syncTeamFunds ( actor = this . actor ){ if ( this . teamMode ) TeamFunds . syncTouchedOrders ( this , actor , priceLockEnv );}
2026-10-17 19:50:24 +08:00
rows ( sql ,... args ){ return this . db . prepare ( sql ). all (... args );}
one ( sql ,... args ){ return this . db . prepare ( sql ). get (... args );}
run ( sql ,... args ){ return this . db . prepare ( sql ). run (... args );}
meta ( key , fallback = null ){ const v = this . one ( 'SELECT value FROM meta WHERE key=?' , key ); return v ? JSON . parse ( v . value ) : fallback ;}
setMeta ( key , value ){ this . run ( 'INSERT INTO meta VALUES (?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value' , key , JSON . stringify ( value ));}
2026-10-25 14:19:24 +08:00
audit ( entity , action , actor , detail ){ this . run ( 'INSERT INTO audit(entity,action,actor,detail,created) VALUES (?,?,?,?,?)' , entity , action , actor . name , JSON . stringify ( this . teamMode ? {... detail , actorIdentity : { id : actor . id , role : actor . role , member : this . memberFor ( actor )}} : detail ), now ());}
2026-10-17 19:50:24 +08:00
transact ( key , actor , payload , fn ){
if ( ! /^[a-zA-Z0-9_-]{16,100}$/ . test ( String ( key ))) fail ( '缺少有效操作号,请刷新后重试' );
const hash = createHash ( 'sha256' ). update ( JSON . stringify ({ actor : actor . id , payload })). digest ( 'hex' );
this . db . exec ( 'BEGIN IMMEDIATE' );
try {
const prior = this . one ( 'SELECT * FROM operations WHERE id=?' , key );
if ( prior ){ if ( prior . hash !== hash ) fail ( '这个操作号已用于其他内容,请重新操作' , 409 ); this . db . exec ( 'COMMIT' ); return JSON . parse ( prior . result );}
2026-10-25 14:19:24 +08:00
const result = fn (); this . syncTeamFunds ( actor ); this . run ( 'INSERT INTO operations VALUES (?,?,?)' , key , hash , JSON . stringify ( result )); this . db . exec ( 'COMMIT' ); return result ;
2026-10-17 19:50:24 +08:00
} catch ( e ){ if ( this . db . isTransaction ) this . db . exec ( 'ROLLBACK' ); throw e ;}
}
touch ( id ){ this . run ( 'UPDATE orders SET revision=revision+1 WHERE id=?' , id ); this . enqueue ( 'order:' + id );}
enqueue ( entity ){
const revision = entity . startsWith ( 'order:' ) ? this . one ( 'SELECT revision FROM orders WHERE id=?' , entity . slice ( 6 )). revision : Math . max ( Date . now (),( this . one ( 'SELECT revision FROM sync WHERE entity=?' , entity ) ? . revision || 0 ) + 1 );
this . run ( 'INSERT INTO sync(entity,revision,updated) VALUES (?,?,?) ON CONFLICT(entity) DO UPDATE SET revision=excluded.revision,updated=excluded.updated' , entity , revision , now ());
}
dirty ( date ){ this . run ( 'UPDATE closes SET stale=1 WHERE date>=?' , date ); this . enqueue ( 'inventory' );}
dirtyInventory ( date ){ this . run ( 'UPDATE inventory_snapshots SET stale=1 WHERE date>=?' , date ); this . dirty ( date );}
2026-10-25 14:19:24 +08:00
rawOrder ( id , actor = this . actor ){ this . assertAccess ( 'order' , id , actor ); const o = this . one ( 'SELECT * FROM orders WHERE id=?' , id ); if ( ! o ) fail ( '订单不存在' , 404 ); o . lines = JSON . parse ( o . lines ); o . fee_items = JSON . parse ( o . fee_items ); if ( this . teamMode ) o . member = this . entityMember ( 'order' , id ); return o ;}
2026-10-22 17:06:32 +08:00
orderEdit ( id , actor ){ return OrderEdit . detail ( this , id , actor , priceLockEnv );}
2026-10-26 17:07:26 +08:00
editOrder ( id , input , actor ){
this . assertAccess ( 'order' , id , actor ); this . guardRecoveryOrder ( id ); const order = this . rawOrder ( id , actor ), currentDate = today ();
const historical = RollingMaterialPools . enabled ( this ) && actor . role === 'owner' && input . verified === true && ( order . date < currentDate || typeof input . date === 'string' && input . date < currentDate );
if ( ! historical ) return OrderEdit . edit ( this , id , input , actor , priceLockEnv );
// 麦麦已核实的既有改单入口保留;权限只覆盖本次原单修改,新增订单不能取得历史重算权限。
this . db . exec ( 'SAVEPOINT owner_historical_order_edit' );
try { const result = RollingMaterialPools . withHistorical ( this ,()=>{
const edited = OrderEdit . edit ( this , id , input , actor , priceLockEnv );
this . audit ( id , '麦麦直接复核历史订单修改' , actor ,{ reason : input . reason , before : { date : order . date , revision : order . revision }, after : { date : edited . order . date , revision : edited . revision }, verified : true }); return edited ;
}); this . db . exec ( 'RELEASE owner_historical_order_edit' ); return result ;}
catch ( error ){ this . db . exec ( 'ROLLBACK TO owner_historical_order_edit' ); this . db . exec ( 'RELEASE owner_historical_order_edit' ); throw error ;}
}
2026-10-23 09:49:36 +08:00
orderChange ( id , actor ){ return OrderChanges . detail ( this , id , actor , priceLockEnv );}
orderChanges ( query = {}, actor ){ return OrderChanges . list ( this , query , actor , priceLockEnv );}
orderChangeRequest ( id , actor ){ return OrderChanges . read ( this , id , actor , priceLockEnv );}
requestOrderChange ( id , input , actor ){ return OrderChanges . request ( this , id , input , actor , priceLockEnv );}
approveOrderChange ( id , input , actor ){ return OrderChanges . approve ( this , id , input , actor , priceLockEnv );}
rejectOrderChange ( id , input , actor ){ return OrderChanges . reject ( this , id , input , actor , priceLockEnv );}
pendingOrderChange ( id ){ return OrderChanges . pending ( this , id );}
guardOrderChange ( id , options ){ return OrderChanges . guard ( this , id , options , priceLockEnv );}
2026-10-23 00:38:04 +08:00
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 );}
2026-10-23 11:58:19 +08:00
cancelOrderToday ( id , input , actor ){ return OrderCancellations . cancelToday ( this , id , input , actor , priceLockEnv );}
2026-10-23 00:38:04 +08:00
rejectOrderCancellation ( id , input , actor ){ return OrderCancellations . reject ( this , id , input , actor , priceLockEnv );}
guardOrderCancellation ( id , options ){ return OrderCancellations . guard ( this , id , options , priceLockEnv );}
2026-10-17 19:50:24 +08:00
detail ( id ){
const o = this . rawOrder ( id );
2026-10-23 09:49:36 +08:00
Object . assign ( o , OrderCancellations . projection ( this , id ), OrderChanges . projection ( this , id ));
2026-10-17 19:50:24 +08:00
o . payments = this . rows ( 'SELECT * FROM payments WHERE order_id=? ORDER BY date,created' , id );
2026-10-21 01:32:49 +08:00
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 ));}
2026-10-17 19:50:24 +08:00
o . expenses = this . rows ( 'SELECT * FROM expenses WHERE order_id=? ORDER BY date,created' , id );
o . settlements = this . rows ( 'SELECT * FROM settlements WHERE order_id=? ORDER BY date,created' , id );
o . corrections = this . rows ( 'SELECT * FROM corrections WHERE target IN (SELECT id FROM payments WHERE order_id=? UNION SELECT id FROM expenses WHERE order_id=? UNION SELECT id FROM settlements WHERE order_id=?)' , id , id , id );
o . received = sum ( o . payments , r => r . kind === 'receipt' ? r . amount : 0 ); o . refunded = sum ( o . payments , r => r . kind === 'refund' ? r . amount : 0 );
o . netReceived = o . received - o . refunded ; o . balance = ([ 'cancelled' , 'returned' ]. includes ( o . status ) ?- o . netReceived : o . total - o . netReceived ) || 0 ;
2026-10-26 14:44:07 +08:00
const recovery = Recoveries . forOrder ( this , id );
if ( recovery ){ o . recovery_id = recovery . id ; o . recovery_mode = 'exchange' ; o . recovery_immutable_reason = Recoveries . IMMUTABLE_REASON ; o . nonCashOffset = recovery . offsetAmount ; o . cashPaid = recovery . cashPayment ; o . netSettlement = recovery . netSettlement ; o . balance = o . total - o . netReceived - o . nonCashOffset ;}
2026-10-17 19:50:24 +08:00
o . rounding_adjustment = o . rounding_mode === 'yuan' ? o . total - ( sum ( o . lines , 'sale' ) - o . discount ) : 0 ;
o . goodsCost = o . lines . some ( l => l . cost === null ) ? null : sum ( o . lines , 'cost' ); o . directCost = sum ( o . expenses , 'amount' );
2026-10-21 01:32:49 +08:00
o . materialCostPending =! [ 'returned' , 'cancelled' ]. includes ( o . status ) && o . lines . some ( l => l . costMaterial ? . mode === 'pool' && l . costParts ? . material == null );
o . knownGoodsCost = sum ( o . lines , l => l . cost ?? sum ( Object . values ( l . costParts || {}). map ( amount =>({ amount : amount ?? 0 })), 'amount' ));
2026-10-17 19:50:24 +08:00
o . pendingFees = [ 'draft' , 'confirmed' ]. includes ( o . status ) ? o . fee_items . filter ( f => f . status !== 'recorded' && ( o . status === 'draft' || f . status === 'estimated' )) : [];
o . draftFees = sum ( o . pendingFees , f => f . amount || 0 );
o . estimatedProfit = o . goodsCost === null || o . pendingFees . some ( f => f . amount === null ) ? null : o . total - o . goodsCost - o . directCost - o . draftFees ;
2026-10-21 01:32:49 +08:00
const j = this . one ( 'SELECT COALESCE(SUM(profit),0) AS profit FROM journal WHERE order_id=?' , id ); o . profit = o . materialCostPending && o . status === 'delivered' ? null : j . profit ; o . knownProfit = o . profit ?? 0 ;
2026-10-17 19:50:24 +08:00
o . ownerCost = o . status === 'delivered' ? Calc . orderCosts ( o ). byPayer . owner . goods : 0 ;
if ([ 'delivered' , 'returned' , 'cancelled' ]. includes ( o . status )) o . ownerCost += sum ( o . expenses , e => e . payer === 'owner' ? e . amount : 0 );
2026-10-21 01:32:49 +08:00
if ( priceLock ){
const delivery = priceLock . delivery ? JSON . parse ( priceLock . delivery ) : null , sources = [];
const leftover = [ 'delivered' , 'returned' ]. includes ( o . status ) && priceLock . buy_payer === 'assistant' ? ( delivery ? . leftover_cost ?? 0 ) : 0 ;
if ( leftover ) sources . push ({ kind : 'leftover' , amount : leftover , quantity : delivery . leftover_mg , explanation : '助理垫付的剩余金料进入自有货盘,按原采购成本抵扣货款待结' });
const returned = o . status === 'returned' ? Calc . orderCosts ({... o , status : 'delivered' }). byPayer . assistant . goods : 0 ;
if ( returned ) sources . push ({ kind : 'returnedGoods' , amount : returned , explanation : '退回自有货盘的商品由助理垫付的货品成本,抵扣货款待结' });
o . assistantInventoryCredit = leftover + returned ; o . assistantInventoryCreditSources = sources ;
o . assistantInventoryCreditExplanation = sources . map ( source => source . explanation ). join ( '; ' );
}
if ( ! priceLock && o . status === 'returned' && o . lines . some ( line => line . costMaterial ? . mode === 'pool' )){
const pooled = o . lines . filter ( line => line . costMaterial ? . mode === 'pool' );
const retained = Calc . orderCosts ({... o , lines : pooled , status : 'delivered' }). rows . filter ( row => row . kind === 'goods' && row . payer === 'assistant' &&! row . materialPoolId );
const amount = sum ( retained , 'amount' );
if ( amount ){
o . assistantInventoryCredit = amount ;
o . assistantInventoryCreditSources = [{ kind : 'returnedGoods' , amount , explanation : '日购料关联商品已退回自有货盘,助理垫付的进货工费、配件和其他货品成本抵扣货款待结;料费由日购料剩余垫款单独抵扣' }];
o . assistantInventoryCreditExplanation = o . assistantInventoryCreditSources [ 0 ]. explanation ;
}
}
2026-10-17 19:50:24 +08:00
o . ownerDirect = sum ( o . payments , p => p . account . startsWith ( '麦麦' ) ? ( p . kind === 'receipt' ? p . amount :- p . amount ) : 0 );
// 取消/退货后的麦麦直收款属于待退客户款,不能再算一次应返助理。
2026-10-21 01:32:49 +08:00
o . ownerCredit = o . status === 'delivered' || ( priceLock && o . status === 'returned' && o . netReceived === 0 ) ? o . ownerDirect : 0 ;
2026-10-17 19:50:24 +08:00
o . costTransferred = sum ( o . settlements , s => s . bucket === 'cost' ? s . amount : 0 ); o . profitTransferred = sum ( o . settlements , s => s . bucket === 'profit' ? s . amount : 0 );
2026-10-21 01:32:49 +08:00
o . costDue = o . ownerCost - ( o . assistantInventoryCredit || 0 ) - o . costTransferred ; o . profitDue = o . profit === null ? null : o . profit - o . profitTransferred ;
o . settlementDue = o . materialCostPending && o . status === 'delivered' ? null : [ 'delivered' , 'returned' , 'cancelled' ]. includes ( o . status ) ? o . costDue + o . profitDue - o . ownerCredit : 0 ;
o . knownSettlementDue = o . settlementDue ?? 0 ;
2026-10-17 19:50:24 +08:00
o . audit = this . rows ( 'SELECT action,actor,detail,created FROM audit WHERE entity=? ORDER BY id DESC LIMIT 100' , id ). map ( r =>({... r , detail : JSON . parse ( r . detail )}));
o . sync = this . one ( 'SELECT revision,done_revision,error,updated FROM sync WHERE entity=?' , 'order:' + id ) || null ;
2026-10-25 14:19:24 +08:00
if ( this . teamMode ){ o . funds_mode = this . one ( "SELECT source_id FROM team_fund_sources WHERE kind='order' AND source_id=?" , id ) ? 'team' : 'legacy' ; if ( o . funds_mode === 'team' ){ o . costDue = 0 ; o . profitDue = 0 ; o . settlementDue = 0 ; o . knownSettlementDue = 0 ;}}
2026-10-17 19:50:24 +08:00
return o ;
}
2026-10-23 00:14:29 +08:00
validateLines ( lines , historicalLines = [], businessDate = null ,{ orderId = null } = {}){
2026-10-17 19:50:24 +08:00
if ( ! Array . isArray ( lines ) ||! lines . length || lines . length > 60 ) fail ( '每单需要1~ 60行商品' );
2026-10-23 00:14:29 +08:00
const prepared = lines . map (( l , i )=>{
2026-10-17 19:50:24 +08:00
const unit = pick ( l . unit ,[ 'g' , '件' ], '单位' ); const qty = unit === 'g' ? weight ( l . quantity , `第 ${ i + 1 } 行克重` ) : fixed ( l . quantity , 1 , '件数' ) / 10 ;
if ( qty <= 0 || ( unit === '件' &&! Number . isInteger ( qty ))) fail ( '克重必须大于0,件数必须为正整数' );
const pocket = l . pocket ? pick ( l . pocket , POCKETS , '货盘' ) : '' ; if ( pocket && unit !== 'g' ) fail ( '货盘库存按克重管理,按件商品请选外配/不扣黄金' );
if ( pocket &&! ACTIVE_POCKETS . includes ( pocket ) && historicalLines [ i ] ? . pocket !== pocket ) fail ( '这个货盘已停用,新商品请选择当前货盘' );
const name = text ( l . name , '商品名称' , 60 );
if ( Calc . isSilver ( name ) && pocket ) fail ( '银饰不扣黄金货盘,请选择外配/不扣黄金' );
const mode = pick ( l . pricingMode || 'manual' ,[ 'auto' , 'manual' ], '计价方式' );
const priced = Calc . sale ({... l , pricingMode : mode });
const pricing = mode === 'auto' ? priced : null ;
2026-10-21 01:32:49 +08:00
if ( l . costMaterial ? . mode === 'pool' &&! l . costParts ) fail ( '日购料商品请填写分项成本;没有发生的成本填0' );
2026-10-17 19:50:24 +08:00
const breakdown = l . costParts ? Calc . purchaseCosts ( l ) : null ;
const costPayers = Calc . costPayers ( l . costPayers === undefined ? historicalLines ? .[ i ] ? . costPayers : l . costPayers );
const cost = breakdown ? breakdown . total : ( l . cost === '' || l . cost == null ? null : money ( l . cost , '货品成本' ));
const priceNote = pricing ? `金价 ${ ( pricing . goldPrice / 100 ). toFixed ( 2 ) } 元/克 + 工费 ${ ( pricing . laborRate / 100 ). toFixed ( 2 ) } 元/ ${ pricing . laborMode === 'gram' ? '克' : `件 × ${ pricing . pieces } 件` } ` : text ( l . priceNote , '客户单价说明' , 100 , true );
2026-10-25 14:19:24 +08:00
return { name , code : text ( l . code , '商品编号' , 30 , true ), unit , quantity : qty , pocket , payer : pick ( l . payer ,[ 'owner' , 'assistant' , 'assistant2' ], '成本垫资人' ),...( costPayers ? { costPayers } : {}),...( l . costFundings === undefined ? {} : { costFundings : costFundingReferences ( l . costFundings )}), cost ,...( breakdown ? { costParts : breakdown . parts , costMaterial : breakdown . costMaterial , costLabor : breakdown . costLabor } : {}), sale : priced . sale , baseSale : priced . baseSale , charges : priced . charges , pricingMode : mode ,...( pricing ? { goldPrice : pricing . goldPrice , laborRate : pricing . laborRate , laborMode : pricing . laborMode , pieces : pricing . pieces } : {}), priceNote };
2026-10-17 19:50:24 +08:00
});
2026-10-23 00:14:29 +08:00
return MaterialPools . prepareLines ( this , prepared , businessDate , priceLockEnv ,{ orderId });
2026-10-17 19:50:24 +08:00
}
paperNumber ( date , allocate = false ){
day ( date ); const prefix = date . replaceAll ( '-' , '' ); let seq = this . meta ( 'paper-sequence' , 0 );
// 接续已经使用过的最大序号,包括旧版按日计数器里不再显示的已占号码。
for ( const r of this . rows ( "SELECT value FROM meta WHERE key LIKE 'paper-seq:%'" )) seq = Math . max ( seq , JSON . parse ( r . value ));
for ( const r of this . rows ( 'SELECT paper_number FROM orders' )){
const match = r . paper_number . match ( /^\d{8}-?(\d+)$/ ); if ( match ) seq = Math . max ( seq , Number ( match [ 1 ]));
}
seq ++ ; if ( ! Number . isSafeInteger ( seq )) fail ( '纸单流水号超出范围' );
if ( allocate ) this . setMeta ( 'paper-sequence' , seq );
return prefix + String ( seq ). padStart ( 3 , '0' );
}
validateFees ( items ){
if ( items == null ) return [];
if ( ! Array . isArray ( items ) || items . length > 6100 ) fail ( '直接费用项目无效' );
const seen = new Set (); return items . map ( item =>{
const key = String ( item . key || '' ); if ( ! Object . hasOwn ( FEE_LABELS , key ) &&! /^(charge|manual):[a-f0-9-]{36}$/ . test ( key )) fail ( '费用项目无效' );
if ( seen . has ( key )) fail ( '同一费用项目不能重复填写' ); seen . add ( key );
const estimated = item . status === 'estimated' ;
const amount = estimated && ( item . amount == null || item . amount === '' ) ? null : money ( item . amount , FEE_LABELS [ key ] || '附加成本' );
2026-10-22 04:21:26 +08:00
const note = text ( item . note || FEE_LABELS [ key ], '费用项目名称' , 150 );
2026-10-25 14:19:24 +08:00
return { key , amount ,...( item . funding === undefined ? {} : { funding : fundingReference ( item . funding )}), payer : pick ( item . payer ,[ 'owner' , 'assistant' , 'assistant2' ], '费用付款人' ), note ,...( estimated ? { status : 'estimated' , edited : item . edited === true } : {}),...( item . sourceName ? { sourceName : text ( item . sourceName , '附加项目名称' , 40 )} : {})};
2026-10-17 19:50:24 +08:00
}). filter ( item => item . status === 'estimated' || item . amount > 0 );
}
2026-10-23 09:49:36 +08:00
recordFees ( o , items , date , actor , context = null ){
2026-10-23 11:58:19 +08:00
if ( actor . role !== 'owner' && context !== NEW_ORDER_ACTION && context !== SAME_DAY_ORDER_ACTION ) fail ( '已开订单的费用须先提交复核申请,由麦麦批准后入账' , 403 );
2026-10-17 19:50:24 +08:00
if ( items . some ( f => f . amount === null )) fail ( '请补齐附加成本;没有发生的费用填0' );
2026-10-25 14:19:24 +08:00
for ( const f of items ) if ( f . amount > 0 ){ const expenseId = randomUUID (); this . run ( 'INSERT INTO expenses VALUES (?,?,?,?,?,?,?,?)' , expenseId , o . id , date , f . amount , f . payer , f . note , actor . name , now ()); if ( f . funding ) f . expense_id = expenseId ;}
2026-10-17 19:50:24 +08:00
const keys = new Set ( items . map ( f => f . key )); this . run ( 'UPDATE orders SET fee_items=?,fees_date=? WHERE id=?' , JSON . stringify ( o . fee_items . map ( f => keys . has ( f . key ) ? {... items . find ( item => item . key === f . key ), status : 'recorded' } : f )), date , o . id );
if ( items . some ( f => f . amount > 0 )) this . dirty ( date );
}
2026-10-25 14:19:24 +08:00
recordCardFee ( id , payment , actor ,{ payer = 'owner' , sourceKind = 'payment' , journal = true , recordedFee = null } = {}){
2026-10-23 09:49:36 +08:00
if ( payment . kind !== 'receipt' || payment . amount <= 0 ||! payment . account . endsWith ( '信用卡' )) return null ;
2026-10-25 14:19:24 +08:00
payer = pick ( payer ,[ 'owner' , 'assistant' , 'assistant2' ], '信用卡手续费付款人' );
2026-10-23 09:49:36 +08:00
const order = this . rawOrder ( id ), key = 'card_fee:' + payment . id , existing = order . fee_items . find ( fee => fee . key === key );
if ( existing ) return existing ;
2026-10-25 14:19:24 +08:00
// 锁价交付继承原事件已发生费用,旧4‰实际费用与备注不能按今天费率重算。
const inherited = sourceKind === 'price_lock' && payment . card_fee_amount !== null && payment . card_fee_amount !== undefined ;
const amount = recordedFee ? . amount ?? ( inherited ? payment . card_fee_amount : cardFeeAmount ( payment . amount )), rate = recordedFee ? recordedFee . rate_permille ?? null : inherited ? payment . card_fee_rate ?? null : CreditCardFees . ratePermille ;
const note = recordedFee ? . note ?? ( inherited ? payment . card_fee_note || ( rate ? CreditCardFees . note ( rate ) : '已记录信用卡手续费' ) : CARD_FEE_NOTE ), expenseId = amount ? randomUUID () : null ;
if ( amount ) this . run ( 'INSERT INTO expenses VALUES (?,?,?,?,?,?,?,?)' , expenseId , id , payment . date , amount , payer , note , actor . name , now ());
const fee = { key , system : 'credit_card' , source_kind : sourceKind , source_id : payment . id , date : payment . date , amount , payer , note ,...( rate ? { rate_permille : rate } : {}), status : 'recorded' ,...( expenseId ? { expense_id : expenseId } : {})};
2026-10-23 09:49:36 +08:00
this . run ( 'UPDATE orders SET fee_items=? WHERE id=?' , JSON . stringify ([... order . fee_items , fee ]), id );
if ( amount && journal && [ 'delivered' , 'returned' , 'cancelled' ]. includes ( order . status )) this . journal ( id , payment . date , '信用卡手续费' , 0 , 0 , amount );
return fee ;
}
reverseCardFee ( id , sourceId , date , actor , reason ,{ journal = true } = {}){
const order = this . rawOrder ( id ), fee = order . fee_items . find ( item => isCardFee ( item ) && item . source_id === sourceId );
if ( ! fee ) return ;
const row = fee . expense_id ? this . one ( 'SELECT * FROM expenses WHERE id=? AND order_id=?' , fee . expense_id , id ) : null ;
if ( row &&! this . one ( 'SELECT target FROM corrections WHERE target=?' , row . id )){
this . run ( 'INSERT INTO corrections VALUES (?,?,?,?,?)' , row . id , 'expense' , reason , actor . name , now ());
this . run ( 'INSERT INTO expenses VALUES (?,?,?,?,?,?,?,?)' , randomUUID (), id , date , - row . amount , row . payer , '更正冲回:' + reason , actor . name , now ());
if ( journal && [ 'delivered' , 'returned' , 'cancelled' ]. includes ( order . status )) this . journal ( id , date , '信用卡手续费更正' , 0 , 0 , - row . amount );
}
this . run ( 'UPDATE orders SET fee_items=? WHERE id=?' , JSON . stringify ( order . fee_items . filter ( item => item . key !== fee . key )), id );
}
cardFeeInputs ( order , items ){
const current = order . fee_items . filter ( isCardFee ), submitted = items . filter ( isCardFee );
if ( current . length !== submitted . length ) fail ( '信用卡手续费由原收款自动维护,请保留全部原费用后重新打开核对' , 409 );
const seen = new Set (); return submitted . map ( item =>{
const original = current . find ( fee => fee . key === item . key );
if ( ! original || seen . has ( item . key )) fail ( '信用卡手续费来源无效,请重新打开订单' , 409 ); seen . add ( item . key );
for ( const key of [ 'system' , 'source_kind' , 'source_id' , 'expense_id' , 'date' , 'note' ]) if (( item [ key ] ?? '' ) !== ( original [ key ] ?? '' )) fail ( '信用卡手续费金额、日期及原流水由系统维护,不能手工改写' , 409 );
if ( money ( item . amount , '信用卡手续费' ) !== original . amount ) fail ( '信用卡手续费金额由实收自动计算,不能手工改写' );
2026-10-25 14:19:24 +08:00
return {... original , payer : pick ( item . payer ,[ 'owner' , 'assistant' , 'assistant2' ], '信用卡手续费付款人' )};
2026-10-23 09:49:36 +08:00
});
}
saveOrder ( input , actor , context = null ){
2026-10-17 19:50:24 +08:00
let id = input . id ;
2026-10-25 14:19:24 +08:00
const prior = id ? this . rawOrder ( id , actor ) : null ;
const member = this . selectedMember ( input , actor , prior ? this . entityMember ( 'order' , id ) : null );
2026-10-26 14:44:07 +08:00
if ( prior ){ this . guardRecoveryOrder ( id ); this . guardOrderCancellation ( id ); this . guardOrderChange ( id ); if ( ! this . teamMode || actor . role !== 'assistant' || prior . date !== today () || input . date !== today ()) owner ( actor );}
2026-10-17 19:50:24 +08:00
if ( prior ){ if ( prior . status !== 'draft' ) fail ( '已确认订单不能直接改写。未交付可取消重开,已交付请办理退货' , 409 ); if ( prior . revision !== input . revision ) fail ( '订单已被更新,请重新打开' , 409 );}
2026-10-23 09:49:36 +08:00
// 历史锁价交付只是内部转换,不强迫改写旧资料;所有实际新建、修改保存必须填写。
const identity = context === PRICE_LOCK_DELIVERY ? ( value , name , max )=> text ( value , name , max , true ) : orderIdentity ;
const customer = identity ( input . customer , '客户称呼/代号' , 60 ), salesperson = identity ( input . salesperson , '开单人' , 30 );
2026-10-21 01:32:49 +08:00
const date = day ( input . date ), lines = this . validateLines ( input . lines , prior ? . lines , date ), discount = money ( input . discount || '0' , '整单优惠' );
2026-10-17 19:50:24 +08:00
const roundingMode = input . rounding_mode === undefined ? ( prior ? . rounding_mode ?? 'yuan' ) : input . rounding_mode ;
2026-10-26 14:44:07 +08:00
const subtotal = sum ( lines , 'sale' );
const { total } = context === RECOVERY_ORDER && subtotal === discount ? { total : 0 } : Calc . orderTotal ( lines . map ( line => line . sale ), discount , roundingMode );
2026-10-17 19:50:24 +08:00
const fees = this . validateFees ( input . fee_items ?? prior ? . fee_items ? . map ( r =>({... r , amount : r . amount === null ? '' : ( r . amount / 100 ). toFixed ( 2 )})));
const feesDate = fees . length ? day ( input . fees_date || date , date ) : '' ;
2026-10-25 14:19:24 +08:00
const account = paymentAccount ( input . payment_account || prior ? . payment_account || '助理微信' );
2026-10-17 19:50:24 +08:00
const newNumber =! prior ? . paper_number ;
const autoNumber = prior ? . paper_date && prior . paper_number . match ( /^\d{8}-?(\d+)$/ );
const paper = newNumber ? this . paperNumber ( date , true ) : autoNumber ? date . replaceAll ( '-' , '' ) + autoNumber [ 1 ] : prior . paper_number ;
if ( this . one ( "SELECT id FROM orders WHERE REPLACE(paper_number,'-','')=? AND id<>?" , paper . replaceAll ( '-' , '' ), id || '' )) fail ( '该日期已有相同纸单号,请保留原日期或取消后重开' , 409 );
2026-10-23 09:49:36 +08:00
const common = [ date , customer , salesperson , text ( input . note , '客户单备注' , 240 , true ), paper , JSON . stringify ( lines ), discount , total ];
2026-10-17 19:50:24 +08:00
if ( id ){
this . run ( 'UPDATE orders SET date=?,customer=?,salesperson=?,note=?,paper_number=?,lines=?,discount=?,total=? WHERE id=?' ,... common , id ); this . touch ( id );
} else {
id = randomUUID (); const number = 'MM' + today (). replaceAll ( '-' , '' ) + '-' + randomUUID (). slice ( 0 , 8 ). toUpperCase ();
2026-10-25 14:19:24 +08:00
this . run ( 'INSERT INTO orders(id,number,date,customer,salesperson,note,paper_number,lines,discount,total,status,created) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)' , id , number ,... common , 'draft' , now ()); this . assignMember ( 'order' , id , member ,{ fresh : true }); this . enqueue ( 'order:' + id );
2026-10-17 19:50:24 +08:00
}
this . run ( 'UPDATE orders SET paper_date=?,payment_account=?,fee_items=?,fees_date=?,rounding_mode=? WHERE id=?' , newNumber || autoNumber ? date : prior ? . paper_date || '' , account , JSON . stringify ( fees ), feesDate , roundingMode , id );
this . audit ( id , '保存草稿' , actor ,{ revision : this . rawOrder ( id ). revision }); return { id };
}
validateCompletedCosts ( lines , fees ){
2026-10-21 01:32:49 +08:00
const missingCosts = lines . flatMap (( line , i )=>{
if ( line . cost != null ) return [];
const missing = line . costParts ? Object . entries ( Calc . costLabels ). filter (([ key ])=> line . costParts [ key ] == null &&! ( key === 'material' && line . costMaterial ? . mode === 'pool' )). map (([, label ])=> label ) : [ '货品成本' ];
return missing . length ? [ `商品 ${ i + 1 } 的 ${ missing . join ( '、' ) } ` ] : [];
});
2026-10-17 19:50:24 +08:00
if ( missingCosts . length ) fail ( `请补齐 ${ missingCosts . join ( '; ' ) } ;没有的成本填0,不能把空白当作0` );
const missingFees = fees . filter ( f => f . amount == null ). map ( f => f . note );
for ( const [ i , line ] of lines . entries ()) for ( const charge of line . charges || []){
if ( ! charge . id ) continue ;
const shipping = [ '快递' , '快递费' , '运费' ]. includes ( charge . name ), key = shipping ? 'shipping' : 'charge:' + charge . id ;
if ( ! fees . some ( f => f . key === key )) missingFees . push ( `商品 ${ i + 1 } 的 ${ charge . name } ` );
}
if ( missingFees . length ) fail ( `请补齐附加成本: ${ missingFees . join ( '、' ) } ;没有发生的费用填0` );
}
issueOrder ( input , actor ){
// 调用方用同一事务生成订单、收全款、记录实际费用并交付;任一步失败全部回滚。
// 旧定金单仍沿用原动作,仅经明确确认 complete 后完成交付,不自动补收款。
2026-10-25 14:19:24 +08:00
const prior = input . id ? this . rawOrder ( input . id , actor ) : null ;
2026-10-26 14:44:07 +08:00
if ( prior ){ this . guardRecoveryOrder ( prior . id ); this . guardOrderCancellation ( prior . id ); this . guardOrderChange ( prior . id ); if ( ! this . teamMode || actor . role !== 'assistant' || prior . date !== today () || input . date !== today ()) owner ( actor );}
2026-10-17 19:50:24 +08:00
if ( prior && prior . status !== 'draft' ) fail ( '已确认订单不能直接改写。未交付可取消重开,已交付请办理退货' , 409 );
2026-10-25 14:19:24 +08:00
this . selectedMember ( input , actor , prior ? this . entityMember ( 'order' , prior . id ) : null );
2026-10-21 01:32:49 +08:00
const lines = this . validateLines ( input . lines , prior ? . lines , day ( input . date ));
2026-10-17 19:50:24 +08:00
const fees = input . fee_items ?? prior ? . fee_items . map ( f =>({... f , amount : f . amount === null ? '' : ( f . amount / 100 ). toFixed ( 2 )})) ?? [];
if ( ! Array . isArray ( fees )) fail ( '直接费用项目无效' );
// 保存时暂用 estimated 保留显式填写的0,随后确认实际费用时统一转为 recorded。
const feeInputs = fees . map ( f =>({... f , status : 'estimated' }));
this . validateCompletedCosts ( lines , this . validateFees ( feeInputs ));
const { id } = this . saveOrder ({... input , fee_items : feeInputs }, actor );
const o = this . rawOrder ( id );
2026-10-23 09:49:36 +08:00
this . action ( id , 'confirm' ,{ date : o . date }, actor , NEW_ORDER_ACTION );
this . action ( id , 'receipt' ,{ date : o . date , amount : ( o . total / 100 ). toFixed ( 2 ), account : o . payment_account , credit_card_fee_payer : input . credit_card_fee_payer ?? 'owner' , verified : true , reference : '开单时已全额收款' }, actor , NEW_ORDER_ACTION );
this . action ( id , 'complete' ,{ date : o . date , verified : true }, actor , NEW_ORDER_ACTION );
2026-10-17 19:50:24 +08:00
this . audit ( id , '生成已交付单据' , actor ,{ amount : o . total , account : o . payment_account });
return { id };
}
inventory ( asOf = null ){
const rows = this . rows ( 'SELECT pocket,SUM(mg) AS mg FROM movements' + ( asOf ? ' WHERE date<=?' : '' ) + ' GROUP BY pocket' ,...( asOf ? [ asOf ] : []));
const reserved = {}; if ( ! asOf ) for ( const row of this . rows ( "SELECT lines FROM orders WHERE status='confirmed'" )) for ( const l of JSON . parse ( row . lines )) if ( l . pocket ) reserved [ l . pocket ] = ( reserved [ l . pocket ] || 0 ) + l . quantity ;
return POCKETS . map ( p =>({ pocket : p , mg : rows . find ( r => r . pocket === p ) ? . mg || 0 , reserved : reserved [ p ] || 0 , available : ( rows . find ( r => r . pocket === p ) ? . mg || 0 ) - ( reserved [ p ] || 0 )}));
}
inventoryRevision ( date ){
// 流水只追加。计数使同日先增后减、净重不变的并发登记也能被发现。
const count = this . one ( 'SELECT COUNT(*) AS count FROM movements WHERE date<=?' , date ). count ;
return createHash ( 'sha256' ). update ( JSON . stringify ({ date , count , inventory : this . inventory ( date )})). digest ( 'hex' );
}
inventorySnapshot ( date ){
const row = this . one ( 'SELECT * FROM inventory_snapshots WHERE date=?' , date );
return row ? {... row , inventory : JSON . parse ( row . inventory ), stale :!! row . stale } : null ;
}
inventoryStatus ( actor ){
const date = today (), yesterdayDate = new Date ( Date . parse ( date + 'T00:00:00Z' ) - 86400000 ). toISOString (). slice ( 0 , 10 );
const inventory = this . inventory ();
return { date , yesterdayDate , pockets : ACTIVE_POCKETS , current : inventory . filter ( r => ACTIVE_POCKETS . includes ( r . pocket )), yesterday : this . inventorySnapshot ( yesterdayDate ), todaySnapshot : this . inventorySnapshot ( date ), revision : this . inventoryRevision ( date ), legacyInventory : inventory . filter ( r => ! ACTIVE_POCKETS . includes ( r . pocket ) && ( r . mg !== 0 || r . reserved !== 0 )), canReview : actor ? . role === 'owner' };
}
2026-10-25 14:19:24 +08:00
inventoryMovements ( query = {}, actor = this . actor ){
2026-10-23 09:49:36 +08:00
const historical = new Set ( this . rows ( 'SELECT DISTINCT pocket FROM movements' ). map ( r => r . pocket ));
const pockets = POCKETS . filter ( pocket => ACTIVE_POCKETS . includes ( pocket ) || historical . has ( pocket )). map ( pocket =>({ pocket , active : ACTIVE_POCKETS . includes ( pocket )}));
const pocket = query . pocket ?? '' ;
if ( typeof pocket !== 'string' || pocket &&! pockets . some ( p => p . pocket === pocket )) fail ( '筛选货盘无效' );
const where = pocket ? ' WHERE pocket=?' : '' , args = pocket ? [ pocket ] : [];
2026-10-25 14:19:24 +08:00
const all = this . rows ( 'SELECT * FROM movements' + where + ' ORDER BY created DESC,rowid DESC' ,... args ). filter ( row => this . canAccess ( 'movement' , row . id , actor ));
const total = all . length ;
2026-10-23 09:49:36 +08:00
// 先筛选再限条数;同一毫秒的流水按实际录入顺序稳定排列。
2026-10-25 14:19:24 +08:00
const movements = InventoryChanges . decorate ( this , all . slice ( 0 , 100 ), actor , priceLockEnv );
2026-10-23 09:49:36 +08:00
return { pocket , pockets , total , shown : movements . length , limit : 100 , movements };
}
2026-10-17 19:50:24 +08:00
inventorySnapshots ( query = {}){
const date = day ( query . date || today ()), from = day ( query . from || '2000-01-01' );
if ( from > date ) fail ( '开始日期不能晚于结束日期' );
const snapshots = this . rows ( 'SELECT * FROM inventory_snapshots WHERE date>=? AND date<=? ORDER BY date DESC' , from , date ). map ( row =>({... row , inventory : JSON . parse ( row . inventory ), stale :!! row . stale }));
return { from , date , snapshots };
}
saveInventorySnapshot ( date , actor ){
owner ( actor ); day ( date );
const inventory = this . inventory ( date ), revision = this . inventoryRevision ( date ), timestamp = now ();
this . run ( 'INSERT INTO inventory_snapshots(date,inventory,actor,created,updated,stale,revision) VALUES (?,?,?,?,?,0,?) ON CONFLICT(date) DO UPDATE SET inventory=excluded.inventory,actor=excluded.actor,updated=excluded.updated,stale=0,revision=excluded.revision' , date , JSON . stringify ( inventory ), actor . name , timestamp , timestamp , revision );
this . audit ( 'inventory:' + date , '复核并保存库存快照' , actor ,{ date , revision , inventory });
return this . inventorySnapshot ( date );
}
reviewInventory ( input , actor ){
owner ( actor ); const date = day ( input . date || today ());
if ( input . verified !== true ) fail ( '请先核对各货盘克重,再确认保存快照' );
if ( typeof input . revision !== 'string' || input . revision !== this . inventoryRevision ( date )) fail ( '库存有新变动,请刷新后重新核对' , 409 );
return { date , snapshot : this . saveInventorySnapshot ( date , actor )};
}
2026-10-25 14:19:24 +08:00
inventoryMovement ( id , actor = this . actor ){ return InventoryChanges . detail ( this , id , actor , priceLockEnv );}
updateInventoryMovement ( id , input , actor = this . actor ){ return InventoryChanges . change ( this , id , 'update' , input , actor , priceLockEnv );}
deleteInventoryMovement ( id , input , actor = this . actor ){ return InventoryChanges . change ( this , id , 'delete' , input , actor , priceLockEnv );}
inventoryChanges ( query = {}, actor = this . actor ){ return InventoryChanges . list ( this , query , actor , priceLockEnv );}
inventoryChange ( id , actor = this . actor ){ return InventoryChanges . read ( this , id , actor , priceLockEnv );}
approveInventoryChange ( id , input , actor = this . actor ){ return InventoryChanges . approve ( this , id , input , actor , priceLockEnv );}
rejectInventoryChange ( id , input , actor = this . actor ){ return InventoryChanges . reject ( this , id , input , actor , priceLockEnv );}
2026-10-26 14:44:07 +08:00
move ({ group = randomUUID (), order = null , date , pocket , mg , kind , note , cost = null , member = null }, actor ){
2026-10-25 14:19:24 +08:00
const movementId = randomUUID (); this . run ( 'INSERT INTO movements VALUES (?,?,?,?,?,?,?,?,?,?,?)' , movementId , group , order , date , pocket , mg , kind , note , cost , actor . name , now ());
2026-10-26 14:44:07 +08:00
this . assignMember ( 'movement' , movementId , order ? this . entityMember ( 'order' , order ) || this . memberFor ( actor ) : member ?? this . memberFor ( actor ));
2026-10-17 19:50:24 +08:00
// 回填历史日期也逐日检查,防止只看当前余额掩盖过去负库存。
let balance = 0 ; for ( const r of this . rows ( 'SELECT date,SUM(mg) AS mg FROM movements WHERE pocket=? GROUP BY date ORDER BY date' , pocket )){ balance += r . mg ; if ( balance < 0 ) fail ( ` ${ pocket } 在 ${ r . date } 库存不足,不能提交` );}
const inv = this . inventory (). find ( r => r . pocket === pocket ); if ( inv . available < 0 ) fail ( ` ${ pocket } 可用库存不足,已有订单占用 ${ ( inv . reserved / 1000 ). toFixed ( 3 ) } g` );
this . dirtyInventory ( date );
}
stock ( input , actor ){
const kind = pick ( input . kind ,[ 'increase' , 'decrease' , 'transfer' , 'opening' , 'purchase' , 'adjustment' ], '库存动作' ); const date = day ( input . date ); const pocket = pick ( input . pocket , ACTIVE_POCKETS , '货盘' ); const note = text ( input . note , '备注' , 200 , true );
let mg = fixed ( input . grams , 3 , '克重' , kind === 'adjustment' ); if ( ! mg ) fail ( '克重不能为0' ); if ( kind === 'opening' || kind === 'adjustment' ) owner ( actor );
if ( kind === 'opening' && this . one ( 'SELECT id FROM movements WHERE pocket=? LIMIT 1' , pocket )) fail ( '该货盘已有流水,起始库存不能重复登记;差异请核查后调整' );
const group = randomUUID (); let cost = null ; if ( kind === 'purchase' && input . cost != null && input . cost !== '' ) cost = money ( input . cost , '本次采购总成本(仅留档,不重复扣订单利润)' );
const to = kind === 'transfer' ? pick ( input . to , ACTIVE_POCKETS , '目标货盘' ) : null ; if ( to === pocket ) fail ( '来源和目标货盘不能相同' );
// 独立调用也保持两边一起提交,任何库存校验失败都不会留下半笔或过期标记。
this . db . exec ( 'SAVEPOINT stock_movement' );
try {
if ( kind === 'transfer' ){
this . move ({ group , date , pocket , mg :- mg , kind , note }, actor ); this . move ({ group , date , pocket : to , mg , kind , note }, actor );
} else this . move ({ group , date , pocket , mg : kind === 'decrease' ?- mg : mg , kind , note , cost }, actor );
this . audit ( 'inventory' , '库存变动' , actor ,{ group , kind , date , pocket ,...( to ? { to } : {}), grams : input . grams , note });
2026-10-25 14:19:24 +08:00
InventoryChanges . register ( this , group , actor , priceLockEnv );
2026-10-17 19:50:24 +08:00
this . db . exec ( 'RELEASE stock_movement' ); return { group };
} catch ( e ){ this . db . exec ( 'ROLLBACK TO stock_movement' ); this . db . exec ( 'RELEASE stock_movement' ); throw e ;}
}
journal ( id , date , kind , sales , goods , expense ){ this . run ( 'INSERT INTO journal VALUES (?,?,?,?,?,?,?,?,?)' , randomUUID (), id , date , kind , sales , goods , expense , sales - goods - expense , now ()); this . dirty ( date );}
2026-10-23 09:49:36 +08:00
action ( id , action , input , actor , context = null ){
2026-10-25 14:19:24 +08:00
this . assertAccess ( 'order' , id , actor ); if ( Object . hasOwn ( input , 'member' )) this . selectedMember ( input , actor , this . entityMember ( 'order' , id ));
2026-10-26 14:44:07 +08:00
if ( context !== NEW_ORDER_ACTION &&! [ 'review' , 'print' ]. includes ( action )) this . guardRecoveryOrder ( id );
2026-10-23 11:58:19 +08:00
const o = this . detail ( id ); const date = day ( input . date || today (), actor . role === 'assistant' && [ 'expense' , 'fees' , 'refund' , 'return' ]. includes ( action ) ? '2000-01-01' : o . date );
2026-10-25 14:19:24 +08:00
if ( o . funds_mode === 'team' && ( action === 'settlement' || action === 'correct' && input . type === 'settlement' )) fail ( '三人新单请在成员间转款中登记实际付款,旧双方交款入口仅保留历史单据' );
2026-10-23 00:38:04 +08:00
if ( action === 'cancel' ) fail ( '取消订单须先提交取消申请,并由麦麦账号审批;旧取消接口不能直接作废订单' , 409 );
this . guardOrderCancellation ( id ,{ action , type : input . type });
2026-10-23 09:49:36 +08:00
this . guardOrderChange ( id ,{ action });
if ( action === 'material' ) owner ( actor );
2026-10-23 11:58:19 +08:00
let sameDayDirect = false ;
2026-10-23 09:49:36 +08:00
if ( actor . role !== 'owner' && context !== NEW_ORDER_ACTION ){
2026-10-23 11:58:19 +08:00
if ([ 'expense' , 'fees' , 'refund' , 'return' , 'cost' ]. includes ( action )){
if ( actor . role !== 'assistant' || action === 'cost' || o . date !== today () || date !== today ()) fail ( '这项订单变更须先提交复核申请;助理仅可直接保存原单日期和操作日期都为今天的费用、退款或退货' , 403 );
if ( ! Number . isSafeInteger ( input . revision ) || input . revision !== o . revision ) fail ( '订单有新变动,请保留输入并重新读取后核对' , 409 );
if ( input . verified !== true ) fail ( '请核实实际凭据与本次操作后勾选确认' );
text ( input . reason , '本次操作原因' , 200 ); sameDayDirect = true ;
}
2026-10-23 09:49:36 +08:00
if ( o . pendingFees . length && ( action === 'complete' || action === 'confirm' && input . feesVerified === true )) fail ( '本单还有待记费用,请先提交旧费用核实申请,由麦麦批准后继续交付' , 403 );
}
2026-10-22 17:06:32 +08:00
// 整单更正后旧错日期可能已全额冲零;审计行仍保留,但不能阻挡后续真实业务。
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 ;
2026-10-17 19:50:24 +08:00
if ([ 'return' , 'expense' , 'refund' , 'settlement' , 'correct' ]. includes ( action ) && financialDate && date < financialDate ) fail ( `该动作日期不能早于本单最近记账日 ${ financialDate } ` );
2026-10-22 17:06:32 +08:00
if ([ 'deliver' , 'return' , 'expense' , 'settlement' , 'cancel' , 'refund' , 'correct' ]. includes ( action ) && o . delivered_date && date < o . delivered_date ) fail ( '该动作日期不能早于交付日期' );
if ([ 'expense' , 'settlement' , 'refund' , 'correct' ]. includes ( action ) && o . returned_date && date < o . returned_date ) fail ( '该动作日期不能早于退货日期' );
2026-10-17 19:50:24 +08:00
if ( action === 'confirm' ){
if ( o . status !== 'draft' ) fail ( '订单已经确认,请刷新查看' , 409 );
if ( o . pendingFees . some ( f => f . status !== 'estimated' ) && input . feesVerified !== true ) fail ( '请核实开单所填快递、包装等费用已实际支付' );
if ( input . feesVerified === true && o . pendingFees . some ( f => f . amount === null )) fail ( '请补齐附加成本;没有发生的费用填0' );
for ( const p of POCKETS ){ const need = sum ( o . lines , l => l . pocket === p ? l . quantity : 0 ); if ( need > this . inventory (). find ( r => r . pocket === p ). available ) fail ( ` ${ p } 可用库存不足,请先登记入库` );}
this . run ( "UPDATE orders SET status='confirmed' WHERE id=?" , id );
2026-10-23 09:49:36 +08:00
if ( input . feesVerified === true && o . pendingFees . length ) this . recordFees ( o , o . pendingFees , o . fees_date || date , actor , context );
2026-10-17 19:50:24 +08:00
} else if ( action === 'receipt' || action === 'refund' ){
if ( input . verified !== true ) fail ( '请核实微信/支付宝/现金实际到账或退款后再勾选确认' );
if ( action === 'receipt' &&! [ 'confirmed' ]. includes ( o . status )) fail ( '仅待交付订单可以补收款' );
if ( action === 'refund' &&! [ 'cancelled' , 'returned' ]. includes ( o . status )) fail ( '先取消预订或登记整单退货,再记录实际退款' );
const amount = money ( input . amount ); if ( amount <= 0 || amount > ( action === 'receipt' ? o . balance : o . netReceived )) fail ( '金额超过本单待收/待退款余额' );
2026-10-25 14:19:24 +08:00
const account = paymentAccount ( input . account );
2026-10-17 19:50:24 +08:00
if ( action === 'refund' ){
2026-10-25 14:19:24 +08:00
const available = sum ( o . payments , p =>( CreditCardFees . isAccount ( account ) ? CreditCardFees . isAccount ( p . account ) : p . account === account ) ? ( p . kind === 'receipt' ? p . amount :- p . amount ) : 0 );
2026-10-17 19:50:24 +08:00
if ( amount > available ) fail ( '原收款账户可退余额不足;请从原收款账户退款并按账户拆笔登记' );
}
2026-10-25 14:19:24 +08:00
const feePayer = action === 'receipt' && account . endsWith ( '信用卡' ) ? pick ( input . credit_card_fee_payer ?? 'owner' ,[ 'owner' , 'assistant' , 'assistant2' ], '信用卡手续费付款人' ) : 'owner' , paymentId = randomUUID ();
2026-10-23 09:49:36 +08:00
this . run ( 'INSERT INTO payments VALUES (?,?,?,?,?,?,?,?,?)' , paymentId , id , date , action , amount , account , text ( input . reference , '收退款凭据备注' , 100 , true ), actor . name , now ());
this . recordCardFee ( id ,{ id : paymentId , date , kind : action , amount , account }, actor ,{ payer : feePayer });
2026-10-17 19:50:24 +08:00
} else if ( action === 'expense' ){
if ( o . status === 'draft' ) fail ( '请先确认订单,再登记实际费用' );
const amount = money ( input . amount ); if ( amount <= 0 ) fail ( '费用须大于0' );
2026-10-25 14:19:24 +08:00
const expenseId = randomUUID (), payer = pick ( input . payer ,[ 'owner' , 'assistant' , 'assistant2' ], '费用付款人' ), note = text ( input . note , '费用项目及原因' , 150 ), funding = input . funding === undefined ? undefined : fundingReference ( input . funding );
this . run ( 'INSERT INTO expenses VALUES (?,?,?,?,?,?,?,?)' , expenseId , id , date , amount , payer , note , actor . name , now ());
if ( funding ) this . run ( 'UPDATE orders SET fee_items=? WHERE id=?' , JSON . stringify ([... o . fee_items ,{ key : 'manual:' + expenseId , amount , payer , note , status : 'recorded' , expense_id : expenseId , funding }]), id );
2026-10-17 19:50:24 +08:00
if ([ 'delivered' , 'returned' , 'cancelled' ]. includes ( o . status )) this . journal ( id , date , '直接费用' , 0 , 0 , amount );
} else if ( action === 'fees' ){
if ( o . status !== 'confirmed' ||! o . pendingFees . length ) fail ( '本单没有待核实的附加成本' , 409 );
if ( input . revision !== o . revision ) fail ( '订单已更新,请重新打开成本核实' , 409 );
if ( input . verified !== true ) fail ( '请核实费用已实际支付,没有发生的填0' );
const fees = this . validateFees ( input . fee_items );
const keys = new Set ( o . pendingFees . map ( f => f . key ));
if ( fees . length !== keys . size || fees . some ( f => ! keys . has ( f . key ))) fail ( '请逐项核实本单预估成本,不要遗漏' );
2026-10-23 11:58:19 +08:00
this . recordFees ( o , fees , date , actor , sameDayDirect ? SAME_DAY_ORDER_ACTION : context );
2026-10-17 19:50:24 +08:00
} else if ( action === 'cost' ){
if ( o . status !== 'confirmed' ) fail ( '只能在交付前补齐成本;交付后成本已锁定' );
if ( ! Array . isArray ( input . costs ) || input . costs . length !== o . lines . length ) fail ( '请逐行填写成本' );
o . lines . forEach (( l , i )=>{
const value = input . costs [ i ];
if ( value && typeof value === 'object' ){
const costPayers = Calc . costPayers ( value . costPayers === undefined ? l . costPayers : value . costPayers );
2026-10-25 14:19:24 +08:00
const payer = value . payer === undefined ? l . payer : pick ( value . payer ,[ 'owner' , 'assistant' , 'assistant2' ], '成本垫资人' );
2026-10-21 01:32:49 +08:00
const result = Calc . purchaseCosts ({ name : l . name , costParts : value . parts || value , costMaterial : value . costMaterial , costLabor : value . costLabor , unit : l . unit , quantity : l . unit === 'g' ? ( l . quantity / 1000 ). toFixed ( 3 ) : l . quantity }); if ( result . total === null && result . costMaterial . mode !== 'pool' ) fail ( '请补齐每项成本;没有的项目填0' );
2026-10-17 19:50:24 +08:00
l . costParts = result . parts ; l . cost = result . total ; l . costMaterial = result . costMaterial ; l . costLabor = result . costLabor ; l . payer = payer ; if ( costPayers ) l . costPayers = costPayers ;
2026-10-21 01:32:49 +08:00
if ( l . costMaterial . mode === 'pool' ){
if ([ 'labor' , 'accessories' , 'other' ]. some ( key => l . costParts [ key ] == null )) fail ( '请补齐每项成本;没有的项目填0' );
} else delete l . materialPool ;
2026-10-17 19:50:24 +08:00
} else { if ( l . costParts ) fail ( '这行已拆分成本,请逐项填写' ); l . cost = money ( value , '货品成本' );}
});
2026-10-23 00:14:29 +08:00
MaterialPools . prepareLines ( this , o . lines , o . date , priceLockEnv ,{ orderId : id });
2026-10-17 19:50:24 +08:00
this . run ( 'UPDATE orders SET lines=? WHERE id=?' , JSON . stringify ( o . lines ), id );
} else if ( action === 'complete' ){
if ( o . status !== 'confirmed' ) fail ( '只有待交付订单可以完成交付' , 409 );
if ( input . revision != null && input . revision !== o . revision ) fail ( '订单有新变动,请重新打开后完成记账' , 409 );
if ( input . verified !== true ) fail ( '请确认已全额收款、核实费用并实际交付' );
if ( o . balance !== 0 ) fail ( '未收齐客户款,不能确认交付' );
this . validateCompletedCosts ( o . lines , o . fee_items );
// 老版本无 status 的费用可能已经入账,只有明确待核实的项目才能在此新增支出。
const fees = o . pendingFees ;
2026-10-23 09:49:36 +08:00
if ( fees . length ) this . recordFees ( o , fees , o . fees_date || date , actor , context );
this . action ( id , 'deliver' ,{ date , verified : true }, actor , context );
2026-10-17 19:50:24 +08:00
this . audit ( id , 'complete' , actor ,{... input , revision : this . rawOrder ( id ). revision }); return { id };
} else if ( action === 'deliver' ){
2026-10-21 01:32:49 +08:00
if ( o . status !== 'confirmed' ) fail ( '订单不在待交付状态' , 409 ); if ( o . balance !== 0 ) fail ( '未收齐客户款,不能确认交付' ); if ( o . goodsCost === null &&! o . materialCostPending ) fail ( '请先补齐货品成本,不能把空白当作0' );
this . validateCompletedCosts ( o . lines , o . fee_items );
2026-10-17 19:50:24 +08:00
if ( o . pendingFees . length ) fail ( '请先核实附加成本,没有发生的费用填0,不能把预估当作实际费用' );
if ( input . verified !== true ) fail ( '请确认已复称、收款核实并实际交给客户/快递' );
if ( o . payments . some ( p => p . date > date ) || o . expenses . some ( e => e . date > date )) fail ( '交付日期不能早于本单已登记的收款或费用日期' );
this . run ( "UPDATE orders SET status='delivered',delivered_date=? WHERE id=?" , date , id );
2026-10-21 01:32:49 +08:00
const delivered = MaterialPools . deliver ( this , o , date , actor , priceLockEnv );
2026-10-17 19:50:24 +08:00
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 );
2026-10-21 01:32:49 +08:00
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 );
2026-10-17 19:50:24 +08:00
} else if ( action === 'return' ){
if ( o . status !== 'delivered' ) fail ( '只有已交付订单可以整单退货' , 409 ); if ( input . verified !== true ) fail ( '请先确认实物已收回或退回供应商' );
2026-10-26 17:07:26 +08:00
RollingMaterialPools . recordReturns ( this , o , date , input , actor , priceLockEnv );
2026-10-17 19:50:24 +08:00
text ( input . reason , '退货原因' , 200 ); this . run ( "UPDATE orders SET status='returned',returned_date=? WHERE id=?" , date , id );
const group = randomUUID (); o . lines . forEach (( l , i )=>{
const destination = input . returnPockets ? .[ i ] ?? l . pocket ;
2026-10-21 01:32:49 +08:00
if ( l . costMaterial ? . mode === 'pool' &&! destination ) fail ( '日购料黄金退货须退回自有货盘,请选择实物退回的货盘;退供应商请先核实购料退款' );
2026-10-17 19:50:24 +08:00
if ( l . pocket &&! destination ) fail ( '原自有货盘商品须选择退回货盘' );
if ( destination ){ pick ( destination , destination === l . pocket ? POCKETS : ACTIVE_POCKETS , '退回货盘' ); if ( l . unit !== 'g' ) fail ( '按件商品不计黄金货盘' ); this . move ({ group , order : id , date , pocket : destination , mg : l . quantity , kind : 'return' , note : o . number }, actor );}
});
2026-10-21 01:32:49 +08:00
this . journal ( id , date , '整单退货' , - o . total , - o . knownGoodsCost , 0 );
MaterialPools . release ( this , o , date , actor , priceLockEnv );
2026-10-17 19:50:24 +08:00
} else if ( action === 'settlement' ){
if ( ! [ 'delivered' , 'returned' , 'cancelled' ]. includes ( o . status )) fail ( '定金阶段不结算货款和利润' );
2026-10-21 01:32:49 +08:00
if ( o . materialCostPending ) fail ( '日购料成本待补,补齐采购后再结算' );
2026-10-17 19:50:24 +08:00
const amount = money ( input . amount ); if ( amount <= 0 ) fail ( '交款须大于0' ); const bucket = pick ( input . bucket ,[ 'cost' , 'profit' ], '款项归属' );
const sign = pick ( input . direction ,[ 'toOwner' , 'toAssistant' ], '转款方向' ) === 'toOwner' ? 1 :- 1 ;
if ( input . verified !== true ) fail ( '请核实双方实际转账' );
// 麦麦直收的订单不猜如何分配货款与利润,由实际转款记录抵减总应结金额。
const due = o . ownerCredit ? o . settlementDue : ( bucket === 'cost' ? o . costDue : o . profitDue );
if ( Math . sign ( due ) !== sign || amount > Math . abs ( due )) fail ( '转款方向或金额超过本单应结余额,请核对实际流水' );
this . run ( 'INSERT INTO settlements VALUES (?,?,?,?,?,?,?,?)' , randomUUID (), id , date , bucket , sign * amount , text ( input . note , '交款凭据/说明' , 150 ), actor . name , now ());
2026-10-21 01:32:49 +08:00
} else if ( action === 'material' ){
return MaterialPools . reassign ( this , o , input , actor , priceLockEnv );
2026-10-17 19:50:24 +08:00
} else if ( action === 'correct' ){
owner ( actor ); const type = pick ( input . type ,[ 'payment' , 'expense' , 'settlement' ], '更正类型' ); const reason = text ( input . reason , '更正原因' , 200 );
if ( input . verified !== true ) fail ( '请核实原凭据和更正内容' );
2026-10-21 01:32:49 +08:00
if ( type === 'payment' && o . payments . some ( payment => payment . id === input . target && payment . price_lock_event_id )) fail ( '锁价实际收退款为不可改写的原始记录,不能从普通订单更正' );
2026-10-17 19:50:24 +08:00
const table = { payment : 'payments' , expense : 'expenses' , settlement : 'settlements' }[ type ]; const row = this . one ( `SELECT * FROM ${ table } WHERE id=? AND order_id=?` , String ( input . target ), id );
if ( ! row ) fail ( '原流水不存在' ); if ( date < row . date ) fail ( '更正日期不能早于原流水' );
2026-10-23 09:49:36 +08:00
if ( type === 'expense' && o . fee_items . some ( fee => isCardFee ( fee ) && fee . expense_id === row . id )) fail ( '信用卡手续费由原收款自动计算;请更正收款或在整单修改中调整手续费付款人' );
2026-10-17 19:50:24 +08:00
if ( this . one ( 'SELECT target FROM corrections WHERE target=?' , row . id ) || row . amount === 0 || row . reference ? . startsWith ( '更正冲回:' ) || row . note ? . startsWith ( '更正冲回:' )) fail ( '这条流水已冲回,请更正最新有效记录' );
const amount = money ( input . amount , '更正后金额' );
this . run ( 'INSERT INTO corrections VALUES (?,?,?,?,?)' , row . id , type , reason , actor . name , now ());
if ( type === 'payment' ){
2026-10-25 14:19:24 +08:00
const account = paymentAccount ( input . account );
const feePayer = account . endsWith ( '信用卡' ) && row . kind === 'receipt' ? pick ( input . credit_card_fee_payer ?? 'owner' ,[ 'owner' , 'assistant' , 'assistant2' ], '信用卡手续费付款人' ) : 'owner' ;
2026-10-17 19:50:24 +08:00
this . run ( 'INSERT INTO payments VALUES (?,?,?,?,?,?,?,?,?)' , randomUUID (), id , date , row . kind , - row . amount , row . account , '更正冲回:' + reason , actor . name , now ());
2026-10-25 14:19:24 +08:00
const originalFee = o . fee_items . find ( fee => isCardFee ( fee ) && fee . source_id === row . id ), unchangedCard = row . amount === amount && row . account === account ? originalFee : null ;
2026-10-23 09:49:36 +08:00
if ( row . kind === 'receipt' ) this . reverseCardFee ( id , row . id , date , actor , reason );
2026-10-25 14:19:24 +08:00
if ( amount ){ const paymentId = randomUUID (); this . run ( 'INSERT INTO payments VALUES (?,?,?,?,?,?,?,?,?)' , paymentId , id , date , row . kind , amount , account , '更正补记:' + reason , actor . name , now ()); this . recordCardFee ( id ,{ id : paymentId , date , kind : row . kind , amount , account }, actor ,{ payer : feePayer , recordedFee : unchangedCard });}
2026-10-21 01:32:49 +08:00
const updated = this . detail ( id ); if (( o . price_lock_id ? updated . netReceived : updated . received ) > updated . total || updated . netReceived < 0 ) fail ( '更正后收退款余额不合理,请核对金额' );
2026-10-17 19:50:24 +08:00
if ( o . status === 'delivered' && updated . netReceived !== o . total ) fail ( '已交付订单须保持收齐;收款账户可更正,金额差异请先核实真实交付情况' );
2026-10-21 01:32:49 +08:00
for ( const acc of ACCOUNTS ){
2026-10-25 14:19:24 +08:00
if ( CreditCardFees . isAccount ( acc ) && acc !== '麦麦信用卡' ) continue ;
const sameAccount = p => CreditCardFees . isAccount ( acc ) ? CreditCardFees . isAccount ( p . account ) : p . account === acc ;
2026-10-21 01:32:49 +08:00
// 锁价交付可明确从另一账户退差额;后续更正不能扩大该既有负净额。
2026-10-25 14:19:24 +08:00
const inherited = o . price_lock_id ? sum ( updated . payments , p => p . price_lock_event_id && sameAccount ( p ) ? ( p . kind === 'receipt' ? p . amount :- p . amount ) : 0 ) : 0 ;
if ( sum ( updated . payments , p => sameAccount ( p ) ? ( p . kind === 'receipt' ? p . amount :- p . amount ) : 0 ) < Math . min ( 0 , inherited )) fail ( '更正后原账户退款超过收款,请先核对关联退款记录' );
2026-10-21 01:32:49 +08:00
}
2026-10-17 19:50:24 +08:00
} else if ( type === 'expense' ){
this . run ( 'INSERT INTO expenses VALUES (?,?,?,?,?,?,?,?)' , randomUUID (), id , date , - row . amount , row . payer , '更正冲回:' + reason , actor . name , now ());
2026-10-25 14:19:24 +08:00
if ( amount ) this . run ( 'INSERT INTO expenses VALUES (?,?,?,?,?,?,?,?)' , randomUUID (), id , date , amount , pick ( input . payer ,[ 'owner' , 'assistant' , 'assistant2' ], '更正后付款人' ), '更正补记:' + reason , actor . name , now ());
2026-10-17 19:50:24 +08:00
if ([ 'delivered' , 'returned' , 'cancelled' ]. includes ( o . status )) this . journal ( id , date , '费用更正' , 0 , 0 , amount - row . amount );
} else {
this . run ( 'INSERT INTO settlements VALUES (?,?,?,?,?,?,?,?)' , randomUUID (), id , date , row . bucket , - row . amount , '更正冲回:' + reason , actor . name , now ());
if ( amount ) this . action ( id , 'settlement' ,{ date , amount : input . amount , bucket : input . bucket , direction : input . direction , note : '更正补记:' + reason , verified : true }, actor );
}
} else if ( action === 'review' ){
owner ( actor ); if ( input . revision !== o . revision ) fail ( '订单有新变动,请重新查看后复核' , 409 );
this . run ( 'UPDATE orders SET revision=revision+1,reviewed_revision=revision+1 WHERE id=?' , id ); this . audit ( id , '麦麦复核' , actor ,{ revision : o . revision + 1 }); this . enqueue ( 'order:' + id ); return { id };
} else if ( action === 'print' ){
this . audit ( id , '打开打印页' , actor ,{ mode : input . mode === 'overlay' ? '预印纸套打' : '完整单据' , notice : '不代表纸张已输出' }); return { id };
} else fail ( '不支持的订单操作' );
2026-10-23 11:58:19 +08:00
if ( sameDayDirect ) this . run ( 'UPDATE orders SET reviewed_revision=0 WHERE id=?' , id );
this . touch ( id ); this . dirty ( date ); this . audit ( id , action , actor ,{... input ,...( sameDayDirect ? { direct : true , directDate : date } : {}), revision : this . rawOrder ( id ). revision }); return { id };
2026-10-17 19:50:24 +08:00
}
publicOrder ( id ){
const o = this . detail ( id );
// 打印展示收款渠道,不以此推定到账。旧单尚无收款流水时沿用开单选择。
// 更正冲回的旧账户不再显示;实际分次使用不同方式时完整保留。
const receiptAccounts = ACCOUNTS . filter ( account => sum ( o . payments , p => p . kind === 'receipt' && p . account === account ? p . amount : 0 ) > 0 );
2026-10-25 14:19:24 +08:00
const paymentMethods = [... new Set (( receiptAccounts . length ? receiptAccounts : [ o . payment_account ]). map ( account => account . replace ( /^(助理2|助理1|助理|麦麦)/ , '' )))];
2026-10-26 14:44:07 +08:00
return { id : o . id ,...( this . teamMode ? { member : o . member } : {}),...( o . recovery_id ? { recovery_id : o . recovery_id , recovery_mode : 'exchange' , nonCashOffset : o . nonCashOffset , cashPaid : o . cashPaid , netSettlement : o . netSettlement } : {}), number : o . number , date : o . date , customer : o . customer , salesperson : o . salesperson , note : o . note , paper_number : o . paper_number , status : o . status , total : o . total , rounding_mode : o . rounding_mode , rounding_adjustment : o . rounding_adjustment , discount : o . discount , received : o . received , refunded : o . refunded , netReceived : o . netReceived , balance : o . balance , paymentMethods : o . recovery_id &&! o . netReceived ? [] : paymentMethods , lines : o . lines . map ( l =>({ name : l . name , code : l . code , unit : l . unit , quantity : l . quantity , sale : l . sale , baseSale : l . baseSale ?? l . sale , charges : ( l . charges || []). filter ( c => c . amount !== null ). map ( c =>({ name : c . name , amount : c . amount })), priceNote : l . priceNote ,...( l . pricingMode === 'auto' ? { pricingMode : 'auto' , goldPrice : l . goldPrice , laborRate : l . laborRate , laborMode : l . laborMode , pieces : l . pieces } : {})}))};
2026-10-17 19:50:24 +08:00
}
2026-10-21 01:32:49 +08:00
createPriceLock ( input , actor ){ return PriceLocks . create ( this , input , actor , priceLockEnv );}
priceLocks ( query = {}){ return PriceLocks . list ( this , query , priceLockEnv );}
priceLockDetail ( id ){ return PriceLocks . detail ( this , id , priceLockEnv );}
2026-10-23 09:49:36 +08:00
deliverPriceLock ( id , input , actor ){
2026-10-25 14:19:24 +08:00
return PriceLocks . deliver ( this , id , input , actor ,{... priceLockEnv , saveDeliveryOrder : input => this . saveOrder ({... input , member : this . entityMember ( 'price_lock' , id ) || this . memberFor ( actor )}, actor , PRICE_LOCK_DELIVERY ), completeNewOrder : ( orderId , date )=>{
2026-10-23 09:49:36 +08:00
this . action ( orderId , 'confirm' ,{ date }, actor , NEW_ORDER_ACTION );
this . action ( orderId , 'complete' ,{ date , verified : true }, actor , NEW_ORDER_ACTION );
}});
}
2026-10-21 01:32:49 +08:00
priceLockReporting ( query = {}){ return PriceLocks . reporting ( this , query , priceLockEnv );}
createMaterialPurchase ( input , actor ){ return MaterialPools . purchase ( this , input , actor , priceLockEnv );}
2026-10-26 17:07:26 +08:00
rollingMaterialPreview ( query = {}, actor = this . actor ){ return RollingMaterialPools . previewEnable ( this , query , actor , priceLockEnv );}
enableRollingMaterial ( input , actor = this . actor ){ return RollingMaterialPools . enable ( this , input , actor , priceLockEnv );}
requestMaterialPurchaseChange ( id , input , actor = this . actor ){ return MaterialPurchaseChanges . request ( this , id , input , actor , priceLockEnv );}
materialPurchaseChanges ( query = {}, actor = this . actor ){ return MaterialPurchaseChanges . list ( this , query , actor , priceLockEnv );}
materialPurchaseChange ( id , actor = this . actor ){ return MaterialPurchaseChanges . detail ( this , id , actor , priceLockEnv );}
approveMaterialPurchaseChange ( id , input , actor = this . actor ){ return MaterialPurchaseChanges . approve ( this , id , input , actor , priceLockEnv );}
rejectMaterialPurchaseChange ( id , input , actor = this . actor ){ return MaterialPurchaseChanges . reject ( this , id , input , actor , priceLockEnv );}
2026-10-25 14:19:24 +08:00
materialPoolAllocationStatus (){ const status = MaterialPools . allocationStatus ( this ); if ( this . teamMode && this . actor ? . role === 'assistant' ){ const usages = this . visibleRows ( 'order' , this . rows ( 'SELECT order_id,active FROM material_pool_usages' ), 'order_id' ); return {... status , usageCount : usages . length , activeUsageCount : usages . filter ( row => row . active ). length };} return status ;}
2026-10-23 00:14:29 +08:00
migrateMaterialPoolAllocation ( actor , options = {}){ return MaterialPools . migrateAllocation ( this , actor , priceLockEnv , options );}
2026-10-21 01:32:49 +08:00
materialPurchaseDetail ( id ){ return MaterialPools . purchaseDetail ( this , id , priceLockEnv );}
editMaterialPurchase ( id , input , actor ){ return MaterialPools . editPurchase ( this , id , input , actor , priceLockEnv );}
deleteMaterialPurchase ( id , input , actor ){ return MaterialPools . deletePurchase ( this , id , input , actor , priceLockEnv );}
materialPools ( query = {}){ return MaterialPools . list ( this , query , priceLockEnv );}
materialPoolDetail ( id ){ return MaterialPools . readPool ( this , id , priceLockEnv );}
materialPoolReporting ( query = {}){ return MaterialPools . reporting ( this , query , priceLockEnv );}
materialPoolSettlement (){ return MaterialPools . settlement ( this , priceLockEnv );}
settleMaterialPool ( id , input , actor ){ return MaterialPools . settle ( this , id , input , actor , priceLockEnv );}
2026-10-17 19:50:24 +08:00
saveAfterSale ( input , actor ){
if ( ! actor ||! [ 'owner' , 'assistant' ]. includes ( actor . role )) fail ( '请使用麦麦或助理账号登记售后' , 403 );
if ( ! input || typeof input !== 'object' || Array . isArray ( input )) fail ( '售后记录格式无效' );
if ( typeof input . project !== 'string' || typeof input . customer !== 'string' ) fail ( '售后项目和客户称呼须填写文字' );
const date = day ( input . date ), project = text ( input . project , '售后项目' , 100 ), customer = text ( input . customer , '客户称呼' , 60 );
2026-10-25 14:19:24 +08:00
const amount = money ( input . amount , '售后金额' ), payer = pick ( input . payer ,[ 'owner' , 'assistant' , 'assistant2' ], '费用付款人' ), id = randomUUID ();
const member = this . selectedMember ( input , actor );
2026-10-17 19:50:24 +08:00
this . run ( 'INSERT INTO after_sales(id,date,project,customer,amount,payer,actor,created) VALUES (?,?,?,?,?,?,?,?)' , id , date , project , customer , amount , payer , actor . name , now ());
2026-10-25 14:19:24 +08:00
this . assignMember ( 'after_sale' , id , member ,{ fresh : true });
2026-10-17 19:50:24 +08:00
// 售后属于所选日期的费用,不能使库存或其他日期的核对状态过期。
this . run ( 'UPDATE closes SET stale=1 WHERE date=?' , date );
this . audit ( 'after-sale:' + id , '登记售后' , actor ,{ date , project , customer , amount , payer });
return { after_sale_id : id , kind : 'afterSale' };
}
2026-10-25 14:19:24 +08:00
peopleCount ( date , actor = this . actor ){
day ( date ); const previousDate = previousPeopleDate ( date ), saved = new Map ( this . rows ( 'SELECT date,count,assistant1_count,assistant2_count,revision FROM daily_people_counts WHERE date IN (?,?)' , date , previousDate ). map ( row =>[ row . date , row ])), record = saved . get ( date );
const result = {... peopleDay ( date , record , saved . get ( previousDate ), peopleParts ( this , actor )), revision : record ? . revision ?? 0 };
if ( ! this . teamMode ) result . count = record ? . count ?? null ; return result ;
2026-10-17 19:50:24 +08:00
}
peopleCountSummary ( date , from = date ){
day ( date ); day ( from ); if ( from > date ) fail ( '开始日期不能晚于结束日期' );
2026-10-25 14:19:24 +08:00
const baselineDate = previousPeopleDate ( from ), saved = new Map ( this . rows ( 'SELECT date,count,assistant1_count,assistant2_count FROM daily_people_counts WHERE date>=? AND date<=? ORDER BY date' , baselineDate , date ). map ( row =>[ row . date , row ]));
const result = { from , date , baselineDate , mode : 'daily-total' ,... peoplePeriod ( date , from , saved , peopleParts ( this ))};
if ( ! this . teamMode ){ result . total = saved . get ( date ) ? . count ?? null ; result . recordedDays = [... saved . values ()]. filter ( row => row . date >= from ). length ;} return result ;
2026-10-17 19:50:24 +08:00
}
2026-10-24 16:09:45 +08:00
peopleCountHistory ( query = {}){
const current = today (), from = day ( query . from ?? current . slice ( 0 , 7 ) + '-01' ), date = day ( query . date ?? current );
const first = Date . parse ( from + 'T00:00:00Z' ), last = Date . parse ( date + 'T00:00:00Z' ), days = ( last - first ) / 86400000 + 1 ;
if ( from > date ) fail ( '开始日期不能晚于结束日期' ); if ( days > 366 ) fail ( '每次最多查看366天,请缩小日期范围' );
2026-10-25 14:19:24 +08:00
const baselineDate = previousPeopleDate ( from ), saved = new Map ( this . rows ( 'SELECT date,assistant1_count,assistant2_count FROM daily_people_counts WHERE date>=? AND date<=? ORDER BY date' , baselineDate , date ). map ( row =>[ row . date , row ]));
const rows = [], parts = peopleParts ( this );
2026-10-24 16:09:45 +08:00
for ( let i = 0 ; i < days ; i ++ ){
2026-10-25 14:19:24 +08:00
const date = new Date ( first + i * 86400000 ). toISOString (). slice ( 0 , 10 ); rows . push ( peopleDay ( date , saved . get ( date ), saved . get ( previousPeopleDate ( date )), parts ));
2026-10-24 16:09:45 +08:00
}
2026-10-25 14:19:24 +08:00
return { from , date , today : current , baselineDate , mode : 'daily-total' , rows , summary : peoplePeriod ( date , from , saved , parts )};
2026-10-24 16:09:45 +08:00
}
2026-10-17 19:50:24 +08:00
savePeopleCount ( input , actor ){
if ( ! actor ||! [ 'owner' , 'assistant' ]. includes ( actor . role )) fail ( '请使用麦麦或助理账号登记人数' , 403 );
if ( ! input || typeof input !== 'object' || Array . isArray ( input )) fail ( '人数记录格式无效' );
2026-10-25 14:19:24 +08:00
if ( this . teamMode && actor . role === 'assistant' ){ const other = this . memberFor ( actor ) === 'assistant' ? 'assistant2Count' : 'assistant1Count' ; if ( Object . hasOwn ( input , other ) || Object . hasOwn ( input , 'count' )) fail ( '只能登记本人的人数' , 403 );}
2026-10-24 16:09:45 +08:00
const date = day ( input . date ), submittedCount = Object . hasOwn ( input , 'count' ) ? peopleNumber ( input . count , '人数' ) : undefined ;
2026-10-17 19:50:24 +08:00
if ( ! Number . isSafeInteger ( input . revision ) || input . revision < 0 ) fail ( '人数记录版本无效,请刷新后再保存' );
2026-10-23 00:21:53 +08:00
const previous = this . one ( 'SELECT count,assistant1_count,assistant2_count,revision FROM daily_people_counts WHERE date=?' , date );
2026-10-17 19:50:24 +08:00
if ( input . revision !== ( previous ? . revision ?? 0 )) fail ( '该日人数已被更新,请刷新后核对再保存' , 409 );
2026-10-24 16:09:45 +08:00
// 新页面只填写两位助理;原人数保留旧值,新行用0满足旧表约束,不由分项求和。
const count = submittedCount ?? previous ? . count ?? 0 ;
// 旧页面或中断操作缺省的助理项仍保留,显式 null/空白才清为未记录。
const assistant1Count = Object . hasOwn ( input , 'assistant1Count' ) ? peopleNumber ( input . assistant1Count , '助理1人数' , true ) : previous ? . assistant1_count ?? null ;
const assistant2Count = Object . hasOwn ( input , 'assistant2Count' ) ? peopleNumber ( input . assistant2Count , '助理2人数' , true ) : previous ? . assistant2_count ?? null ;
2026-10-17 19:50:24 +08:00
const revision = input . revision + 1 , timestamp = now ();
2026-10-23 00:21:53 +08:00
const changed = this . run ( 'INSERT INTO daily_people_counts(date,count,assistant1_count,assistant2_count,revision,actor,created,updated) VALUES (?,?,?,?,?,?,?,?) ON CONFLICT(date) DO UPDATE SET count=excluded.count,assistant1_count=excluded.assistant1_count,assistant2_count=excluded.assistant2_count,revision=excluded.revision,actor=excluded.actor,updated=excluded.updated WHERE daily_people_counts.revision=?' , date , count , assistant1Count , assistant2Count , revision , actor . name , timestamp , timestamp , input . revision );
2026-10-17 19:50:24 +08:00
if ( changed . changes !== 1 ) fail ( '该日人数已被更新,请刷新后核对再保存' , 409 );
2026-10-23 00:21:53 +08:00
this . audit ( 'people-count:' + date , previous ? '更新人数' : '登记人数' , actor ,{ date , count , assistant1Count , assistant2Count , previousCount : previous ? . count ?? null , previousAssistant1Count : previous ? . assistant1_count ?? null , previousAssistant2Count : previous ? . assistant2_count ?? null , revision });
2026-10-25 14:19:24 +08:00
return this . peopleCount ( date , actor );
2026-10-17 19:50:24 +08:00
}
2026-10-26 17:07:26 +08:00
orderBook ( query = {}){ const member = TeamMembers . queryMember ( this , query , this . actor ) || this . memberFilter ; return this . scope ( this . actor ,()=> orderBook ( this , query ,{ today : today (), validateDay : day , pockets : POCKETS , accounts : this . teamMode ? ACCOUNTS : ACCOUNTS . filter ( account => ! account . startsWith ( '助理2' ))}), member );}
2026-10-25 14:19:24 +08:00
reportFor ( query = {}, actor = this . actor ){ const date = query . date || today (), from = query . from || date , basis = query . basis ; if ( basis !== undefined && basis !== 'orderDate' ) fail ( '对账日期口径无效' ); const member = TeamMembers . queryMember ( this , query , actor ); return this . scope ( actor ,()=> basis === 'orderDate' ? this . reportByOrderDate ( date , from , actor ) : this . report ( date , from ), member );}
orderTemplates ( query = {}){ return this . scope ( this . actor ,()=> OrderTemplates . list ( this ), TeamMembers . queryMember ( this , query , this . actor ));}
2026-10-22 04:21:26 +08:00
orderTemplate ( id ){ return OrderTemplates . detail ( this , id );}
saveOrderTemplate ( id , input , actor ){ return OrderTemplates . save ( this , id , input , actor );}
deleteOrderTemplate ( id , input , actor ){ return OrderTemplates . remove ( this , id , input , actor );}
2026-10-25 14:19:24 +08:00
reimbursementFundingOptions ( query = {}, actor = this . actor ){ return DailyFunds . fundingOptions ( this , query , actor , priceLockEnv );}
2026-10-23 09:49:36 +08:00
reimbursements ( query = {}, actor ){ return DailyFunds . list ( this , query , actor , priceLockEnv );}
createReimbursement ( input , actor ){ return DailyFunds . create ( this , input , actor , priceLockEnv );}
updateReimbursement ( id , input , actor ){ return DailyFunds . update ( this , id , input , actor , priceLockEnv );}
approveReimbursement ( id , input , actor ){ return DailyFunds . approve ( this , id , input , actor , priceLockEnv );}
rejectReimbursement ( id , input , actor ){ return DailyFunds . reject ( this , id , input , actor , priceLockEnv );}
confirmDailyOutlay ( input , actor ){ return DailyFunds . confirm ( this , input , actor , priceLockEnv );}
dailyFunds ( query = {}, actor ){ return DailyFunds . report ( this , query , actor , priceLockEnv , date => dailyFundsReceipts ( this , date ));}
reportByOrderDate ( date , from = date , actor = null ){ return reportByOrderDate ( this , date , from , actor , priceLockEnv );}
2026-10-17 19:50:24 +08:00
report ( date , from = date ){
day ( date ); day ( from ); if ( from > date ) fail ( '开始日期不能晚于结束日期' );
2026-10-25 14:19:24 +08:00
const j = this . visibleRows ( 'order' , this . rows ( 'SELECT j.*,o.number FROM journal j JOIN orders o ON o.id=j.order_id WHERE j.date>=? AND j.date<=? ORDER BY j.date,j.created' , from , date ), 'order_id' );
const payments = this . visibleRows ( 'order' , this . rows ( 'SELECT p.*,o.number FROM payments p JOIN orders o ON o.id=p.order_id WHERE p.date>=? AND p.date<=? ORDER BY p.date,p.created' , from , date ), 'order_id' );
2026-10-21 01:32:49 +08:00
payments . push (... this . priceLockReporting ({ from , to : date }). customerCash . map ( event =>({... event , price_lock_event_id : event . id })));
2026-10-25 14:19:24 +08:00
const settles = this . visibleRows ( 'order' , this . rows ( 'SELECT s.*,o.number FROM settlements s JOIN orders o ON o.id=s.order_id WHERE s.date>=? AND s.date<=? ORDER BY s.date,s.created' , from , date ), 'order_id' );
const afterSales = this . visibleRows ( 'after_sale' , this . rows ( 'SELECT * FROM after_sales WHERE date>=? AND date<=? ORDER BY date,created,id' , from , date ));
const orders = this . visibleRows ( 'order' , this . rows ( 'SELECT id FROM orders ORDER BY created DESC' )). map ( r => this . detail ( r . id ));
2026-10-17 19:50:24 +08:00
const accounts = ACCOUNTS . map ( account =>({ account , receipt : sum ( payments , p => p . account === account && p . kind === 'receipt' ? p . amount : 0 ), refund : sum ( payments , p => p . account === account && p . kind === 'refund' ? p . amount : 0 )}));
const warnings = []; for ( const o of orders ){
if ( o . status === 'confirmed' && o . pendingFees . length ) warnings . push ({ id : o . id , number : o . number , message : '附加成本待核实' });
2026-10-21 01:32:49 +08:00
if ( o . status === 'confirmed' && o . goodsCost === null || o . status === 'delivered' && o . materialCostPending ) warnings . push ({ id : o . id , number : o . number , message : o . materialCostPending ? '日购料成本待补,利润与结算暂不确认' : '成本待补' });
2026-10-17 19:50:24 +08:00
if ([ 'returned' , 'cancelled' ]. includes ( o . status ) && o . netReceived > 0 ) warnings . push ({ id : o . id , number : o . number , message : `客户退款待登记: ${ ( o . netReceived / 100 ). toFixed ( 2 ) } 元` });
if ( o . status !== 'draft' && o . reviewed_revision !== o . revision ) warnings . push ({ id : o . id , number : o . number , message : '有记录待麦麦复核' });
2026-10-21 01:32:49 +08:00
if ( o . ownerDirect !== 0 ) warnings . push ({ id : o . id , number : o . number , message : o . status === 'delivered' ? '麦麦直接收客户款,已扣减总待结金额;货款/利润拆分需单独复核' : o . status === 'confirmed' ? '定金由麦麦直接收取,预订阶段不结算' : o . price_lock_id && o . status === 'returned' && o . netReceived === 0 ? '跨账户收退款差额已纳入双方结算' : '麦麦原收款账户仍有待退客户款,不计为应返助理' });
2026-10-17 19:50:24 +08:00
}
const check = this . one ( 'SELECT COALESCE(SUM(sales-goods-expense-profit),0) AS delta FROM journal' ). delta ;
if ( check ) warnings . push ({ message : '利润流水计算不一致,需要维护者检查' });
2026-10-21 01:32:49 +08:00
const close = this . one ( 'SELECT * FROM closes WHERE date=?' , date ), poolSettlement = this . materialPoolSettlement (), poolActivity = this . materialPoolReporting ({ from , to : date });
const pendingMaterialOrders = orders . filter ( o => o . status === 'delivered' && o . materialCostPending && j . some ( row => row . order_id === o . id ));
const hasPendingSettlement = orders . some ( o => o . settlementDue === null ) || poolSettlement . pendingCount > 0 ;
const pendingIds = new Set ( pendingMaterialOrders . map ( order => order . id ));
const knownProfit = sum ( j . filter ( row => ! pendingIds . has ( row . order_id )), 'profit' ) - sum ( afterSales , 'amount' ), knownSettlementDue = sum ( orders , o => o . knownSettlementDue ) + poolSettlement . knownSettlementDue ;
return { date , from , sales : sum ( j , 'sales' ), goods : pendingMaterialOrders . length ? null : sum ( j , 'goods' ), knownGoods : sum ( j , 'goods' ), expense : sum ( j , 'expense' ) + sum ( afterSales , 'amount' ), profit : pendingMaterialOrders . length ? null : knownProfit , knownProfit , materialCostPending : pendingMaterialOrders . length > 0 , pendingMaterialCount : pendingMaterialOrders . length ,
materialPoolActivity : poolActivity , materialPoolSettlement : poolSettlement ,
2026-10-25 14:19:24 +08:00
delivered : orders . filter ( o => ! o . cancellationApproved && o . delivered_date >= from && o . delivered_date <= date ). length , returns : j . filter ( r => r . kind === '整单退货' ). length , accounts , payments , settlements : settles , journal : j . map ( row => pendingIds . has ( row . order_id ) ? {... row , goods : null , profit : null , materialCostPending : true } : row ), afterSales , afterSaleCount : afterSales . length , inventory : this . inventory ( date ), warnings , unsettled : orders . filter ( o => o . settlementDue !== 0 ). map ( o =>({ id : o . id , number : o . number , date : o . delivered_date || o . date , status : o . status , costDue : o . costDue , profitDue : o . profitDue , ownerDirect : o . ownerDirect , total : o . settlementDue , materialCostPending : o . materialCostPending })), settlementDue : hasPendingSettlement ? null : sum ( orders , 'settlementDue' ) + poolSettlement . settlementDue , knownSettlementDue , customerBalance : sum ( orders , o => o . status === 'confirmed' ? o . balance : 0 ), close : close && ( ! this . teamMode || this . actor ? . role !== 'assistant' ) ? { date : close . date , actor : close . actor , created : close . created , stale :!! close . stale } : null };
2026-10-17 19:50:24 +08:00
}
closeDay ( date , actor , basis ){
owner ( actor ); if ( basis !== undefined && basis !== 'orderDate' ) fail ( '对账日期口径无效' );
const report = basis === 'orderDate' ? this . reportByOrderDate ( day ( date )) : this . report ( day ( date ));
this . run ( 'INSERT INTO closes VALUES (?,?,?,?,0) ON CONFLICT(date) DO UPDATE SET report=excluded.report,actor=excluded.actor,created=excluded.created,stale=0' , date , JSON . stringify ( report ), actor . name , now ());
const snapshot = this . saveInventorySnapshot ( date , actor );
this . audit ( 'day:' + date , '保存核对快照' , actor ,{ warnings : report . warnings . length ,...( basis ? { basis } : {}), notice : '有待核项不等于已封账;补录会标记快照过期' });
return { date , snapshot ,...( basis ? { basis , reportRevision : report . reportRevision } : {})};
}
async backupTo ( filename ){ fs . mkdirSync ( path . dirname ( filename ),{ recursive : true , mode : 0o700 }); await backup ( this . db , filename ); fs . chmodSync ( filename , 0o600 ); return filename ;}
close (){ this . db . close ();}
}
module . exports = { Ledger , POCKETS , ACTIVE_POCKETS , ACCOUNTS , today , day , money , weight , fail , text , owner , now };