2026-10-17 19:50:24 +08:00
'use strict' ;
const $ = s => document . querySelector ( s );
const e = s => String ( s ?? '' ). replace ( /[&<>"']/g , c =>({ '&' : '&' , '<' : '<' , '>' : '>' , '"' : '"' , "'" : ''' }[ c ]));
const yuan = n => n == null ? '待补' : ( n / 100 ). toLocaleString ( 'zh-CN' ,{ minimumFractionDigits : 2 , maximumFractionDigits : 2 });
const grams = n =>( n / 1000 ). toFixed ( 3 );
2026-10-26 14:44:07 +08:00
const label = { draft : '旧草稿' , confirmed : '旧单待补齐' , delivered : '已完成' , returned : '已退货' , cancelled : '已取消' , after_sale : '售后' , recovery : '回收' };
2026-10-26 20:25:31 +08:00
const actionName = { confirm : '确认订单' , receipt : '登记收款' , refund : '登记退款' , expense : '直接费用' , fees : '补记旧单费用' , cost : '补齐货品成本' , deliver : '完成销售记账' , complete : '补齐旧单账务' , cancel : '取消订单' , return : '整单退货' , settlement : '实际交款' , review : '麦麦复核' , correct : '更正流水' , ownership : '修改订单归属' };
2026-10-17 19:50:24 +08:00
let state , session , tab = 'create' , currentOrder = null , editDraft = null , busy = false , reportDate = '' , currentReport = null , reportMonth = false ;
let reportRequest = 0 , reportDateInitialized = false , reportLoadedUser = '' ;
let peopleRequest = 0 , peopleEntry = null , peopleEntryUser = '' ;
2026-10-24 16:09:45 +08:00
let peopleHistoryRequest = 0 , peopleHistoryToday = '' ;
2026-10-28 00:22:04 +08:00
let afterSaleEntry = null , afterSaleRequest = 0 , afterSaleDialogBound = null ;
let afterSaleChangesStatus = 'pending' , afterSaleChangesRequest = 0 , afterSaleReviewEntry = null , afterSaleChangesDialogBound = null ;
2026-10-17 19:50:24 +08:00
let printSettingsSaving = false ;
2026-10-23 00:38:04 +08:00
let orderCopyLoading = false , orderDetailRequest = 0 ;
2026-10-23 09:49:36 +08:00
let orderBookDetailList = null , orderBookDetailVersion = 0 ;
let orderDetailNavigation = null , orderDetailLoad = null , orderDetailRetry = null , orderDetailSwitchError = '' , orderDetailListChanged = false , orderDetailDialogBound = null ;
2026-10-22 04:21:26 +08:00
const showOrderCopyEntry = false ; // 复制新增入口暂时隐藏;需要恢复时改为 true。
2026-10-17 19:50:24 +08:00
let orderBookFilters = null , orderBookUser = '' , orderBookRequest = 0 , orderBookTimer = null , orderBookDayChecking = false ;
let inventoryPage = null , inventoryRequest = 0 , inventoryHistoryOpen = false , inventoryHistoryMode = 'month' , inventoryHistoryDate = '' , inventoryHistoryRequest = 0 ;
2026-10-26 22:46:55 +08:00
let inventoryMovementPocket = '' , inventoryMovementKind = 'all' , inventoryMovementPage = 1 , inventoryMovementPockets = [], inventoryMovementPagination = null , inventoryMovementsRequest = 0 ;
2026-10-31 14:59:30 +08:00
let inventoryExporting = false ;
2026-11-08 03:30:58 +08:00
const opts = ( values , selected )=> values . map ( v =>{ const [ value , name , disabled ] = Array . isArray ( v ) ? v : [ v , v ]; return `<option value=" ${ e ( value ) } " ${ value === selected ? 'selected' : '' }${ disabled ? ' disabled' : '' } > ${ e ( /^(助理2|助理1|助理|麦麦)(微信|支付宝|现金|信用卡)$/ . test ( name ) ? accountDisplayName ( name ) : name ) } </option>` ;}). join ( '' );
const defaultPocketKeys = [ '现货' , '金料' , '找金' , '回收旧料' , '君宝汇' ];
function activePocketKeys (){ return Array . isArray ( state ? . pockets ) ? state . pockets : defaultPocketKeys ;}
function pocketLabel ( key ){ return state ? . pocketCatalog ? . find ( row => row . key === key ) ? . name || String ( key ?? '' );}
function pocketOptions ( selected = '' , historical = false ){
const keys = activePocketKeys (), options = keys . map ( key =>[ key , pocketLabel ( key )]);
if ( selected &&! keys . includes ( selected )) options . push ([ selected , pocketLabel ( selected ) + ( historical ? '(已停用 · 原货盘)' : '(已停用,请重新选择)' ), true ]);
return options ;
}
function pocketChoice ( title , name , selected = '' ,{ historical = false , blank = '外配/不扣黄金' } = {}){
const inactive = selected &&! activePocketKeys (). includes ( selected );
return choice ( title , name ,[...( blank === null ? [] : [[ '' , blank ]]),... pocketOptions ( selected , historical )], selected ) + ( inactive &&! historical ? '<p class="small danger-text pocket-selection-note">原货盘已停用,请重新选择已启用货盘,或明确选择外配。</p>' : '' );
}
function validateNewPocketSelections ( form ){
for ( const select of form . querySelectorAll ( 'select[name="pocket"]' )) if ( select . value &&! activePocketKeys (). includes ( select . value ) && select . closest ( '.line-item' ) ? . dataset . historicalPocket !== 'true' ) throw new Error ( '货盘「' + pocketLabel ( select . value ) + '」已停用,请重新选择已启用货盘,或明确选择外配。' );
}
2026-10-17 19:50:24 +08:00
const field = ( title , name , value = '' , type = 'text' , extra = '' )=> `<label> ${ e ( title ) } <input name=" ${ name } " value=" ${ e ( value ) } " type=" ${ type } " ${ extra } ></label>` ;
const choice = ( title , name , values , selected )=> `<label> ${ e ( title ) } <select name=" ${ name } "> ${ opts ( values , selected ) } </select></label>` ;
const moneyField = ( title , name , value = '' )=> field ( title , name , value , 'number' , 'min="0" step="0.01" required' );
const dateField = ( name = 'date' , value )=> field ( '业务日期' , name , value || state . today , 'date' , `max=" ${ state . today } " required` );
const button = ( text , action , cls = '' , attrs = '' )=> `<button type="button" data-action=" ${ action } " class=" ${ cls } " ${ attrs } > ${ text } </button>` ;
const badge = o => `<span class="order-status ${ [ 'draft' , 'confirmed' ]. includes ( o . status ) ? 'danger-text' : 'muted' } "> ${ e ( label [ o . status ] || o . status ) } </span>` ;
const card = ( title , value , hint = '' , emphasis = false )=> `<div class="stat ${ emphasis ? 'emphasis' : '' } "><small> ${ title } </small><strong> ${ value } </strong><div class="hint"> ${ hint } </div></div>` ;
function toast ( message , error = false ){ const t = $ ( '#toast' ); t . textContent = message ; t . className = error ? 'error-toast' : '' ; t . hidden = false ; clearTimeout ( toast . timer ); toast . timer = setTimeout (()=> t . hidden = true , error ? 9000 : 3500 );}
2026-10-29 00:27:36 +08:00
const MUTATION_RETRY = Symbol ( 'mutationRetry' );
const requestBackoffs = [ 400 , 1200 ];
const requestProgress = new Map ();
const requestUser = ()=> session ? session . user ? . id || '' : state ? . user ? . id || '' ;
function accountChangedError (){ return Object . assign ( new Error ( '登录账号已切换,请刷新后继续;原操作已暂停。' ),{ status : 409 , code : 'ACCOUNT_CHANGED' });}
function showRequestProgress ( token , message = '' ){
if ( message ) requestProgress . set ( token , message ); else requestProgress . delete ( token );
const text = [... requestProgress ]. filter (([ key ])=> key . user === requestUser ()). sort (([ a ],[ b ])=> Number ( a . write ) - Number ( b . write )). at ( - 1 ) ? .[ 1 ] || '' ;
2026-11-02 18:55:10 +08:00
for ( const selector of [ '#request-status' , '#order-edit-save-status' ]){ const target = $ ( selector ); if ( target ){ target . hidden =! text ; target . textContent = text ;}}
2026-10-29 00:27:36 +08:00
for ( const dialog of document . querySelectorAll ( 'dialog[open]' )){
let notice = dialog . querySelector ( '.request-progress' );
if ( text &&! notice ){ notice = document . createElement ( 'p' ); notice . className = 'request-progress small muted' ; notice . setAttribute ( 'role' , 'status' ); dialog . append ( notice );}
if ( notice ){ notice . textContent = text ; notice . hidden =! text ;}
}
}
function retryableMutation ( url ){
// 只有服务端事务幂等入口可自动确认;密码、备份、同步及新未知接口不在这里。
2026-11-08 03:30:58 +08:00
return [ '/api/orders' , '/api/orders/issue' , '/api/people-count' , '/api/after-sales' , '/api/recoveries' , '/api/material-purchases' , '/api/material-pools/rolling-enable' , '/api/price-locks' , '/api/order-templates' , '/api/reimbursements' , '/api/daily-funds/confirm' , '/api/team-funds/transfers' , '/api/team-funds/transfer' , '/api/stock' , '/api/inventory/review' , '/api/pockets' , '/api/close' , '/api/printing' ]. includes ( url ) || [
/^\/api\/pockets\/[^/]+\/update$/ ,
2026-10-29 00:27:36 +08:00
/^\/api\/orders\/[^/]+\/(?:edit|ownership|change|cancellation|canceltoday|confirm|receipt|refund|expense|fees|cost|deliver|complete|cancel|return|settlement|review|correct|print)$/ ,
2026-11-08 02:22:58 +08:00
/^\/api\/(?:order-templates\/[^/]+\/(?:update|delete)|reimbursements\/[^/]+\/(?:update|approve|reject)|price-locks\/[^/]+\/(?:deliver|edit|cancel|change-requests)|price-lock-changes\/[^/]+\/(?:approve|reject)|material-purchases\/[^/]+\/(?:edit|delete|change)|material-pools\/\d{4}-\d{2}-\d{2}\/settlement|after-sales\/[^/]+\/update|after-sales\/changes\/[^/]+\/(?:approve|reject)|(?:order-changes|order-ownership-changes|order-cancellations|material-purchase-changes)\/[^/]+\/(?:approve|reject)|inventory\/movements\/[^/]+\/(?:update|delete)|inventory\/changes\/[^/]+\/(?:approve|reject))$/
2026-10-29 00:27:36 +08:00
]. some ( pattern => pattern . test ( url ));
}
async function api ( url , data , operation , retryContext ){
const write =!! data , body = write ? JSON . stringify ( data ) : undefined ;
const protectedRequest = url . startsWith ( '/api/' ) &&! [ '/api/session' , '/api/login' , '/api/setup' , '/api/demo-login' ]. includes ( url ), user = protectedRequest ? ( retryContext ? . user || requestUser ()) : '' ;
const retry =! write || retryContext ? . permission === MUTATION_RETRY && retryableMutation ( url ) && /^[a-zA-Z0-9_-]{16,100}$/ . test ( operation || '' );
const token = { user : user || requestUser (), write }, active = ()=> ! user || requestUser () === user ;
if ( write && retryContext ) showRequestProgress ( token , '正在保存,请稍候…' );
try {
for ( let attempt = 0 ;; attempt ++ ){
if ( ! active ()) throw accountChangedError ();
const controller = new AbortController (), timer = setTimeout (()=> controller . abort (), 25000 );
try {
const r = await fetch ( url ,{ method : write ? 'POST' : 'GET' , headers : {...( write ? { 'Content-Type' : 'application/json' , 'X-Requested-With' : 'maimai-ledger' ,...( operation ? { 'Idempotency-Key' : operation } : {})} : {}),...( user ? { 'X-Ledger-User' : user } : {})},...( write ? { body } : {}), signal : controller . signal });
// 网关可能返回HTML,先按状态识别,不能让JSON解析失败掩盖502等。
if ([ 408 , 502 , 503 , 504 ]. includes ( r . status )) throw Object . assign ( new Error ( '服务器暂时没有响应(' + r . status + ') ' ),{ status : r . status , retryable : true });
2026-10-31 14:59:30 +08:00
const binary = r . ok && retryContext ? . responseType === 'xlsx' ;
if ( binary && r . headers . get ( 'content-type' ) ? . split ( ';' )[ 0 ] !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ) throw Object . assign ( new Error ( '导出文件格式异常,请重新导出。' ),{ confirmed : true , status : r . status });
let result ; try { result = binary ? { blob : await r . blob (), contentDisposition : r . headers . get ( 'content-disposition' )} : await r . json ();} catch ( error ){ if ( r . ok ){ error . retryable = true ; throw error ;} result = null ;}
2026-10-29 00:27:36 +08:00
if ( ! r . ok ){ const confirmed =!! result && typeof result . error === 'string' ; throw Object . assign ( new Error ( confirmed ? result . error : '请求被拒绝(' + r . status + '),服务器未返回可确认的业务结果。' ),{ confirmed , status : r . status ,...( result ? . code ? { code : result . code } : {})});}
if ( ! active ()) throw Object . assign ( accountChangedError (),{ completed : true });
return result ;
} catch ( err ){
if ( ! active () && err . code !== 'ACCOUNT_CHANGED' ) throw accountChangedError ();
const transient = err . retryable ||! err . status && [ 'TypeError' , 'AbortError' , 'TimeoutError' ]. includes ( err . name );
if ( ! retry ||! transient || attempt >= requestBackoffs . length ) throw err ;
showRequestProgress ( token , '连接暂时中断,正在自动' + ( write ? '确认' : '重连' ) + '( ' + ( attempt + 1 ) + '/2)…' );
await new Promise ( resolve => setTimeout ( resolve , requestBackoffs [ attempt ]));
} finally { clearTimeout ( timer );}
}
} finally { showRequestProgress ( token );}
2026-10-17 19:50:24 +08:00
}
const pendingKey = ()=> `mm-pending- ${ session ? . user ? . id } ` ;
function pending (){ try { return JSON . parse ( localStorage . getItem ( pendingKey ()) || 'null' );} catch { return null ;}}
2026-10-29 00:27:36 +08:00
function showPending (){ const p = pending (), target = $ ( '#pending' ); if ( ! target ) return ; target . hidden =! p || busy ; if ( p &&! busy ) target . innerHTML = `上次提交结果尚未确认,请先恢复原操作。重试会使用同一个操作号。 ${ button ( '恢复原操作' , 'retry' , 'danger' ) } ` ;}
function clearPendingJob ( storageKey , job ){ try { if ( JSON . parse ( localStorage . getItem ( storageKey ) || 'null' ) ? . key === job . key ) localStorage . removeItem ( storageKey );} catch {}}
2026-10-17 19:50:24 +08:00
async function mutate ( url , data , existing ){
if ( busy ) throw new Error ( '正在保存,请稍候' ); if ( pending () &&! existing ) throw new Error ( '请先点击顶部“恢复原操作”,确认上次提交结果' );
2026-10-29 00:27:36 +08:00
const user = requestUser (); if ( ! user ) throw new Error ( '请先登录后再保存' );
// 首次发送前复制完整请求,表单继续变动也不能改变自动重试的内容。
const job = JSON . parse ( JSON . stringify ( existing || { url , data , key : crypto . randomUUID (), userId : user })), storageKey = pendingKey ();
if ( existing && ( job . userId && job . userId !== user || JSON . stringify ( pending ()) !== JSON . stringify ( existing ))) throw new Error ( '待恢复操作与当前账号不匹配,请刷新后核对。' );
busy = true ;
const buttons = [... document . querySelectorAll ( 'button' )]. map ( button =>[ button , button . disabled ]);
try {
localStorage . setItem ( storageKey , JSON . stringify ( job )); showPending (); buttons . forEach (([ button ])=> button . disabled = true );
const r = await api ( job . url , job . data , job . key ,{ permission : MUTATION_RETRY , user }); clearPendingJob ( storageKey , job ); return r ;
} catch ( err ){
if ( err . completed || err . code !== 'ACCOUNT_CHANGED' && err . confirmed && [ 400 , 403 , 404 , 409 , 413 ]. includes ( err . status )) clearPendingJob ( storageKey , job );
if ( err . code !== 'ACCOUNT_CHANGED' ){
if ( err . status === 401 ) err . message = '登录已过期,请刷新并登录,再恢复原操作。' ;
else if ( ! err . confirmed && ( ! err . status || err . retryable )) err . message = '连接中断,提交结果待确认。请点“恢复原操作”,不要重新开单。' ;
else if ( ! err . confirmed ) err . message += ' 提交结果仍待确认,请保留原操作。' ;
}
throw err ;
2026-11-08 03:30:58 +08:00
} finally { busy = false ; buttons . forEach (([ button , disabled ])=> button . disabled = disabled ); showPending (); applyAfterSaleRestrictions (); if ( typeof applyOrderCancellationRestrictions === 'function' ) applyOrderCancellationRestrictions (); if ( typeof applyOrderChangeRestrictions === 'function' ) applyOrderChangeRestrictions (); if ( typeof applyOrderOwnershipRestrictions === 'function' ) applyOrderOwnershipRestrictions (); if ( typeof applyOrderEditRestrictions === 'function' ) applyOrderEditRestrictions (); if ( typeof applyDailyFundsRestrictions === 'function' ) applyDailyFundsRestrictions (); if ( typeof applyInventoryChangeRestrictions === 'function' ) applyInventoryChangeRestrictions (); if ( typeof applyRecoveryRestrictions === 'function' ) applyRecoveryRestrictions (); if ( typeof applyMaterialRollingRestrictions === 'function' ) applyMaterialRollingRestrictions (); updateOrderDetailNavigation (); if ( typeof applyPocketManagerRestrictions === 'function' ) applyPocketManagerRestrictions ();}
2026-10-17 19:50:24 +08:00
}
async function init (){
2026-11-08 03:30:58 +08:00
if ( typeof invalidatePocketManager === 'function' ) invalidatePocketManager ();
2026-11-04 22:18:56 +08:00
if ( typeof invalidateRecoveryChangeViews === 'function' ) invalidateRecoveryChangeViews ();
2026-10-28 00:22:04 +08:00
invalidateAfterSaleViews ();
2026-10-26 20:25:31 +08:00
if ( typeof invalidateOrderOwnershipViews === 'function' ) invalidateOrderOwnershipViews ();
2026-10-25 14:19:24 +08:00
invalidatePeopleEntry (); const peopleDialog = $ ( '#people-count-dialog' ); if ( peopleDialog ){ peopleDialog . close (); peopleDialog . innerHTML = '' ;}
2026-10-26 22:46:55 +08:00
if ( typeof invalidateInventoryChangeViews === 'function' ) invalidateInventoryChangeViews (); ++ inventoryRequest ; ++ inventoryHistoryRequest ; inventoryPage = null ; invalidateInventoryMovementViews ( true );
2026-10-24 16:09:45 +08:00
closePeopleCountHistory ();
2026-10-23 09:49:36 +08:00
invalidateOrderDetailView ( true ); orderBookDetailList = null ; ++ orderBookRequest ; clearTimeout ( orderBookTimer );
2026-10-22 17:06:32 +08:00
try { session = await api ( '/api/session' ); if ( ! session . user ) return login (); $ ( '#login' ). innerHTML = '' ; $ ( '#shell' ). hidden = false ; restoreOrderEditTab (); await refresh (); showPending ();} catch ( err ){ $ ( '#login' ). innerHTML = `<div class="login-wrap"><h1>系统暂时没有连接上</h1><p> ${ e ( err . message ) } </p><p>请保持启动窗口打开,再刷新页面。</p></div>` ;}
2026-10-17 19:50:24 +08:00
}
function login (){
$ ( '#shell' ). hidden = true ;
const intro = session . mode === 'demo' ? '用虚构订单练习完整流程,演示数据与新账隔离。' : '先设置账号。当前是本机试用,正式云端开账另行配置。' ;
2026-11-03 01:15:41 +08:00
$ ( '#login' ). innerHTML = `<section class="login-wrap"><div class="brand-mark">麦</div><h1>麦麦珠宝 · 新账系统</h1><p class="muted"> ${ session . setup || session . mode === 'demo' ? intro : '录入、收款与复核,从同一张订单开始。' } </p><div id="login-error"></div> ${ session . mode === 'demo' ? ` ${ button ( '以麦麦身份进入演示' , 'demo-owner' , 'primary' ) }${ button ( '以娜娜身份进入演示' , 'demo-assistant' ) }${ button ( '以小昊身份进入演示' , 'demo-assistant2' ) } ` : session . setup ? `<form id="setup-form"> ${ field ( '麦麦密码(至少12个字符)' , 'ownerPassword' , '' , 'password' , 'required minlength="12" autocomplete="new-password"' ) }${ field ( '娜娜密码(至少12个字符)' , 'assistantPassword' , '' , 'password' , 'required minlength="12" autocomplete="new-password"' ) } <button class="primary">建立试用账号</button></form>` : `<form id="login-form"> ${ choice ( '账号' , 'name' ,[[ '麦麦' , '麦麦' ],[ '助理1' , '娜娜' ],[ '助理2' , '小昊' ]], '麦麦' ) }${ field ( '密码' , 'password' , '' , 'password' , 'required autocomplete="current-password"' ) } <button class="primary">登录</button></form>` } <p class="small muted" style="margin-top:25px">云端数据库和飞书同步的真实状态,会在系统内显示。</p></section>` ;
2026-10-17 19:50:24 +08:00
}
2026-11-03 01:15:41 +08:00
async function refresh ( renderPage = true , stillCurrent ){ const latest = await api ( '/api/state' ); if ( stillCurrent &&! stillCurrent ()) return ; state = latest ; $ ( '#identity' ). textContent = state . user . label || state . user . name ; $ ( '#mode' ). textContent = state . mode === 'demo' ? '三人功能预览 · 虚构数据' : state . mode === 'production' ? '云端系统' : '本机试用' ; $ ( '#notice' ). textContent = state . mode === 'production' ? `主账保存于云端服务器。飞书 ${ state . sync . enabled ? '待同步 ' + state . sync . pending + ' 项' : '尚未连接' } 。` : state . mode === 'demo' ? '三人功能预览·虚构数据,可切换麦麦、娜娜、小昊练习。此预览使用独立样例账本,不影响原账;不会写入飞书。' : '当前为本机试用数据,请先练习核对。正式云端数据库尚未部署;不会写入原飞书账。' ; if ( renderPage ) await render ();}
2026-10-17 19:50:24 +08:00
function heading ( kicker , title , desc , actions = '' ){ return `<div class="page-heading"><div><div class="eyebrow"> ${ kicker } </div><h1> ${ title } </h1><p class="muted"> ${ desc } </p></div><div class="actions"> ${ actions } </div></div>` ;}
async function render (){
window . scrollTo ( 0 , 0 );
2026-11-06 01:29:35 +08:00
if ( tab === 'team-funds' && state . user . role !== 'owner' ) tab = 'report' ;
document . querySelectorAll ( 'nav button' ). forEach ( b =>{ if ( b . dataset . tab === 'team-funds' ) b . hidden = b . disabled = state . user . role !== 'owner' ; b . classList . toggle ( 'active' , b . dataset . tab === ( tab === 'order-edit' ? 'orders' : tab ));});
2026-10-22 17:06:32 +08:00
if ( tab === 'order-edit' ) return await renderOrderEdit ();
2026-10-26 14:44:07 +08:00
if ( tab === 'create' ) renderCreate (); if ( tab === 'price-locks' ) await renderPriceLocks (); if ( tab === 'material-pools' ) await renderMaterialPools (); if ( tab === 'recoveries' && typeof renderRecoveries === 'function' ) await renderRecoveries (); if ( tab === 'orders' ) await renderOrders (); if ( tab === 'stock' ) await renderStock (); if ( tab === 'report' ) await renderReport (); if ( tab === 'settings' ) renderSettings (); if ( tab === 'team-funds' ) await renderTeamFunds ();
2026-10-25 14:19:24 +08:00
}
const teamMemberKeys = [ 'owner' , 'assistant' , 'assistant2' ];
function teamMode (){ return !! ( state ? . user ? . member || state ? . members ? . some ( member => member . member === 'assistant2' ));}
function currentMember (){ return state ? . user ? . member || session ? . user ? . member || ( state ? . user ? . role === 'owner' ? 'owner' : 'assistant' );}
2026-11-03 01:15:41 +08:00
function teamMemberName ( member ){ return ({ owner : '麦麦' , assistant : '娜娜' , assistant2 : '小昊' })[ member ] || '待确认' ;}
function accountDisplayName ( value ){ const match = /^(助理2|助理1|助理|麦麦)(微信|支付宝|现金|信用卡)?$/ . exec ( String ( value ?? '' )); return match ? teamMemberName ( match [ 1 ] === '麦麦' ? 'owner' : match [ 1 ] === '助理2' ? 'assistant2' : 'assistant' ) + ( match [ 2 ] || '' ) : value ;}
2026-10-25 14:19:24 +08:00
function teamMemberOptions ( assistantFirst = false ){ const keys = teamMode () ? ( assistantFirst ? [ 'assistant' , 'assistant2' , 'owner' ] : teamMemberKeys ) : ( assistantFirst ? [ 'assistant' , 'owner' ] : [ 'owner' , 'assistant' ]); return keys . map ( member =>[ member , teamMemberName ( member )]);}
function teamDataKeys ( data ){ return [ 'assistant' , 'assistant2' , 'owner' ]. filter ( member => data && Object . hasOwn ( data , member ));}
function teamDefaultPayer (){ return teamMode () ? orderFormMember () : 'assistant' ;}
function orderMemberField ( member = currentMember (), locked = false ){
if ( ! teamMode ()) return '' ;
const selected = teamMemberKeys . includes ( member ) ? member : currentMember ();
return state . user . role === 'owner' &&! locked ? choice ( '订单归属(经营款与业绩)' , 'member' , teamMemberOptions (), selected ) : `<label>订单归属(经营款与业绩)<input value=" ${ e ( teamMemberName ( selected )) } " readonly><input type="hidden" name="member" value=" ${ e ( selected ) } "></label>` ;
}
function orderFormMember (){ return $ ( '#order-form [name="member"]' ) ? . value || $ ( '#price-lock-create-form [name="member"]' ) ? . value || currentMember ();}
2026-11-03 01:15:41 +08:00
function peopleParts (){ return state ? . user ? . role === 'assistant' && teamMode () ? [ currentMember () === 'assistant2' ? [ 'assistant2' , '小昊人数' ] : [ 'assistant1' , '娜娜人数' ]] : [[ 'assistant1' , '娜娜人数' ],[ 'assistant2' , '小昊人数' ]];}
2026-10-25 14:19:24 +08:00
function memberFilterHTML ( id , selected = '' ){ return state . user . role === 'owner' && teamMode () ? `<label class="member-filter">订单归属<select id=" ${ e ( id ) } "> ${ opts ([[ '' , '全部成员' ],... teamMemberOptions ()], selected ) } </select></label>` : '' ;}
let reportMember = '' ;
2026-10-17 19:50:24 +08:00
const productNames = [ '足金999' , '足银999' , '纯银925' ];
const chargeNames = [ '编绳' , '证书' , '包装' , '快递' , '附加费' ];
const chargeSaleDefaults = { '编绳' : '55' , '证书' : '10' , '包装' : '10' , '快递' : '8' };
const feeLabels = { shipping : '快递费' , box : '包装盒' , certificate : '证书' , braiding : '编绳' , sticker : '手机贴' , other : '其他直接费用' };
const amountInput = ( title , name , value = '' , extra = '' )=> field ( title , name , value , 'number' , `min="0" step="0.01" ${ extra } ` );
2026-10-25 14:19:24 +08:00
function normalizePaymentAccount ( account ){ return typeof CreditCardFees === 'object' && typeof CreditCardFees . normalizeAccount === 'function' ? CreditCardFees . normalizeAccount ( account ) : ([ '助理信用卡' , '助理1信用卡' , '助理2信用卡' , '麦麦信用卡' ]. includes ( account ) ? '麦麦信用卡' : account );}
function defaultPaymentRecipient (){ return teamMode () ? ({ owner : '麦麦' , assistant : '助理' , assistant2 : '助理2' })[ orderFormMember ()] : '助理' ;}
function accountFields ( account ){
2026-10-23 09:49:36 +08:00
const methods = [ '微信' , '支付宝' , '现金' ,...( creditCardAvailable () ? [ '信用卡' ] : [])];
2026-10-25 14:19:24 +08:00
account = normalizePaymentAccount ( account || defaultPaymentRecipient () + '微信' );
const card = isCreditCardAccount ( account ), prefix = account . startsWith ( '麦麦' ) ? '麦麦' : account . startsWith ( '助理2' ) ? '助理2' : '助理' ;
2026-11-03 01:15:41 +08:00
const recipients = ( teamMode () ? [ '麦麦' , '助理' , '助理2' ] : [ '助理' , '麦麦' ]). map ( value =>[ value , accountDisplayName ( value )]);
2026-10-25 14:19:24 +08:00
return choice ( '收款方式' , 'payment_method' , methods , account . replace ( /^(助理2|助理1|助理|麦麦)/ , '' )) + `<label>收款人<select name="payment_recipient" data-non-card-recipient=" ${ e ( card ? defaultPaymentRecipient () : prefix ) } " data-card-locked=" ${ card } " ${ card ? 'disabled' : '' } > ${ opts ( recipients , card ? '麦麦' : prefix ) } </select> ${ creditCardAvailable () ? `<small class="small muted payment-account-note" ${ card ? '' : 'hidden' } >信用卡统一由麦麦收款。</small>` : '' } </label>` ;
}
function syncPaymentRecipient ( form ){
const method = form ? . querySelector ? .( '[name="payment_method"]' ), recipient = form ? . querySelector ? .( '[name="payment_recipient"]' ); if ( ! method ||! recipient ) return '' ;
const dataset = recipient . dataset || ( recipient . dataset = {}), card = method . value === '信用卡' ;
if ( card ){ if ( dataset . cardLocked !== 'true' ) dataset . nonCardRecipient = recipient . value || defaultPaymentRecipient (); recipient . value = '麦麦' ; recipient . disabled = true ; dataset . cardLocked = 'true' ;}
else { if ( dataset . cardLocked === 'true' ) recipient . value = dataset . nonCardRecipient || defaultPaymentRecipient (); recipient . disabled = busy ||!! pending () || form . dataset ? . stale === 'true' || recipient . closest ( '[hidden]' ) ? . hidden === true ; dataset . cardLocked = 'false' ; dataset . nonCardRecipient = recipient . value ;}
const note = recipient . closest ( 'label' ) ? . querySelector ? .( '.payment-account-note' ); if ( note ) note . hidden =! card ;
return normalizePaymentAccount ( recipient . value + method . value );
}
function readPaymentAccount ( form ){ return normalizePaymentAccount (( form ? . querySelector ? .( '[name="payment_recipient"]' ) ? . value || '' ) + ( form ? . querySelector ? .( '[name="payment_method"]' ) ? . value || '' ));}
function creditCardAvailable (){ return typeof CreditCardFees === 'object' && state ? . accounts ? . includes ( '麦麦信用卡' );}
2026-10-23 09:49:36 +08:00
function isAutomaticCardFee ( item ){ return item ? . system === 'credit_card' || String ( item ? . key || '' ). startsWith ( 'card_fee:' );}
2026-10-25 14:19:24 +08:00
function isCreditCardAccount ( account ){ return typeof CreditCardFees === 'object' && typeof CreditCardFees . isAccount === 'function' ? CreditCardFees . isAccount ( account ) : [ '助理信用卡' , '助理1信用卡' , '麦麦信用卡' , '助理2信用卡' ]. includes ( account );}
2026-10-23 09:49:36 +08:00
function creditCardPreviewHTML ( id , payer = 'owner' , basis = '客户付款金额' ){
2026-10-25 14:19:24 +08:00
return `<div class="credit-card-preview" id=" ${ e ( id ) } " hidden data-basis=" ${ e ( basis ) } "><div class="credit-card-heading"><strong>信用卡手续费(内部)</strong><span class="small muted">自动计算 · 客户单据不显示</span></div><div class="credit-card-fields"><label>手续费(元,自动)<input type="number" min="0" step="0.01" readonly data-credit-card-amount aria-label="信用卡手续费自动金额"></label> ${ choice ( '手续费付款人' , 'credit_card_fee_payer' , teamMemberOptions (), payer || 'owner' ) } </div><p class="small muted" data-credit-card-formula aria-live="polite"></p></div>` ;
2026-10-23 09:49:36 +08:00
}
function syncCreditCardPreview ( root , account , cents ,{ basis = root ? . dataset . basis || '客户付款金额' , enabled = true } = {}){
if ( ! root ) return 0 ;
const visible = enabled && isCreditCardAccount ( account ), payer = root . querySelector ( '[name="credit_card_fee_payer"]' ); root . hidden =! visible ; payer . disabled =! visible || busy ||!! pending (); payer . required = visible ;
if ( ! visible ) return 0 ;
const field = root . querySelector ( '[data-credit-card-amount]' ), note = root . querySelector ( '[data-credit-card-formula]' );
2026-10-25 14:19:24 +08:00
try { const amount = CreditCardFees . amount ( cents ); field . value = ( amount / 100 ). toFixed ( 2 ); note . textContent = ` ${ basis } ¥ ${ yuan ( cents ) } × 6‰ = ¥ ${ yuan ( amount ) } 。计入内部成本,客户付款金额不变;退款不退回已发生的手续费。` ; return amount ;}
catch { field . value = '' ; note . textContent = '填写客户付款金额后自动计算6‰手续费;付款人默认麦麦,可按实际修改。' ; return null ;}
2026-10-23 09:49:36 +08:00
}
function readCreditCardPayer ( form ){ return form ? . querySelector ( '[name="credit_card_fee_payer"]' ) ? . value || 'owner' ;}
2026-10-17 19:50:24 +08:00
function materialCostInput ( line ){
if ([ 'gram' , 'total' ]. includes ( line . costMaterial ? . mode )) return line . costMaterial ;
const amount = line . costParts ? . material , hasTotal = amount != null && String ( amount ). trim () !== '' ;
return { mode : ( line . unit || 'g' ) === 'g' &&! hasTotal ? 'gram' : 'total' };
}
2026-10-25 14:19:24 +08:00
function costPayerInput ( line ){ return { material : line . costPayers ? . material ?? line . payer ?? ( teamMode () ? orderFormMember () : 'owner' ), labor : line . costPayers ? . labor ?? line . payer ?? ( teamMode () ? orderFormMember () : 'owner' )};}
function purchasePayerField ( title , name , value ){ return `<label class="purchase-payer"> ${ e ( title ) } <select name=" ${ e ( name ) } " required> ${ [ 'owner' , 'assistant' , 'assistant2' ]. includes ( value ) ? '' : '<option value="" disabled selected>请选择</option>' }${ opts ( teamMemberOptions (), value ) } </select></label>` ;}
2026-10-17 19:50:24 +08:00
function compactExtraCosts ( parts , prefix , required , payer = 'owner' ){
const keys = [ 'accessories' , 'other' ], valid = key => /^ \ d + ( ?: \ . \ d { 1 , 2 }) ? $ / . test ( String ( parts [ key ] ?? '' ). trim ());
const needsReview = keys . some ( key => ! valid ( key )), hasAmount = keys . some ( key => valid ( key ) && Number ( parts [ key ]) !== 0 );
if ( ! needsReview &&! hasAmount ) return keys . map ( key => `<input type="hidden" name=" ${ e ( prefix + key ) } " value=" ${ e ( parts [ key ]) } ">` ). join ( '' ) + `<input type="hidden" name="payer" value=" ${ e ( payer ) } ">` ;
const known = keys . reduce (( sum , key )=>{ try { return sum + LedgerCalc . cents ( parts [ key ]);} catch { return sum ;}}, 0 );
2026-10-25 14:19:24 +08:00
return `<details class="legacy-extra-costs" ${ needsReview ? 'open' : '' } ><summary>原有其他货品成本 · ${ needsReview ? '待补齐' : '已保留 ¥' + yuan ( known ) } </summary><p class="small muted">这里保留原来填写的货品成本,不要在下方实际费用重复登记。</p><div class="grid three"> ${ amountInput ( '配件成本(元,本行合计)' , prefix + 'accessories' , parts . accessories ?? '' , required ? 'required' : '' ) }${ amountInput ( '其他货品成本(元,本行合计)' , prefix + 'other' , parts . other ?? '' , required ? 'required' : '' ) }${ choice ( '原有配件及其他成本付款人' , 'payer' , teamMemberOptions (), payer ) } </div></details>` ;
2026-10-17 19:50:24 +08:00
}
function costFields ( parts = {}, prefix = 'cost-' , required = false , costLabor = {}, costMaterial = { mode : 'total' }, materialDraft = {}, unit = 'g' , costPayers = { material : 'owner' , labor : 'owner' }, options = {}){
2026-10-21 01:32:49 +08:00
if ( options . poolLine )({ parts , costMaterial , materialDraft , costPayers } = materialPoolFieldsSetup ( options . poolLine , unit , parts , costMaterial , materialDraft , costPayers ));
2026-10-17 19:50:24 +08:00
const amount = ( k , title )=> amountInput ( title , prefix + k , parts [ k ] ?? '' , ` ${ required ? 'required' : '' } placeholder="开单前必填,没有填0"` );
const materialMode = unit === 'g' ? ( costMaterial . mode || 'total' ) : 'total' , materialRate = costMaterial . rate ?? materialDraft . rate ?? '' ;
const rememberedTotal = materialDraft . total ?? ( materialMode === 'total' ? ( parts . material ?? '' ) : '' ), originalTotal = materialDraft . originalTotal ?? ( materialMode === 'total' ? ( parts . material ?? '' ) : '' );
2026-10-21 01:32:49 +08:00
return ( options . poolLine ? materialSourceFieldsHTML ( options . poolLine , prefix , unit ) : '' ) + `<div class="purchase-material" data-prefix=" ${ e ( prefix ) } " data-required=" ${ required } " data-mode=" ${ e ( materialMode ) } " data-preferred-mode=" ${ e ( materialDraft . mode || costMaterial . mode || 'total' ) } " data-unit=" ${ e ( unit ) } " data-total=" ${ e ( rememberedTotal ) } " data-original-total=" ${ e ( originalTotal ) } "><div class="grid purchase-cost-grid"> ${ choice ( '进货料费方式' , prefix + 'materialMode' ,[[ 'gram' , '按克料价' ],[ 'total' , '直接填总料费' ]], materialMode ) }${ amountInput ( '进货料价(元/克)' , prefix + 'materialRate' , materialRate , 'placeholder="填写每克进货料价"' ) }${ amount ( 'material' , '料费成本合计(元)' ). replace ( '<label>' , '<label class="purchase-total">' ) }${ purchasePayerField ( '料费付款人' , prefix + 'materialPayer' , costPayers . material ) } </div><p class="purchase-formula small muted" aria-live="polite"></p><p class="purchase-original small muted" hidden></p></div>` +
2026-10-25 14:19:24 +08:00
`<div class="purchase-labor" data-prefix=" ${ e ( prefix ) } " data-mode=" ${ e ( costLabor . mode || 'total' ) } "><div class="grid purchase-cost-grid"> ${ choice ( '进货工费方式' , prefix + 'laborMode' ,[[ 'gram' , '克工费' ],[ 'total' , '总工费' ]], costLabor . mode || 'total' ) }${ amountInput ( '进货克工费(元/克)' , prefix + 'laborRate' , costLabor . rate ?? '' , 'min="0" placeholder="填写每克工费"' ) }${ amount ( 'labor' , '进货总工费(元)' ). replace ( '<label>' , '<label class="purchase-total">' ) }${ purchasePayerField ( '进货工费付款人' , prefix + 'laborPayer' , costPayers . labor ) } </div><p class="purchase-formula small muted" aria-live="polite"></p> ${ typeof reimbursementFundingHTML === 'function' ? reimbursementFundingHTML ( 'labor' , options . costFundings ? . labor ) : '' } </div>` +
2026-10-17 19:50:24 +08:00
( options . compact ? compactExtraCosts ( parts , prefix , required , options . payer ?? 'owner' ) : amount ( 'accessories' , '配件成本(元,本行合计)' ) + amount ( 'other' , '其他货品成本(元,本行合计)' ));
}
function readPurchaseCost ( root ){
const prefix = root . querySelector ( '.purchase-labor' ). dataset . prefix , get = n => root . querySelector ( `[name=" ${ prefix + n } "]` ). value ;
const material = root . querySelector ( '.purchase-material' ), mode = get ( 'materialMode' );
2026-10-25 14:19:24 +08:00
return readMaterialPoolCost ( root ,{ costParts : Object . fromEntries ( Object . keys ( LedgerCalc . costLabels ). map ( k =>[ k , get ( k )])), costPayers : { material : get ( 'materialPayer' ), labor : get ( 'laborPayer' )}, costMaterial : { mode ,...( mode === 'gram' ? { rate : get ( 'materialRate' )} : {})}, costMaterialDraft : { mode : material . dataset . preferredMode , rate : get ( 'materialRate' ), total : mode === 'total' ? get ( 'material' ) : material . dataset . total , originalTotal : material . dataset . originalTotal }, costLabor : { mode : get ( 'laborMode' ),...( get ( 'laborMode' ) === 'gram' ? { rate : get ( 'laborRate' )} : {})},...( typeof readReimbursementFunding === 'function' && root . querySelector ( '.cost-funding' ) ? { costFundings : { labor : readReimbursementFunding ( root . querySelector ( '.cost-funding' ))}} : {})});
2026-10-17 19:50:24 +08:00
}
function syncPurchaseCost ( root , unit , quantity ){
2026-10-21 01:32:49 +08:00
const pooled = syncMaterialPoolSelection ( root , unit , quantity );
2026-10-17 19:50:24 +08:00
const material = root . querySelector ( '.purchase-material' ), prefix = material . dataset . prefix , get = n => root . querySelector ( `[name=" ${ prefix + n } "]` ), materialMode = get ( 'materialMode' ), materialTotal = get ( 'material' ), required = material . dataset . required === 'true' ;
const previousMode = material . dataset . mode , changedUnit = material . dataset . unit !== unit ;
// 总额与每克料价分别保留;按件时绝不把隐藏的每克料价当作总额。
2026-10-21 01:32:49 +08:00
if ( ! pooled && previousMode === 'total' ) material . dataset . total = materialTotal . value ;
if ( ! pooled && changedUnit ){
2026-10-17 19:50:24 +08:00
if ( unit !== 'g' && previousMode === 'gram' ){ material . dataset . preferredMode = 'gram' ; materialMode . value = 'total' ; materialTotal . value = material . dataset . total ;}
else if ( unit === 'g' && material . dataset . preferredMode === 'gram' ) materialMode . value = 'gram' ;
2026-10-21 01:32:49 +08:00
} else if ( ! pooled && materialMode . value !== previousMode ){
2026-10-17 19:50:24 +08:00
material . dataset . preferredMode = materialMode . value ;
if ( materialMode . value === 'total' ){
if ( material . dataset . total === '' ) material . dataset . total = materialTotal . value ;
materialTotal . value = material . dataset . total ;
}
}
materialMode . querySelector ( 'option[value="gram"]' ). disabled = unit !== 'g' ;
if ( unit !== 'g' ) materialMode . value = 'total' ;
material . dataset . mode = materialMode . value ; material . dataset . unit = unit ;
2026-10-21 01:32:49 +08:00
const original = material . querySelector ( '.purchase-original' ); original . hidden = pooled || material . dataset . originalTotal === '' ;
2026-10-17 19:50:24 +08:00
original . textContent = original . hidden ? '' : `已保留原料费合计 ${ material . dataset . originalTotal } 元。原金额不会当成每克料价;切换按克后请填写实际进货料价。` ;
for ( const [ key , metaKey , group ] of [[ 'material' , 'costMaterial' , material ],[ 'labor' , 'costLabor' , root . querySelector ( '.purchase-labor' )]]){
2026-10-21 01:32:49 +08:00
if ( key === 'material' && pooled ) continue ;
2026-10-17 19:50:24 +08:00
const mode = get ( key + 'Mode' ), rate = get ( key + 'Rate' ), total = get ( key ), note = group . querySelector ( '.purchase-formula' );
mode . querySelector ( 'option[value="gram"]' ). disabled = unit !== 'g' ; if ( unit !== 'g' && mode . value === 'gram' ) mode . value = 'total' ;
group . dataset . mode = mode . value ;
const gram = mode . value === 'gram' ; rate . closest ( 'label' ). hidden =! gram ; rate . disabled =! gram ; rate . required = gram && required ; total . readOnly = gram ; total . required =! gram && required ;
if ( ! gram ){ note . textContent = key === 'material' ? ( unit === 'g' ? '直接填写本行料费合计,不再乘以克重。' : `按件商品请填写本行料费合计 ${ get ( 'materialRate' ). value !== '' ? ';每克料价已保留,切回g可恢复' : '' } 。` ) : '直接填写本行总工费。' ; continue ;}
try {
const result = LedgerCalc . purchaseCosts ({ unit , quantity , costParts : { material : '0' , labor : '0' , accessories : '0' , other : '0' }, costMaterial : { mode : 'total' }, costLabor : { mode : 'total' },[ metaKey ] : { mode : 'gram' , rate : rate . value }}), value = result . parts [ key ];
total . value = value === null ? '' : ( value / 100 ). toFixed ( 2 );
note . textContent = value === null ? ( key === 'material' ? '填写每克进货料价后,系统自动乘以本行克重。' : '填写每克工费后自动乘以克重。' ) : ` ${ quantity } g × ${ rate . value } 元/克 = ${ yuan ( value ) } 元` ;
} catch ( err ){ total . value = '' ; note . textContent = err . message ;}
}
try { return LedgerCalc . purchaseCosts ({... readPurchaseCost ( root ), unit , quantity });} catch { return null ;}
}
function syncCostEditor (){
document . querySelectorAll ( '#action-form .cost-editor' ). forEach (( row , i )=>{
const line = currentOrder . lines [ i ], result = syncPurchaseCost ( row , line . unit , line . unit === 'g' ? ( line . quantity / 1000 ). toFixed ( 3 ) : line . quantity );
row . querySelector ( '.cost-summary' ). textContent = '本行货品成本合计:' + ( result ? . total == null ? '请补齐(没有的项目填0)' : '¥' + yuan ( result . total ));
});
}
function chargeHTML ( c = {}){
const type = c . nameType || ( chargeNames . includes ( c . name ) ? c . name : c . name ? '其他' : '编绳' );
// 只给新选择预填报价;旧金额、手填0和主动清空都原样保留。
const amount = Object . hasOwn ( c , 'amount' ) ? ( c . amount ?? '' ) : ( chargeSaleDefaults [ type ] ?? '' );
const prices = {... c . chargePrices ,[ type ] : amount };
return `<div class="charge-row" data-charge-id=" ${ e ( c . id || crypto . randomUUID ()) } " data-charge-type=" ${ e ( type ) } " data-charge-prices=" ${ e ( JSON . stringify ( prices )) } "> ${ choice ( '附加项目' , 'chargeType' ,[... chargeNames , '其他' ], type ) }${ field ( '附加项目名称' , 'chargeName' , c . customName ?? ( type === '其他' ? c . name : '' ), 'text' , 'maxlength="40"' ) }${ amountInput ( '附加金额(元)' , 'chargeAmount' , amount , 'required placeholder="没有收费填0,可修改金额"' ) }${ button ( '移除附加项' , 'remove-charge' , 'quiet' ) } </div>` ;
}
function syncChargePrice ( target ){
const row = target . closest ( '.charge-row' ); if ( ! row ||! [ 'chargeType' , 'chargeAmount' ]. includes ( target . name )) return ;
const type = row . querySelector ( '[name="chargeType"]' ). value , amount = row . querySelector ( '[name="chargeAmount"]' ), prices = JSON . parse ( row . dataset . chargePrices );
if ( type !== row . dataset . chargeType ){
prices [ row . dataset . chargeType ] = amount . value ;
amount . value = Object . hasOwn ( prices , type ) ? prices [ type ] : ( chargeSaleDefaults [ type ] ?? '' );
row . dataset . chargeType = type ;
}
prices [ type ] = amount . value ; row . dataset . chargePrices = JSON . stringify ( prices );
}
2026-10-21 01:32:49 +08:00
function lineHTML ( l = {}, index = 1 , options = {}){
2026-10-17 19:50:24 +08:00
// 旧页面自动暂存的空白行直接使用新表单;已经填写的旧报价保留原金额。
if ( ! l . name &&! l . quantity &&! l . sale &&! l . cost &&! l . costParts &&! l . pricingMode ) l = {... l , cost : undefined , sale : undefined };
const name = l . nameType || ( productNames . includes ( l . name ) ? l . name : l . name ? '其他' : '足金999' );
const legacy = l . costParts == null && l . cost !== undefined ;
const mode = l . pricingMode || ( l . sale !== undefined ? 'manual' : 'auto' );
2026-11-08 03:30:58 +08:00
return `<div class="line-item" data-legacy=" ${ legacy ? 'true' : 'false' } " data-historical-pocket=" ${ options . historicalPocket ? 'true' : 'false' } "><div class="line-top"><strong>商品 ${ index . toString (). padStart ( 2 , '0' ) } </strong> ${ button ( '移除' , 'remove-line' , 'quiet' ) } </div>
2026-10-17 19:50:24 +08:00
<div class="grid four"> ${ choice ( '商品名称' , 'nameType' ,[... productNames , '其他' ], name ) }${ field ( '其他商品名称' , 'customName' , l . customName ?? ( name === '其他' ? l . name : '' ), 'text' , 'maxlength="60"' ) }${ choice ( '计价方式' , 'pricingMode' ,[[ 'auto' , '按金价与工费计算' ],[ 'manual' , '直接填写金额' ]], mode ) }${ choice ( '单位' , 'unit' ,[ 'g' , '件' ], l . unit || 'g' ) }${ field ( '克重/数量' , 'quantity' , l . quantity ?? '' , 'number' , 'required min="0.001" step="0.001"' ) } </div>
<div class="grid four sale-inputs"> ${ amountInput ( '金价/银价(元/克)' , 'goldPrice' , l . goldPrice ?? '' ) }${ choice ( '销售工费方式' , 'laborMode' ,[[ 'gram' , '克工费' ],[ 'piece' , '件工费' ]], l . laborMode || 'gram' ) }${ amountInput ( '销售工费' , 'laborRate' , l . laborRate ?? '' ) }${ field ( '计工费件数' , 'pieces' , l . pieces ?? '1' , 'number' , 'min="1" step="1"' ) }${ field ( '销售单价说明(客户可见)' , 'priceNote' , l . priceNote || '' , 'text' , 'maxlength="100"' ) }${ moneyField ( '商品基础金额(不含附加项目)' , 'baseSale' , l . baseSale ?? l . sale ?? '' ) } </div>
<div class="sale-charges"><div class="panel-title"><strong>工费附加项目(选填)</strong> ${ button ( '+ 添加附加项目' , 'add-charge' ) } </div><p class="small muted">向客户收费预填:编绳55元、证书10元、包装10元、快递8元,均可修改;按填写金额自动加进本行销售额。</p><div class="charge-list"> ${ ( l . charges || []). map ( chargeHTML ). join ( '' ) } </div></div>
<div class="grid two sale-result"> ${ field ( '本行销售额(元,含附加项目)' , 'sale' , l . sale ?? '' , 'number' , 'readonly' ) } <p class="calculation small" aria-live="polite"></p></div>
2026-11-08 03:30:58 +08:00
<div class="internal"><div class="internal-title">内部成本 · 客户单据不显示</div><div class="grid two cost-source-fields"> ${ pocketChoice ( '出库货盘(仅黄金)' , 'pocket' , l . pocket ?? ( name === '足金999' ? '现货' : '' ),{ historical :!! options . historicalPocket } )} ${ legacy ? choice ( '货品成本由谁垫付' , 'payer' , teamMemberOptions (), l . payer || 'owner' ) : '' } </div>
2026-10-25 14:19:24 +08:00
<div class="cost-fields grid"> ${ legacy ? ` ${ field ( '原单货品成本(旧版未分项)' , 'cost' , l . cost ?? '' , 'number' , 'readonly' ) } <div class="legacy-cost-note small">保留原金额,拆分时请根据凭据填写。 ${ button ( '拆分这行成本' , 'split-cost' , 'quiet' ) } </div>` : costFields ( l . costParts || { material : '' , labor : '' , accessories : '0' , other : '0' } ,'cost-',true,l.costLabor||{},materialCostInput(l),l.costMaterialDraft,l.unit||'g',costPayerInput(l),{compact:true,payer:l.payer??'owner',costFundings:l.costFundings,...(options.materialPool?{poolLine:l}:{})})}</div>
2026-10-17 19:50:24 +08:00
</div></div>` ;
}
2026-10-21 01:32:49 +08:00
function draftInputs ( o ){ return {... o , rounding_mode : o . rounding_mode || 'cent' , discount : ( o . discount / 100 ). toFixed ( 2 ), fee_items : o . fee_items . map ( item =>({... item , amount : item . amount === null ? '' : ( item . amount / 100 ). toFixed ( 2 )})), lines : o . lines . map ( l =>({... l , costMaterial : l . costMaterial ? . mode === 'pool' ? {... l . costMaterial } : { mode : materialCostInput ( l ). mode ,...( l . costMaterial ? . mode === 'gram' ? { rate : l . costMaterial . rate == null ? '' : ( l . costMaterial . rate / 100 ). toFixed ( 2 )} : {})}, costLabor : { mode : l . costLabor ? . mode || 'total' , rate : l . costLabor ? . rate == null ? '' : ( l . costLabor . rate / 100 ). toFixed ( 2 )}, quantity : l . unit === 'g' ? grams ( l . quantity ) : l . quantity , sale : ( l . sale / 100 ). toFixed ( 2 ), baseSale : (( l . baseSale ?? l . sale ) / 100 ). toFixed ( 2 ), charges : ( l . charges || []). map ( c =>({... c , amount : c . amount === null ? '' : ( c . amount / 100 ). toFixed ( 2 )})), cost : l . cost === null ? '' : ( l . cost / 100 ). toFixed ( 2 ),...( l . pricingMode === 'auto' ? { goldPrice : ( l . goldPrice / 100 ). toFixed ( 2 ), laborRate : ( l . laborRate / 100 ). toFixed ( 2 )} : {}),...( l . costParts ? { costParts : Object . fromEntries ( Object . entries ( l . costParts ). map (([ k , v ])=>[ k , v === null ? '' : ( v / 100 ). toFixed ( 2 )]))} : {})}))};}
2026-10-17 19:50:24 +08:00
function feeRowHTML ( item ){
2026-10-23 09:49:36 +08:00
const automatic = isAutomaticCardFee ( item ), linked = item . key . startsWith ( 'charge:' ), manual =! automatic && item . key . startsWith ( 'manual:' );
return '<div class="fee-row' + ( automatic ? ' fee-automatic' : '' ) + '" ' + ( automatic ? 'data-automatic-fee="' + e ( JSON . stringify ( item )) + '" ' : '' ) + 'data-expense-id="' + e ( item . expense_id || '' ) + '" data-fee-date="' + e ( item . date || '' ) + '" data-fee="' + e ( item . key ) + '" data-source="' + e ( item . sourceName || '' ) + '" data-edited="' + ( item . edited ? 'true' : 'false' ) + '" data-status="' + e ( item . status || 'legacy' ) + '">' +
'<div class="fee-title"><strong class="fee-name"' + ( manual ? ' hidden' : '' ) + '>' + e ( item . note ) + '</strong>' + ( manual ? field ( '费用项目名称' , 'feeNote' , item . note , 'text' , 'required maxlength="150"' ) : '' ) + '<span class="small muted fee-source">' + ( automatic ? '已记录的信用卡收款手续费' : linked ? '商品 ' + item . lineNumber + ' 的附加项目' : '整单费用' ) + '</span></div>' +
2026-10-25 14:19:24 +08:00
amountInput ( automatic ? '手续费(元,自动)' : '实际成本(元)' , 'feeAmount' , item . amount ?? '' , automatic ? 'required readonly' : 'required placeholder="没有成本填0"' ) + choice ( '费用付款人' , 'feePayer' , teamMemberOptions ( true ), item . payer || ( automatic ? 'owner' : teamDefaultPayer ())) +
2026-10-23 09:49:36 +08:00
( tab === 'order-edit' ? field ( '本笔费用支付日期' , 'feeDate' , item . date || $ ( '#order-form [name="fees_date"]' ) ? . value || orderEditEntry . inputs . fees_date || orderEditEntry . inputs . date , 'date' , `required max=" ${ state . today } " ${ automatic ? ' readonly' : '' } ` ) : '' ) +
2026-10-25 14:19:24 +08:00
( automatic ? '<small class="muted fee-help">沿用已记录的手续费金额与费率,支付日期保留。</small>' : linked ? '<small class="muted fee-help">随上方项目同步;没有成本填0</small>' : button ( '移除费用' , 'remove-fee' , 'quiet' )) + ( typeof reimbursementFundingHTML === 'function' &&! automatic ? reimbursementFundingHTML ( 'fee' , item . funding ) : '' ) + '</div>' ;
2026-10-23 09:49:36 +08:00
}
2026-10-25 14:19:24 +08:00
function readFeeRows ( root = $ ( '#fee-rows' )){ return [... root . querySelectorAll ( '.fee-row' )]. map ( row =>{ const date = row . querySelector ( '[name="feeDate"]' ) ? . value || row . dataset . feeDate , amount = row . querySelector ( '[name="feeAmount"]' ). value , payer = row . querySelector ( '[name="feePayer"]' ). value ; if ( row . dataset . automaticFee ) return {... JSON . parse ( row . dataset . automaticFee ),...( date ? { date } : {}), amount , payer }; return { key : row . dataset . fee , sourceName : row . dataset . source || undefined , edited : row . dataset . edited === 'true' ,...( row . dataset . expenseId ? { expense_id : row . dataset . expenseId } : {}),...( date ? { date } : {}),...( row . dataset . status === 'estimated' ? { status : 'estimated' } : {}), note : row . querySelector ( '[name="feeNote"]' ) ? . value ?? row . querySelector ( '.fee-name' ). textContent , amount , payer ,...( typeof readReimbursementFunding === 'function' && row . querySelector ( '.cost-funding' ) ? { funding : readReimbursementFunding ( row . querySelector ( '.cost-funding' ))} : {})};});}
2026-10-17 19:50:24 +08:00
function syncFeeRows (){
const root = $ ( '#fee-rows' ); if ( ! root ) return ;
2026-10-25 14:19:24 +08:00
const existing = readFeeRows ( root ), next = [... FeeEstimates . sync ( existing . filter ( item => ! isAutomaticCardFee ( item )),[... document . querySelectorAll ( '#lines .line-item' )]. map ( collectLine ),{ defaultPayer : teamMode () ? orderFormMember () : 'assistant' }),... existing . filter ( isAutomaticCardFee )];
2026-10-23 09:49:36 +08:00
if ( tab === 'order-edit' ) for ( const item of existing ){ if ( ! isAutomaticCardFee ( item ) && item . expense_id &&! next . some ( row => row . expense_id === item . expense_id )) next . push ({... item , key : 'manual:' + item . expense_id , sourceName : undefined });}
2026-10-17 19:50:24 +08:00
if ( existing . map ( r => r . key ). join ( '|' ) !== next . map ( r => r . key ). join ( '|' )){ root . innerHTML = next . map ( feeRowHTML ). join ( '' ); return ;}
2026-10-23 09:49:36 +08:00
next . forEach (( item , i )=>{ const row = root . children [ i ]; row . dataset . source = item . sourceName || '' ; row . querySelector ( '.fee-name' ). textContent = item . note ; row . querySelector ( '.fee-source' ). textContent = isAutomaticCardFee ( item ) ? '已记录的信用卡收款手续费' : item . key . startsWith ( 'charge:' ) ? '商品 ' + item . lineNumber + ' 的附加项目' : '整单费用' ; const amount = row . querySelector ( '[name="feeAmount"]' ); if ( amount . value !== String ( item . amount ?? '' )) amount . value = item . amount ?? '' ; const payer = row . querySelector ( '[name="feePayer"]' ); if ( payer . value !== item . payer ) payer . value = item . payer ;});
2026-10-17 19:50:24 +08:00
}
2026-10-23 09:49:36 +08:00
function feeHTML ( draft ,{ cardPreview = true } = {}){
2026-10-17 19:50:24 +08:00
const items = ( draft . fee_items || []). map ( f =>({... f , note : f . note || feeLabels [ f . key ], edited : f . edited ?? true }));
2026-10-25 14:19:24 +08:00
if ( ! draft . id &&! draft . fee_auto_initialized &&! items . some ( f => f . key === 'shipping' )) items . unshift ({ key : 'shipping' , note : '快递费' , amount : '6' , payer : teamDefaultPayer (), status : 'estimated' , edited : false });
2026-10-23 09:49:36 +08:00
return '<section class="panel internal"><div class="panel-title"><h2>实际费用(内部)</h2>' + button ( '+ 添加其他成本' , 'add-fee' ) + '</div><p class="small muted">' + ( tab === 'order-edit' ? '以下按当前有效费用记录预填,每笔保留原支付日期。普通费用可按凭据修改;信用卡手续费金额和日期自动维护,只可修改付款人。' : '' ) + '上方附加项目自动带入成本。证书默认4元、包装3元,包装默认由麦麦付款;快递按整单默认6元,均可修改。请填写实际已付金额,没有成本填0;不需要的整单费用可移除。开单时记录费用和付款人,客户单据不显示。</p>' + field ( tab === 'order-edit' ? '新增费用默认支付日期' : '费用实际支付日期' , 'fees_date' , draft . fees_date || draft . date || state . today , 'date' , 'required max="' + state . today + '"' ) + '<div class="fee-grid" id="fee-rows">' + items . map ( feeRowHTML ). join ( '' ) + '</div>' + ( cardPreview ? creditCardPreviewHTML ( 'order-credit-card-fee' , draft . credit_card_fee_payer , '成交合计' ) : '' ) + '<div class="small" id="fees-total"></div></section>' ;
2026-10-17 19:50:24 +08:00
}
async function updatePaperNumber (){
const form = $ ( '#order-form' ); if ( ! form ) return ; const date = form . elements . date . value ;
2026-10-22 17:06:32 +08:00
if ( form . dataset . orderEdit === 'true' ){ form . elements . paper_number . value = orderEditEntry . order . paper_number || orderEditEntry . order . number ; return ;}
2026-10-17 19:50:24 +08:00
const old = editDraft ;
if ( old ? . paper_number ){ const match = old . paper_date && old . paper_number . match ( /^\d{8}-?(\d+)$/ ); form . elements . paper_number . value = match ? date . replaceAll ( '-' , '' ) + match [ 1 ] : old . paper_number ; return ;}
form . elements . paper_number . value = '保存时分配' ;
try { const r = await api ( '/api/paper-number?date=' + encodeURIComponent ( date )); if ( $ ( '#order-form' ) === form && form . elements . date . value === date ) form . elements . paper_number . value = r . number + '(预计)' ;} catch { /* 日期校验由表单和服务端提示 */ }
}
function draftRoundingMode ( draft ){ return draft . id ? ( draft . rounding_mode || 'cent' ) : 'yuan' ;}
function orderAmount ( value , mode ){ return value == null ? '待补' : '¥' + ( mode === 'yuan' ? ( value / 100 ). toLocaleString ( 'zh-CN' ,{ minimumFractionDigits : 0 , maximumFractionDigits : 0 }) : yuan ( value ));}
function orderRoundingHint ( total ){
if ( total . rounding_mode !== 'yuan' ) return '保留原单金额,精确到分。' ;
const adjustment = total . rounding_adjustment ;
return '四舍五入到元' + ( adjustment ? ' · 优惠后 ¥' + yuan ( total . unroundedTotal ) + ' → ' + orderAmount ( total . total , 'yuan' ) + '(差额 ' + ( adjustment > 0 ? '+' : '-' ) + yuan ( Math . abs ( adjustment )) + '元)' : '' );
}
function savedOrderRoundingHint ( order ){
if ( order . rounding_mode !== 'yuan' ) return '' ;
const unroundedTotal = order . lines . reduce (( sum , line )=> sum + line . sale , 0 ) - order . discount ;
return orderRoundingHint ({ rounding_mode : 'yuan' , unroundedTotal , total : order . total , rounding_adjustment : order . rounding_adjustment ?? order . total - unroundedTotal });
}
2026-10-28 18:41:14 +08:00
function orderInternalNoteField ( value = '' ){
return `<label>内部备注(客户不可见)<span class="small muted">选填,最多500字</span><textarea name="internal_note" maxlength="500" rows="3" placeholder="仅供内部跟进,不会出现在客户销售单或打印件中"> ${ e ( value ) } </textarea></label>` ;
}
function orderInternalNoteHTML ( order ){
return `<section class="panel internal detail-internal-note" aria-label="内部备注(客户不可见)"><h2>内部备注(客户不可见)</h2><p> ${ order . internal_note ? e ( order . internal_note ). replace ( /\r\n?|\n/g , '<br>' ) : '<span class="muted">未填写</span>' } </p></section>` ;
}
2026-10-17 19:50:24 +08:00
function renderCreate (){
2026-10-22 17:06:32 +08:00
if ( tab === 'order-edit' ) return renderOrderEditForm ();
2026-10-21 01:32:49 +08:00
if ( createMode === 'lock' ) return renderPriceLockCreate ();
2026-10-17 19:50:24 +08:00
let draft = editDraft ; if ( ! draft ){ try { draft = JSON . parse ( localStorage . getItem ( 'mm-draft-' + session . user . id ) || 'null' );} catch {}}
draft = draft || { date : state . today , lines : [{}]};
draft = {... draft , rounding_mode : draftRoundingMode ( draft )};
2026-10-28 18:41:14 +08:00
const blank =! draft . id &&! draft . customer &&! draft . note &&! draft . internal_note &&! Number ( draft . discount ) &&! draft . fee_items ? . some ( r => Number ( r . amount ) && ( r . edited || r . status !== 'estimated' || r . key !== 'shipping' )) && draft . lines . every ( l => ! l . charges ? . some ( c => Number ( c . amount )) &&! l . quantity &&! l . sale &&! l . goldPrice &&! l . laborRate &&! l . cost &&! Object . values ( l . costParts || {}). some ( Number ));
2026-10-17 19:50:24 +08:00
if ( blank ) draft = {... draft , date : state . today , fees_date : state . today };
if ( draft . id &&! editDraft ) editDraft = draft ;
2026-11-08 03:30:58 +08:00
$ ( '#main' ). innerHTML = heading ( 'NEW ORDER' , '开一张新单' , '开单即交付,一次记录全额收款、实际费用、出库和利润。' , priceLockCreateControls () + button ( '清空表单' , 'clear-draft' , 'quiet' )) + orderTemplatesPanelHTML () + `<form id="order-form" data-copy-kind=" ${ e ( draft . copy_kind || '' ) } "> ${ draft . copy_kind ? '<div class="note" role="status">' + ( draft . copy_kind === 'price-lock' ? '已复制为未保存的普通订单,客户称呼已留空。原锁价收付款与金料关联不带入;请重新填写本次普通销售的料费并选择付款人,再核对报价和费用。' : '已复制为未保存的新订单,客户称呼已留空。核对本次克重、报价、费用和收款账户后,再生成销售单据。' ) + '</div>' : '' } <input type="hidden" name="rounding_mode" value=" ${ e ( draft . rounding_mode ) } "><input type="hidden" name="orderId" value=" ${ e ( draft . id || '' ) } "><input type="hidden" name="revision" value=" ${ e ( draft . revision || '' ) } "><section class="panel"><div class="panel-title"><h2>客户与单据</h2><span class="small muted"> ${ draft . id ? '补齐原草稿,生成销售单据后完成记账' : '填写内容自动暂存,生成单据即完成记账' } </span></div><div class="grid four"> ${ dateField ( 'date' , draft . date ) }${ field ( '纸单编号(自动)' , 'paper_number' , draft . paper_number || '保存时分配' , 'text' , 'readonly' ) }${ field ( '客户称呼/代号(必填)' , 'customer' , draft . customer || '' , 'text' , 'required maxlength="60" placeholder="方便找回订单即可"' ) }${ field ( '开单人(必填)' , 'salesperson' , draft . salesperson || session . user . name , 'text' , 'required maxlength="30"' ) }${ orderMemberField ( draft . member || currentMember (), !! draft . id ) }${ accountFields ( draft . payment_account ) } </div><p class="small muted" style="margin:12px 0 0">纸单号前半段为业务日期,后半段序号持续累计,中间不加横线,换日期不归零;生成时分配。生成单据即按成交合计记录全额收款,同时按所选货盘扣减黄金库存并计入实际利润。请核对商品已交付,选择实际收款方式与收款人;业务日期作为收款和出库日期。</p></section><section class="panel"><div class="panel-title"><h2>商品明细</h2><span class="small muted">金价与工费分开填写</span></div><div id="lines"> ${ draft . lines . map (( l , i )=> lineHTML ( l , i + 1 ,{ materialPool : true , historicalPocket :!! draft . id } )).join('')}</div><div class="form-actions"> ${ button ( '+ 添加商品' , 'add-line' ) } <span class="small muted">银饰不扣黄金货盘;外配使用店内金料时,选实际出库货盘。</span></div></section> ${ feeHTML ( draft ) } <section class="panel"><div class="grid two"> ${ moneyField ( '整单优惠/抹零(元)' , 'discount' , draft . discount || '0' ) } <label>客户单备注<textarea name="note" maxlength="240" rows="2" placeholder="只写可让客户看到的内容"> ${ e ( draft . note || '' ) } </textarea></label></div> ${ orderInternalNoteField ( draft . internal_note || '' ) } <div class="form-actions"><div><span class="small muted">成交合计</span><div id="create-total" class="summary-amount">待填写</div><div id="create-rounding-note" class="small muted order-rounding-note" aria-live="polite"></div></div><button class="primary" type="submit">生成销售单据</button></div><div id="order-error" aria-live="polite"></div></section></form>` ; updateTotal (); updatePaperNumber (); loadMaterialPoolChoices ( true ); loadOrderTemplates (); if ( typeof loadReimbursementFundingOptions === 'function' ) loadReimbursementFundingOptions ();
2026-10-17 19:50:24 +08:00
}
function collectLine ( row ){
const values = Object . fromEntries ([... row . querySelectorAll ( 'input,select' )]. filter ( el => ! el . closest ( '.charge-row' )). map ( el =>[ el . name , el . value ]));
values . charges = [... row . querySelectorAll ( '.charge-row' )]. map ( r =>{ const get = n => r . querySelector ( `[name=" ${ n } "]` ). value ; const type = get ( 'chargeType' ), customName = get ( 'chargeName' ); return { id : r . dataset . chargeId , nameType : type , customName , name : type === '其他' ? customName : type , amount : get ( 'chargeAmount' ), chargePrices : JSON . parse ( r . dataset . chargePrices )};});
values . name = values . nameType === '其他' ? values . customName : values . nameType ;
if ( row . dataset . legacy !== 'true' ) Object . assign ( values , readPurchaseCost ( row . querySelector ( '.cost-fields' )));
return values ;
}
2026-10-28 18:41:14 +08:00
function collectDraft (){ const form = $ ( '#order-form' ); if ( ! form ) return null ; const editing = form . dataset . orderEdit === 'true' , original = editing ? orderEditEntry . order : editDraft ; const get = n => form . querySelector ( `[name=" ${ n } "]` ). value ; return {...( form . dataset . copyKind ? { copy_kind : form . dataset . copyKind } : {}), id : get ( 'orderId' ) || undefined , revision : Number ( get ( 'revision' )) || undefined , paper_date : original ? . paper_date || '' , rounding_mode : get ( 'rounding_mode' ),...( teamMode () ? { member : form . querySelector ( '[name="member"]' ) ? . value || original ? . member || currentMember ()} : {}), date : get ( 'date' ), customer : get ( 'customer' ), salesperson : get ( 'salesperson' ), paper_number : original ? . paper_number || '' , payment_account : readPaymentAccount ( form ), credit_card_fee_payer : readCreditCardPayer ( form ), fees_date : get ( 'fees_date' ), fee_auto_initialized : true , fee_items : readFeeRows (). filter ( item => editing ||! isAutomaticCardFee ( item )), discount : get ( 'discount' ), note : get ( 'note' ), internal_note : form . querySelector ( '[name="internal_note"]' ) ? . value ?? original ? . internal_note ?? '' , lines : [... form . querySelectorAll ( '.line-item' )]. map ( collectLine )};}
2026-10-17 19:50:24 +08:00
function syncLine ( row ){
const el = n => row . querySelector ( `[name=" ${ n } "]` ), auto = el ( 'pricingMode' ). value === 'auto' ;
const show = ( n , visible , required = false )=>{ const input = el ( n ); input . closest ( 'label' ). hidden =! visible ; input . required = visible && required ; input . disabled =! visible ;};
show ( 'customName' , el ( 'nameType' ). value === '其他' , true );
for ( const n of [ 'goldPrice' , 'laborMode' , 'laborRate' ]) show ( n , auto , true );
show ( 'pieces' , auto && el ( 'laborMode' ). value === 'piece' , true ); show ( 'priceNote' , ! auto ); show ( 'baseSale' , ! auto , true );
for ( const r of row . querySelectorAll ( '.charge-row' )){ const custom = r . querySelector ( '[name="chargeType"]' ). value === '其他' , input = r . querySelector ( '[name="chargeName"]' ); input . closest ( 'label' ). hidden =! custom ; input . disabled =! custom ; input . required = custom ;}
const note = row . querySelector ( '.calculation' );
try { const result = LedgerCalc . sale ( collectLine ( row )); el ( 'sale' ). value = ( result . sale / 100 ). toFixed ( 2 ); if ( auto ) el ( 'baseSale' ). value = ( result . baseSale / 100 ). toFixed ( 2 ); const formula = auto ? ( el ( 'laborMode' ). value === 'gram' ? ` ${ el ( 'quantity' ). value } ×( ${ el ( 'goldPrice' ). value } + ${ el ( 'laborRate' ). value } ) `: ` ${ el ( 'quantity' ). value } × ${ el ( 'goldPrice' ). value } + ${ el ( 'laborRate' ). value } × ${ el ( 'pieces' ). value } 件` ) : `基础金额 ${ yuan ( result . baseSale ) } ` ; note . textContent = formula + ( result . charges . length ? ' + 附加 ' + yuan ( result . chargesTotal ) : '' ) + ' = ' + yuan ( result . sale ) + ' 元' ;} catch ( err ){ el ( 'sale' ). value = '' ; note . textContent = err . message ;}
if ( row . dataset . legacy !== 'true' ) syncPurchaseCost ( row . querySelector ( '.cost-fields' ), el ( 'unit' ). value , el ( 'quantity' ). value );
}
function updateTotal (){
2026-11-04 22:18:56 +08:00
if ( typeof priceLockOrderEditable === 'function' && priceLockOrderEditable () && orderEditForm () ? . dataset . priceLockEdit === 'true' ){ syncPriceLockOrderEdit ( 'fee_rows_changed' ); rememberOrderEditDraft (); return ;}
2026-10-25 14:19:24 +08:00
syncPaymentRecipient ( $ ( '#order-form' ));
if ( typeof syncReimbursementFundingControls === 'function' ) syncReimbursementFundingControls ();
2026-10-21 01:32:49 +08:00
if ( $ ( '#price-lock-create-form' ) || $ ( '#price-lock-delivery-form' )) return syncPriceLockForm ();
2026-10-17 19:50:24 +08:00
document . querySelectorAll ( '#lines .line-item' ). forEach ( syncLine );
syncFeeRows (); const d = collectDraft (); if ( ! d ) return ;
2026-10-23 09:49:36 +08:00
let totalCents = null ;
try { const total = LedgerCalc . orderTotal ( d . lines . map ( l => LedgerCalc . cents ( l . sale , '商品销售额' )), LedgerCalc . cents ( d . discount , '整单优惠' ), d . rounding_mode ); totalCents = total . total ; $ ( '#create-total' ). textContent = orderAmount ( total . total , total . rounding_mode ); $ ( '#create-rounding-note' ). textContent = orderRoundingHint ( total );} catch ( err ){ $ ( '#create-total' ). textContent = '待填写' ; $ ( '#create-rounding-note' ). textContent = d . rounding_mode === 'yuan' ? '合计后四舍五入到元,请先填写商品金额与优惠。' : '保留原单金额,精确到分。' ;}
const cardCost = syncOrderCreditCardFees ( d , totalCents );
updateFeeTotal ( d . fee_items . filter ( item => ! isAutomaticCardFee ( item )), cardCost );
2026-10-22 17:06:32 +08:00
if ( $ ( '#order-form' ). dataset . orderEdit === 'true' ){ rememberOrderEditDraft ( d ); applyOrderEditRestrictions ();} else { localStorage . setItem ( 'mm-draft-' + session . user . id , JSON . stringify ( d )); if ( editDraft ) editDraft = d ;}
2026-10-17 19:50:24 +08:00
}
2026-10-23 09:49:36 +08:00
function syncOrderCreditCardFees ( d , total ){
const editing = $ ( '#order-form' ) ? . dataset . orderEdit === 'true' && orderEditEntry , original = editing ? . order ;
2026-10-25 14:19:24 +08:00
const preserve =!! editing && total !== null && original . netReceived === total && normalizePaymentAccount ( editing . paymentAccount || original . payment_account ) === normalizePaymentAccount ( d . payment_account );
2026-10-23 09:49:36 +08:00
document . querySelectorAll ( '#fee-rows .fee-automatic' ). forEach ( row =>{ row . classList . toggle ( 'is-replaced' , ! preserve ); row . querySelector ( '.fee-help' ). textContent = preserve ? ( d . date !== original . date ? '本次仅调整日期,按原逐笔金额和付款人重新记账。' : '保留原逐笔手续费,金额自动维护,可修改付款人。' ) : '原手续费将随收款冲回;实际费用合计只计下方重新计算的金额。' ; row . querySelector ( '[name="feePayer"]' ). disabled =! preserve || busy ||!! pending ();});
const preview = syncCreditCardPreview ( $ ( '#order-credit-card-fee' ), d . payment_account , total ,{ basis : '成交合计' , enabled :! preserve });
return preserve ? d . fee_items . filter ( isAutomaticCardFee ). reduce (( sum , item )=> sum + LedgerCalc . cents ( item . amount ), 0 ) : preview ;
}
function updateFeeTotal ( items , cardCost = 0 ,{ knownCardCost = 0 } = {}){
const target = $ ( '#fees-total' ); if ( ! target ) return ;
try { const missing = items . filter ( item => item . amount === '' ). length , total = items . reduce (( sum , item )=> sum + ( item . amount === '' ? 0 : LedgerCalc . cents ( item . amount )), 0 ) + ( cardCost ?? knownCardCost ); target . textContent = '实际费用合计' + ( missing || cardCost === null ? '(已知部分)' : '' ) + ':¥' + yuan ( total ) + ( missing ? ' · 还有 ' + missing + ' 项待补齐(没有成本填0)' : '' ) + ( cardCost === null ? ' · 信用卡手续费待计算' : '' );}
catch { target . textContent = '请检查费用金额' ;}
}
2026-10-17 19:50:24 +08:00
2026-10-23 09:49:36 +08:00
function validateOrderIdentity ( input ){
const customer = String ( input . customer ?? '' ). trim (), salesperson = String ( input . salesperson ?? '' ). trim ();
if ( ! customer || customer . length > 60 ) throw new Error ( '客户称呼/代号必填,请填写 1~60 字。' );
if ( ! salesperson || salesperson . length > 30 ) throw new Error ( '开单人必填,请填写 1~ 30 字。' );
2026-10-28 18:41:14 +08:00
if ( String ( input . internal_note ?? '' ). trim (). length > 500 ) throw new Error ( '内部备注最多填写500字。' );
2026-10-23 09:49:36 +08:00
return {... input , customer , salesperson };
}
function validateIssueDraft ( d ,{ requireIdentity = true } = {}){
if ( requireIdentity ) d = validateOrderIdentity ( d );
if ( isCreditCardAccount ( d . payment_account ) &&! creditCardAvailable ()) throw new Error ( '信用卡收款暂未准备好,请刷新后重新核对收款方式。' );
2026-10-17 19:50:24 +08:00
const missing = [];
const blank = v => v == null || String ( v ). trim () === '' ;
if ( ! d . lines . length ) throw new Error ( '请至少填写一行商品。' );
d . lines . forEach (( l , i )=>{
const item = '商品 ' + ( i + 1 );
if ( blank ( l . name )) missing . push ( item + '的名称' );
if ( blank ( l . quantity )) missing . push ( item + '的克重/数量' );
if ( l . pricingMode === 'auto' ){
if ( blank ( l . goldPrice )) missing . push ( item + '的金价/银价' );
if ( blank ( l . laborRate )) missing . push ( item + '的销售工费' );
} else if ( blank ( l . baseSale ?? l . sale )) missing . push ( item + '的基础金额' );
( l . charges || []). forEach (( c , j )=>{
if ( blank ( c . name )) missing . push ( item + '附加项目 ' + ( j + 1 ) + '的名称' );
if ( blank ( c . amount )) missing . push ( item + '的' + ( c . name || '附加项目 ' + ( j + 1 )) + '收费' );
});
if ( l . costParts ){
2026-10-25 14:19:24 +08:00
if ( ! [ 'material' , 'labor' ]. every ( key =>[ 'owner' , 'assistant' , 'assistant2' ]. includes ( l . costPayers ? .[ key ]))) throw new Error ( item + '请选择料费和进货工费付款人。' );
2026-10-17 19:50:24 +08:00
const result = LedgerCalc . purchaseCosts ( l );
2026-10-21 01:32:49 +08:00
if ( l . costMaterial ? . mode === 'pool' && ( ! validOrderDate ( l . costMaterial . poolId ) || l . costMaterial . poolId > d . date )) throw new Error ( item + '请选择不晚于订单日期的料价日期。' );
for ( const [ key , value ] of Object . entries ( result . parts )) if ( value === null &&! ( key === 'material' && l . costMaterial ? . mode === 'pool' )) missing . push ( item + '的' + LedgerCalc . costLabels [ key ]);
2026-10-17 19:50:24 +08:00
} else if ( blank ( l . cost )) missing . push ( item + '的货品成本' );
});
d . fee_items . forEach (( f , i )=>{
if ( blank ( f . note )) missing . push ( '费用 ' + ( i + 1 ) + '的名称' );
if ( blank ( f . amount )) missing . push (( f . note || '费用 ' + ( i + 1 )) + '的实际成本' );
});
if ( missing . length ) throw new Error ( '开单前请补齐:' + missing . join ( '、' ) + '。没有收费或成本的项目填0,不需要的费用请移除。' );
d . lines . forEach (( l , i )=>{ try { LedgerCalc . sale ( l ); if ( ! l . costParts ) LedgerCalc . cents ( l . cost , '货品成本' );} catch ( err ){ throw new Error ( '商品 ' + ( i + 1 ) + ': ' + err . message );}});
d . fee_items . forEach ( f => LedgerCalc . cents ( f . amount , f . note + '实际成本' ));
LedgerCalc . orderTotal ( d . lines . map ( l => LedgerCalc . sale ( l ). sale ), LedgerCalc . cents ( d . discount , '整单优惠' ), d . rounding_mode );
return d ;
}
2026-10-21 01:32:49 +08:00
async function finishIssuedOrderSave ( input , result ){
2026-10-22 04:21:26 +08:00
const id = result . id ; localStorage . removeItem ( 'mm-draft-' + session . user . id ); editDraft = null ; orderTemplateSelection = '' ; invalidateMaterialPools (); tab = 'orders' ;
2026-10-21 01:32:49 +08:00
const filters = getOrderBookFilters (); Object . assign ( filters ,{ mode : 'date' , date : input . date , q : '' , status : '' }); saveOrderBookFilters ();
$ ( '#main' ). innerHTML = heading ( 'ORDER SAVED' , '销售单据已生成' , '收款与交付已经记账,可查看同一张销售单。' ) + `<section class="panel"><p id="order-saved-status" aria-live="polite">正在读取已生成的销售单…</p><div class="actions"> ${ button ( '查看已生成销售单' , 'open-order' , 'primary' , `data-id=" ${ e ( id ) } "` ) }${ button ( '重新读取订单' , 'refresh' ) } </div></section>` ;
document . querySelectorAll ( 'nav button' ). forEach ( b => b . classList . toggle ( 'active' , b . dataset . tab === tab ));
try { await refresh (); await openOrder ( id ); toast ( currentOrder . materialCostPending ? '销售单据已生成;料费待补,补足购料后自动核算利润' : '销售单据已生成,收款、费用、出库和利润已记账' );}
catch { if ( $ ( '#order-saved-status' )) $ ( '#order-saved-status' ). textContent = '销售单据已经生成,最新订单暂未读到。请重新读取或查看已生成销售单;不要重复开单。' ; toast ( '销售单据已经生成,请重新读取查看;不要重复开单。' , true );}
}
2026-10-17 19:50:24 +08:00
function profitSummary ( o ){
const done = [ 'delivered' , 'returned' , 'cancelled' ]. includes ( o . status );
if ( ! done ) return { title : '实际订单利润' , value : '旧单待补齐' , hint : '现有旧单尚未完成销售记账,补齐款项、货品成本与费用后计算实际利润。' };
2026-10-21 01:32:49 +08:00
return { title : o . status === 'delivered' ? '实际订单利润' : '订单净利润' , value : o . profit === null ? ( o . materialCostPending ? '料费待补' : '成本未补齐' ) : '¥' + yuan ( o . profit ), hint : o . materialCostPending ? '补足当日购料后自动核算' : '已扣货品成本和实际费用' };
2026-10-17 19:50:24 +08:00
}
function validOrderDate ( value ){
if ( ! /^\d{4}-\d{2}-\d{2}$/ . test ( value || '' )) return false ;
const date = new Date ( value + 'T12:00:00Z' );
return ! Number . isNaN ( date . getTime ()) && date . toISOString (). slice ( 0 , 10 ) === value ;
}
function previousOrderDate ( today ){ const date = new Date ( today + 'T12:00:00Z' ); date . setUTCDate ( date . getUTCDate () - 1 ); return date . toISOString (). slice ( 0 , 10 );}
2026-10-26 17:07:26 +08:00
function orderBookPocketOptions (){
2026-11-08 03:30:58 +08:00
const active = activePocketKeys (), historical = [... new Set ([...( state ? . pocketCatalog || []). filter ( row => ! row . active ). map ( row => row . key ),...( state ? . orders || []). flatMap ( order =>( order . lines || []). map ( line => line . pocket ))]. filter ( pocket => pocket &&! active . includes ( pocket )))];
return [[ '' , '全部货盘' ],[ 'external' , '配货' ],... active . map ( pocket =>[ pocket , pocketLabel ( pocket )]),... historical . map ( pocket =>[ pocket , pocketLabel ( pocket ) + '(已停用 · 历史)' ])];
2026-10-26 17:07:26 +08:00
}
2026-10-29 02:28:48 +08:00
const orderBookStatusOptions = [[ '' , '全部状态' ],[ 'reviewed' , '已复核' ],[ 'unreviewed' , '未复核' ],[ 'after_sale' , '售后' ],[ 'recovery' , '回收' ],[ 'price_lock' , '锁价' ]];
2026-11-01 23:40:44 +08:00
const orderBookPeriodOptions = [[ 'today' , '今天' ],[ 'yesterday' , '昨天' ],[ 'month' , '本月' ],[ 'date' , '某天' ],[ 'range' , '自定义区间' ]];
2026-10-17 19:50:24 +08:00
function getOrderBookFilters (){
const user = String ( state . user . id || session . user . id || state . user . name );
if ( orderBookFilters && orderBookUser === user ) return orderBookFilters ;
let saved ; try { saved = JSON . parse ( sessionStorage . getItem ( 'mm-order-book-' + user ) || 'null' );} catch {}
orderBookUser = user ;
2026-11-01 23:40:44 +08:00
orderBookFilters = { mode : orderBookPeriodOptions . some (([ value ])=> value === saved ? . mode ) ? saved . mode : 'today' , date : validOrderDate ( saved ? . date ) ? saved . date : '' , from : typeof saved ? . from === 'string' ? saved . from : '' , to : typeof saved ? . to === 'string' ? saved . to : '' , q : typeof saved ? . q === 'string' ? saved . q : '' , status : orderBookStatusOptions . some (([ value ])=> value === saved ? . status ) ? saved . status : '' , member : teamMemberKeys . includes ( saved ? . member ) ? saved . member : '' , pocket : orderBookPocketOptions (). some (([ value ])=> value === saved ? . pocket ) ? saved . pocket : '' };
2026-10-17 19:50:24 +08:00
if ( orderBookFilters . mode === 'date' &&! orderBookFilters . date ) orderBookFilters . mode = 'today' ;
return orderBookFilters ;
}
function saveOrderBookFilters (){ try { sessionStorage . setItem ( 'mm-order-book-' + orderBookUser , JSON . stringify ( orderBookFilters ));} catch {}}
function orderBookRange (){
const f = getOrderBookFilters (), today = state . today ;
2026-11-01 23:40:44 +08:00
if ( f . mode === 'range' ){
if ( ! f . from ||! f . to ) throw new Error ( '请选择开始日期和结束日期。' );
if ( ! validOrderDate ( f . from ) ||! validOrderDate ( f . to ) || f . from < '2000-01-01' || f . to < '2000-01-01' ) throw new Error ( '日期区间无效,请选择2000-01-01起的有效日期。' );
if ( f . from > today || f . to > today ) throw new Error ( '请选择今天或之前的日期。' );
if ( f . from > f . to ) throw new Error ( '开始日期不能晚于结束日期。' );
return { from : f . from , date : f . to , name : '自定义区间' };
}
2026-10-17 19:50:24 +08:00
if ( f . mode === 'date' ){
if ( ! f . date ) throw new Error ( '请选择要查看的日期。' );
if ( ! validOrderDate ( f . date )) throw new Error ( '日期无效,请重新选择。' );
if ( f . date > today ) throw new Error ( '请选择今天或之前的日期。' );
return { from : f . date , date : f . date , name : f . date };
}
if ( f . mode === 'yesterday' ){ const date = previousOrderDate ( today ); return { from : date , date , name : '昨日' };}
return { from : f . mode === 'month' ? today . slice ( 0 , 7 ) + '-01' : today , date : today , name : f . mode === 'month' ? '本月' : '今日' };
}
2026-11-01 23:40:44 +08:00
function selectOrderBookPeriod ( mode ){
if ( ! orderBookPeriodOptions . some (([ value ])=> value === mode )) return ;
const f = getOrderBookFilters (); let range ; try { range = orderBookRange ();} catch {}
if ( mode === 'range' &&! f . from &&! f . to ){ f . from = range ? . from || state . today ; f . to = range ? . date || state . today ;}
if ( mode === 'date' &&! f . date ) f . date = range ? . date || state . today ;
f . mode = mode ; saveOrderBookFilters (); return loadOrderBook ();
}
function updateOrderBookDate ( input ){
const f = getOrderBookFilters ();
if ( input . id === 'order-date' ){ f . mode = 'date' ; f . date = input . value ;}
else { f . mode = 'range' ; f [ input . id === 'order-from' ? 'from' : 'to' ] = input . value ;}
saveOrderBookFilters (); return loadOrderBook ();
}
2026-10-26 14:44:07 +08:00
function orderBookScope (){ return '销售与利润按开单/交付日期,售后与回收按记录日期筛选。普通订单收款显示当前累计;锁价收退款按实际发生日期计入,待交付不计销售和利润。已取消订单不计本页销售汇总;直接回收付款计入每日购料,不计销售和利润。' ;}
2026-10-17 19:50:24 +08:00
function updateOrderBookDateControls ( range ){
document . querySelectorAll ( '[data-action="order-period"]' ). forEach ( b =>{ const active = b . dataset . period === orderBookFilters . mode ; b . classList . toggle ( 'active' , active ); b . setAttribute ( 'aria-pressed' , String ( active ));});
const input = $ ( '#order-date' ); if ( input ){ input . max = state . today ; if ( document . activeElement !== input ) input . value = orderBookFilters . mode === 'date' ? orderBookFilters . date : ( range ? . date || state . today );}
2026-11-01 23:40:44 +08:00
const single = $ ( '#order-single-date' ); if ( single ) single . hidden = orderBookFilters . mode !== 'date' ;
const fields = $ ( '#order-range-fields' ); if ( fields ) fields . hidden = orderBookFilters . mode !== 'range' ;
for ( const [ id , key ] of [[ 'order-from' , 'from' ],[ 'order-to' , 'to' ]]){ const field = $ ( '#' + id ); if ( field ){ field . max = state . today ; if ( document . activeElement !== field ) field . value = orderBookFilters [ key ] || '' ;}}
const caption = $ ( '#order-period-caption' ); if ( caption ) caption . textContent = range ? ( range . from === range . date ? range . date : range . from + ' 至 ' + range . date + ( orderBookFilters . mode === 'range' ? '(含首尾)' : '' )) : orderBookFilters . mode === 'range' ? '请选择有效的日期区间' : '指定日期' ;
2026-10-26 17:07:26 +08:00
const pocketHint = $ ( '#order-pocket-hint' ); if ( pocketHint ) pocketHint . hidden =! orderBookFilters . pocket ;
2026-10-29 02:28:48 +08:00
const statusHint = $ ( '#order-status-hint' ); if ( statusHint ) statusHint . hidden = orderBookFilters . status !== 'price_lock' ;
2026-10-17 19:50:24 +08:00
}
function showAfterSaleForm (){
2026-10-28 00:22:04 +08:00
afterSaleEntry = null ; ++ afterSaleRequest ; const dialog = afterSaleDialog ();
2026-10-25 14:19:24 +08:00
dialog . innerHTML = `<button class="dialog-close" data-action="close-after-sale" aria-label="关闭新增售后">× </button><h2 id="after-sale-title">新增售后</h2><p class="small muted">售后费用计入所选日期,并扣减当天利润。</p><form id="after-sale-form"><div class="grid two"> ${ field ( '售后日期' , 'date' , state . today , 'date' , `required max=" ${ e ( state . today ) } "` ) }${ field ( '售后项目' , 'project' , '' , 'text' , 'required maxlength="100" placeholder="例如:维修、补寄快递"' ) }${ field ( '客户' , 'customer' , '' , 'text' , 'required maxlength="60" placeholder="客户称呼或代号"' ) }${ moneyField ( '金额(元)' , 'amount' , '' ) }${ orderMemberField () } <label>谁支付<select name="payer" required><option value="" selected disabled>请选择</option> ${ opts ( teamMemberOptions (), '' ) } </select></label></div><div id="after-sale-error" aria-live="polite"></div><div class="form-actions"><span class="small muted">金额可填 0,请按实际支出填写。</span><div class="actions"> ${ button ( '取消' , 'close-after-sale' , 'quiet' ) } <button class="primary" type="submit">保存售后</button></div></div></form>` ;
2026-10-17 19:50:24 +08:00
dialog . showModal ();
}
async function showSavedAfterSale ( date ){
$ ( '#after-sale-dialog' ) ? . close (); toast ( '售后已保存,已计入 ' + date + ' 的费用与利润' ); await showRecordDate ( date );
}
2026-10-28 00:22:04 +08:00
async function showRecordDate ( date , stillCurrent ){
if ( stillCurrent &&! stillCurrent ()) return ;
2026-10-17 19:50:24 +08:00
currentOrder = null ; editDraft = null ; invalidateReport (); clearTimeout ( orderBookTimer ); ++ orderBookRequest ; tab = 'orders' ;
2026-10-28 00:22:04 +08:00
const filters = getOrderBookFilters (); Object . assign ( filters ,{ mode : 'date' , date , q : '' , status : '' , pocket : '' }); saveOrderBookFilters (); await refresh ( true , stillCurrent );
}
function afterSaleDialog (){
let dialog = $ ( '#after-sale-dialog' );
if ( ! dialog ){ dialog = document . createElement ( 'dialog' ); dialog . id = 'after-sale-dialog' ; dialog . setAttribute ( 'aria-labelledby' , 'after-sale-title' ); document . body . append ( dialog );}
if ( afterSaleDialogBound !== dialog ){ dialog . addEventListener ( 'close' ,()=>{ afterSaleEntry = null ; ++ afterSaleRequest ;}); afterSaleDialogBound = dialog ;}
return dialog ;
}
function closeAfterSaleDialog (){ afterSaleEntry = null ; ++ afterSaleRequest ; $ ( '#after-sale-dialog' ) ? . close ();}
function closeAfterSaleChanges (){ afterSaleReviewEntry = null ; ++ afterSaleChangesRequest ; $ ( '#after-sale-changes-dialog' ) ? . close ();}
function invalidateAfterSaleViews (){ closeAfterSaleDialog (); closeAfterSaleChanges ();}
function afterSaleValuesValid ( record ){
return record && validOrderDate ( record . date ) && typeof record . project === 'string' && record . project . trim () && record . project . length <= 100 && typeof record . customer === 'string' && record . customer . trim () && record . customer . length <= 60 && Number . isSafeInteger ( record . amount ) && record . amount >= 0 && teamMemberKeys . includes ( record . payer );
}
function validateAfterSaleRequest ( request ){
if ( ! request || typeof request . id !== 'string' ||! request . id || typeof request . afterSaleId !== 'string' ||! request . afterSaleId ||! Number . isSafeInteger ( request . revision ) || request . revision < 1 ||! Number . isSafeInteger ( request . recordRevision ) || request . recordRevision < 1 ||! [ 'pending' , 'approved' , 'rejected' ]. includes ( request . status ) ||! afterSaleValuesValid ( request . before ) ||! afterSaleValuesValid ( request . after ) || typeof request . canApprove !== 'boolean' ) throw new Error ( '售后修改申请资料未完整返回,请重新读取。' );
return request ;
}
function validateAfterSaleDetail ( detail , id ){
const record = detail ? . record , permissions = detail ? . permissions ;
if ( ! record || detail . id !== id || record . id !== id ||! Number . isSafeInteger ( detail . revision ) || detail . revision < 1 || record . revision !== detail . revision ||! afterSaleValuesValid ( record ) ||! teamMemberKeys . includes ( record . member ) || typeof permissions ? . canEdit !== 'boolean' || typeof permissions . canDirectEdit !== 'boolean' || typeof permissions . requiresApproval !== 'boolean' ||! Array . isArray ( detail . history )) throw new Error ( '售后记录资料未完整返回,请重新读取后再修改。' );
if ( detail . pending && ( validateAfterSaleRequest ( detail . pending ). afterSaleId !== id || permissions . canEdit )) throw new Error ( '售后修改状态不一致,请重新读取。' );
for ( const request of detail . history ) if ( validateAfterSaleRequest ( request ). afterSaleId !== id ) throw new Error ( '售后修改历史不一致,请重新读取。' );
return detail ;
}
function afterSaleStatus ( request ){ return { pending : '待麦麦审批' , approved : '已同意' , rejected : '已驳回' }[ request . status ] || '状态待确认' ;}
function afterSaleTime ( value ){ return String ( value || '未提供' ). replace ( 'T' , ' ' ). replace ( /\.\d{3}Z$/ , ' UTC' ). replace ( /Z$/ , ' UTC' );}
function afterSaleComparisonHTML ( raw ){
const request = validateAfterSaleRequest ( raw ), pair = ( title , key , format = value => value )=>{ const changed = request . before [ key ] !== request . after [ key ]; return `<tr ${ changed ? ' class="order-change-modified"' : '' } ><th scope="row"> ${ e ( title ) }${ changed ? '<span class="change-mark">已修改</span>' : '' } </th><td> ${ e ( format ( request . before [ key ])) } </td><td> ${ e ( format ( request . after [ key ])) } </td></tr>` ;};
return `<div class="table-wrap after-sale-comparison"><table class="order-change-table" aria-label="售后修改原值与申请值对照"><thead><tr><th>核对项目</th><th>原值(申请时)</th><th>申请值(同意后)</th></tr></thead><tbody> ${ pair ( '售后日期' , 'date' ) }${ pair ( '售后项目' , 'project' ) }${ pair ( '客户' , 'customer' ) }${ pair ( '金额' , 'amount' , value => '¥' + yuan ( value )) }${ pair ( '谁支付' , 'payer' , teamMemberName ) } </tbody></table></div>` ;
}
function afterSaleRecordHTML ( record ){
return `<dl class="after-sale-facts"> ${ [[ '售后日期' , record . date ],[ '售后项目' , record . project ],[ '客户' , record . customer ],[ '金额' , '¥' + yuan ( record . amount )],[ '谁支付' , teamMemberName ( record . payer )],[ '订单归属' , teamMemberName ( record . member )]]. map (([ title , value ])=> `<div><dt> ${ e ( title ) } </dt><dd> ${ e ( value ) } </dd></div>` ). join ( '' ) } </dl>` ;
}
function afterSaleHistoryHTML ( request ){
return `<li><strong> ${ e ( afterSaleStatus ( request )) } </strong><small> ${ e ( request . requesterName || '申请人未提供' ) } · ${ e ( afterSaleTime ( request . created )) } </small> ${ request . reason ? `<p class="change-reason">修改说明: ${ e ( request . reason ) } </p>` : '' }${ request . status !== 'pending' ? `<small>复核人: ${ e ( request . reviewerName || '未提供' ) } · ${ e ( afterSaleTime ( request . reviewed )) } </small> ${ request . note ? `<p class="change-reason"> ${ request . status === 'rejected' ? '驳回意见' : '复核备注' } : ${ e ( request . note ) } </p>` : '' } ` : '' } <details><summary>查看原值与申请值</summary> ${ afterSaleComparisonHTML ( request ) } </details></li>` ;
}
function afterSaleRequiresApproval ( date ){
const detail = afterSaleEntry ? . detail ; if ( ! detail ) return true ;
return detail . permissions . requiresApproval ||! detail . permissions . canDirectEdit || state . user . role !== 'owner' && ( detail . record . date !== state . today || date !== state . today );
}
function syncAfterSaleEditMode (){
const form = $ ( '#after-sale-edit-form' ); if ( ! form ||! afterSaleEntry ) return ;
const approval = afterSaleRequiresApproval ( form . querySelector ( '[name="date"]' ) ? . value ), submit = form . querySelector ( '[type="submit"]' ), mode = $ ( '#after-sale-edit-mode' );
if ( submit ) submit . textContent = approval ? '提交修改申请' : '直接保存修改' ;
if ( mode ) mode . textContent = approval ? '本次修改需麦麦审批。同意后才更新售后费用和利润;待审批期间仍按原记录计账。' : state . user . role === 'owner' ? '保存后直接更新这笔售后,费用与利润按修改后的日期重算。' : '原日期与修改后日期均为今天,直接保存;改为其他日期须提交麦麦审批。' ;
form . dataset . approval = String ( approval ); applyAfterSaleRestrictions (); return approval ;
}
function renderAfterSaleEdit (){
const entry = afterSaleEntry , detail = entry ? . detail ; if ( ! entry || entry . user !== orderDetailUser () ||! detail ) return ;
const record = detail . record , request = detail . pending , dialog = afterSaleDialog ();
const pendingHTML = request ? `<section class="after-sale-pending"><h3>待麦麦审批</h3><p class="small muted">申请尚未生效,当前仍按原记录计账。</p> ${ afterSaleComparisonHTML ( request ) }${ request . reason ? `<p class="change-reason">修改说明: ${ e ( request . reason ) } </p>` : '' }${ state . user . role === 'owner' ? button ( '查看并复核' , 'after-sale-change-open' , 'primary' , `data-id=" ${ e ( request . id ) } "` ) : '<p class="small muted">麦麦同意后才更新这笔记录。</p>' } </section>` : '' ;
dialog . innerHTML = `<button class="dialog-close" data-action="close-after-sale" aria-label="关闭售后记录">× </button><h2 id="after-sale-title">修改售后</h2> ${ detail . permissions . canEdit ? `<form id="after-sale-edit-form" data-id=" ${ e ( record . id ) } "><div class="grid two"> ${ field ( '售后日期' , 'date' , record . date , 'date' , `required max=" ${ e ( state . today ) } "` ) }${ field ( '售后项目' , 'project' , record . project , 'text' , 'required maxlength="100"' ) }${ field ( '客户' , 'customer' , record . customer , 'text' , 'required maxlength="60"' ) }${ moneyField ( '金额(元)' , 'amount' ,( record . amount / 100 ). toFixed ( 2 )) }${ orderMemberField ( record . member , true ) }${ choice ( '谁支付' , 'payer' , teamMemberOptions (), record . payer ) } </div><div class="note" id="after-sale-edit-mode" aria-live="polite"></div><label>修改说明(选填)<textarea name="reason" rows="2" maxlength="200" placeholder="例如:售后金额或付款人录错。"></textarea></label><div id="after-sale-edit-error" aria-live="polite"></div><div class="form-actions"><span class="small muted">金额可填 0。归属沿用原记录。</span><div class="actions"> ${ button ( '取消' , 'close-after-sale' , 'quiet' ) } <button type="submit" class="primary">保存修改</button></div></div></form>` : ` ${ afterSaleRecordHTML ( record ) }${ ! request ? `<p class="note"> ${ e ( detail . permissions . reason || '这笔售后当前不可修改。' ) } </p>` : '' }${ pendingHTML } ` } <div id="after-sale-read-error" aria-live="polite"></div> ${ detail . history . length ? `<details><summary>售后修改记录( ${ detail . history . length } ) </summary><ul class="timeline">${ detail . history . map ( afterSaleHistoryHTML ). join ( '' ) } </ul></details>` : '' } ` ;
syncAfterSaleEditMode ();
}
async function openAfterSaleEdit ( id ){
if ( busy ) throw new Error ( '正在保存,请稍候。' );
const dialog = afterSaleDialog (), request =++ afterSaleRequest , user = orderDetailUser (); afterSaleEntry = null ;
const active = ()=> request === afterSaleRequest && user === orderDetailUser () && dialog === $ ( '#after-sale-dialog' ) && dialog . open ;
dialog . innerHTML = `<button class="dialog-close" data-action="close-after-sale" aria-label="关闭售后记录">× </button><h2 id="after-sale-title">修改售后</h2><p role="status">正在读取售后记录…</p>` ; if ( ! dialog . open ) dialog . showModal ();
try { await refresh ( false , active ); if ( ! active ()) return ; const detail = validateAfterSaleDetail ( await api ( '/api/after-sales/' + encodeURIComponent ( id )), id ); if ( ! active ()) return ; afterSaleEntry = { id , user , detail , invalid : false }; renderAfterSaleEdit ();}
catch ( err ){ if ( ! active ()) return ; dialog . innerHTML = `<button class="dialog-close" data-action="close-after-sale" aria-label="关闭售后记录">× </button><h2 id="after-sale-title">修改售后</h2><div class="error"> ${ e ( err . message ) } </div> ${ button ( '重新读取售后' , 'after-sale-edit' , '' , `data-id=" ${ e ( id ) } "` ) } ` ;}
}
function applyAfterSaleRestrictions (){
for ( const [ selector , entry ] of [[ '#after-sale-edit-form' , afterSaleEntry ],[ '#after-sale-review-form' , afterSaleReviewEntry ]]){
const form = $ ( selector ); if ( ! form ) continue ; const blocked = busy ||!! pending () ||! entry || entry . invalid || entry . user !== orderDetailUser ();
form . querySelectorAll ( 'input,select,textarea,button' ). forEach ( control =>{ control . disabled = [ 'close-after-sale' , 'after-sale-review-cancel' ]. includes ( control . dataset . action ) ? busy : [ 'after-sale-edit' , 'after-sale-change-open' , 'retry' ]. includes ( control . dataset . action ) ? busy : blocked ;});
}
}
function afterSaleOperation ( url ){
let match = String ( url ). match ( /^\/api\/after-sales\/changes\/([^/]+)\/(approve|reject)$/ ); if ( match ) return { kind : match [ 2 ], id : decodeURIComponent ( match [ 1 ])};
match = String ( url ). match ( /^\/api\/after-sales\/([^/]+)\/update$/ ); return match ? { kind : 'update' , id : decodeURIComponent ( match [ 1 ])} : null ;
}
function captureAfterSaleView ( operation ){ const update = operation . kind === 'update' ; return { user : orderDetailUser (), tab , update , version : update ? afterSaleRequest : afterSaleChangesRequest , dialog : $ ( update ? '#after-sale-dialog' : '#after-sale-changes-dialog' )};}
function afterSaleOperationError ( err , operation ){
const review = operation ? operation . kind !== 'update' :!! $ ( '#after-sale-review-form' ), entry = review ? afterSaleReviewEntry : afterSaleEntry , id = operation ? . id || ( review ? entry ? . request . id : entry ? . id );
err . message = err . message . replace ( '不要重新开单' , '不要重复提交售后修改' );
if ([ 403 , 404 , 409 ]. includes ( err . status ) && entry ){ entry . invalid = true ; const verified = $ ( '#after-sale-review-form [name="verified"]' ); if ( verified ) verified . checked = false ;}
const target = $ ( review ? '#after-sale-review-error' : '#after-sale-edit-error' ) || $ ( '#after-sale-read-error' );
if ( target ) target . innerHTML = `<div class="error"> ${ e ( err . message ) }${ pending () ? ' ' + button ( '恢复原操作' , 'retry' , 'danger' ) : id ? ' ' + button ( review ? '重新读取申请并复核' : '重新读取售后' , review ? 'after-sale-change-open' : 'after-sale-edit' , '' , `data-id=" ${ e ( id ) } "` ) : '' } </div>` ;
applyAfterSaleRestrictions (); toast ( err . message , true );
}
async function submitAfterSaleEdit ( form ){
const entry = afterSaleEntry ; if ( form !== $ ( '#after-sale-edit-form' ) ||! entry || entry . invalid || entry . user !== orderDetailUser () || entry . id !== form . dataset . id ||! entry . detail . permissions . canEdit || entry . detail . pending ) throw new Error ( '请重新读取售后记录后再修改。' );
const read = name => String ( form . querySelector ( '[name="' + name + '"]' ) ? . value || '' ). trim (), input = { revision : entry . detail . revision , date : read ( 'date' ), project : read ( 'project' ), customer : read ( 'customer' ), amount : read ( 'amount' ), payer : read ( 'payer' ), reason : read ( 'reason' )};
if ( ! validOrderDate ( input . date ) || input . date > state . today ) throw new Error ( '售后日期请选择今天或之前的有效日期。' );
if ( ! input . project || input . project . length > 100 ) throw new Error ( '售后项目请填写1~ 100字。' ); if ( ! input . customer || input . customer . length > 60 ) throw new Error ( '客户请填写1~60字的称呼或代号。' ); if ( ! teamMemberKeys . includes ( input . payer )) throw new Error ( '请选择这笔售后由谁支付。' ); if ( input . reason . length > 200 ) throw new Error ( '修改说明最多200字。' ); LedgerCalc . cents ( input . amount , '售后金额' );
syncAfterSaleEditMode (); $ ( '#after-sale-edit-error' ). innerHTML = '' ; const url = '/api/after-sales/' + encodeURIComponent ( entry . id ) + '/update' ;
const view = captureAfterSaleView ({ kind : 'update' }); try { const result = await mutate ( url , input ); await finishAfterSaleSave ( url , input , result , view );} catch ( err ){ if ( view . user === orderDetailUser ()) afterSaleOperationError ( err ,{ kind : 'update' , id : entry . id });}
}
function afterSaleChangesDialog (){
let dialog = $ ( '#after-sale-changes-dialog' ); if ( ! dialog ){ dialog = document . createElement ( 'dialog' ); dialog . id = 'after-sale-changes-dialog' ; dialog . setAttribute ( 'aria-labelledby' , 'after-sale-changes-title' ); document . body . append ( dialog );}
if ( afterSaleChangesDialogBound !== dialog ){ dialog . addEventListener ( 'close' ,()=>{ afterSaleReviewEntry = null ; ++ afterSaleChangesRequest ;}); afterSaleChangesDialogBound = dialog ;}
return dialog ;
}
async function loadAfterSaleChangeCount (){
const element = $ ( '#after-sale-changes-entry' ); if ( ! element ) return ; const user = orderDetailUser (), name = state . user . role === 'owner' ? '售后修改复核' : '售后修改申请' ;
try { const data = await api ( '/api/after-sales/changes?status=pending' ); if ( ! Number . isSafeInteger ( data . counts ? . pending ) || data . counts . pending < 0 ) throw new Error ( '数量未返回' ); if ( element === $ ( '#after-sale-changes-entry' ) && user === orderDetailUser ()) element . textContent = name + '( ' + data . counts . pending + ') ' ;}
catch { if ( element === $ ( '#after-sale-changes-entry' ) && user === orderDetailUser ()) element . textContent = name + '(读取失败)' ;}
}
async function openAfterSaleChanges (){
closeAfterSaleDialog (); const dialog = afterSaleChangesDialog (); if ( ! dialog . open ) dialog . showModal (); await loadAfterSaleChanges ();
}
function afterSaleChangeListHTML ( data ){
if ( ! Array . isArray ( data . requests ) ||! data . counts ||! [ 'pending' , 'approved' , 'rejected' ]. every ( key => Number . isSafeInteger ( data . counts [ key ]) && data . counts [ key ] >= 0 )) throw new Error ( '售后修改列表未完整返回,请重新读取。' );
const tabs = [[ 'pending' , '待审批' ],[ 'approved' , '已同意' ],[ 'rejected' , '已驳回' ],[ 'all' , '全部' ]]. map (([ status , name ])=> button ( name + ( status === 'all' ? '' : '( ' + data . counts [ status ] + ') ' ), 'after-sale-changes-filter' , status === afterSaleChangesStatus ? 'active' : '' , `data-status=" ${ e ( status ) } " aria-pressed=" ${ status === afterSaleChangesStatus } "` )). join ( '' );
const rows = data . requests . map ( validateAfterSaleRequest );
return `<div class="change-list-tabs" role="group" aria-label="售后修改申请状态"> ${ tabs } </div> ${ rows . length ? `<div class="table-wrap"><table class="change-list-table"><thead><tr><th>售后记录</th><th>修改后日期</th><th>申请人</th><th>申请时间</th><th>状态</th><th>操作</th></tr></thead><tbody> ${ rows . map ( request => `<tr><td><strong> ${ e ( request . before . customer ) } </strong><div class="small muted"> ${ e ( request . before . date ) } · ${ e ( request . before . project ) } </div></td><td> ${ e ( request . after . date ) } </td><td> ${ e ( request . requesterName || '未提供' ) } </td><td> ${ e ( afterSaleTime ( request . created )) } </td><td> ${ e ( afterSaleStatus ( request )) }${ request . stale ? '<div class="small danger-text">原记录已有变动</div>' : '' } </td><td> ${ button ( state . user . role === 'owner' && request . status === 'pending' ? '查看并复核' : '查看修改' , 'after-sale-change-open' , '' , `data-id=" ${ e ( request . id ) } "` ) } </td></tr>` ). join ( '' ) } </tbody></table></div>` : '<p class="empty">没有符合状态的售后修改申请。</p>' } ` ;
}
async function loadAfterSaleChanges (){
const dialog = afterSaleChangesDialog (), request =++ afterSaleChangesRequest , user = orderDetailUser (); afterSaleReviewEntry = null ;
const active = ()=> request === afterSaleChangesRequest && user === orderDetailUser () && dialog . open ;
dialog . innerHTML = `<button class="dialog-close" data-action="after-sale-changes-close" aria-label="关闭售后修改复核">× </button><h2 id="after-sale-changes-title"> ${ state . user . role === 'owner' ? '售后修改复核' : '售后修改申请' } </h2><p class="small muted"> ${ state . user . role === 'owner' ? '跨日期查看售后修改,核对原值与申请值后复核。' : '查看自己归属售后的修改申请。' } 待审批期间仍按原记录计账。</p><div id="after-sale-changes-content" role="status">正在读取…</div>` ;
try { const data = await api ( '/api/after-sales/changes?' + new URLSearchParams ({ status : afterSaleChangesStatus })); if ( active ()) $ ( '#after-sale-changes-content' ). innerHTML = afterSaleChangeListHTML ( data );}
catch ( err ){ if ( active ()) $ ( '#after-sale-changes-content' ). innerHTML = `<div class="error"> ${ e ( err . message ) } </div> ${ button ( '重新读取列表' , 'after-sale-changes-reload' ) } ` ;}
}
function renderAfterSaleReview (){
const entry = afterSaleReviewEntry ; if ( ! entry || entry . user !== orderDetailUser ()) return ; const request = entry . request , canReview = state . user . role === 'owner' && request . status === 'pending' , dialog = afterSaleChangesDialog ();
dialog . innerHTML = `<button class="dialog-close" data-action="after-sale-changes-close" aria-label="关闭售后修改复核">× </button><h2 id="after-sale-changes-title">售后修改 ${ request . status === 'pending' ? '复核' : '记录' } </h2><div class="actions"> ${ button ( '返回申请列表' , 'after-sale-changes-reload' , 'quiet' ) } </div><p> ${ e ( afterSaleStatus ( request )) } · ${ e ( request . requesterName || '申请人未提供' ) } · ${ e ( afterSaleTime ( request . created )) } </p><p class="small muted">订单归属: ${ e ( teamMemberName ( request . member )) } 。 ${ request . status === 'pending' ? '本次申请尚未生效;麦麦同意后才更新原售后。' : '' } </p> ${ request . reason ? `<p class="change-reason">修改说明: ${ e ( request . reason ) } </p>` : '' }${ afterSaleComparisonHTML ( request ) }${ request . stale ? `<div class="error"> ${ e ( request . staleReason || '原记录已有变动,不能同意这份旧申请。请驳回后按最新记录重新申请。' ) } </div>` : '' }${ request . status !== 'pending' ? `<p class="small muted">复核人: ${ e ( request . reviewerName || '未提供' ) } · ${ e ( afterSaleTime ( request . reviewed )) } </p> ${ request . note ? `<p class="change-reason"> ${ request . status === 'rejected' ? '驳回意见' : '复核备注' } : ${ e ( request . note ) } </p>` : '' } ` : '' } <div id="after-sale-review-actions"> ${ canReview ? `<div class="actions"> ${ request . canApprove &&! request . stale ? button ( '同意修改' , 'after-sale-review-decision' , 'primary' , 'data-kind="approve"' ) : '' }${ button ( '驳回申请' , 'after-sale-review-decision' , '' , 'data-kind="reject"' ) } </div>` : '' } </div><div id="after-sale-review-error" aria-live="polite"></div>` ;
}
async function openAfterSaleChange ( id ){
if ( busy ) throw new Error ( '正在保存,请稍候。' ); closeAfterSaleDialog (); const dialog = afterSaleChangesDialog (), request =++ afterSaleChangesRequest , user = orderDetailUser (); afterSaleReviewEntry = null ;
const active = ()=> request === afterSaleChangesRequest && user === orderDetailUser () && dialog . open ;
dialog . innerHTML = `<button class="dialog-close" data-action="after-sale-changes-close" aria-label="关闭售后修改复核">× </button><h2 id="after-sale-changes-title">售后修改复核</h2><p role="status">正在读取申请…</p>` ; if ( ! dialog . open ) dialog . showModal ();
try { const data = validateAfterSaleRequest ( await api ( '/api/after-sales/changes/' + encodeURIComponent ( id ))); if ( data . id !== id ) throw new Error ( '申请编号不一致,请重新读取。' ); if ( ! active ()) return ; afterSaleReviewEntry = { request : data , user , invalid : false , kind : null }; renderAfterSaleReview ();}
catch ( err ){ if ( active ()) dialog . innerHTML = `<button class="dialog-close" data-action="after-sale-changes-close" aria-label="关闭售后修改复核">× </button><h2 id="after-sale-changes-title">售后修改复核</h2><div class="error"> ${ e ( err . message ) } </div><div class="actions"> ${ button ( '重新读取申请' , 'after-sale-change-open' , '' , `data-id=" ${ e ( id ) } "` ) }${ button ( '返回申请列表' , 'after-sale-changes-reload' ) } </div>` ;}
}
function showAfterSaleReviewForm ( kind ){
const entry = afterSaleReviewEntry , request = entry ? . request ; if ( state . user . role !== 'owner' ) throw new Error ( '请使用麦麦账号复核。' ); if ( ! entry || entry . invalid || entry . user !== orderDetailUser () || request . status !== 'pending' ) throw new Error ( '请重新读取申请后再复核。' ); if ( ! [ 'approve' , 'reject' ]. includes ( kind )) throw new Error ( '请选择同意或驳回。' ); if ( kind === 'approve' && ( ! request . canApprove || request . stale )) throw new Error ( '原记录已有变动,请重新读取并核对。' );
entry . kind = kind ; $ ( '#after-sale-review-actions' ). innerHTML = `<form id="after-sale-review-form" data-id=" ${ e ( request . id ) } " data-kind=" ${ kind } "><h3> ${ kind === 'approve' ? '同意售后修改' : '驳回售后修改' } </h3><label> ${ kind === 'approve' ? '复核备注(选填)' : '驳回意见' } <textarea name="note" rows="2" maxlength="200" ${ kind === 'reject' ? 'required' : '' } ></textarea></label> ${ kind === 'approve' ? '<label class="check"><input type="checkbox" name="verified" required>已核对原值、申请值、日期、金额和付款人。</label>' : '' } <div class="form-actions"> ${ button ( '取消' , 'after-sale-review-cancel' , 'quiet' ) } <button type="submit" class=" ${ kind === 'approve' ? 'primary' : '' } "> ${ kind === 'approve' ? '确认同意修改' : '确认驳回申请' } </button></div></form>` ; applyAfterSaleRestrictions ();
}
async function submitAfterSaleReview ( form ){
const entry = afterSaleReviewEntry , request = entry ? . request , kind = form . dataset . kind ; if ( state . user . role !== 'owner' ) throw new Error ( '请使用麦麦账号复核。' ); if ( form !== $ ( '#after-sale-review-form' ) ||! entry || entry . invalid || entry . user !== orderDetailUser () || entry . kind !== kind || form . dataset . id !== request . id || request . status !== 'pending' ) throw new Error ( '请重新读取申请后再复核。' ); if ( kind === 'approve' && ( ! request . canApprove || request . stale )) throw new Error ( '原记录已有变动,请重新读取并核对。' ); if ( ! [ 'approve' , 'reject' ]. includes ( kind )) throw new Error ( '请选择同意或驳回。' );
const note = String ( form . querySelector ( '[name="note"]' ) ? . value || '' ). trim (); if ( kind === 'reject' &&! note ) throw new Error ( '请填写驳回意见。' ); if ( note . length > 200 ) throw new Error ( '复核意见最多200字。' ); if ( kind === 'approve' &&! form . querySelector ( '[name="verified"]' ) ? . checked ) throw new Error ( '请核对修改前后内容并勾选确认。' );
const input = { revision : request . revision , note ,...( kind === 'approve' ? { verified : true } : {})}, url = '/api/after-sales/changes/' + encodeURIComponent ( request . id ) + '/' + kind ; $ ( '#after-sale-review-error' ). innerHTML = '' ;
const view = captureAfterSaleView ({ kind }); try { const result = await mutate ( url , input ); await finishAfterSaleSave ( url , input , result , view );} catch ( err ){ if ( view . user === orderDetailUser ()) afterSaleOperationError ( err ,{ kind , id : request . id });}
}
async function finishAfterSaleSave ( url , input , result , savedView ){
const operation = afterSaleOperation ( url ), update = operation . kind === 'update' , applied = update && result . applied === true , message = update ? ( applied ? '售后修改已保存' : '售后修改申请已提交,待麦麦审批' ) : operation . kind === 'approve' ? '已同意售后修改' : '已驳回售后修改申请' ;
const view = savedView || captureAfterSaleView ( operation ); if ( view . user !== orderDetailUser ()) return ;
const replaceView = view . dialog ? . open && view . dialog === $ ( update ? '#after-sale-dialog' : '#after-sale-changes-dialog' ) && view . version === ( update ? afterSaleRequest : afterSaleChangesRequest );
if ( replaceView ){ if ( update ){ afterSaleEntry = null ; ++ afterSaleRequest ;} else { afterSaleReviewEntry = null ; ++ afterSaleChangesRequest ;} view . dialog . innerHTML = `<button class="dialog-close" data-action=" ${ update ? 'close-after-sale' : 'after-sale-changes-close' } " aria-label="关闭">× </button><h2 id=" ${ update ? 'after-sale-title' : 'after-sale-changes-title' } "> ${ e ( message ) } </h2><p>正在刷新…</p>` ;}
const version = update ? afterSaleRequest : afterSaleChangesRequest , active = ()=> replaceView && view . user === orderDetailUser () && view . tab === tab && view . dialog . open && version === ( update ? afterSaleRequest : afterSaleChangesRequest ); invalidateReport ();
try {
if ( applied && tab === 'orders' && active ()) await showRecordDate ( result . record ? . record ? . date || input . date ,()=> view . user === orderDetailUser () && view . tab === tab );
else { await refresh ( false ,()=> view . user === orderDetailUser ()); if ( view . user !== orderDetailUser ()) return ; if ( tab === 'orders' ) await renderOrders (); else if ( tab === 'report' ) await renderReport ();}
if ( view . user !== orderDetailUser ()) return ;
if ( update && active ()){ if ( applied ) closeAfterSaleDialog (); else await openAfterSaleEdit ( operation . id );}
if ( ! update && active ()){ afterSaleReviewEntry = { request : validateAfterSaleRequest ( result ), user : orderDetailUser (), invalid : false , kind : null }; renderAfterSaleReview ();}
await loadAfterSaleChangeCount (); if ( view . user === orderDetailUser ()) toast ( message );
} catch ( err ){
if ( view . user !== orderDetailUser ()) return ;
if ( active ()) view . dialog . innerHTML = `<button class="dialog-close" data-action=" ${ update ? 'close-after-sale' : 'after-sale-changes-close' } " aria-label="关闭">× </button><h2 id=" ${ update ? 'after-sale-title' : 'after-sale-changes-title' } "> ${ e ( message ) } </h2><p class="error">结果已保存,刷新失败: ${ e ( err . message ) } 。请重新读取查看结果。</p> ${ button ( update ? '重新读取售后' : '重新读取申请' , update ? 'after-sale-edit' : 'after-sale-change-open' , '' , `data-id=" ${ e ( operation . id ) } "` ) } ` ; toast ( message + ',请重新读取查看结果。' , true );
}
2026-10-17 19:50:24 +08:00
}
2026-10-23 00:21:53 +08:00
function peopleCountText ( count , part = null ){
const value = part ? count ? .[ part ] : count ;
2026-10-25 14:19:24 +08:00
if ( ! value ||! Object . hasOwn ( value , 'endTotal' ) ||! Object . hasOwn ( value , 'netChange' )) return '尚未取得总人数' ;
const period = count . from !== count . date , total = value . endTotal === null ? ( period ? '结束日未记录' : '当日未记录' ) : value . endTotal + ' 人(已记录)' ;
2026-10-29 00:27:36 +08:00
const baseline = value . baselineDate , comparison = '较上次记录' + ( baseline ? '( ' + baseline + ') ' : '' );
return total + ' · ' + ( period ? '本期净增 ' + ( value . netChange === null ? '未知(' + peopleCountUnknownReason ( value . netChangeReason , true ) + ') ' : peopleCountSignedText ( value . netChange )) + ( baseline ? '(基准 ' + baseline + ') ' : '' ) : value . netChange === null ? ( value . endTotal !== null && value . netChangeReason === 'missing-previous' ? '首次记录(暂无上次记录)' : comparison + '变化未知(' + peopleCountUnknownReason ( value . netChangeReason ) + ') ' ) : comparison + peopleCountDeltaText ( value . netChange ));
2026-10-25 14:19:24 +08:00
}
function peopleCountDisplayName ( name , period = false ){ return name . replace ( '人数' , period ? '结束日总人数' : '当日总人数' );}
function peopleCountNumber ( value ){ return Number . isSafeInteger ( value ) && value >= 0 && value <= 1000000 ;}
function peopleCountPreviousDate ( date ){ return new Date ( Date . parse ( date + 'T00:00:00Z' ) - 86400000 ). toISOString (). slice ( 0 , 10 );}
function peopleCountChangeReason ( current , previous ){ return current === null ? ( previous === null ? 'missing-both' : 'missing-current' ) : previous === null ? 'missing-previous' : null ;}
2026-10-29 00:27:36 +08:00
function peopleCountUnknownReason ( reason , period = false ){ return ({ 'missing-current' : period ? '结束日未记录' : '当日未记录' , 'missing-previous' : period ? '开始日前暂无记录' : '暂无上次记录' , 'missing-both' : period ? '结束日未记录,开始日前暂无记录' : '当日未记录,暂无上次记录' })[ reason ] || '缺少人数记录' ;}
2026-10-25 14:19:24 +08:00
function peopleCountDeltaText ( value ){ return value > 0 ? '新增 ' + value + ' 人' : value < 0 ? '减少 ' + Math . abs ( value ) + ' 人' : '无变化(0 人)' ;}
function peopleCountSignedText ( value ){ return ( value > 0 ? '+' : '' ) + value + ' 人' ;}
2026-10-23 00:21:53 +08:00
function peopleCountHTML ( count ){
2026-10-25 14:19:24 +08:00
const period = count ? . from !== count ? . date ;
2026-10-29 00:27:36 +08:00
return peopleParts (). map (([ part , name ])=> `<div class="people-count-item"><strong> ${ peopleCountDisplayName ( name , period ) } </strong><span> ${ e ( peopleCountText ( count , part )) } </span></div>` ). join ( '' ) + `<small> ${ period ? '本期净增=结束日总人数-各自开始日前最近记录总人数;缺任一端则未知,每日总人数不累加。' : '各自与上次有记录日期比较,未记录日自动跳过;0为有效记录。' } 不随订单搜索与状态筛选变化。</small>` ;
2026-10-25 14:19:24 +08:00
}
2026-10-29 00:27:36 +08:00
function peopleCountReportLines ( count ){ const period = count ? . from !== count ? . date ; return peopleParts (). map (([ part , name ])=> ` ${ peopleCountDisplayName ( name , period ) } : ${ peopleCountText ( count , part ) }${ period ? '(期末 ' + ( count ? . date || '未知' ) + ';开始日前最近记录 ' + ( count ? .[ part ] ? . baselineDate || '暂无' ) + ') ' : '' } ` );}
function validPeopleCountDaily ( entry , date , names ){ return entry ? . mode === 'daily-total' && entry . date === date && entry . previousDate === peopleCountPreviousDate ( date ) && names . every ( name =>{ const current = entry [ name ], previous = entry . previous ? .[ name ], prefix = name . replace ( /Count$/ , '' ), previousDate = entry . previousDates ? .[ prefix ]; return ( current === null || peopleCountNumber ( current )) && ( previous === null || peopleCountNumber ( previous )) && ( previous === null ? previousDate === null : validOrderDate ( previousDate ) && previousDate >= '2000-01-01' && previousDate < date ) && entry [ prefix + 'Change' ] === ( current === null || previous === null ? null : current - previous ) && entry [ prefix + 'ChangeReason' ] === peopleCountChangeReason ( current , previous );});}
2026-10-25 14:19:24 +08:00
function syncPeopleCountPreview (){
const form = $ ( '#people-count-form' ), target = $ ( '#people-count-preview' ); if ( ! form ||! target ) return ;
2026-10-29 00:27:36 +08:00
if ( ! peopleEntry || peopleEntry . date !== form . elements . date . value || peopleEntryUser !== ( state . user . id || state . user . name )){ target . innerHTML = '<p class="small muted">正在读取上次记录…</p>' ; return ;}
target . innerHTML = peopleParts (). map (([ part , name ])=>{ const field = part + 'Count' , previous = peopleEntry . previous [ field ], previousDate = peopleEntry . previousDates [ part ]; let current ; try { current = peopleCountInput ( form . elements [ field ]. value , peopleCountDisplayName ( name ), true );} catch { return `<div class="people-count-preview-item"><strong> ${ e ( name . replace ( '人数' , '' )) } </strong><span class="small muted">请填写有效的当日总人数后查看变化。</span></div>` ;} const change = current === null || previous === null ? null : current - previous ; return `<div class="people-count-preview-item"><strong> ${ e ( name . replace ( '人数' , '' )) } </strong><span class="small muted"> ${ previousDate ? '上次记录(' + e ( previousDate ) + ')总人数:' + previous + ' 人' : '暂无上次记录' } </span><span> ${ change === null ? ( current !== null ? '首次记录(暂无上次记录)' : '变化未知:' + peopleCountUnknownReason ( peopleCountChangeReason ( current , previous ))) : `较上次记录 ${ previous } → ${ current } , ${ peopleCountDeltaText ( change ) } ` } </span></div>` ;}). join ( '' );
2026-10-23 00:21:53 +08:00
}
function peopleCountInput ( 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 ) ||! Number . isSafeInteger ( Number ( raw )) || Number ( raw ) > 1000000 ) throw new Error ( name + '请填写0~ 1000000的整数。' );
return Number ( raw );
2026-10-17 19:50:24 +08:00
}
function invalidatePeopleEntry (){ ++ peopleRequest ; peopleEntry = null ; peopleEntryUser = '' ;}
async function showPeopleCountForm ( date = state . today , message = '' ){
invalidatePeopleEntry (); let dialog = $ ( '#people-count-dialog' );
if ( ! dialog ){ dialog = document . createElement ( 'dialog' ); dialog . id = 'people-count-dialog' ; dialog . setAttribute ( 'aria-labelledby' , 'people-count-title' ); dialog . addEventListener ( 'cancel' , invalidatePeopleEntry ); document . body . append ( dialog );}
2026-10-29 00:27:36 +08:00
dialog . innerHTML = `<button class="dialog-close" data-action="close-people-count" aria-label="关闭人数记录">× </button><h2 id="people-count-title">记录当日总人数</h2><form id="people-count-form"><div class="grid two"> ${ field ( '日期' , 'date' , date , 'date' , `id="people-count-date" required max=" ${ e ( state . today ) } "` ) }${ peopleParts (). map (([ part , label ])=> field ( peopleCountDisplayName ( label ), part + 'Count' , '' , 'number' , 'min="0" max="1000000" step="1" placeholder="未记录" disabled' )). join ( '' ) } </div><div id="people-count-preview" class="people-count-preview" aria-live="polite"></div><p class="small muted">填当天总人数,例:上次记录100、今天108,自动显示新增8人。没营业或漏录的日期自动跳过。同一天再次保存会替换当天总数。</p><p id="people-count-status" class="small muted" aria-live="polite">正在读取…</p><div id="people-count-error" aria-live="polite"></div><div class="form-actions"><span class="small muted">各自独立记录。留空为未记录,填0为已记录0人。</span><div class="actions"> ${ button ( '取消' , 'close-people-count' , 'quiet' ) } <button class="primary" type="submit" disabled>保存人数</button></div></div></form>` ;
2026-10-17 19:50:24 +08:00
if ( ! dialog . open ) dialog . showModal (); await loadPeopleCount ( message );
}
async function loadPeopleCount ( message = '' ){
const dialog = $ ( '#people-count-dialog' ), form = $ ( '#people-count-form' ); if ( ! dialog ? . open ||! form ) return ;
invalidatePeopleEntry (); const request = peopleRequest , date = form . elements . date . value , user = state . user . id || state . user . name ;
2026-10-25 14:19:24 +08:00
const names = peopleParts (). map (([ part ])=> part + 'Count' ), save = form . querySelector ( '[type="submit"]' ), status = $ ( '#people-count-status' );
2026-10-23 00:21:53 +08:00
for ( const name of names ){ form . elements [ name ]. value = '' ; form . elements [ name ]. disabled = true ;}
2026-10-25 14:19:24 +08:00
save . disabled = true ; status . textContent = '正在读取…' ; $ ( '#people-count-error' ). innerHTML = '' ; syncPeopleCountPreview ();
2026-10-17 19:50:24 +08:00
if ( ! validOrderDate ( date ) || date > state . today ){ status . textContent = '请选择今天或之前的有效日期。' ; return ;}
try {
const entry = await api ( '/api/people-count?' + new URLSearchParams ({ date }));
if ( request !== peopleRequest ||! dialog . open || form !== $ ( '#people-count-form' ) || form . elements . date . value !== date || ( state . user . id || state . user . name ) !== user ) return ;
2026-10-25 14:19:24 +08:00
if ( entry . mode !== 'daily-total' ||! Number . isSafeInteger ( entry . revision ) || entry . revision < 0 ||! validPeopleCountDaily ( entry , date , names )) throw new Error ( '人数记录未完整返回,请重新读取。' );
2026-10-23 00:21:53 +08:00
peopleEntry = entry ; peopleEntryUser = user ;
for ( const name of names ){ form . elements [ name ]. value = entry [ name ] === null ? '' : entry [ name ]; form . elements [ name ]. disabled = false ;}
2026-10-25 14:19:24 +08:00
save . disabled = false ; syncPeopleCountPreview ();
2026-10-29 00:27:36 +08:00
status . textContent = message || '填写当日总人数后保存;较上次记录变化会自动计算。' ;
2026-10-17 19:50:24 +08:00
} catch ( err ){ if ( request !== peopleRequest ||! dialog . open || form !== $ ( '#people-count-form' )) return ; status . textContent = '尚未取得人数记录' ; $ ( '#people-count-error' ). innerHTML = `<div class="error"> ${ e ( err . name === 'AbortError' ? '读取超时,请重新读取。' : err . message ) } ${ button ( '重新读取' , 'people-count-retry' ) } </div>` ;}
}
async function showSavedPeopleCount ( date ){
invalidatePeopleEntry (); $ ( '#people-count-dialog' ) ? . close (); toast ( date + ' 人数已保存' ); await showRecordDate ( date );
}
2026-10-24 16:09:45 +08:00
function closePeopleCountHistory (){ ++ peopleHistoryRequest ; $ ( '#people-count-history-dialog' ) ? . close ();}
async function openPeopleCountHistory (){
let dialog = $ ( '#people-count-history-dialog' ); peopleHistoryToday = state . today ;
if ( ! dialog ){ dialog = document . createElement ( 'dialog' ); dialog . id = 'people-count-history-dialog' ; dialog . setAttribute ( 'aria-labelledby' , 'people-count-history-title' ); dialog . addEventListener ( 'cancel' ,()=>{ ++ peopleHistoryRequest ;}); dialog . addEventListener ( 'close' ,()=>{ ++ peopleHistoryRequest ;}); document . body . append ( dialog );}
2026-10-29 00:27:36 +08:00
dialog . innerHTML = `<button class="dialog-close" data-action="close-people-history" aria-label="关闭每日人数">× </button><h2 id="people-count-history-title">每日人数</h2><p class="small muted">按日期查看当日总人数和较上次记录变化;每位助理分别跳过未记录日,0为有效记录。每次最多查看366天。</p><form id="people-count-history-form" class="people-history-filters"> ${ field ( '开始日期' , 'from' , state . today . slice ( 0 , 7 ) + '-01' , 'date' , `required min="2000-01-01" max=" ${ e ( state . today ) } "` ) }${ field ( '结束日期' , 'date' , state . today , 'date' , `required min="2000-01-01" max=" ${ e ( state . today ) } "` ) } <button type="submit" class="primary">查询</button><div class="actions"> ${ button ( '本月' , 'people-history-month' , '' , 'data-period="current"' ) }${ button ( '上月' , 'people-history-month' , '' , 'data-period="previous"' ) } </div></form><div id="people-count-history-content" aria-live="polite"></div>` ;
2026-10-24 16:09:45 +08:00
if ( ! dialog . open ) dialog . showModal (); await loadPeopleCountHistory ( true );
}
function peopleCountHistoryHTML ( result ){
2026-10-26 14:44:07 +08:00
const parts = peopleParts (), rows = result . rows . filter ( row => parts . some (([ part ])=> row [ part + 'Count' ] !== null && row [ part + 'Count' ] !== undefined ));
const number = value => value == null ? '<span class="muted">未记录</span>' : value . toLocaleString ( 'zh-CN' ) + ' 人' ;
2026-10-29 00:27:36 +08:00
const change = ( row , part )=>{ const value = row [ part + 'Change' ], reason = row [ part + 'ChangeReason' ], previousDate = row . previousDates ? .[ part ]; return ( value === null ? `<span class="muted"> ${ row [ part + 'Count' ] !== null && reason === 'missing-previous' ? '首次记录' : '未知' } </span><div class="small muted"> ${ e ( peopleCountUnknownReason ( reason )) } </div>` : e ( peopleCountDeltaText ( value ))) + ( previousDate ? `<div class="small muted">上次记录: ${ e ( previousDate ) } </div>` : '' );};
return `<p class="small muted"> ${ e ( result . from ) } 至 ${ e ( result . date ) } · 已记录 ${ rows . length } 天。</p><div class="table-wrap"><table class="people-history-table" aria-label="助理每日总人数与较上次记录变化"><thead><tr><th rowspan="2">日期</th> ${ parts . map (([, label ])=> `<th colspan="2" class="number"> ${ e ( label . replace ( '人数' , '' )) } </th>` ). join ( '' ) } </tr><tr> ${ parts . map (()=> '<th class="number">当日总人数</th><th class="number">较上次记录变化</th>' ). join ( '' ) } </tr></thead><tbody> ${ rows . length ? rows . map ( row => `<tr><td> ${ e ( row . date ) } </td> ${ parts . map (([ part ])=> `<td class="number"> ${ number ( row [ part + 'Count' ]) } </td><td class="number"> ${ change ( row , part ) } </td>` ). join ( '' ) } </tr>` ). join ( '' ) : `<tr><td colspan=" ${ 1 + parts . length * 2 } " class="muted">所选日期暂无人数记录</td></tr>` } </tbody><tfoot><tr><th>期末/本期变化</th> ${ parts . map (([ key ])=>{ const value = result . summary [ key ]; return `<td colspan="2" class="number"><div>结束日总人数 <strong> ${ number ( value . endTotal ) } </strong></div><div class="small">本期净增 ${ value . netChange === null ? '未知' : e ( peopleCountSignedText ( value . netChange )) } </div> ${ value . baselineDate ? `<div class="small muted">期初基准: ${ e ( value . baselineDate ) } </div>` : '' }${ value . netChange === null ? `<div class="small muted"> ${ e ( peopleCountUnknownReason ( value . netChangeReason , true )) } </div>` : '' } </td>` ; } ).join('')}</tr></tfoot></table></div><p class="small muted">本期净增= ${ e ( result . date ) } 总人数-各自开始日前最近记录总人数;结束日未记录则未知,每日总人数不累加。</p>` ;
2026-10-24 16:09:45 +08:00
}
function validatePeopleCountHistory ( result , range ){
2026-10-25 14:19:24 +08:00
if ( ! result || result . mode !== 'daily-total' ||! validOrderDate ( result . today ) ||! validOrderDate ( result . from ) ||! validOrderDate ( result . date ) || result . date > result . today || result . from > result . date || result . baselineDate !== peopleCountPreviousDate ( result . from ) || range && ( result . from !== range . from || result . date !== range . date ) ||! Array . isArray ( result . rows )) throw new Error ( '每日人数资料未完整返回,请重新查询。' );
2026-10-24 16:09:45 +08:00
const first = Date . parse ( result . from + 'T00:00:00Z' ), days = ( Date . parse ( result . date + 'T00:00:00Z' ) - first ) / 86400000 + 1 ;
2026-10-29 00:27:36 +08:00
const parts = peopleParts (), names = parts . map (([ part ])=> part + 'Count' ), previous = {};
if ( days > 366 || result . rows . length !== days ||! result . rows . every (( row , i )=>{
if ( ! validPeopleCountDaily ( row , new Date ( first + i * 86400000 ). toISOString (). slice ( 0 , 10 ), names )) return false ;
for ( const [ key ] of parts ){ const name = key + 'Count' ; if ( i && ( row . previous [ name ] !== previous [ key ]. total || row . previousDates [ key ] !== previous [ key ]. date )) return false ; previous [ key ] = row [ name ] === null ? { total : row . previous [ name ], date : row . previousDates [ key ]} : { total : row [ name ], date : row . date };}
return true ;
}) ||! parts . every (([ key ])=>{ const value = result . summary ? .[ key ], end = result . rows . at ( - 1 )[ key + 'Count' ], baseline = result . rows [ 0 ]. previous [ key + 'Count' ], baselineDate = result . rows [ 0 ]. previousDates [ key ]; return value ? . total === end && value ? . endTotal === end && value ? . baselineTotal === baseline && value ? . baselineDate === baselineDate && value ? . netChange === ( end === null || baseline === null ? null : end - baseline ) && value ? . netChangeReason === peopleCountChangeReason ( end , baseline ) && value . recordedDays === result . rows . filter ( row => row [ key + 'Count' ] !== null ). length ;})) throw new Error ( '每日总人数或变化资料不完整,请重新查询。' );
2026-10-24 16:09:45 +08:00
return result ;
}
async function loadPeopleCountHistory ( defaults = false ){
const dialog = $ ( '#people-count-history-dialog' ), form = $ ( '#people-count-history-form' ), target = $ ( '#people-count-history-content' ); if ( ! dialog ? . open ||! form ||! target ) return ;
const request =++ peopleHistoryRequest , user = state . user . id || state . user . name , sessionUser = session ? . user ? . id , from = form . elements . from . value , date = form . elements . date . value ;
const active = ()=> request === peopleHistoryRequest && dialog . open && form === $ ( '#people-count-history-form' ) && form . elements . from . value === from && form . elements . date . value === date && ( state . user . id || state . user . name ) === user && session ? . user ? . id === sessionUser ;
target . setAttribute ( 'aria-busy' , 'true' ); target . innerHTML = '<p class="muted">正在读取每日人数…</p>' ;
try {
if ( ! defaults && ( ! validOrderDate ( from ) ||! validOrderDate ( date ) || from < '2000-01-01' || from > date || date > peopleHistoryToday || ( Date . parse ( date ) - Date . parse ( from )) / 86400000 >= 366 )) throw new Error ( '请选择今天或之前的有效起止日期,每次最多366天。' );
const result = await api ( '/api/people-count-history' + ( defaults ? '' : '?' + new URLSearchParams ({ from , date }))); if ( ! active ()) return ;
validatePeopleCountHistory ( result , defaults ? null : { from , date }); peopleHistoryToday = result . today ;
for ( const name of [ 'from' , 'date' ]){ form . elements [ name ]. max = result . today ; if ( defaults ) form . elements [ name ]. value = result [ name ];}
target . setAttribute ( 'aria-busy' , 'false' ); target . innerHTML = peopleCountHistoryHTML ( result );
} catch ( err ){ if ( ! active ()) return ; target . setAttribute ( 'aria-busy' , 'false' ); target . innerHTML = `<div class="error"> ${ e ( err . name === 'AbortError' ? '读取超时,请重新查询。' : err . message ) } ${ button ( '重新查询' , 'people-history-retry' ) } </div>` ;}
}
async function peopleCountHistoryMonth ( previous = false ){
const form = $ ( '#people-count-history-form' ); if ( ! form ) return ; const first = peopleHistoryToday . slice ( 0 , 7 ) + '-01' , date = previous ? new Date ( Date . parse ( first + 'T00:00:00Z' ) - 86400000 ). toISOString (). slice ( 0 , 10 ) : peopleHistoryToday ;
form . elements . from . value = previous ? date . slice ( 0 , 7 ) + '-01' : first ; form . elements . date . value = date ; return await loadPeopleCountHistory ();
}
2026-11-03 01:15:41 +08:00
function afterSalePayerName ( row ){ return ({ owner : '麦麦' , assistant : teamMemberName ( 'assistant' ), assistant2 : teamMemberName ( 'assistant2' )})[ row . costItems ? .[ 0 ] ? . payer ] || '付款人待补' ;}
2026-10-28 00:22:04 +08:00
function afterSaleEditButton ( row ){ return button ( '修改' , 'after-sale-edit' , 'after-sale-edit-button' , `data-id=" ${ e ( row . after_sale_id || row . id ) } " aria-label="修改 ${ e ( row . customer ) } 的售后记录"` );}
2026-10-23 09:49:36 +08:00
function orderBookIdentity ( row , version ){
2026-10-26 14:44:07 +08:00
if ( row . kind === 'recovery' ) return `<button class="link-button order-book-link order-book-customer-first" data-action="recovery-open" data-id=" ${ e ( row . recovery_id || row . id ) } "><span class="order-book-identity-line"><strong class="order-book-customer-name"> ${ e ( row . customer || '未填称呼' ) } </strong><span class="order-book-recovery-badge">回收</span></span><span class="order-book-secondary muted"> ${ e ( row . number ) } </span><span class="order-book-recovery-payment">回收付款 ¥ ${ yuan ( row . cashPayment ) } </span></button> ${ button ( '打印' , 'recovery-print' , 'quiet order-book-recovery-print' , `data-id=" ${ e ( row . recovery_id || row . id ) } " aria-label="打印 ${ e ( row . customer || '客户' ) } 的回收单"` ) } ` ;
2026-10-23 09:49:36 +08:00
if ( version !== undefined ){
2026-10-26 14:44:07 +08:00
const name = `<strong class="order-book-customer-name"> ${ e ( row . customer || '未填称呼' ) } </strong>` ;
const customer = row . recovery_mode === 'exchange' ? `<span class="order-book-identity-line"> ${ name } <span class="order-book-recovery-badge is-exchange">置换</span></span>` : name ;
2026-10-28 00:22:04 +08:00
if ( row . kind === 'afterSale' ) return `<div class="after-sale-identity order-book-customer-first"> ${ customer } <span class="order-book-secondary muted">售后 · ${ e ( row . project || row . note ) } </span> ${ afterSaleEditButton ( row ) } </div>` ;
2026-10-23 09:49:36 +08:00
return `<button class="link-button order-book-link order-book-customer-first" data-action="open-order" data-id=" ${ e ( row . id ) } " data-order-book-version=" ${ version } "> ${ customer } <span class="order-book-secondary muted"> ${ e ( row . paper_number || row . number ) } </span></button>` ;
}
2026-10-28 00:22:04 +08:00
if ( row . kind === 'afterSale' ) return `<div class="after-sale-identity"><strong>售后 · ${ e ( row . project || row . note ) } </strong><span> ${ e ( row . customer ) } </span> ${ afterSaleEditButton ( row ) } </div>` ;
2026-10-23 09:49:36 +08:00
return `<button class="link-button order-book-link" data-action="open-order" data-id=" ${ e ( row . id ) } " data-order-book-version=" ${ version } "><strong> ${ e ( row . paper_number || row . number ) } </strong><span> ${ e ( row . customer || '未填称呼' ) } </span></button>` ;
2026-10-17 19:50:24 +08:00
}
2026-10-26 14:44:07 +08:00
function orderIsReviewed ( row ){ return ! [ 'afterSale' , 'recovery' ]. includes ( row . kind ) && Number . isSafeInteger ( row . revision ) && row . revision > 0 && row . reviewed_revision === row . revision ;}
2026-10-23 11:58:19 +08:00
function orderReviewBadge ( row ){ return orderIsReviewed ( row ) ? '<span class="order-review-status">已复核</span>' : '' ;}
2026-10-17 19:50:24 +08:00
async function renderOrders (){
const f = getOrderBookFilters (); let range ; try { range = orderBookRange ();} catch {}
2026-11-01 23:40:44 +08:00
$ ( '#main' ). innerHTML = heading ( 'ORDER BOOK' , '订单' , '按日期查看销售订单、回收与售后,点击客户查看明细。' , button ( '待变更复核(…)' , 'open-order-changes' , '' , 'id="order-changes-entry"' ) + ( typeof openOrderOwnerships === 'function' ? button ( '归属复核(…)' , 'order-ownership-open-list' , '' , 'id="order-ownership-entry"' ) : '' ) + button ( '待取消复核(…)' , 'open-order-cancellations' , '' , 'id="order-cancellations-entry"' ) + button ( state . user . role === 'owner' ? '售后修改复核(…)' : '售后修改申请(…)' , 'after-sale-changes-open' , '' , 'id="after-sale-changes-entry"' ) + button ( '新增售后' , 'new-after-sale' ) + button ( '记录人数' , 'people-count' ) + button ( '每日人数' , 'people-history' ) + button ( '刷新' , 'refresh' )) + `<div class="order-book-dates"><div class="order-period-buttons" role="group" aria-label="订单日期"> ${ orderBookPeriodOptions . map (([ value , name ])=> button ( name , 'order-period' , '' , `data-period=" ${ value } " aria-pressed="false"` )). join ( '' ) } </div><label class="order-date-field" id="order-single-date" ${ f . mode === 'date' ? '' : 'hidden' } >指定日期<input type="date" id="order-date" value=" ${ e ( f . mode === 'date' ? f . date : ( range ? . date || state . today )) } " min="2000-01-01" max=" ${ e ( state . today ) } " aria-label="指定订单日期"></label><div class="order-range-fields" id="order-range-fields" ${ f . mode === 'range' ? '' : 'hidden' } ><label class="order-date-field">开始日期<input type="date" id="order-from" value=" ${ e ( f . from ) } " min="2000-01-01" max=" ${ e ( state . today ) } " aria-label="订单开始日期"></label><label class="order-date-field">结束日期<input type="date" id="order-to" value=" ${ e ( f . to ) } " min="2000-01-01" max=" ${ e ( state . today ) } " aria-label="订单结束日期"></label></div><span class="small muted" id="order-period-caption"></span></div><div id="order-book-people" class="order-people-strip" aria-live="polite"></div><div class="cards order-book-cards" id="order-book-summary" aria-live="polite"></div><div id="order-lock-activity"></div><p class="small muted order-book-scope" id="order-book-scope"> ${ orderBookScope () } </p><section class="panel order-book-panel"><div class="filters order-book-filters"><input id="order-search" aria-label="搜索订单(单号、客户、商品或克重)" value=" ${ e ( f . q ) } " placeholder="单号、客户、商品或克重,如1.38克" maxlength="100"><select id="order-filter" aria-label="筛选状态"> ${ opts ( orderBookStatusOptions , f . status ) } </select><label class="order-pocket-field">出货货盘<select id="order-pocket-filter" aria-label="出货货盘"> ${ opts ( orderBookPocketOptions (), f . pocket ) } </select></label> ${ memberFilterHTML ( 'order-member-filter' , f . member ) } <span class="small muted" id="order-book-count"></span></div><p class="small muted" id="order-status-hint" ${ f . status === 'price_lock' ? '' : 'hidden' } >锁价仅显示已生成的销售单;未交付的锁价单请到「待交付」查看。</p><p class="small muted order-pocket-hint" id="order-pocket-hint" ${ f . pocket ? '' : 'hidden' } >包含所选货盘的订单,金额按整单汇总。锁价实际收付区仍按日期显示。</p><div id="order-list" aria-live="polite"></div><p class="small muted order-book-footnote">订单成本和利润为当前累计结果;售后费用按售后记录日期扣减利润。已取消订单不计汇总,原收退款、费用和作废冲回明细保留在每日对账。销售克重合计不含银饰和直接回收,单行仍显示实际克重;件数照常合计。旧草稿报价不计入合计。</p></section>` ;
2026-10-28 00:22:04 +08:00
updateOrderBookDateControls ( range ); await Promise . all ([ loadOrderBook (), typeof loadOrderCancellationCount === 'function' ? loadOrderCancellationCount () : Promise . resolve (), typeof loadOrderChangeCount === 'function' ? loadOrderChangeCount () : Promise . resolve (), typeof loadOrderOwnershipCount === 'function' ? loadOrderOwnershipCount () : Promise . resolve (), loadAfterSaleChangeCount ()]);
2026-10-17 19:50:24 +08:00
}
function orderBookLoading ( range ){
2026-10-21 01:32:49 +08:00
if ( $ ( '#order-lock-activity' )) $ ( '#order-lock-activity' ). innerHTML = '' ;
2026-10-24 16:09:45 +08:00
if ( $ ( '#order-book-people' )) $ ( '#order-book-people' ). innerHTML = '<strong>助理人数</strong><span>正在读取…</span>' ;
2026-10-17 19:50:24 +08:00
$ ( '#order-book-summary' ). innerHTML = [ '订单数量' , '利润' , '收款' , '成本' ]. map ( title => card ( e (( range ? . name || '所选日期' ) + title ), '—' , '正在读取' )). join ( '' );
$ ( '#order-book-count' ). textContent = '' ; $ ( '#order-list' ). setAttribute ( 'aria-busy' , 'true' );
$ ( '#order-list' ). innerHTML = '<div class="order-book-message">正在读取' + e ( range ? . name || '所选日期' ) + '订单…</div>' ;
}
function orderBookError ( message ){
2026-10-21 01:32:49 +08:00
if ( $ ( '#order-lock-activity' )) $ ( '#order-lock-activity' ). innerHTML = '' ;
2026-10-24 16:09:45 +08:00
if ( $ ( '#order-book-people' )) $ ( '#order-book-people' ). innerHTML = '<strong>助理人数</strong><span>尚未取得数据</span>' ;
2026-10-17 19:50:24 +08:00
$ ( '#order-book-summary' ). innerHTML = [ '订单数量' , '利润' , '收款' , '成本' ]. map ( title => card ( title , '—' , '尚未取得数据' )). join ( '' );
$ ( '#order-book-count' ). textContent = '' ; $ ( '#order-list' ). setAttribute ( 'aria-busy' , 'false' );
$ ( '#order-list' ). innerHTML = `<div class="order-book-message error"><strong> ${ e ( message ) } </strong><div> ${ button ( '重新读取' , 'order-book-retry' ) } </div></div>` ;
}
async function loadOrderBook ( delay = 0 ){
2026-10-23 09:49:36 +08:00
clearTimeout ( orderBookTimer ); invalidateOrderBookDetailList (); const request =++ orderBookRequest , user = orderDetailUser (); let range ;
2026-10-17 19:50:24 +08:00
try { range = orderBookRange ();} catch ( err ){ updateOrderBookDateControls (); orderBookError ( err . message ); return ;}
updateOrderBookDateControls ( range ); orderBookLoading ( range );
2026-10-26 17:07:26 +08:00
const pocket = orderBookFilters . pocket || '' , scope = orderDetailFilterScope (), query = new URLSearchParams ({ from : range . from , date : range . date , q : orderBookFilters . q . trim (), status : orderBookFilters . status || 'all' ,...( pocket ? { pocket } : {}),...( state . user . role === 'owner' && orderBookFilters . member ? { member : orderBookFilters . member } : {})}), serverDay = state . today ;
2026-10-17 19:50:24 +08:00
const read = async ()=>{
try {
const book = await api ( '/api/order-book?' + query );
2026-10-26 17:07:26 +08:00
if ( request !== orderBookRequest || user !== orderDetailUser () || scope !== orderDetailFilterScope () || tab !== 'orders' ||! $ ( '#order-list' )) return ;
2026-10-17 19:50:24 +08:00
if ( validOrderDate ( book . today ) && book . today !== serverDay ){ state . today = book . today ; if ( orderBookFilters . mode !== 'date' ) return renderOrders (); updateOrderBookDateControls ( range );}
if ( book . from !== range . from || book . date !== range . date ) throw new Error ( '返回日期与所选日期不一致,请重新读取。' );
2026-10-26 17:07:26 +08:00
if (( book . pocket ?? '' ) !== pocket ) throw new Error ( '返回货盘与所选货盘不一致,请重新读取。' );
2026-10-17 19:50:24 +08:00
renderOrderBook ( book , range );
2026-10-23 09:49:36 +08:00
} catch ( err ){ if ( request === orderBookRequest && user === orderDetailUser () && tab === 'orders' && $ ( '#order-list' )) orderBookError ( err . name === 'AbortError' ? '读取超时,请重新读取。' : err . message );}
2026-10-17 19:50:24 +08:00
};
if ( delay ){ orderBookTimer = setTimeout ( read , delay ); return ;} await read ();
}
function filterOrders ( delay = 0 ){
2026-10-26 17:07:26 +08:00
const f = getOrderBookFilters (); f . member = $ ( '#order-member-filter' ) ? . value || '' ; f . pocket = $ ( '#order-pocket-filter' ) ? . value || '' ; f . q = $ ( '#order-search' ). value ; f . status = $ ( '#order-filter' ). value ; saveOrderBookFilters (); return loadOrderBook ( delay );
2026-10-17 19:50:24 +08:00
}
function orderBookQuantity ( value ){ return [ value . mg ? grams ( value . mg ) + 'g' : '' , value . pieces ? value . pieces + '件' : '' ]. filter ( Boolean ). join ( ' / ' ) || '—' ;}
function orderBookSummaryQuantity ( summary ){ return grams ( summary . mg ) + 'g' + ( summary . pieces ? ' / ' + summary . pieces + '件' : '' ) + '<div class="small muted">克重不含银饰</div>' ;}
function orderBookMoney ( row , key ){
2026-10-26 14:44:07 +08:00
if ( row . kind === 'recovery' ) return '<span class="muted">—</span>' ;
2026-10-17 19:50:24 +08:00
if ( row . status === 'draft' ) return `<span class="muted">未开单</span> ${ key === 'sale' && row . originalSale != null ? `<div class="small muted">报价 ¥ ${ yuan ( row . originalSale ) } </div>` : '' } ` ;
if ( row [ key ] != null ) return '¥' + yuan ( row [ key ]);
const known = row . known ? .[ key ], unallocated = [ 'material' , 'laborAndFees' ]. includes ( key ) && row . legacyUnallocated ;
2026-10-21 01:32:49 +08:00
const hint = unallocated ? '未分项' : row . materialCostPending && [ 'material' , 'totalCost' , 'profit' ]. includes ( key ) ? '料费待补' : key === 'profit' && row . status === 'confirmed' ? '旧单待补齐' : '待补齐' ;
2026-10-17 19:50:24 +08:00
return ` ${ known ? '已知 ¥' + yuan ( known ) : '' } <div class="small ${ unallocated ? 'muted' : 'danger-text' } "> ${ hint } </div>` ;
}
function orderBookFeeParts ( row ){
2026-10-26 14:44:07 +08:00
if ( row . kind === 'recovery' ) return '' ;
2026-10-17 19:50:24 +08:00
if ( row . status === 'draft' ) return '' ;
if ( row . kind === 'afterSale' ) return '<div class="order-fee-parts"><span>售后费用</span></div>' ;
const grouped = new Map ();
for ( const item of row . laborAndFeeItems || []){ const key = item . component + ':' + item . name , previous = grouped . get ( key ); grouped . set ( key ,{ name : item . name , amount : ( previous ? . amount || 0 ) + ( item . amount || 0 ), missing : previous ? . missing || item . amount == null });}
const items = [... grouped . values ()]. filter ( item => item . amount || item . missing );
return items . length ? `<div class="order-fee-parts"> ${ items . map ( item => `<span> ${ e ( item . name ) } ${ item . missing ? ( item . amount ? '已知 ¥' + yuan ( item . amount ) + ',待补' : '待补' ) : '¥' + yuan ( item . amount ) } </span>` ). join ( '' ) } </div>` : '' ;
}
function orderBookSummaryAmount ( summary , key ){
const missing = summary . unknownCounts ? .[ key ] || 0 , known = summary . knownCounts ? .[ key ];
if ( missing && known === 0 &&! summary [ key ] &&! summary . afterSaleCount ) return '<span class="muted">' + ([ 'material' , 'laborAndFees' ]. includes ( key ) && summary . unallocated ? '未分项' : '未补齐' ) + '</span>' ;
return ( missing ? '已知 ' : '' ) + '¥' + yuan ( summary [ key ]);
}
function validateOrderBook ( book ){
const s = book ? . summaryWithoutCancelled , r = book ? . receiptsWithoutCancelled ;
const amounts = [ 'sale' , 'material' , 'laborAndFees' , 'unallocated' , 'totalCost' , 'profit' , 'ownerCost' , 'assistantCost' ];
const counts = [ 'orderCount' , 'completedCount' , 'draftCount' , 'incompleteCount' , 'afterSaleCount' , 'recordCount' , 'mg' , 'pieces' , 'unknownCosts' , 'unknownCostCount' , 'unknownProfitCount' ];
2026-10-26 14:44:07 +08:00
if ( ! Array . isArray ( book ? . rows ) || ( book . displayRows !== undefined &&! Array . isArray ( book . displayRows )) || ( book . recoveryCount !== undefined && ( ! Number . isSafeInteger ( book . recoveryCount ) || book . recoveryCount < 0 )) ||! s ||! r || r . basis !== 'orderDate' || r . filterScope !== 'matchingOrdersWithoutCancelled' || r . from !== book . from || r . date !== book . date ||
2026-10-17 19:50:24 +08:00
! amounts . every ( key => Number . isSafeInteger ( s [ key ]) && Number . isSafeInteger ( s . knownCounts ? .[ key ]) && s . knownCounts [ key ] >= 0 && Number . isSafeInteger ( s . unknownCounts ? .[ key ]) && s . unknownCounts [ key ] >= 0 ) ||
! counts . every ( key => Number . isSafeInteger ( s [ key ]) && s [ key ] >= 0 ) ||! [ 'receipt' , 'refund' , 'net' ]. every ( key => Number . isSafeInteger ( r [ key ])) ||
! Array . isArray ( r . channels ) ||! r . channels . every ( channel => channel && typeof channel . name === 'string' && [ 'receipt' , 'refund' , 'net' ]. every ( key => Number . isSafeInteger ( channel [ key ]))) ||
! [ 'wechat' , 'alipay' , 'cash' ]. every ( channel => r . channels . some ( item => item . channel === channel ))) throw new Error ( '订单汇总数据尚未完整返回,请刷新后重新读取。' );
return book ;
}
function renderOrderBook ( book , range ){
2026-10-26 14:44:07 +08:00
validateOrderBook ( book ); const s = book . summaryWithoutCancelled , receipts = book . receiptsWithoutCancelled , recoveryCount = book . recoveryCount || 0 ;
2026-10-23 09:49:36 +08:00
invalidateOrderBookDetailList ();
2026-10-26 17:07:26 +08:00
const detailList = { version :++ orderBookDetailVersion , request : orderBookRequest , user : orderDetailUser (), scope : orderDetailFilterScope (), element : $ ( '#order-list' ), ids : [... new Set ( book . rows . filter ( row => row . kind !== 'afterSale' && typeof row . id === 'string' && row . id ). map ( row => row . id ))]};
2026-10-23 09:49:36 +08:00
orderBookDetailList = detailList ;
2026-10-21 01:32:49 +08:00
$ ( '#order-lock-activity' ). innerHTML = priceLockActivityHTML ( book . priceLockActivity );
2026-10-17 19:50:24 +08:00
const cancelledCount = book . rows . filter ( row => row . status === 'cancelled' ). length ;
$ ( '#order-book-people' ). innerHTML = peopleCountHTML ( book . peopleCount );
const profitMissing = s . unknownProfitCount || 0 , costMissing = s . unknownCosts || 0 , costPartial = ( s . unknownCostCount || 0 ) > 0 || costMissing > 0 ;
2026-10-26 14:44:07 +08:00
const countHints = [ `已完成 ${ s . completedCount } 单` , recoveryCount ? `另有回收 ${ recoveryCount } 笔` : null , s . afterSaleCount ? `另有售后 ${ s . afterSaleCount } 笔` : null , s . draftCount ? `旧草稿 ${ s . draftCount } 单` : null , s . incompleteCount ? ` ${ s . incompleteCount } 单账务待补齐` : null , cancelledCount ? ` ${ cancelledCount } 单取消未计汇总` : null ]. filter ( Boolean ). join ( ' · ' );
2026-10-23 09:49:36 +08:00
const channels = [ 'wechat' , 'alipay' , 'cash' , 'credit_card' ]. map ( channel => receipts . channels . find ( r => r . channel === channel ) || { channel , name : { wechat : '微信' , alipay : '支付宝' , cash : '现金' , credit_card : '信用卡' }[ channel ], receipt : 0 , refund : 0 }). filter ( r => ! [ 'cash' , 'credit_card' ]. includes ( r . channel ) || r . receipt !== 0 || r . refund !== 0 );
2026-10-17 19:50:24 +08:00
const receiptDetails = `<div class="order-stat-lines"> ${ channels . map ( r => `<span><b> ${ e ( r . name ) } </b><span>¥ ${ yuan ( r . receipt ) } </span></span>` ). join ( '' ) } </div><div class="order-stat-refund">退款 ¥ ${ yuan ( receipts . refund ) } </div>` ;
2026-11-03 01:15:41 +08:00
const costDetails = `<div class="order-stat-lines"><span><b>麦麦</b><span> ${ orderBookSummaryAmount ( s , 'ownerCost' ) } </span></span><span><b> ${ e ( teamMemberName ( 'assistant' )) } </b><span> ${ orderBookSummaryAmount ( s , 'assistantCost' ) } </span></span> ${ teamMode () ? `<span><b> ${ e ( teamMemberName ( 'assistant2' )) } </b><span> ${ orderBookSummaryAmount ( s , 'assistant2Cost' ) } </span></span>` : '' } </div> ${ costPartial ? `<div class="order-stat-refund danger-text"> ${ s . unknownCostCount ? ` ${ s . unknownCostCount } 单成本未补齐` : '' }${ s . unknownCostCount && costMissing ? ' · ' : '' }${ costMissing ? ` ${ costMissing } 项成本未补齐/未入账` : '' } </div>` : '' } ` ;
2026-10-17 19:50:24 +08:00
const costValue = s . unknownCostCount && s . knownCounts ? . totalCost === 0 &&! s . totalCost &&! s . afterSaleCount ? '未补齐' : '¥' + yuan ( s . totalCost );
2026-10-21 01:32:49 +08:00
$ ( '#order-book-summary' ). innerHTML = card ( e ( range . name + '销售订单' ), s . orderCount + '<span class="stat-unit">单</span>' , e ( countHints )) + card ( e ( range . name + '利润' + ( profitMissing ? '(已核算部分)' : '' )), profitMissing && s . knownCounts ? . profit === 0 &&! s . profit &&! s . afterSaleCount ? '待补齐' : '¥' + yuan ( s . profit ), profitMissing ? profitMissing + ' 单利润待补齐' : '已扣货品成本、实际费用和售后费用' , true ) + card ( e ( range . name + '收款' ), '¥' + yuan ( receipts . receipt ), receiptDetails ) + card ( e ( range . name + '成本' + ( costPartial ? '(已知部分)' : '' )), costValue , costDetails );
2026-10-26 17:07:26 +08:00
$ ( '#order-book-scope' ). textContent = orderBookScope (); $ ( '#order-book-count' ). textContent = ` ${ range . name } · 汇总 ${ s . orderCount } 单 ${ recoveryCount ? ' · 回收 ' + recoveryCount + ' 笔' : '' }${ s . afterSaleCount ? ' · 售后 ' + s . afterSaleCount + ' 笔' : '' }${ cancelledCount ? ',另有 ' + cancelledCount + ' 单取消未计' : '' }${ orderBookFilters . q || orderBookFilters . status || orderBookFilters . pocket || orderBookFilters . member ? '(已筛选)' : '' } ` ; $ ( '#order-list' ). setAttribute ( 'aria-busy' , 'false' );
2026-10-26 14:44:07 +08:00
const rows = book . displayRows ?? book . rows ;
if ( ! rows . length ){ $ ( '#order-list' ). innerHTML = '<div class="empty"><strong>这个日期没有符合条件的订单、回收或售后</strong>可以切换日期,或调整搜索和状态筛选。</div>' ; return ;}
$ ( '#order-list' ). innerHTML = `<div class="table-wrap order-book-table-wrap"><table class="order-book-table" aria-label=" ${ e ( range . name ) } 订单账本"><thead><tr><th class="order-index">序号</th><th>客户/销售、回收或售后</th><th>类型</th><th class="number">克重/件数</th><th class="number">售价</th><th class="number">料成本</th><th class="number">工费及附加成本</th><th class="number">成本合计</th><th class="number">利润</th><th>备注</th></tr></thead><tbody> ${ rows . map (( row , i )=> `<tr class=" ${ row . kind === 'afterSale' ? 'order-after-sale' : row . kind === 'recovery' ? 'order-recovery' : row . status === 'draft' ? 'order-draft' : row . status === 'returned' || row . status === 'cancelled' ? 'order-reversed' : '' } "><td class="order-index"> ${ i + 1 } </td><td class="order-customer"> ${ orderBookIdentity ( row , detailList . version ) } <div class="small muted"> ${ e ( row . date ) } · ${ row . kind === 'recovery' ? '<span class="order-status muted">已记录</span>' : badge ( row ) }${ orderReviewBadge ( row ) } </div> ${ showOrderCopyEntry &&! [ 'afterSale' , 'recovery' ]. includes ( row . kind ) ? button ( '<span aria-hidden="true">+ </span>复制新增' , 'copy-order' , 'order-copy-button' , `data-id=" ${ e ( row . id ) } " aria-label="复制 ${ e ( row . paper_number || row . number ) } 为新订单"` ) : '' }${ row . status === 'cancelled' ? '<div class="small muted">未计入汇总</div>' : '' }${ row . balance < 0 ? '<div class="small danger-text">退款待处理</div>' : '' } </td><td class="order-type"> ${ row . types . map ( e ). join ( '<br>' ) || '—' } </td><td class="number"> ${ orderBookQuantity ( row ) }${ row . kind === 'recovery' ? '<div class="small muted">折后克重</div>' : '' } </td><td class="number"> ${ orderBookMoney ( row , 'sale' ) } </td><td class="number"> ${ orderBookMoney ( row , 'material' ) } </td><td class="number order-fees"> ${ orderBookMoney ( row , 'laborAndFees' ) }${ orderBookFeeParts ( row ) } </td><td class="number"> ${ orderBookMoney ( row , 'totalCost' ) }${ row . unallocated ? `<div class="small muted">含未分项 ¥ ${ yuan ( row . unallocated ) } </div>` : '' }${ row . pendingCosts ? '<div class="small danger-text">另有 ' + row . pendingCosts + ' 项费用未入账</div>' : '' } </td><td class="number order-profit"> ${ orderBookMoney ( row , 'profit' ) } </td><td class="order-notes"> ${ row . kind === 'afterSale' ? e ( afterSalePayerName ( row ) + '支付' ) : e ( row . note ) || '<span class="muted">—</span>' }${ row . costHint ? `<div class="small ${ row . incomplete ? 'danger-text' : 'muted' } "> ${ e ( row . costHint ) } </div>` : '' } </td></tr>` ). join ( '' ) } </tbody><tfoot><tr><td colspan="2">汇总 ${ s . orderCount } 单 ${ recoveryCount ? '<br>回收 ' + recoveryCount + ' 笔' : '' }${ s . afterSaleCount ? '<br>售后 ' + s . afterSaleCount + ' 笔' : '' } </td><td></td><td class="number"> ${ orderBookSummaryQuantity ( s ) } </td><td class="number"> ${ orderBookSummaryAmount ( s , 'sale' ) } </td><td class="number"> ${ orderBookSummaryAmount ( s , 'material' ) } </td><td class="number"> ${ orderBookSummaryAmount ( s , 'laborAndFees' ) } </td><td class="number"> ${ costPartial ? '已知 ' : '' } ¥ ${ yuan ( s . totalCost ) }${ s . unallocated ? `<div class="small muted">含未分项 ¥ ${ yuan ( s . unallocated ) } </div>` : '' } </td><td class="number"> ${ orderBookSummaryAmount ( s , 'profit' ) } </td><td class="small order-notes"> ${ [ cancelledCount ? cancelledCount + ' 单取消未计汇总' : '' , s . draftCount ? s . draftCount + ' 单草稿未计金额' : '' , s . unknownCostCount ? s . unknownCostCount + ' 单成本未补齐' : '' , profitMissing ? profitMissing + ' 单利润待补齐' : '' ]. filter ( Boolean ). join ( '; ' ) || '账本金额' } </td></tr></tfoot></table></div>` ;
2026-10-17 19:50:24 +08:00
}
async function checkOrderBookDay (){
if ( tab !== 'orders' || document . hidden ||! state || busy || orderBookDayChecking ) return ;
orderBookDayChecking = true ; const previous = state . today , user = state . user . id ;
try { const latest = await api ( '/api/state' ); if ( tab === 'orders' && latest . user . id === user && latest . today !== previous ){ state = latest ; await renderOrders ();}} catch {} finally { orderBookDayChecking = false ;}
}
setInterval ( checkOrderBookDay , 60000 );
document . addEventListener ( 'visibilitychange' ,()=>{ if ( ! document . hidden ) checkOrderBookDay ();});
2026-10-23 09:49:36 +08:00
function orderDetailUser (){ return String ( session ? . user ? . id || session ? . user ? . name || '' ) + '|' + String ( state ? . user ? . id || state ? . user ? . name || '' );}
function orderDetailNavigationValid ( navigation = orderDetailNavigation ){
2026-10-26 17:07:26 +08:00
return !! navigation && navigation . list === orderBookDetailList && navigation . list . request === orderBookRequest && navigation . list . user === orderDetailUser () && navigation . list . scope === orderDetailFilterScope () && navigation . list . element === $ ( '#order-list' ) && tab === 'orders' ;
2026-10-23 09:49:36 +08:00
}
function invalidateOrderBookDetailList (){
orderBookDetailList = null ;
if ( orderDetailNavigation || orderDetailLoad ? . navigation ){
++ orderDetailRequest ; orderDetailLoad = null ; orderDetailRetry = null ; orderDetailSwitchError = '' ; orderDetailNavigation = null ; orderDetailListChanged =!! currentOrder &&!! $ ( '#order-dialog' ) ? . open ; updateOrderDetailNavigation ();
}
}
function invalidateOrderDetailView ( close = false ){
++ orderDetailRequest ; orderDetailLoad = null ; orderDetailRetry = null ; orderDetailSwitchError = '' ; orderDetailNavigation = null ; orderDetailListChanged = false ;
if ( close ){ currentOrder = null ; $ ( '#order-dialog' ) ? . close ();}
updateOrderDetailNavigation ();
}
function bindOrderDetailDialog (){
const dialog = $ ( '#order-dialog' ); if ( ! dialog || orderDetailDialogBound === dialog ) return ;
orderDetailDialogBound = dialog ;
dialog . addEventListener ? .( 'cancel' ,()=>{ invalidateOrderDetailView (); currentOrder = null ;});
dialog . addEventListener ? .( 'close' ,()=>{ if ( ! dialog . open ){ invalidateOrderDetailView (); currentOrder = null ;}});
}
function orderDetailNavigationHTML (){
2026-10-23 11:58:19 +08:00
const navigation = orderDetailNavigation , valid = orderDetailNavigationValid ( navigation ), loading =!! orderDetailLoad , blocked = busy ||!! pending () || loading ||!! orderDetailRetry ? . savedContext ||! valid ;
2026-10-23 09:49:36 +08:00
if ( ! navigation &&! orderDetailListChanged &&! orderDetailRetry &&! orderDetailSwitchError ) return '' ;
const index = valid ? navigation . index :- 1 , count = valid ? navigation . list . ids . length : 0 ;
const hint = orderDetailListChanged ? '订单列表已变化,请返回列表重新打开。' : loading ? '正在读取订单,当前单据暂时保留。' : busy ? '正在保存,请完成后切换。' : pending () ? '请先恢复原操作,再切换订单。' : '按当前筛选后的销售订单顺序查看' ;
const retryBlocked = busy ||!! pending () || loading ||!! orderDetailRetry ? . navigation &&! orderDetailNavigationValid ( orderDetailRetry . navigation );
return `<div class="order-detail-navigation-row" role="group" aria-label="切换订单"> ${ button ( '← 上一条' , 'order-detail-prev' , 'order-detail-step' , `id="order-detail-prev" ${ blocked || index <= 0 ? 'disabled' : '' } ` ) } <span class="order-detail-position" aria-live="polite" aria-label=" ${ valid ? '第' + ( index + 1 ) + '条,共' + count + '条订单' : '没有可切换的订单列表' } "> ${ valid ? index + 1 + ' / ' + count : '—' } </span> ${ button ( '下一条 →' , 'order-detail-next' , 'order-detail-step' , `id="order-detail-next" ${ blocked || index >= count - 1 ? 'disabled' : '' } ` ) } <span class="small muted order-detail-navigation-hint" role="status"> ${ e ( hint ) } </span></div> ${ orderDetailSwitchError ? `<div class="error order-detail-navigation-error" role="alert"> ${ e ( orderDetailSwitchError ) } </div>` : '' }${ orderDetailRetry ? `<div class="error order-detail-navigation-error" role="alert"> ${ e ( orderDetailRetry . message ) } 当前订单已保留。 ${ button ( '重试读取' , 'order-detail-retry' , '' , retryBlocked ? 'disabled' : '' ) } </div>` : '' } ` ;
}
function updateOrderDetailNavigation (){
const target = $ ( '#order-detail-navigation' ); if ( ! target ) return ;
target . innerHTML = orderDetailNavigationHTML (); target . hidden =! target . innerHTML ; target . setAttribute ( 'aria-busy' , String ( !! orderDetailLoad ));
}
function requireOrderDetailSwitch (){
const refuse = message =>{ orderDetailSwitchError = message ; updateOrderDetailNavigation (); throw new Error ( message );};
if ( busy ) refuse ( '正在保存,请完成后再切换订单。' );
if ( pending ()) refuse ( '请先点击顶部“恢复原操作”,确认上次提交结果后再切换订单。' );
if ( orderCopyLoading || typeof orderEditLoading !== 'undefined' && orderEditLoading ) refuse ( '正在处理订单,请稍候再切换。' );
if ( $ ( '#detail-form' ) ? . querySelector ? .( 'form' )) refuse ( '当前有未收起的填写内容,请先保存或收起,再切换订单。' );
orderDetailSwitchError = '' ;
}
async function navigateOrderDetail ( direction ){
if ( orderDetailLoad ) return ;
requireOrderDetailSwitch ();
const navigation = orderDetailNavigation ; if ( ! $ ( '#order-dialog' ) ? . open ||! orderDetailNavigationValid ( navigation ) || navigation . list . ids [ navigation . index ] !== currentOrder ? . id ) return ;
const index = navigation . index + direction ; if ( index < 0 || index >= navigation . list . ids . length ) return ;
return await openOrder ( navigation . list . ids [ index ],{ navigation : { list : navigation . list , index }});
}
async function retryOrderDetail (){
if ( orderDetailLoad ||! orderDetailRetry ) return ;
requireOrderDetailSwitch (); const retry = orderDetailRetry ;
2026-10-23 11:58:19 +08:00
if ( retry . savedContext ) return await refreshOrderDetailAfterSave ( retry . id , retry . savedContext );
2026-10-23 09:49:36 +08:00
if ( retry . navigation &&! orderDetailNavigationValid ( retry . navigation )) return ;
return await openOrder ( retry . id ,{ navigation : retry . navigation });
}
2026-10-26 17:07:26 +08:00
function orderDetailFilterScope (){ try { const range = orderBookRange (), filters = getOrderBookFilters (); return JSON . stringify ({ from : range . from , date : range . date , q : filters . q . trim (), status : filters . status || 'all' , pocket : filters . pocket || '' , member : filters . member || '' });} catch { return '' ;}}
2026-10-23 11:58:19 +08:00
function captureOrderDetailReload ( id ){
const dialog = $ ( '#order-dialog' ); if ( ! dialog ? . open || currentOrder ? . id !== id ) return null ;
const navigation = orderDetailNavigation , list = orderDetailNavigationValid ( navigation ) && navigation . list . ids [ navigation . index ] === id ;
if ( ! list ) return null ;
return { id , user : orderDetailUser (), tab , dialog , request : orderDetailRequest , bookRequest : orderBookRequest , list , scope : list ? orderDetailFilterScope () : '' };
}
async function refreshOrderDetailAfterSave ( id , savedContext = captureOrderDetailReload ( id )){
if ( ! savedContext ){ await refresh (); return await openOrder ( id );}
const context = {... savedContext };
const active = ()=> context . id === id && context . user === orderDetailUser () && context . tab === tab && context . dialog === $ ( '#order-dialog' ) && context . dialog . open && context . request === orderDetailRequest && context . bookRequest === orderBookRequest && ( ! context . list || context . scope && context . scope === orderDetailFilterScope ());
if ( ! active ()) return false ;
// POST 已成功,移除原提交表单;后续重读失败只复用只读重试,不再提交。
if ( $ ( '#detail-form' )) $ ( '#detail-form' ). innerHTML = '' ;
orderDetailRetry = null ; orderDetailSwitchError = '' ; updateOrderDetailNavigation ();
try {
await refresh ( false , active ); if ( ! active ()) return false ;
let navigation = null , outside = false ;
if ( context . list ){
const loading = loadOrderBook (); context . request = orderDetailRequest ; context . bookRequest = orderBookRequest ; await loading ; if ( ! active ()) return false ;
const list = orderBookDetailList ; if ( ! list || list . request !== context . bookRequest ) throw new Error ( '原筛选的订单列表尚未读到' );
const index = list . ids . indexOf ( id ); if ( index !==- 1 ) navigation = { list , index }; else outside = true ;
}
const opening = openOrder ( id ,{ navigation }); context . request = orderDetailRequest ; const opened = await opening ; if ( ! active ()) return false ;
if ( opened === false && orderDetailRetry ? . id === id ){ orderDetailRetry = {... orderDetailRetry , savedContext : context }; updateOrderDetailNavigation ();}
if ( outside ){ orderDetailListChanged = true ; orderDetailSwitchError = '当前订单已不在原筛选结果中,请返回列表选择其他单据。' ; updateOrderDetailNavigation ();}
return opened ;
} catch ( err ){
if ( ! active ()) return false ;
orderDetailRetry = { id , navigation : null , savedContext : context , message : '操作已保存,最新资料暂未读到,请重试读取。' + ( err . name === 'AbortError' ? '' : err . message )};
updateOrderDetailNavigation (); return false ;
}
}
2026-10-23 09:49:36 +08:00
async function openOrder ( id , options = {}){
bindOrderDetailDialog ();
let navigation = options . navigation || null ;
const list = orderBookDetailList , source = options . source ;
if ( source && list && tab === 'orders' && list . user === orderDetailUser () && list . request === orderBookRequest && source . closest ( '#order-list' ) === list . element && source . dataset . orderBookVersion === String ( list . version )){
const index = list . ids . indexOf ( id ); if ( index !==- 1 ) navigation = { list , index };
}
if ( navigation &&! orderDetailNavigationValid ( navigation )) return ;
if ( navigation && currentOrder && $ ( '#order-dialog' ) ? . open ) requireOrderDetailSwitch ();
// 只有订单账本里的显式入口绑定列表;审批、报表和锁价入口不沿用之前的顺序。
if ( ! navigation ){ orderDetailNavigation = null ; orderDetailListChanged = false ;}
const load = { request :++ orderDetailRequest , user : orderDetailUser (), originTab : tab , navigation , id , previous : currentOrder , wasOpen :!! $ ( '#order-dialog' ) ? . open };
orderDetailLoad = load ; orderDetailRetry = null ; orderDetailSwitchError = '' ; updateOrderDetailNavigation ();
const active = ()=> load === orderDetailLoad && load . request === orderDetailRequest && load . user === orderDetailUser () && tab === load . originTab && ( ! navigation || orderDetailNavigationValid ( navigation ));
try {
2026-10-26 20:25:31 +08:00
const [ orderResult , cancellationResult , changeResult , ownershipResult ] = await Promise . allSettled ([ api ( '/api/orders/' + encodeURIComponent ( id )), api ( '/api/orders/' + encodeURIComponent ( id ) + '/cancellation' ), typeof useOrderChangeDetail === 'function' ? api ( '/api/orders/' + encodeURIComponent ( id ) + '/change' ) : Promise . resolve ( null ), typeof useOrderOwnershipDetail === 'function' ? api ( '/api/orders/' + encodeURIComponent ( id ) + '/ownership' ) : Promise . resolve ( null )]);
2026-10-23 09:49:36 +08:00
if ( ! active ()) return ;
if ( orderResult . status === 'rejected' ) throw orderResult . reason ;
2026-10-26 20:25:31 +08:00
if ( state . user . role === 'assistant' ) for ( const result of [ cancellationResult , changeResult , ownershipResult ]) if ( result . status === 'rejected' && [ 403 , 404 ]. includes ( result . reason ? . status )) throw result . reason ;
2026-10-23 09:49:36 +08:00
if ( orderResult . value ? . id !== id ) throw new Error ( '返回的订单与所选订单不一致,请重试读取。' );
if ( navigation && load . wasOpen ) requireOrderDetailSwitch ();
currentOrder = orderResult . value ; orderDetailNavigation = navigation ; orderDetailListChanged = false ; orderDetailLoad = null ;
if ( typeof useOrderCancellationDetail === 'function' ) useOrderCancellationDetail ( currentOrder , cancellationResult . status === 'fulfilled' ? cancellationResult . value : null , cancellationResult . status === 'rejected' ? cancellationResult . reason : null );
if ( typeof useOrderChangeDetail === 'function' ) useOrderChangeDetail ( currentOrder , changeResult . status === 'fulfilled' ? changeResult . value : null , changeResult . status === 'rejected' ? changeResult . reason : null );
2026-10-26 20:25:31 +08:00
if ( typeof useOrderOwnershipDetail === 'function' ) useOrderOwnershipDetail ( currentOrder , ownershipResult . status === 'fulfilled' ? ownershipResult . value : null , ownershipResult . status === 'rejected' ? ownershipResult . reason : null );
2026-10-23 09:49:36 +08:00
renderDetail (); const dialog = $ ( '#order-dialog' ); if ( ! dialog . open ) dialog . showModal (); dialog . scrollTop = 0 ;
return true ;
} catch ( err ){
if ( ! active ()) return ;
2026-10-26 20:25:31 +08:00
if ( typeof handleOrderOwnershipAccessError === 'function' && await handleOrderOwnershipAccessError ( err , id )) return false ;
2026-10-23 09:49:36 +08:00
if ( load . wasOpen && currentOrder === load . previous && $ ( '#order-dialog' ) ? . open ){
orderDetailRetry = { id , navigation , message : err . name === 'AbortError' ? '订单读取超时,请重试。' : err . message };
return false ;
}
throw err ;
} finally { if ( orderDetailLoad === load ){ orderDetailLoad = null ; updateOrderDetailNavigation ();}}
2026-10-23 00:38:04 +08:00
}
2026-10-22 04:21:26 +08:00
async function copyOrder ( id , source ){
2026-10-22 17:06:32 +08:00
if ( tab === 'order-edit' ) throw new Error ( '请先保存或取消订单修改,再复制新增。' );
2026-10-22 04:21:26 +08:00
if ( busy || orderCopyLoading ) throw new Error ( '正在处理订单,请稍候再复制。' );
if ( pending ()) throw new Error ( '请先点击顶部“恢复原操作”,确认上次提交结果后再复制新单。' );
const user = session . user . id , originTab = tab , originDialog = source ? . closest ( 'dialog' ); orderCopyLoading = true ;
try {
const [ order , latest ] = await Promise . all ([ api ( '/api/orders/' + encodeURIComponent ( id )), api ( '/api/session' )]);
if ( session . user . id !== user || latest . user ? . id !== user ) throw new Error ( '登录账号已变化,请刷新后再复制。' );
if ( tab !== originTab || source &&! source . isConnected || originDialog &&! originDialog . open ) return ;
if ( busy || pending ()) throw new Error ( '已有提交正在处理或结果待确认,请恢复原操作后再复制。' );
const draft = OrderCopy . fromOrder ( order ,{ today : latest . today }), key = 'mm-draft-' + user , raw = localStorage . getItem ( key );
let saved , unreadable = false ; try { saved = JSON . parse ( raw || 'null' );} catch { unreadable =!! raw ;}
2026-10-22 15:31:10 +08:00
if (( unreadable || OrderCopy . hasDraftContent ( saved ,{ today : latest . today , salesperson : session . user . name })) &&! window . confirm ( '当前还有未保存的开单内容。复制新增会替换这份本地草稿,是否继续?' )) return ;
2026-10-22 04:21:26 +08:00
if ( busy || pending ()) throw new Error ( '请先确认上次提交结果,再复制新单。' );
// 先成功保存本地草稿再切换页面;这里没有任何提交接口或记账操作。
localStorage . setItem ( key , JSON . stringify ( draft )); editDraft = draft ; orderTemplateSelection = '' ; state . today = latest . today ; currentOrder = null ; createMode = 'direct' ; tab = 'create' ;
$ ( '#order-dialog' ) ? . close (); await render (); $ ( '#order-form [name="customer"]' ) ? . focus (); toast ( '已复制为新单,请修改并核对后再生成销售单据' );
} finally { orderCopyLoading = false ;}
}
2026-11-02 19:30:28 +08:00
function validateRelatedPriceLocks ( items ){
if ( items === undefined ) return [];
const amount = value => value === null || Number . isSafeInteger ( value ) && value >= 0 ;
const snapshot = value => value && amount ( value . materialAmount ) && [ 'usedMaterialAmount' , 'leftoverCost' ]. every ( key => ! Object . hasOwn ( value , key ) || amount ( value [ key ])) && Array . isArray ( value . allocations ) && value . allocations . every ( part =>[ 'owner' , 'assistant' , 'assistant2' ]. includes ( part . payer ) && Number . isSafeInteger ( part . amount ) && part . amount >= 0 ) && ( value . materialAmount === null || value . allocations . reduce (( sum , part )=> sum + part . amount , 0 ) === value . materialAmount );
if ( ! Array . isArray ( items ) ||! items . every ( item => item && typeof item . id === 'string' && item . id && validOrderDate ( item . date ) && snapshot ( item . before ) && snapshot ( item . after ))) throw new Error ( '关联锁价单的成本影响未完整返回,请重新读取后复核。' );
return items ;
}
function relatedPriceLocksHTML ( items ){
const locks = validateRelatedPriceLocks ( items ); if ( ! locks . length ) return '' ;
const money = value => value === null ? '待补齐' : '¥' + yuan ( value ), sources = value => value . allocations . length ? value . allocations . map ( part => teamMemberName ( part . payer ) + ' ' + money ( part . amount )). join ( '; ' ) : value . materialAmount === null ? '待补齐后分摊' : '无分摊金额' ;
const pair = ( name , before , after )=> `<tr><th scope="row"> ${ e ( name ) } </th><td> ${ e ( before ) } </td><td> ${ e ( after ) } </td></tr>` ;
return `<section class="price-lock-related-impact"><h3>同时受影响的锁价单( ${ locks . length } 张)</h3><p class="small muted">以下只调整料池成本和付款归属,客户锁定售价与实际收付款保持原记录。</p> ${ locks . map ( lock => `<h3> ${ e ( lock . date ) } · ${ e ( lock . number || lock . id ) }${ lock . customer ? ' · ' + e ( lock . customer ) : '' } </h3><div class="table-wrap"><table class="material-detail-table material-change-comparison" aria-label="关联锁价单成本影响"><thead><tr><th>核对项目</th><th>变更前</th><th>批准后</th></tr></thead><tbody> ${ pair ( '原锁预留料费' , money ( lock . before . materialAmount ), money ( lock . after . materialAmount )) }${ [ 'before' , 'after' ]. some ( side => Object . hasOwn ( lock [ side ], 'usedMaterialAmount' )) ? pair ( '交付耗用原锁料费' , Object . hasOwn ( lock . before , 'usedMaterialAmount' ) ? money ( lock . before . usedMaterialAmount ) : '未交付' , Object . hasOwn ( lock . after , 'usedMaterialAmount' ) ? money ( lock . after . usedMaterialAmount ) : '未交付' ) : '' }${ [ 'before' , 'after' ]. some ( side => Object . hasOwn ( lock [ side ], 'leftoverCost' )) ? pair ( '少重回池成本' , Object . hasOwn ( lock . before , 'leftoverCost' ) ? money ( lock . before . leftoverCost ) : '未交付' , Object . hasOwn ( lock . after , 'leftoverCost' ) ? money ( lock . after . leftoverCost ) : '未交付' ) : '' }${ pair ( '自动付款归属' , sources ( lock . before ), sources ( lock . after )) } </tbody></table></div>` ). join ( '' ) } </section>` ;
}
2026-10-23 09:49:36 +08:00
function orderDetailCostSummary ( o ){
const costs = LedgerCalc . orderCosts ( o ), rows = [], pools = new Map ();
// 日购料的每条分摊共用整行克重,先合并,再展示付款人各自承担的金额。
for ( const row of costs . rows ){
2026-11-02 19:30:28 +08:00
if (( row . materialPoolId || row . priceLockSource ) && row . calculation ? . weighted ){
2026-10-23 09:49:36 +08:00
const key = row . source , existing = pools . get ( key );
if ( existing ){ existing . amount += row . amount ; existing . allocations . push ({ payer : row . payer , amount : row . amount });}
else { const grouped = {... row , allocations : [{ payer : row . payer , amount : row . amount }]}; pools . set ( key , grouped ); rows . push ( grouped );}
} else rows . push ( row );
}
const corrected = new Set (( o . corrections || []). filter ( row => row . type === 'expense' ). map ( row => row . target ));
// 更正冲回留在流水中;独立的负费用仍是有效成本记录,不能因金额为负被隐藏。
for ( const fee of o . expenses || []) if ( fee . amount < 0 &&! corrected . has ( fee . id ) &&! String ( fee . note || '' ). startsWith ( '更正冲回:' )) rows . push ({ kind : 'paid' , name : fee . note , source : fee . date , amount : fee . amount , payer : fee . payer });
const goods = costs . goodsExcluded ? 0 : o . goodsCost , knownGoods = costs . goodsExcluded ? 0 : Number . isSafeInteger ( goods ) ? goods : Number . isSafeInteger ( o . knownGoodsCost ) ? o . knownGoodsCost : costs . total . goods ;
const paidFees = Number . isSafeInteger ( o . directCost ) ? o . directCost : rows . filter ( row => row . kind === 'paid' ). reduce (( sum , row )=> sum + ( row . amount ?? 0 ), 0 );
const missing =! costs . goodsExcluded && ( ! Number . isSafeInteger ( goods ) || costs . total . goodsMissing > 0 );
return { costs , rows , goods , knownGoods , paidFees , missing , knownTotal : knownGoods + paidFees , total : missing ? null : knownGoods + paidFees };
}
function orderSalesHTML ( o ,{ voided = false } = {}){
const historical = voided || [ 'returned' , 'cancelled' ]. includes ( o . status ), unbooked = [ 'draft' , 'confirmed' ]. includes ( o . status );
const subtotal = o . lines . reduce (( sum , line )=> sum + line . sale , 0 ), discount = o . discount || 0 , unrounded = subtotal - discount ;
const adjustment = Number . isSafeInteger ( o . rounding_adjustment ) ? o . rounding_adjustment : o . total - unrounded ;
const totalLabel = voided ? '原成交金额(已作废)' : historical ? '原成交金额' : unbooked ? '报价合计' : '成交金额' ;
const salesNote = voided ? '本单已作废,以下原销售计算仅供追溯。' : historical ? '原销售已冲回,以下保留原成交计算。' : unbooked ? '尚未完成销售记账,以下为已保存报价。' : '' ;
return `<section class="panel detail-sales" aria-label="销售计算"><div class="panel-title"><h2>销售怎么算</h2> ${ historical || unbooked ? '<span class="small muted">原单记录</span>' : '' } </div> ${ salesNote ? `<p class="small muted"> ${ salesNote } </p>` : '' }
${ o . lines . map (( line , index )=>{
const charges = line . charges || [], chargeTotal = charges . reduce (( sum , charge )=> sum + ( charge . amount ?? 0 ), 0 ), base = Number . isSafeInteger ( line . baseSale ) ? line . baseSale : line . sale - chargeTotal ;
const auto = line . pricingMode === 'auto' && line . unit === 'g' && Number . isSafeInteger ( line . goldPrice ) && Number . isSafeInteger ( line . laborRate ) && [ 'gram' , 'piece' ]. includes ( line . laborMode ) && ( line . laborMode !== 'piece' || Number . isSafeInteger ( line . pieces ) && line . pieces > 0 );
const quantity = line . unit === 'g' ? grams ( line . quantity ) + 'g' : line . quantity + '件' ;
const formula = auto ? ( line . laborMode === 'gram' ? ` ${ grams ( line . quantity ) } g ×(金价 ${ yuan ( line . goldPrice ) } 元/克 + 工费 ${ yuan ( line . laborRate ) } 元/克)` : ` ${ grams ( line . quantity ) } g × 金价 ${ yuan ( line . goldPrice ) } 元/克 + ${ line . pieces } 件 × 件工费 ${ yuan ( line . laborRate ) } 元/件` ) : '直接填基础金额' ;
2026-10-25 17:50:26 +08:00
return `<article class="detail-sale-line"><div class="detail-line-heading"><div class="detail-line-identity"><strong> ${ o . lines . length > 1 ? index + 1 + ' · ' : '' }${ e ( line . name ) } </strong> ${ orderLinePocketHTML ( o , line ) } </div><span class="small muted"> ${ quantity } </span></div><p class="detail-formula"> ${ formula }${ auto ? ' = ' : ' ' } <strong>¥ ${ yuan ( base ) } </strong></p> ${ ! auto && line . priceNote ? `<p class="small muted detail-price-note"> ${ e ( line . priceNote ) } </p>` : '' }${ charges . length ? `<div class="detail-sale-addons"> ${ charges . map ( charge => `<span>+ ${ e ( charge . name ) } <b> ${ charge . amount == null ? '收费未填' : '¥' + yuan ( charge . amount ) } </b></span>` ). join ( '' ) } </div>` : '' }${ o . lines . length > 1 || charges . length ? `<div class="detail-line-total"><span>本行合计</span><b>¥ ${ yuan ( line . sale ) } </b></div>` : '' } </article>` ;
2026-10-23 09:49:36 +08:00
} ).join('')}
<div class="detail-sale-total"> ${ o . lines . length > 1 || discount || o . rounding_mode === 'yuan' ? `<div class="detail-total-row"><span>销售小计</span><span>¥ ${ yuan ( subtotal ) } </span></div>` : '' }${ discount ? `<div class="detail-total-row"><span>- 整单优惠</span><span>¥ ${ yuan ( discount ) } </span></div>` : '' }${ o . rounding_mode === 'yuan' ? `<p class="small muted detail-rounding">整单四舍五入到元:¥ ${ yuan ( unrounded ) } → ${ orderAmount ( o . total , 'yuan' ) }${ adjustment ? '( ' + ( adjustment > 0 ? '+' : '− ' ) + yuan ( Math . abs ( adjustment )) + '元)' : '' } </p>` : '' } <div class="detail-total-row detail-total-final"><span> ${ totalLabel } </span><strong> ${ orderAmount ( o . total , o . rounding_mode ) } </strong></div></div> ${ o . note ? `<p class="detail-customer-note small"><span class="muted">客户单备注:</span> ${ e ( o . note ) } </p>` : '' } </section>` ;
}
function orderCostRowsHTML ( rows , label ){
2026-11-03 01:15:41 +08:00
const names = { owner : '麦麦' , assistant : teamMemberName ( 'assistant' ), assistant2 : teamMemberName ( 'assistant2' )};
2026-10-23 09:49:36 +08:00
return `<div class="table-wrap"><table class="detail-cost-table" aria-label=" ${ e ( label ) } "><thead><tr><th>成本项目</th><th>付款人</th><th class="number">金额</th></tr></thead><tbody> ${ rows . map ( row =>{
const calculation = row . calculation , weighted = calculation ? . weighted ;
const formula = calculation ? weighted ? `耗用 ${ grams ( calculation . quantity ) } g ${ calculation . rate == null ? '' : ' · 加权均价约 ' + yuan ( calculation . rate ) + '元/克' } ;按实际购料分摊` : ` ${ grams ( calculation . quantity ) } g × ${ calculation . rate == null ? '单价待补' : yuan ( calculation . rate ) + '元/克' } ` : '' ;
const payer = row . poolPending ? '待补采购后分摊' : row . allocations ? row . allocations . filter ( part => part . amount !== 0 ). map ( part => e ( names [ part . payer ] || '待补' ) + ' ¥' + yuan ( part . amount )). join ( '<br>' ) : e ( names [ row . payer ] || '待补' );
return `<tr ${ row . amount == null ? ' class="detail-cost-missing"' : '' } ><td> ${ e ( row . priceLockSource === 'original' ? '原锁料费' : row . priceLockSource === 'extra' ? '补重料费' : row . name ) } <div class="small muted"> ${ e ( row . source ) }${ row . excluded ? ' · 已冲回' : '' } </div> ${ formula ? `<div class="small muted"> ${ formula } </div>` : '' } </td><td class="detail-cost-payer"> ${ payer } </td><td class="number"> ${ row . amount == null ? '<span class="danger-text">待补齐</span>' : '¥' + yuan ( row . amount ) } </td></tr>` ;
} ).join('')}</tbody></table></div>` ;
}
function orderCostsHTML ( o , summary = orderDetailCostSummary ( o ),{ voided = false } = {}){
const { costs , rows , knownTotal , missing , knownGoods , paidFees } = summary ;
const actual = rows . filter ( row => ! row . excluded && row . kind !== 'pending' && row . amount !== 0 ), pending = rows . filter ( row => row . kind === 'pending' && row . amount !== 0 ), historical = rows . filter ( row => row . excluded && row . amount !== 0 );
const numbers = actual . filter ( row => row . amount != null ). map ( row => row . amount ), rowTotal = numbers . reduce (( sum , amount )=> sum + amount , 0 );
// 合计使用订单权威成本。旧单分项与总额不一致时,按保存的货品与费用合计展示。
const terms = rowTotal === knownTotal ? numbers : [ knownGoods , paidFees ]. filter ( amount => amount !== 0 );
const equation = ( terms . length ? terms : [ 0 ]). map ( amount => '¥' + yuan ( amount )). join ( ' + ' );
2026-10-25 14:19:24 +08:00
const payerTotals = { owner : 0 , assistant : 0 , assistant2 : 0 };
2026-10-23 09:49:36 +08:00
for ( const row of actual ) for ( const part of row . allocations || [ row ]) if ( Object . hasOwn ( payerTotals , part . payer )) payerTotals [ part . payer ] += part . amount ?? 0 ;
2026-10-25 14:19:24 +08:00
const payerParts = Object . entries ( payerTotals ). filter (([, amount ])=> amount !== 0 ). map (([ payer , amount ])=> `<span> ${ e ( teamMemberName ( payer )) } <b>¥ ${ yuan ( amount ) } </b></span>` );
2026-10-23 09:49:36 +08:00
return `<section class="panel order-costs detail-costs" aria-label="成本明细与付款人"><div class="panel-title"><h2>成本怎么算</h2><span class="small muted"> ${ costs . goodsExcluded ? '冲回后保留成本' : '货品成本+实际费用' } </span></div>
${ actual . length ? orderCostRowsHTML ( actual , '有效成本明细与付款人' ) : `<p class="small muted detail-zero-cost"> ${ missing ? '成本尚未补齐。' : '已核实成本为 ¥0.00。' } </p>` }
<div class="detail-cost-sum"><span> ${ missing ? '已知成本' : '成本合计' } </span><div class="detail-cost-equation"> ${ equation } = <strong>¥ ${ yuan ( knownTotal ) } </strong></div> ${ payerParts . length ? `<p class="detail-cost-payer-totals" aria-label="有效成本按付款人合计"><span class="muted">付款人合计 ${ missing || rowTotal !== knownTotal ? '(已知)' : '' } </span> ${ payerParts . join ( '' ) } </p>` : '' } </div>
${ missing ? `<p class="small danger-text detail-cost-warning"> ${ o . materialCostPending ? '料费待补,补足当日购料后自动更新成本和利润。' : '货品成本尚未补齐,以上只合计已知金额,不能当作完整成本。' } </p>` : '' }
${ pending . length ? `<div class="detail-pending-costs"><p class="small danger-text">以下 ${ pending . length } 项费用尚未入账,不计入成本合计和实际利润。</p> ${ orderCostRowsHTML ( pending , '尚未入账的费用' ) } </div>` : '' }
${ costs . goodsExcluded ? `<p class="small muted detail-cost-status"> ${ voided ? '本单已按录错作废,原货品成本和费用保留供查阅,已撤销的金额不计入本单成本。' : '原货品成本已冲回,不计当前成本;实际发生的费用仍保留。' } </p>` : '' }
${ historical . length ? `<details class="detail-cost-history"><summary>原货品成本(已冲回,不计当前成本)</summary> ${ orderCostRowsHTML ( historical , '已冲回的原货品成本' ) } </details>` : '' } </section>` ;
}
function orderProfitHTML ( o , summary ,{ voided = false } = {}){
const { total , missing } = summary , done = [ 'delivered' , 'returned' , 'cancelled' ]. includes ( o . status ), historical = voided || [ 'returned' , 'cancelled' ]. includes ( o . status );
const title = voided ? '作废后净额' : o . status === 'returned' ? '退货后净额' : o . status === 'cancelled' ? '取消后净额' : '实际订单利润' ;
const known = done &&! missing && o . profit != null , value =! done ? '尚未完成销售记账' :! known ? '待核算' : '¥' + yuan ( o . profit );
const sale = historical ? 0 : o . total ;
let equation =! done ? '旧单账务补齐后,按实际销售与成本核算利润。' :! known ? `成交金额 ¥ ${ yuan ( o . total ) } − 完整成本待补,利润暂不确认。` : ` ${ historical ? '销售净额' : '成交金额' } ¥ ${ yuan ( sale ) } − ${ historical ? '保留成本' : '成本合计' } ¥ ${ yuan ( total ) } = ${ title } ¥ ${ yuan ( o . profit ) } ` ;
if ( known && sale - total !== o . profit ) equation = ` ${ historical ? '销售净额' : '成交金额' } ¥ ${ yuan ( sale ) } ;成本合计 ¥ ${ yuan ( total ) } 。利润沿用已记账金额,历史差异请核对下方流水。` ;
return `<section class="panel detail-profit ${ known ? ' detail-profit-known' : '' } " aria-label=" ${ title } "><div class="detail-profit-heading"><h2> ${ title } </h2><strong> ${ value } </strong></div><p class="detail-profit-formula"> ${ equation } </p> ${ historical ? '<p class="small muted">原成交金额不计有效销售;未退清的客户款另在收退款记录中核对。</p>' : '' } </section>` ;
}
function orderProductTraceHTML ( o ){
2026-11-08 03:30:58 +08:00
return `<details class="panel detail-product-trace"><summary>商品来源与原始说明</summary><ul class="detail-product-sources"> ${ o . lines . map (( line , index )=> `<li><strong> ${ index + 1 } · ${ e ( line . name ) } </strong><span> ${ line . unit === 'g' ? grams ( line . quantity ) + 'g' : line . quantity + '件' } · ${ e ( pocketLabel ( String ( line . pocket || '' ). trim ()) || '配货' ) }${ line . code ? ' · 编号 ' + e ( line . code ) : '' } </span> ${ line . priceNote ? `<span> ${ e ( line . priceNote ) } </span>` : '' } </li>` ). join ( '' ) } </ul></details>` ;
2026-10-17 19:50:24 +08:00
}
2026-10-25 17:50:26 +08:00
function orderLinePocketHTML ( order , line ){
2026-11-08 03:30:58 +08:00
const pocket = pocketLabel ( String ( line . pocket || '' ). trim ()) || '配货' ;
2026-10-25 17:50:26 +08:00
const title = order . status === 'delivered' ? '出货货盘' : order . status === 'returned' ? '原出货货盘' : order . status === 'cancelled' ? '原登记货盘' : [ 'draft' , 'confirmed' ]. includes ( order . status ) ? '拟出库货盘' : '登记货盘' ;
return `<span class="detail-line-pocket"> ${ e ( title ) } : ${ e ( pocket ) } </span>` ;
2026-10-25 14:19:24 +08:00
}
2026-10-25 17:50:26 +08:00
2026-10-17 19:50:24 +08:00
function renderDetail (){
2026-10-23 09:49:36 +08:00
const o = currentOrder , done = [ 'delivered' , 'returned' , 'cancelled' ]. includes ( o . status );
2026-10-26 20:25:31 +08:00
const cancellationPending = typeof orderCancellationPending === 'function' ? orderCancellationPending ( o ) : o . cancellationPending , changePending = typeof orderChangePending === 'function' ? orderChangePending ( o ) : o . changePending , ownershipPending = typeof orderOwnershipPending === 'function' ? orderOwnershipPending ( o ) : o . ownershipPending , approvalPending =!! cancellationPending ||!! changePending ||!! ownershipPending , voided = typeof orderCancellationApproved === 'function' ? orderCancellationApproved ( o ) : o . cancellationApproved , financialBlocked = approvalPending ||!! voided , owner = state . user . role === 'owner' ;
2026-10-22 04:21:26 +08:00
let actions = button ( '客户预览/打印' , 'print' , 'primary' , `data-id=" ${ o . id } "` ) + ( showOrderCopyEntry ? button ( '<span aria-hidden="true">+ </span>复制新增' , 'copy-order' , 'order-copy-button' , `data-id=" ${ e ( o . id ) } "` ) : '' );
2026-10-23 11:58:19 +08:00
if (( o . status !== 'draft' ||! owner ) &&! approvalPending ) actions = button ( owner || o . date === state . today ? '修改订单' : '申请修改' , 'edit-order' , 'primary' , `data-id=" ${ e ( o . id ) } "` ) + actions ;
2026-10-23 09:49:36 +08:00
if ( o . status === 'draft' && owner &&! financialBlocked ) actions += button ( '继续填写并开单' , 'edit' );
2026-10-23 11:58:19 +08:00
const needsApproval = kind => typeof orderActionRequiresApproval === 'function' ? orderActionRequiresApproval ( kind ) :! owner ;
if ( o . status === 'confirmed' &&! financialBlocked ){ if ( o . pendingFees . length ) actions += button ( needsApproval ( 'fees' ) ? '申请补记旧单费用' : '补记旧单费用' , 'show-fees' ); if ( o . balance > 0 ) actions += button ( '登记收款' , 'show-receipt' ); actions += button ( owner ? '补齐/核对货品成本' : '申请补录货品成本' , 'show-cost' ); actions += button ( '补齐旧单账务' , 'show-complete' );}
if ( o . status !== 'draft' &&! financialBlocked ) actions += button ( needsApproval ( 'expense' ) ? '申请补记费用' : '记额外费用' , 'show-expense' );
2026-10-23 00:38:04 +08:00
if ( typeof orderCancellationActionHTML === 'function' ) actions += orderCancellationActionHTML ( o );
2026-10-23 11:58:19 +08:00
if ( o . status === 'delivered' &&! financialBlocked ) actions += button ( needsApproval ( 'return' ) ? '申请整单退货' : '整单退货' , 'show-return' , 'danger' );
if ([ 'cancelled' , 'returned' ]. includes ( o . status ) && o . netReceived > 0 &&! financialBlocked ) actions += button ( needsApproval ( 'refund' ) ? '申请登记退款' : '登记实际退款' , 'show-refund' );
2026-10-25 14:19:24 +08:00
if ( done &&! approvalPending && o . settlementDue != null && o . settlementDue !== 0 &&! o . materialCostPending &&! teamMode ()) actions += button ( '登记实际交款/返款' , 'show-settlement' );
2026-10-23 09:49:36 +08:00
if ( owner &&! approvalPending && (( ! voided && ( o . payments . some ( p => ! p . price_lock_event_id ) || o . expenses . length )) || o . settlements . length )) actions += button ( '更正记错的流水' , 'show-correct' );
if ( owner &&! approvalPending && o . reviewed_revision !== o . revision ) actions += button ( '麦麦复核' , 'show-review' );
2026-10-26 14:44:07 +08:00
if ( o . recovery_id && typeof recoveryLinkedOrderActionsHTML === 'function' ) actions = recoveryLinkedOrderActionsHTML ( o ,{ reviewAllowed : owner &&! approvalPending && o . reviewed_revision !== o . revision });
2026-10-23 09:49:36 +08:00
const costs = orderDetailCostSummary ( o );
2026-10-23 11:58:19 +08:00
const reviewSeal =! approvalPending && orderIsReviewed ( o ) ? '<div class="order-review-seal" role="status" aria-label="已审批,麦麦已复核"><svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><circle cx="12" cy="12" r="10"/><path d="m7 12 3.2 3.2L17 8.5"/></svg><strong>已审批</strong><small>麦麦已复核</small></div>' : '' ;
2026-11-03 01:15:41 +08:00
$ ( '#order-content' ). innerHTML = `<div id="order-detail-navigation" class="order-detail-navigation" ${ orderDetailNavigationHTML () ? '' : 'hidden' } aria-busy=" ${ !! orderDetailLoad } "> ${ orderDetailNavigationHTML () } </div><div class="order-header order-detail-header"><div class="eyebrow">ORDER DETAIL</div><div class="order-detail-heading"><h2> ${ e ( String ( o . customer ?? '' ). trim () || '未填客户称呼' ) } </h2> ${ reviewSeal } </div><p class="small muted order-detail-identifiers">纸单号 ${ e ( o . paper_number || '未分配' ) } · 系统单号 ${ e ( o . number ) } · 收款账户 ${ e ( accountDisplayName ( o . payment_account )) } </p> ${ badge ( o ) }${ o . member ? `<span class="badge member-badge"> ${ e ( teamMemberName ( o . member )) } 的订单</span>` : '' }${ typeof orderOwnershipActionHTML === 'function' ? orderOwnershipActionHTML ( o ) : '' } <span class="muted small">日期 ${ e ( o . date ) } · 开单人 ${ e ( o . salesperson ) } </span></div> ${ materialPoolOrderNoticeHTML ( o ) }${ typeof recoveryLinkedOrderNoticeHTML === 'function' ? recoveryLinkedOrderNoticeHTML ( o ) : '' }${ ! done ? `<div class="note"> ${ o . status === 'draft' ? '这是尚未开单的旧草稿,继续填写后生成销售单据。' : '这张旧单尚未完成销售记账。请按实际情况补齐款项、货品成本和费用,再点“补齐旧单账务”;保存时一并记费用、扣库存和计算利润。' } </div>` : '' } <div class="actions detail-actions"> ${ actions } </div> ${ typeof orderCancellationDetailHTML === 'function' ? orderCancellationDetailHTML ( o ) : '' }${ typeof orderChangeDetailHTML === 'function' ? orderChangeDetailHTML ( o ) : '' }${ typeof orderOwnershipDetailHTML === 'function' ? orderOwnershipDetailHTML ( o ) : '' } <div id="detail-form" class="detail-form"></div><div id="detail-error"></div> ${ orderInternalNoteHTML ( o ) } <div class="order-detail-breakdown"> ${ orderSalesHTML ( o ,{ voided } )} ${ orderCostsHTML ( o , costs ,{ voided } )}</div> ${ orderProfitHTML ( o , costs ,{ voided } )} ${ orderProductTraceHTML ( o ) }${ o . funds_mode === 'team' ? orderTeamFundsHTML ( o ) : `<details class="panel detail-settlement"><summary> ${ teamMode () ? '历史两人结算(只供追溯,不计入团队往来)' : '与娜娜的结算' } </summary><div class="grid three"><div>麦麦垫资应回收 <strong>¥ ${ yuan ( o . ownerCost ) } </strong><br><small class="muted">实际已交净额 ¥ ${ yuan ( o . costTransferred ) } </small></div><div>已记账订单利润 <strong> ${ done ? ( o . profit == null ? ( o . materialCostPending ? '料费待补' : '成本未补齐' ) : '¥' + yuan ( o . profit )) : '旧单待补齐' } </strong><br><small class="muted">实际已交净额 ¥ ${ yuan ( o . profitTransferred ) } </small></div><div> ${ o . settlementDue < 0 ? '麦麦待转回娜娜' : '娜娜待交麦麦' } <strong> ${ o . settlementDue == null ? '料费待补' : '¥' + yuan ( Math . abs ( o . settlementDue )) } </strong><br><small class="muted"> ${ o . materialCostPending ? '补足购料后自动计算;当前不能登记交款' : done ? '含本单货款与利润,该日购料结算另行核对' : '旧单完成销售记账后形成应交款' } </small></div></div> ${ priceLockInventoryCreditHTML ( o ) }${ o . ownerDirect ? `<div class="note">麦麦直接收客户净额 ¥ ${ yuan ( o . ownerDirect ) } , ${ o . status === 'delivered' ? '已从总待结金额扣除,货款/利润拆分需单独复核。' : o . price_lock_id && o . status === 'returned' && o . netReceived === 0 ? '客户已退清;跨账户收退款形成的差额已计入双方结算。' : '这部分属于客户款,取消/退货后须从原账户退客户,不算应返助理。' } </div>` : '' } <p class="small muted" style="margin:14px 0 0">开单后按单交货款,利润月底交。退货返款单独记录,不抵下一笔。这里记录实际转账,不会发起付款。</p></details>` } <details class="panel"><summary>收退款与费用记录</summary> ${ transactionTable ( o ) } <details><summary>操作记录</summary><ul class="timeline"> ${ o . audit . map ( a => `<li> ${ e ( actionName [ a . action ] || a . action ) } · ${ e ( a . actor ) } <small> ${ e ( new Date ( a . created ). toLocaleString ( 'zh-CN' )) } </small> ${ a . detail . reason ? e ( a . detail . reason ) : '' } </li>` ). join ( '' ) } </ul></details></details>` ;
2026-10-23 00:38:04 +08:00
}
2026-11-03 01:15:41 +08:00
function transactionTable ( o ){ const rows = [... o . payments . map ( p =>({ date : p . date , type : String ( p . reference || '' ). startsWith ( '更正冲回:取消审批作废;' ) ? '作废冲回' + ( p . kind === 'receipt' ? '收款' : '退款' ) : p . kind === 'receipt' ? '客户收款' : '客户退款' , amount : p . amount , who : accountDisplayName ( p . account ), note : p . reference })),... o . expenses . map ( x =>({ date : x . date , type : String ( x . note || '' ). startsWith ( '更正冲回:取消审批作废;' ) ? '作废冲回费用' : '直接费用' , amount : x . amount , who : teamMemberName ( x . payer ) + '支付' , note : x . note })),... o . settlements . map ( s =>({ date : s . date , type : ( s . amount < 0 ? '麦麦返娜娜' : '娜娜交麦麦' ) + ' · ' + ( s . bucket === 'cost' ? '货款' : '利润' ), amount : Math . abs ( s . amount ), who : s . actor , note : s . note }))]. sort (( a , b )=> a . date . localeCompare ( b . date )); return rows . length ? `<div class="table-wrap"><table><thead><tr><th>日期</th><th>业务</th><th>金额</th><th>账户/经办人</th><th>说明</th></tr></thead><tbody> ${ rows . map ( r => `<tr><td> ${ r . date } </td><td> ${ r . type } </td><td>¥ ${ yuan ( r . amount ) } </td><td> ${ e ( r . who ) } </td><td> ${ e ( r . note ) } </td></tr>` ). join ( '' ) } </tbody></table></div>` : '<p class="muted">还没有收退款、费用或交款记录。</p>' ;}
2026-10-17 19:50:24 +08:00
function showAction ( action ){
2026-10-23 11:58:19 +08:00
const o = currentOrder ; let html = '' ; const dt = dateField (), changeForm = typeof orderActionUsesChangeForm === 'function' && orderActionUsesChangeForm ( action ), requiresApproval = typeof orderActionRequiresApproval === 'function' && orderActionRequiresApproval ( action );
if ( action === 'cancel' ) throw new Error ( '请重新读取订单后,从“取消订单”或“申请取消”核对办理。' );
2026-10-26 20:25:31 +08:00
if ( o . ownershipPending || typeof orderOwnershipPending === 'function' && orderOwnershipPending ( o )) throw new Error ( '归属申请待麦麦复核,当前暂停本单其他修改和记账。' );
2026-10-23 00:38:04 +08:00
if ( o . cancellationPending || typeof orderCancellationPending === 'function' && orderCancellationPending ( o )) throw new Error ( '取消申请待麦麦复核,当前暂停本单修改和退货。' );
2026-10-23 09:49:36 +08:00
if ( o . changePending || typeof orderChangePending === 'function' && orderChangePending ( o )) throw new Error ( '修改申请待麦麦复核,当前暂停本单其他记账和取消申请。' );
2026-10-23 00:38:04 +08:00
if ( o . cancellationApproved &&! [ 'settlement' , 'correct' , 'review' ]. includes ( action )) throw new Error ( '本单已按录错作废,不能继续登记销售、费用或退款。' );
2026-10-23 11:58:19 +08:00
if ( changeForm ) prepareOrderActionChange ( action );
2026-10-23 09:49:36 +08:00
if ( action === 'complete' && state . user . role === 'assistant' && o . pendingFees . length ) throw new Error ( '这张旧单还有费用尚未入账,请先申请补记旧单费用,麦麦同意后再补齐旧单账务。' );
2026-10-25 14:19:24 +08:00
if ( action === 'fees' ) html = `<p>补齐旧单实际已付费用,没有发生的填0。保存后只记一次实际费用;完成旧单账务后计算完整利润。</p> ${ dt } <div class="fee-grid" id="verify-fees"> ${ o . pendingFees . map ( f => `<div class="fee-verify-row" data-key=" ${ e ( f . key ) } "><h3> ${ e ( f . note ) } </h3> ${ moneyField ( '实际成本(元)' , 'verifiedAmount' , f . amount === null ? '' : ( f . amount / 100 ). toFixed ( 2 )) }${ choice ( '实际付款人' , 'verifiedPayer' , teamMemberOptions ( true ), f . payer ) } </div>` ). join ( '' ) } </div><label class="check"><input type="checkbox" name="verified" required>已核实实际支付,没有发生的费用已填0。</label>` ;
2026-10-17 19:50:24 +08:00
if ([ 'receipt' , 'refund' ]. includes ( action )) html = `<div class="grid three"> ${ dt }${ moneyField ( action === 'receipt' ? '本次实收金额' : '本次实退金额' , 'amount' ,(( action === 'receipt' ? o . balance : o . netReceived ) / 100 ). toFixed ( 2 )) }${ accountFields ( action === 'refund' ? ( o . payments . find ( p => p . kind === 'receipt' && o . payments . filter ( r => r . account === p . account ). reduce (( n , r )=> n + ( r . kind === 'receipt' ? r . amount :- r . amount ), 0 ) > 0 ) ? . account || o . payment_account ) : o . payment_account ) } </div> ${ field ( '凭据备注(选填)' , 'reference' , '' , 'text' , 'maxlength="100" placeholder="交易凭据末几位或说明"' ) } <label class="check"><input type="checkbox" name="verified" required>已在实际账户核实 ${ action === 'receipt' ? '到账' : '退款成功' } ,不是仅收到客户截图。</label>` ;
2026-10-25 14:19:24 +08:00
if ( action === 'expense' ) html = ` ${ o . pendingFees . length ? '<div class="note">本旧单还有费用尚未入账,请从“补记旧单费用”补齐,或完成旧单账务时一并入账。这里仅记额外发生的费用。</div>' : '' } <p class="small muted">记录额外已支付的费用;已包含在货品成本或已记账费用中的不要重复登记。</p><div class="grid three"> ${ dt }${ moneyField ( '本次费用' , 'amount' ) }${ choice ( '实际付款人' , 'payer' , teamMemberOptions ( true ), 'assistant' ) } </div> ${ field ( '费用项目与说明' , 'note' , '' , 'text' , 'required maxlength="150"' ) } ` ;
if ( action === 'cost' ) html = `<div class="note">进货料价和克工费按该行克重自动计算;原单合计金额保留,改按克录入时需填写实际单价。没有的成本填0,完成销售记账后锁定。快递和附加费用可从“补记旧单费用”填写。</div> ${ o . lines . map (( l , i )=> `<div class="internal cost-editor"><h3> ${ e ( l . name ) } · ${ l . unit === 'g' ? grams ( l . quantity ) + 'g' : l . quantity + '件' } </h3><div class="cost-fallback-payer"> ${ choice ( '配件及其他成本付款人' , 'goodsPayer' , teamMemberOptions (), l . payer || 'owner' ) } </div> ${ ! l . costParts && l . cost !== null ? `<p class="small">原记录未分项,总额 ¥ ${ yuan ( l . cost ) } ;请按凭据拆分,不要把总额再填入每个项目。</p>` : '' } <div class="cost-fields grid"> ${ costFields ( l . costParts ? Object . fromEntries ( Object . entries ( l . costParts ). map (([ k , v ])=>[ k , v === null ? '' : ( v / 100 ). toFixed ( 2 )])) : { material : '' , labor : '' , accessories : '0' , other : '0' } ,'cost-'+i+'-',true,{mode:l.costLabor?.mode||'total',rate:l.costLabor?.rate==null?'':(l.costLabor.rate/100).toFixed(2)},{...materialCostInput(l),...(l.costMaterial?.mode==='gram'?{rate:l.costMaterial.rate==null?'':(l.costMaterial.rate/100).toFixed(2)}:{})},{},l.unit,costPayerInput(l))}</div><div class="cost-summary small"></div></div>` ). join ( '' ) } ` ;
2026-10-17 19:50:24 +08:00
if ( action === 'complete' ) html = ` ${ dt } <p>补齐这张旧单的销售记账:按填写金额记录实际费用、从原货盘扣减黄金并计入销售与利润。款项未收齐或成本金额有空白时,请先补齐。</p><label class="check"><input type="checkbox" name="verified" required>已核实全额收款、商品已交付,所填费用为实际已付金额,没有发生的已填0。</label>` ;
2026-11-08 03:30:58 +08:00
if ( action === 'return' ) html = ` ${ dt }${ field ( '退货原因' , 'reason' , '' , 'text' , 'required maxlength="200"' ) } <div class="grid two"> ${ o . lines . map (( l , i )=> choice ( l . name + ' · 实物去向' , 'return-' + i , l . unit === 'g' ? [...( l . pocket || l . costMaterial ? . mode === 'pool' ? [] : [[ '' , '已退供应商,不留店内' ]]),... pocketOptions ( l . pocket , true )] : [[ '' , '按件商品,不记黄金货盘' ]], l . pocket || ( l . costMaterial ? . mode === 'pool' ? state . pockets [ 0 ] : '' ))). join ( '' ) } </div><div class="note">本入口办理整单退货,原销售额与货品成本在退货日冲回。已花费的运费等仍保留。换货先退原单,再开新单;部分退货暂未开放。</div><label class="check"><input type="checkbox" name="verified" required>已核实本单全部商品退回,所选去向与实际一致。</label>` ;
2026-11-06 01:29:35 +08:00
if ( action === 'settlement' && teamMode ()) throw new Error ( '三人成员往来请在每日对账核对。' );
2026-10-21 01:32:49 +08:00
if ( action === 'settlement' && ( o . materialCostPending || o . settlementDue == null )) throw new Error ( '本批料费尚未补齐,补足采购后再核对实际交款。' );
2026-11-03 01:15:41 +08:00
if ( action === 'settlement' ) html = `<div class="grid three"> ${ dt }${ choice ( '转款方向' , 'direction' ,[[ 'toOwner' , '娜娜 → 麦麦' ],[ 'toAssistant' , '麦麦 → 娜娜' ]], o . settlementDue < 0 ? 'toAssistant' : 'toOwner' ) }${ choice ( '本笔归属' , 'bucket' ,[[ 'cost' , '货款' ],[ 'profit' , '利润' ]], 'cost' ) } </div><div class="grid two"> ${ moneyField ( '实际转账金额' , 'amount' ) }${ field ( '转账凭据/说明' , 'note' , '' , 'text' , 'required maxlength="150"' ) } </div><p class="small muted"> ${ o . ownerCredit ? '麦麦已直接收到部分客户款,先按实际情况核清归属。' : `货款待结 ¥ ${ yuan ( o . costDue ) } ;利润待结 ¥ ${ yuan ( o . profitDue ) } (负数为麦麦需转回)。` } </p><label class="check"><input type="checkbox" name="verified" required>已核实各人实际转账,不是仅记录计划交款。</label>` ;
2026-10-17 19:50:24 +08:00
if ( action === 'correct' ){
2026-10-21 01:32:49 +08:00
const valid = ( r )=> ! r . price_lock_event_id &&! o . corrections . some ( c => c . target === r . id ) &&! String ( r . note || r . reference || '' ). startsWith ( '更正冲回:' );
2026-10-23 09:49:36 +08:00
const cardExpenseIds = new Set (( o . fee_items || []). filter ( isAutomaticCardFee ). map ( item => item . expense_id ));
2026-11-03 01:15:41 +08:00
const entries = [...( o . cancellationApproved ? [] : o . payments . filter ( valid )). map ( r =>[ 'payment:' + r . id , r . date + ' ' + ( r . kind === 'receipt' ? '客户收款' : '客户退款' ) + ' ' + yuan ( r . amount ) + '元 ' + accountDisplayName ( r . account )]),...( o . cancellationApproved ? [] : o . expenses . filter ( r => valid ( r ) &&! isAutomaticCardFee ( r ) &&! cardExpenseIds . has ( r . id ))). map ( r =>[ 'expense:' + r . id , r . date + ' 直接费用 ' + yuan ( r . amount ) + '元 ' + r . note ]),... o . settlements . filter ( valid ). map ( r =>[ 'settlement:' + r . id , r . date + ' ' + ( r . amount < 0 ? '麦麦返款' : '娜娜交款' ) + ' ' + yuan ( Math . abs ( r . amount )) + '元' ])];
html = `<div class="note">更正录错的流水,保留原记录。填0表示撤回误记。真实客户退货请用退货入口,不要用更正代替。更正发生在所选日期,不覆盖原日记录。</div> ${ choice ( '选择原流水' , 'entry' , entries , entries [ 0 ] ? .[ 0 ]) } <div class="grid three"> ${ dt }${ moneyField ( '更正后金额(元)' , 'amount' ) }${ choice ( '更正后收退款账户(仅收退款)' , 'account' ,[... new Set ( state . accounts . map ( normalizePaymentAccount ))], '助理微信' ) }${ choice ( '更正后付款人(仅费用)' , 'payer' , teamMemberOptions ( true ), 'assistant' ) }${ choice ( '更正后转款方向(仅交款)' , 'direction' ,[[ 'toOwner' , '娜娜 → 麦麦' ],[ 'toAssistant' , '麦麦 → 娜娜' ]], 'toOwner' ) }${ choice ( '更正后款项归属(仅交款)' , 'bucket' ,[[ 'cost' , '货款' ],[ 'profit' , '利润' ]], 'cost' ) } </div> ${ field ( '更正原因' , 'reason' , '' , 'text' , 'required maxlength="200"' ) } <label class="check"><input type="checkbox" name="verified" required>已核实原凭据,这次是修正登记错误。</label>` ;
2026-10-17 19:50:24 +08:00
}
2026-10-23 09:49:36 +08:00
if ([ 'receipt' , 'correct' ]. includes ( action )) html += creditCardPreviewHTML ( 'action-credit-card-fee' );
2026-10-17 19:50:24 +08:00
if ( action === 'review' ) html = '<p>确认已查看商品、克重、成本、收退款与交款凭据。复核后再有变动,会重新提示待复核。</p>' ;
2026-10-25 14:19:24 +08:00
$ ( '#detail-form' ). innerHTML = `<form class="panel" id="action-form" data-kind=" ${ action } " ${ changeForm ? `data-order-change="true" data-order-direct=" ${ ! requiresApproval } "` : '' } ><h2> ${ requiresApproval ? '申请' + orderChangeActionLabels [ action ] : actionName [ action ] } </h2> ${ html }${ changeForm ? orderActionChangeReviewHTML ( action ) : '' } <div class="form-actions"><button class="primary" ${ changeForm ? 'data-order-action-submit' : '' } > ${ requiresApproval ? '提交变更申请' : changeForm ? '核实并保存' : '确认保存' } </button> ${ button ( '收起' , 'hide-action' , 'quiet' ) } </div></form>` ; if ( action === 'cost' ) syncCostEditor (); if ([ 'receipt' , 'refund' , 'correct' ]. includes ( action )) syncActionCreditCardFee (); $ ( '#detail-form' ). scrollIntoView ({ block : 'nearest' , behavior : 'smooth' });
2026-10-23 09:49:36 +08:00
}
function syncActionCreditCardFee (){
2026-10-25 14:19:24 +08:00
const form = $ ( '#action-form' ), root = $ ( '#action-credit-card-fee' ); if ( ! form ) return ;
syncPaymentRecipient ( form ); const correction = form . querySelector ( '[name="account"]' ); if ( correction ) correction . value = normalizePaymentAccount ( correction . value );
let note = form . querySelector ( '.correction-card-note' ); if ( correction &&! note && typeof correction . closest ( 'label' ) ? . insertAdjacentHTML === 'function' ){ correction . closest ( 'label' ). insertAdjacentHTML ( 'beforeend' , '<small class="small muted correction-card-note" hidden>信用卡统一由麦麦收款。</small>' ); note = form . querySelector ( '.correction-card-note' );} if ( note ) note . hidden =! isCreditCardAccount ( correction ? . value );
if ( ! root ) return ;
2026-10-23 09:49:36 +08:00
const get = name => form . querySelector ( `[name=" ${ name } "]` ) ? . value || '' , kind = form . dataset . kind ;
2026-10-25 14:19:24 +08:00
let enabled = kind === 'receipt' , account = readPaymentAccount ( form ), amount = null ;
2026-10-23 09:49:36 +08:00
if ( kind === 'correct' ){ const [ type , id ] = get ( 'entry' ). split ( ':' ); enabled = type === 'payment' && currentOrder . payments . some ( item => item . id === id && item . kind === 'receipt' ); account = get ( 'account' );}
try { amount = LedgerCalc . cents ( get ( 'amount' ));} catch {}
syncCreditCardPreview ( root , account , amount ,{ enabled });
2026-10-17 19:50:24 +08:00
}
function stockQuantity ( rows , pocket ){ const value = rows ? . find ( r => r . pocket === pocket ) ? . mg ; return Number . isSafeInteger ( value ) ? grams ( value ) + 'g' : null ;}
function stockTime ( value ){ const date = new Date ( value ); return Number . isNaN ( date . getTime ()) ? '时间未提供' : date . toLocaleString ( 'zh-CN' ,{ timeZone : 'Asia/Shanghai' , month : '2-digit' , day : '2-digit' , hour : '2-digit' , minute : '2-digit' , hour12 : false });}
2026-10-26 22:46:55 +08:00
function stockSnapshotSource ( snapshot ){ return snapshot ? . source === 'automatic' ? 'automatic' : snapshot ? . source == null || snapshot . source === 'manual' ? 'manual' : 'unknown' ;}
function stockSnapshotLabel ( snapshot ){ return { automatic : '系统自动保存' , manual : '麦麦复核' , unknown : '已保存' }[ stockSnapshotSource ( snapshot )];}
function stockAutomaticStatus ( page ){
const automatic = page . automaticSnapshot ; if ( ! automatic ) return '' ;
const time = /^\d{2}:\d{2}$/ . test ( automatic . time ) ? automatic . time : '23:50' , plan = `北京时间每日 ${ time } 自动保存` ;
if ( automatic . enabled === false || automatic . status === 'stopped' ) return `<p class="small muted stock-automatic-status">计划: ${ plan } ,当前未启动。</p>` ;
let detail = '' ;
if ( automatic . status === 'saved' ) detail = `今天已自动保存 ${ automatic . lastSuccess ? . savedAt ? ' · 实际保存 ' + e ( stockTime ( automatic . lastSuccess . savedAt )) : '' } 。` ;
if ( automatic . status === 'failed' ){
const raw = String ( automatic . lastError ? . message || '请稍后刷新查看。' ). replace ( /\s+/g , ' ' ). trim (), message = raw . length > 120 ? raw . slice ( 0 , 120 ) + '…' : raw ;
detail = `<span class="stock-stale-text">本次自动保存未成功 ${ automatic . lastError ? . attemptedAt ? '( ' + e ( stockTime ( automatic . lastError . attemptedAt )) + ') ' : '' } : ${ e ( message ) }${ automatic . nextAttemptAt ? ' 下次重试 ' + e ( stockTime ( automatic . nextAttemptAt )) + '。' : '' } </span>` ;
}
return `<p class="small muted stock-automatic-status"> ${ plan } 。 ${ detail } </p>` ;
}
2026-10-17 19:50:24 +08:00
function stockHeading ( page ){
2026-11-08 03:30:58 +08:00
const actions = page ? ` ${ state . user . role === 'owner' && typeof pocketManagerPanel === 'function' ? button ( '管理货盘' , 'pocket-manager-toggle' , 'pocket-manage-entry' , `aria-expanded=" ${ pocketManagerOpen } " aria-controls="pocket-manager"` ) : '' }${ typeof inventoryChangesPanel === 'function' ? button ( state . user . role === 'owner' ? '库存修改审批' : '我的库存申请' , 'inventory-change-jump' , '' , `id="inventory-changes-entry"` ) : '' }${ page . canReview && state . user . role === 'owner' ? button ( '复核并保存今日快照' , 'inventory-review' , 'primary' ) : '' }${ button ( inventoryHistoryOpen ? '收起每日快照' : '查看每日快照' , 'inventory-history' , '' , `aria-expanded=" ${ inventoryHistoryOpen } " aria-controls="inventory-history"` ) }${ state . user . role === 'owner' ? '<a class="stock-export" href="/api/export/inventory">导出当前库存</a>' : '' } ` : '' ;
2026-10-26 22:46:55 +08:00
return heading ( 'INVENTORY' , '货盘库存' , '登记实物增加、减少或平移,查看当天与历史库存快照。' , actions ). replace ( 'class="page-heading"' , 'class="page-heading stock-heading"' );
2026-10-17 19:50:24 +08:00
}
function stockReviewStatus ( page ){
2026-10-26 22:46:55 +08:00
const snapshot = page . todaySnapshot , manual = snapshot && stockSnapshotSource ( snapshot ) === 'manual' ;
const saved = snapshot ? `<span class="badge ${ snapshot . stale ? ' warn' : '' } "> ${ stockSnapshotLabel ( snapshot ) } </span> ${ manual && snapshot . actor ? e ( snapshot . actor ) + ' · ' : '' } 实际保存 ${ e ( stockTime ( snapshot . updated || snapshot . created )) } ` : '' ;
const status =! snapshot ? '今天尚未保存快照。' : ` ${ saved }${ snapshot . stale ? ' · 保存后有库存变动,保留当时保存值。' + ( manual ? '需重新复核。' : '' ) : manual ? ' · 今天已复核' : '' } ` ;
return `<div class="stock-review-status ${ snapshot ? . stale ? 'stock-review-stale' : '' } " aria-live="polite"><div> ${ status } </div> ${ stockAutomaticStatus ( page ) } <p class="small muted">同一天再次保存将更新当天记录。人工复核由麦麦操作。 ${ page . yesterday ? . stale ? '昨天保存后有补记,卡片仍显示昨天当时保存的数量。' : '' } </p></div>` ;
2026-10-17 19:50:24 +08:00
}
function stockCards ( page ){
2026-11-08 03:30:58 +08:00
return `<div class="stock-cards"> ${ activePocketKeys (). map ( pocket =>{
2026-10-17 19:50:24 +08:00
const item = page . current . find ( r => r . pocket === pocket ), yesterday = page . yesterday ? stockQuantity ( page . yesterday . inventory , pocket ) : null ;
2026-11-08 03:30:58 +08:00
return `<div class="stat stock-card"><small class="stock-pocket-name"> ${ e ( pocketLabel ( pocket )) } </small><div class="stock-current-label">当前数量</div><strong> ${ grams ( item . mg ) } <span>g</span></strong> ${ item . reserved ? `<div class="small muted stock-reserved">旧单占用 ${ grams ( item . reserved ) } g · 可用 ${ grams ( item . available ) } g</div>` : '' } <div class="stock-yesterday"><span>昨天快照 <small> ${ e ( page . yesterdayDate . slice ( 5 )) } </small></span><b class=" ${ yesterday ? '' : 'muted' } "> ${ yesterday || ( page . yesterday ? '未记录该货盘' : '未保存快照' ) } </b> ${ page . yesterday ? `<small class="stock-yesterday-source"> ${ stockSnapshotLabel ( page . yesterday ) }${ page . yesterday . stale ? ' · 后有补记' : '' } </small>` : '' } </div></div>` ;
2026-10-17 19:50:24 +08:00
} ).join('')}</div>` ;
}
function stockHistoryPanel (){
2026-10-26 22:46:55 +08:00
return `<section class="panel stock-history" id="inventory-history" ${ inventoryHistoryOpen ? '' : 'hidden' } ><div class="panel-title"><h2>每日库存快照</h2><span class="small muted" id="inventory-history-count"></span></div><div class="stock-history-filters"><div class="stock-history-periods" role="group" aria-label="快照日期"> ${ [[ 'month' , '本月' ],[ 'all' , '全部记录' ]]. map (([ value , name ])=> button ( name , 'inventory-history-period' , '' , `data-period=" ${ value } " aria-pressed="false"` )). join ( '' ) } </div><label class="order-date-field">指定日期<input type="date" id="inventory-history-date" value=" ${ e ( inventoryHistoryDate || inventoryPage . date ) } " max=" ${ e ( inventoryPage . date ) } " aria-label="查询每日快照日期"></label><span class="small muted" id="inventory-history-caption"></span></div><div id="inventory-history-list" aria-live="polite"></div><p class="small muted stock-history-note">显示各日实际保存的数量,并标明系统自动保存或麦麦复核;未保存的日期没有记录。同一天再次保存只更新当天那一条。</p></section>` ;
2026-10-17 19:50:24 +08:00
}
function stockEntryForm (){
2026-11-08 03:30:58 +08:00
return `<section class="panel stock-entry"><h2>登记库存变动</h2><p class="small muted">销售与退货会随订单自动记账,无需重复登记。</p><form id="stock-form"><div class="stock-entry-fields"> ${ choice ( '动作' , 'kind' ,[[ 'increase' , '增加' ],[ 'decrease' , '减少' ],[ 'transfer' , '平移' ]], 'increase' ) } <label><span data-stock-pocket-label>货盘</span><select name="pocket"> ${ opts ( pocketOptions (), '现货' ) } </select></label><label data-stock-to hidden>移到哪<select name="to" disabled> ${ opts ( pocketOptions (), '金料' ) } </select></label> ${ field ( '数量(g) ' , 'grams' , '' , 'number' , 'min="0.001" step="0.001" required inputmode="decimal" placeholder="填写正数"' ) }${ dateField () } </div><div class="stock-entry-bottom"> ${ field ( '备注(选填)' , 'note' , '' , 'text' , 'maxlength="200" placeholder="可填写来源或原因"' ) } <button class="primary" id="stock-submit">登记增加</button></div><div id="stock-error" aria-live="polite"></div></form></section>` ;
2026-10-17 19:50:24 +08:00
}
function syncStockForm (){
const form = $ ( '#stock-form' ); if ( ! form ) return ;
const kind = form . elements . kind . value , transfer = kind === 'transfer' , target = form . querySelector ( '[name="to"]' );
2026-11-08 03:30:58 +08:00
form . classList . toggle ( 'is-transfer' , transfer ); form . querySelector ( '[data-stock-pocket-label]' ). textContent = transfer ? '从哪移出' : '货盘' ; target . closest ( 'label' ). hidden =! transfer ; target . disabled =! transfer ; target . required = transfer ; $ ( '#stock-submit' ). disabled =! activePocketKeys (). length ;
2026-10-17 19:50:24 +08:00
$ ( '#stock-submit' ). textContent = '登记' + ({ increase : '增加' , decrease : '减少' , transfer : '平移' })[ kind ]; $ ( '#stock-error' ). innerHTML = '' ;
}
function stockMovements (){
2026-11-08 03:30:58 +08:00
const pockets = inventoryMovementPockets . length ? inventoryMovementPockets : activePocketKeys (). map ( pocket =>({ pocket , active : true }));
return `<section class="panel" id="inventory-movements"><div class="panel-title"><h2>库存流水</h2><div class="actions"><span class="small muted" id="inventory-movements-count"></span> ${ button ( inventoryExporting ? '正在导出…' : '导出Excel' , 'inventory-movements-export' , 'primary' , `id="inventory-movements-export" ${ inventoryExporting ? 'disabled' : '' } ` ) } </div></div><p class="small muted">三人共用库存,全部流水可查看。助理仅能申请修改或删除自己登记的手动记录,须由麦麦审批。</p><p class="small muted">Excel按当前货盘和流水类型导出全部匹配记录,包含其他页。</p><p class="small muted" id="inventory-movements-export-status" role="status" aria-live="polite"></p><div class="stock-history-filters"><label class="order-date-field">筛选货盘<select id="inventory-movements-pocket"> ${ opts ([[ '' , '全部货盘' ],... pockets . map ( p =>[ p . pocket , pocketLabel ( p . pocket ) + ( p . active ? '' : '(已停用 · 历史)' )])], inventoryMovementPocket ) } </select></label><label class="order-date-field">流水类型<select id="inventory-movements-kind"> ${ opts ([[ 'all' , '全部流水' ],[ 'increase' , '手动增加' ],[ 'decrease' , '手动减少' ],[ 'transfer' , '手动平移' ],[ 'manual' , '全部手动变动' ]], inventoryMovementKind ) } </select></label><span class="small muted">每页100条,可翻页查看更早记录。平移按两边货盘分别记一条。</span></div><div id="inventory-movements-pagination" class="inventory-movement-pagination" aria-live="polite"></div><p class="small muted stock-movement-scroll-hint">左右滑动查看完整流水;修改和删除在行末「状态/操作」。手动筛选保留已修改、已删除的原记录,不含更正冲回。</p><div id="inventory-movements-list" aria-live="polite"></div></section>` ;
2026-10-31 14:59:30 +08:00
}
async function exportInventoryMovements (){
if ( inventoryExporting || busy || tab !== 'stock' ) return ;
const user = inventoryMovementUser (), pocket = $ ( '#inventory-movements-pocket' ) ? . value ?? inventoryMovementPocket , kind = $ ( '#inventory-movements-kind' ) ? . value ?? inventoryMovementKind ;
const control = $ ( '#inventory-movements-export' ), status = $ ( '#inventory-movements-export-status' ), active = ()=> user === inventoryMovementUser () && tab === 'stock' ;
inventoryExporting = true ; if ( control ){ control . disabled = true ; control . textContent = '正在导出…' ;} if ( status ) status . textContent = '正在生成当前筛选下的全部库存流水…' ;
try {
const result = await api ( '/api/inventory/movements/export.xlsx?' + new URLSearchParams ({ pocket , kind }), undefined , undefined ,{ responseType : 'xlsx' });
if ( ! active ()) return ;
if ( ! result . blob || result . blob . size < 4 ) throw new Error ( '导出文件为空,请重新导出。' );
const match = result . contentDisposition ? . match ( /filename\*=UTF-8''([^;]+)/i );
let filename = '库存流水-' + state . today + '.xlsx' ; if ( match ) try { filename = decodeURIComponent ( match [ 1 ]);} catch {}
const url = URL . createObjectURL ( result . blob ), link = document . createElement ( 'a' ); link . href = url ; link . download = filename ; document . body . append ( link );
try { link . click ();} finally { link . remove (); setTimeout (()=> URL . revokeObjectURL ( url ), 1000 );}
if ( status ? . isConnected ) status . textContent = '所选货盘与类型的Excel已生成,包含全部匹配记录。' ; toast ( '所选货盘与类型的库存流水Excel已生成' );
} catch ( err ){ if ( active ()){ const message = err . name === 'AbortError' ? '导出超时,请重新导出。' : err . message ; if ( status ? . isConnected ) status . textContent = message ; toast ( message , true );}}
finally { inventoryExporting = false ; const currentControl = $ ( '#inventory-movements-export' ); if ( currentControl ){ currentControl . disabled = busy ; currentControl . textContent = '导出Excel' ;}}
2026-10-23 09:49:36 +08:00
}
function stockMovementRows ( movements ){
2026-10-31 14:59:30 +08:00
const names = { increase : '增加' , decrease : '减少' , transfer : '平移' , opening : '开账' , purchase : '入库' , adjustment : '调整' , manual : '手动变动' , sale : '销售出库' , return : '退货入库' , manual_reversal : '更正冲回' , lock_purchase : '锁价黄金入库' , order_edit_reverse : '改单出库冲回' , order_edit_sale : '改单出库' , order_cancel_reverse : '订单作废冲回' , recovery : '回收旧料入库' };
2026-11-08 03:30:58 +08:00
return `<div class="table-wrap"><table class="inventory-movement-table"><thead><tr><th>日期</th><th>货盘</th><th class="number">变动</th><th>动作</th><th>备注/原单</th><th>经办人</th><th>状态/操作</th></tr></thead><tbody> ${ movements . map ( r => `<tr data-movement-id=" ${ e ( r . id ) } "><td> ${ e ( r . date ) } </td><td> ${ e ( pocketLabel ( r . pocket )) }${ activePocketKeys (). includes ( r . pocket ) ? '' : '<div class="small muted">已停用 · 历史</div>' } </td><td class="number"> ${ r . mg > 0 ? '+' : '' }${ grams ( r . mg ) } g</td><td> ${ e ( names [ r . kind ] || r . kind ) } </td><td> ${ r . reversal || r . kind === 'manual_reversal' ? '撤回旧记录的库存影响' : e ( r . note ) || '—' } </td><td> ${ e ( r . actor ) } </td><td> ${ typeof inventoryMovementStateHTML === 'function' ? inventoryMovementStateHTML ( r ) : '' }${ typeof inventoryMovementActionsHTML === 'function' ? inventoryMovementActionsHTML ( r ) : '' } </td></tr>` ). join ( '' ) } </tbody></table></div>` ;
2026-10-23 09:49:36 +08:00
}
2026-10-26 22:46:55 +08:00
function inventoryMovementUser (){ return state ? . user ? [ state . user . id , state . user . member || '' , state . user . role ]. join ( ':' ) : '' ;}
function invalidateInventoryMovementViews ( reset = false ){
++ inventoryMovementsRequest ; inventoryMovementPagination = null ;
if ( reset ){ inventoryMovementPocket = '' ; inventoryMovementKind = 'all' ; inventoryMovementPage = 1 ; inventoryMovementPockets = [];}
}
function inventoryMovementMatches ( row , kind ){
if ( kind === 'all' ) return true ;
if ( row . manual !== true || row . reversal || row . order_id ) return false ;
if ( kind === 'manual' ) return true ;
if ( kind === 'transfer' ) return row . kind === 'transfer' ;
return kind === 'increase' ? row . mg > 0 && [ 'increase' , 'purchase' , 'adjustment' , 'manual' ]. includes ( row . kind ) : row . mg < 0 && [ 'decrease' , 'adjustment' , 'manual' ]. includes ( row . kind );
}
function inventoryMovementPaginationHTML ( result ){
return `<span class="small muted">第 ${ result . page } / ${ result . totalPages } 页 · 每页 ${ result . pageSize } 条</span><div class="actions" role="group" aria-label="库存流水翻页"> ${ button ( '上一页' , 'inventory-movements-page' , '' , `data-direction="previous" ${ result . hasPrev ? '' : 'disabled' } ` ) }${ button ( '下一页' , 'inventory-movements-page' , '' , `data-direction="next" ${ result . hasNext ? '' : 'disabled' } ` ) } </div>` ;
}
async function moveInventoryMovementPage ( direction ){
const result = inventoryMovementPagination ;
if ( ! result || tab !== 'stock' || result . user !== inventoryMovementUser () || result . request !== inventoryMovementsRequest || result . pocket !== inventoryMovementPocket || result . kind !== inventoryMovementKind ) return ;
if ( direction === 'previous' && result . hasPrev ) inventoryMovementPage = result . page - 1 ;
else if ( direction === 'next' && result . hasNext ) inventoryMovementPage = result . page + 1 ;
else return ;
await loadInventoryMovements ();
}
2026-10-23 09:49:36 +08:00
async function loadInventoryMovements (){
2026-10-26 22:46:55 +08:00
const list = $ ( '#inventory-movements-list' ), count = $ ( '#inventory-movements-count' ), pagination = $ ( '#inventory-movements-pagination' );
if ( ! inventoryPage || tab !== 'stock' ||! list ||! count ||! pagination ) return ;
const request =++ inventoryMovementsRequest , pocket = inventoryMovementPocket , kind = inventoryMovementKind , requestedPage = inventoryMovementPage , user = inventoryMovementUser ();
const current = ()=> request === inventoryMovementsRequest && tab === 'stock' && list . isConnected && $ ( '#inventory-movements-list' ) === list && pocket === inventoryMovementPocket && kind === inventoryMovementKind && requestedPage === inventoryMovementPage && user === inventoryMovementUser ();
inventoryMovementPagination = null ; pagination . innerHTML = '' ; list . setAttribute ( 'aria-busy' , 'true' ); list . innerHTML = '<div class="stock-message">正在读取库存流水…</div>' ; count . textContent = '' ;
2026-10-23 09:49:36 +08:00
try {
2026-10-26 22:46:55 +08:00
const result = await api ( '/api/inventory/movements?' + new URLSearchParams ({ pocket , kind , page : String ( requestedPage )}));
2026-10-23 09:49:36 +08:00
if ( ! current ()) return ;
2026-10-26 22:46:55 +08:00
const totalPages = Math . max ( 1 , Math . ceil ( result . total / 100 )), page = Math . min ( requestedPage , totalPages );
if ( result . pocket !== pocket || result . kind !== kind ||! Array . isArray ( result . pockets ) ||! result . pockets . every ( p => p && typeof p . pocket === 'string' && typeof p . active === 'boolean' ) ||! Array . isArray ( result . movements ) ||! Number . isSafeInteger ( result . total ) || result . total < 0 || result . limit !== 100 || result . pageSize !== 100 || result . totalPages !== totalPages || result . page !== page || result . hasPrev !== ( page > 1 ) || result . hasNext !== ( page < totalPages ) || result . shown !== result . movements . length || result . shown !== Math . min ( 100 , result . total - ( page - 1 ) * 100 ) ||! result . movements . every ( r => r && Number . isSafeInteger ( r . mg ) && ( ! pocket || r . pocket === pocket ) && inventoryMovementMatches ( r , kind ))) throw new Error ( '流水数据与筛选不一致,请重新读取。' );
inventoryMovementPockets = result . pockets ; inventoryMovementPage = result . page ;
inventoryMovementPagination = {... result , user , request };
2026-11-08 03:30:58 +08:00
$ ( '#inventory-movements-pocket' ). innerHTML = opts ([[ '' , '全部货盘' ],... result . pockets . map ( p =>[ p . pocket , pocketLabel ( p . pocket ) + ( p . active ? '' : '(已停用 · 历史)' )])], pocket );
2026-10-26 22:46:55 +08:00
list . setAttribute ( 'aria-busy' , 'false' ); count . textContent = result . total ? `共 ${ result . total } 条,当前显示 ${ ( result . page - 1 ) * 100 + 1 } ~ ${ ( result . page - 1 ) * 100 + result . shown } 条` : '共 0 条' ;
pagination . innerHTML = inventoryMovementPaginationHTML ( result );
list . innerHTML = ( result . shown ? stockMovementRows ( result . movements ) : '<div class="stock-message muted">当前筛选下暂无库存流水。</div>' ) + `<div class="inventory-movement-pagination"> ${ inventoryMovementPaginationHTML ( result ) } </div>` ;
2026-10-23 09:49:36 +08:00
} catch ( err ){
if ( ! current ()) return ;
2026-10-26 22:46:55 +08:00
inventoryMovementPagination = null ; pagination . innerHTML = '' ; list . setAttribute ( 'aria-busy' , 'false' ); count . textContent = '' ; list . innerHTML = `<div class="stock-message error"> ${ e ( err . name === 'AbortError' ? '读取超时,请重新读取。' : err . message ) } <div> ${ button ( '重新读取流水' , 'inventory-movements-retry' ) } </div></div>` ;
2026-10-23 09:49:36 +08:00
}
2026-10-17 19:50:24 +08:00
}
function stockLegacyInventory ( page ){
if ( ! page . legacyInventory ? . length ) return '' ;
2026-11-08 03:30:58 +08:00
return `<section class="panel stock-legacy"><h2>已停用货盘库存</h2><p class="small muted">库存、历史流水与快照继续保留,启用后可继续用于新交易。</p><div class="stock-legacy-balances"> ${ page . legacyInventory . map ( i => `<div><strong> ${ e ( pocketLabel ( i . pocket )) } </strong><span class="badge warn">已停用</span><b> ${ grams ( i . mg ) } g</b> ${ i . reserved ? '<span class="small muted">旧单占用 ' + grams ( i . reserved ) + 'g</span>' : '' } </div>` ). join ( '' ) } </div></section>` ;
2026-10-17 19:50:24 +08:00
}
async function renderStock (){
2026-10-23 09:49:36 +08:00
const request =++ inventoryRequest ; ++ inventoryHistoryRequest ; ++ inventoryMovementsRequest ; inventoryPage = null ;
2026-10-26 22:46:55 +08:00
$ ( '#main' ). innerHTML = stockHeading () + `<div id="inventory-content" aria-busy="true"><div class="stock-message">正在读取库存与快照记录…</div></div>` ;
2026-10-17 19:50:24 +08:00
try {
const page = await api ( '/api/inventory' );
if ( request !== inventoryRequest || tab !== 'stock' ||! $ ( '#inventory-content' )) return ;
2026-11-08 03:30:58 +08:00
if ( ! validOrderDate ( page . date ) ||! validOrderDate ( page . yesterdayDate ) || typeof page . revision !== 'string' ||! activePocketKeys (). every ( p => page . current ? . some ( i => i . pocket === p && Number . isSafeInteger ( i . mg ) && Number . isSafeInteger ( i . reserved ) && Number . isSafeInteger ( i . available )))) throw new Error ( '库存数据不完整,请重新读取。' );
2026-10-17 19:50:24 +08:00
inventoryPage = page ; state . today = page . date ;
2026-11-08 03:30:58 +08:00
$ ( '#main' ). innerHTML = stockHeading ( page ) + `<div id="inventory-content" aria-busy="false"> ${ stockCards ( page ) }${ typeof pocketManagerPanel === 'function' ? pocketManagerPanel () : '' }${ stockReviewStatus ( page ) }${ stockHistoryPanel () }${ stockEntryForm () }${ typeof inventoryChangesPanel === 'function' ? inventoryChangesPanel () : '' }${ stockLegacyInventory ( page ) }${ stockMovements () } </div>` ;
syncStockForm (); if ( typeof applyPocketManagerRestrictions === 'function' ) applyPocketManagerRestrictions (); await Promise . all ([ loadInventoryMovements (), typeof loadInventoryChanges === 'function' ? loadInventoryChanges () : Promise . resolve (), inventoryHistoryOpen ? loadInventorySnapshots () : Promise . resolve ()]);
2026-10-17 19:50:24 +08:00
} catch ( err ){
if ( request !== inventoryRequest || tab !== 'stock' ||! $ ( '#inventory-content' )) return ;
inventoryPage = null ; $ ( '#inventory-content' ). setAttribute ( 'aria-busy' , 'false' ); $ ( '#inventory-content' ). innerHTML = `<div class="stock-message error"> ${ e ( err . name === 'AbortError' ? '读取超时,请重新读取。' : err . message ) } <div> ${ button ( '重新读取库存' , 'inventory-retry' ) } </div></div>` ;
}
}
function inventoryHistoryRange (){
const today = inventoryPage . date ;
if ( inventoryHistoryMode === 'date' ){
if ( ! validOrderDate ( inventoryHistoryDate ) || inventoryHistoryDate > today ) throw new Error ( '请选择今天或之前的有效日期。' );
return { from : inventoryHistoryDate , date : inventoryHistoryDate };
}
return inventoryHistoryMode === 'month' ? { from : today . slice ( 0 , 7 ) + '-01' , date : today } : null ;
}
function updateInventoryHistoryControls ( range ){
document . querySelectorAll ( '[data-action="inventory-history-period"]' ). forEach ( b =>{ const active = b . dataset . period === inventoryHistoryMode ; b . classList . toggle ( 'active' , active ); b . setAttribute ( 'aria-pressed' , String ( active ));});
$ ( '#inventory-history-caption' ). textContent = range ? ( range . from === range . date ? range . date : range . from + ' 至 ' + range . date ) : inventoryHistoryMode === 'all' ? '全部已保存日期' : '指定日期' ;
const input = $ ( '#inventory-history-date' ); if ( document . activeElement !== input ) input . value = inventoryHistoryMode === 'date' ? inventoryHistoryDate : inventoryPage . date ;
}
async function loadInventorySnapshots (){
if ( ! inventoryPage ||! inventoryHistoryOpen || tab !== 'stock' ||! $ ( '#inventory-history-list' )) return ;
const request =++ inventoryHistoryRequest ; let range ;
const error = message =>{ $ ( '#inventory-history-list' ). setAttribute ( 'aria-busy' , 'false' ); $ ( '#inventory-history-list' ). innerHTML = `<div class="stock-message error"> ${ e ( message ) } <div> ${ button ( '重新读取快照' , 'inventory-history-retry' ) } </div></div>` ; $ ( '#inventory-history-count' ). textContent = '' ;};
try { range = inventoryHistoryRange ();} catch ( err ){ updateInventoryHistoryControls (); error ( err . message ); return ;}
updateInventoryHistoryControls ( range ); $ ( '#inventory-history-list' ). setAttribute ( 'aria-busy' , 'true' ); $ ( '#inventory-history-list' ). innerHTML = '<div class="stock-message">正在读取已保存的快照…</div>' ; $ ( '#inventory-history-count' ). textContent = '' ;
try {
const result = await api ( '/api/inventory/snapshots' + ( range ? '?' + new URLSearchParams ( range ) : '' ));
if ( request !== inventoryHistoryRequest || tab !== 'stock' ||! inventoryHistoryOpen ||! $ ( '#inventory-history-list' )) return ;
if ( ! Array . isArray ( result . snapshots ) || range && ( result . from !== range . from || result . date !== range . date )) throw new Error ( '快照日期与查询不一致,请重新读取。' );
$ ( '#inventory-history-list' ). setAttribute ( 'aria-busy' , 'false' ); $ ( '#inventory-history-count' ). textContent = result . snapshots . length + ' 天' ;
2026-10-26 22:46:55 +08:00
if ( ! result . snapshots . length ){ $ ( '#inventory-history-list' ). innerHTML = '<div class="stock-message muted">这段日期尚未保存每日库存快照。</div>' ; return ;}
2026-11-08 03:30:58 +08:00
$ ( '#inventory-history-list' ). innerHTML = `<div class="table-wrap"><table class="stock-snapshot-table"><thead><tr><th>日期</th> ${ activePocketKeys (). map ( p => `<th class="number"> ${ e ( pocketLabel ( p )) } ( g) </th>`). join ( '' ) } <th>保存来源/时间</th><th>说明</th></tr></thead><tbody> ${ result . snapshots . map ( snapshot =>{
const legacy = ( snapshot . inventory || []). filter ( i => ! activePocketKeys (). includes ( i . pocket ) && ( i . mg || i . reserved ));
return `<tr><td> ${ e ( snapshot . date ) } </td> ${ activePocketKeys (). map ( p => `<td class="number"> ${ stockQuantity ( snapshot . inventory , p ) ? . replace ( /g$/ , '' ) || '<span class="muted">未记录</span>' } </td>` ). join ( '' ) } <td> ${ stockSnapshotLabel ( snapshot ) }${ stockSnapshotSource ( snapshot ) === 'manual' && snapshot . actor ? `<div class="small muted"> ${ e ( snapshot . actor ) } </div>` : '' } <div class="small muted">实际保存 ${ e ( stockTime ( snapshot . updated || snapshot . created )) } </div></td><td class="stock-snapshot-note"> ${ snapshot . stale ? '<span class="stock-stale-text">保存后有库存补记,保留当时保存值。</span>' : '<span class="muted">已保存</span>' }${ legacy . length ? `<div class="small muted">历史货盘: ${ legacy . map ( i => ` ${ e ( pocketLabel ( i . pocket )) } ${ grams ( i . mg ) } g` ). join ( '; ' ) } </div>` : '' } </td></tr>` ;
2026-10-17 19:50:24 +08:00
} ).join('')}</tbody></table></div>` ;
} catch ( err ){ if ( request === inventoryHistoryRequest && tab === 'stock' && inventoryHistoryOpen && $ ( '#inventory-history-list' )) error ( err . name === 'AbortError' ? '读取超时,请重新读取。' : err . message );}
}
2026-10-23 09:49:36 +08:00
function invalidateReport (){ if ( typeof invalidateDailyFunds === 'function' ) invalidateDailyFunds (); ++ reportRequest ; currentReport = null ; reportLoadedUser = '' ;}
2026-10-17 19:50:24 +08:00
function reportRange (){
if ( ! validOrderDate ( reportDate )) throw new Error ( '请选择有效的对账日期。' );
if ( reportDate > state . today ) throw new Error ( '请选择今天或之前的日期。' );
return { from : reportMonth ? reportDate . slice ( 0 , 7 ) + '-01' : reportDate , date : reportDate };
}
function reportPeriod ( range ){ return range . from === range . date ? range . date : range . from + ' 至 ' + range . date ;}
function reportCostAmount ( value , partial = 0 ){ return partial && value === 0 ? '待补齐' : ( partial ? '已知 ' : '' ) + '¥' + yuan ( value );}
function reportSummaryAmount ( summary , key ){
const missing = summary . unknownCounts ? .[ key ] || 0 ;
return missing && summary . knownCounts ? .[ key ] === 0 &&! summary [ key ] &&! summary . afterSaleCount ? '待补齐' : ( missing ? '已知 ' : '' ) + '¥' + yuan ( summary [ key ]);
}
function reportPayerHints ( cost ){ return [ cost . missingCount ? cost . missingCount + ' 项成本待补齐' : '' , cost . pendingCount ? cost . pendingCount + ' 项费用未入账,不计合计' : '' ]. filter ( Boolean ). join ( '; ' );}
function reportCostItems ( cost ){ return cost . items . filter ( item => item . kind !== 'goods' || item . amount !== 0 );}
function reportCostFormula ( item ){
const c = item . calculation ; if ( ! c ) return '' ;
return grams ( c . quantity ) + 'g × ' + ( c . rate == null ? ( item . component === 'material' ? '每克料价待补齐' : '每克工费待补齐' ) : yuan ( c . rate ) + '元/克' ) + ( item . amount == null ? '' : ' = ' + yuan ( item . amount ) + '元' );
}
function reportCostItemAmount ( item ){
if ( item . kind === 'pending' ) return '未入账' + ( item . amount == null ? '(金额待补)' : '(登记 ¥' + yuan ( item . amount ) + ') ' );
return item . amount == null ? '待补齐' : '¥' + yuan ( item . amount );
}
function reportRowCost ( row ){
const goods = ( row . costItems || []). filter ( item => item . kind === 'goods' );
return { goods : goods . reduce (( sum , item )=> sum + ( item . amount ?? 0 ), 0 ), missing : goods . filter ( item => item . amount == null ). length , paidFees : ( row . costItems || []). filter ( item =>[ 'paid' , 'afterSale' ]. includes ( item . kind )). reduce (( sum , item )=> sum + item . amount , 0 )};
}
function reportAfterSaleAmount ( cost ){ return cost . items . filter ( item => item . kind === 'afterSale' ). reduce (( sum , item )=> sum + item . amount , 0 );}
function reportAfterSaleHint ( cost ){ return cost . items . some ( item => item . kind === 'afterSale' ) ? `<div class="small muted">其中售后 ¥ ${ yuan ( reportAfterSaleAmount ( cost )) } </div>` : '' ;}
2026-10-21 01:32:49 +08:00
function reportCostIdentity ( item ){ if ( item . materialPoolId ) return item . materialPoolId + ' 购料' ; return item . kind === 'afterSale' ? '售后 · ' + ( item . customer || '未填客户' ) : ( item . price_lock_id ? '锁价 · ' : '' ) + ( item . paper_number || item . number || '锁价记录' ) + ( item . customer ? ' · ' + item . customer : '' );}
2026-10-17 19:50:24 +08:00
function reportRowAmount ( row , key ){
if ( row . status === 'draft' ) return '未开单' ;
if ( key === 'goods' ){ const c = reportRowCost ( row ); return reportCostAmount ( c . goods , c . missing );}
if ( key === 'paidFees' ) return '¥' + yuan ( reportRowCost ( row ). paidFees );
if ( row [ key ] != null ) return '¥' + yuan ( row [ key ]);
return row . known ? .[ key ] ? '已知 ¥' + yuan ( row . known [ key ]) + '(待补齐)' : '待补齐' ;
}
function reportCostDetails ( cost ){
const items = reportCostItems ( cost );
2026-10-21 01:32:49 +08:00
return `<details class="report-cost-detail"><summary> ${ e ( cost . name ) } 逐项明细 <span class="small muted"> ${ items . length } 项 ${ cost . pendingCount ? ',含未入账项目' : '' } </span></summary><div class="table-wrap"><table class="report-cost-detail-table" aria-label=" ${ e ( cost . name ) } 支出成本逐项明细"><thead><tr><th>日期/单号或客户</th><th>成本项目/来源</th><th class="number">金额</th></tr></thead><tbody> ${ items . map ( item => `<tr ${ item . kind === 'pending' ? ' class="report-pending-cost"' : '' } ><td> ${ e ( item . date ) } <br> ${ materialReportCostLink ( item ) } </td><td> ${ e ( item . name ) } <div class="small muted"> ${ e ( item . source ) } </div> ${ item . calculation ? `<div class="small muted"> ${ e ( reportCostFormula ( item )) } </div>` : '' }${ item . kind === 'pending' ? '<div class="small danger-text">未计入实际成本与合计</div>' : '' } </td><td class="number ${ item . amount == null || item . kind === 'pending' ? ' danger-text' : '' } "> ${ item . kind === 'pending' ? '未入账' + ( item . amount == null ? '<div class="small">金额待补</div>' : '<div class="small muted">登记 ¥' + yuan ( item . amount ) + '</div>' ) : e ( reportCostItemAmount ( item )) } </td></tr>` ). join ( '' ) || '<tr><td colspan="3" class="muted">没有需逐项核对的成本。货品成本为 0 的分项已省略。</td></tr>' } </tbody></table></div></details>` ;
2026-10-17 19:50:24 +08:00
}
function reportPayerCostsHTML ( r ){
2026-10-25 14:19:24 +08:00
const people = teamDataKeys ( r . payerCosts ). map ( key => r . payerCosts [ key ]), missing = people . reduce (( sum , c )=> sum + c . missingCount , 0 ), pending = people . reduce (( sum , c )=> sum + c . pendingCount , 0 );
2026-10-28 00:22:04 +08:00
return `<section class="panel report-costs"><h2>按付款人核对成本</h2><p class="small muted">普通订单按开单日归集;每日购料按实际购买日期归集,订单耗用料费不再计一次支出;锁价料费、工费与费用按实际付款日归集,原锁料费不在交付时重复计入。实际支出可能与本期订单耗用成本不同。转账请以核实后的完整实际支出为准。</p><div class="table-wrap"><table class="report-payer-table" aria-label="助理与麦麦支出成本"><thead><tr><th>付款人</th><th class="number">货品成本</th><th class="number">已付费用</th><th class="number">支出合计</th></tr></thead><tbody> ${ people . map ( c => `<tr><td><strong> ${ e ( c . name ) } 支出成本</strong> ${ reportPayerHints ( c ) ? `<div class="small danger-text"> ${ e ( reportPayerHints ( c )) } </div>` : '' } </td><td class="number"> ${ e ( reportCostAmount ( c . goods , c . missingCount )) } </td><td class="number">¥ ${ yuan ( c . paidFees ) }${ reportAfterSaleHint ( c ) } </td><td class="number report-cost-total"> ${ e ( reportCostAmount ( c . total , c . missingCount + c . pendingCount )) } </td></tr>` ). join ( '' ) } </tbody><tfoot><tr><td>合计</td><td class="number"> ${ e ( reportCostAmount ( r . outlayGoods ?? r . goods , missing )) } </td><td class="number">¥ ${ yuan ( r . outlayExpense ?? r . expense ) }${ r . summary . afterSaleCount ? `<div class="small muted">其中售后 ¥ ${ yuan ( people . reduce (( sum , c )=> sum + reportAfterSaleAmount ( c ), 0 )) } </div>` : '' } </td><td class="number"> ${ e ( reportCostAmount ( r . outlayTotal ?? r . goods + r . expense , missing + pending )) } </td></tr></tfoot></table></div> ${ people . map ( reportCostDetails ). join ( '' ) } <p class="small muted report-cost-note">普通订单按开单日期、售后按记录日期归集;每日购料按购买日期、锁价支出按实际付款日。旧草稿与未入账费用不计合计;退货冲回订单耗用成本,锁价已经支付的金料款仍保留。0元货品分项省略,已核实的0元费用保留。</p></section>` ;
2026-10-23 09:49:36 +08:00
}
function reportReceiptLabel ( item ){ return ( item . kind === 'receipt' ? '收款' : '退款' ) + ( item . amount < 0 ? '冲回' : '' );}
function reportReceiptBasis ( item ){ return item . price_lock_id ? '锁价 · 按实际收付日' : '普通订单 · 开单 ' + ( item . order_date || '日期未提供' );}
function reportReceiptIdentityHTML ( item ){
const number = item . paper_number || item . number || ( item . price_lock_id ? '锁价记录' : '订单记录' );
const identity = item . order_id ? button ( e ( number ), 'open-order' , 'link-button' , `data-id=" ${ e ( item . order_id ) } "` ) : item . price_lock_id ? button ( e ( number ), 'open-price-lock' , 'link-button' , `data-id=" ${ e ( item . price_lock_id ) } "` ) : e ( number );
return identity + `<div class="small muted"> ${ e ( item . customer || '未填客户称呼' ) } </div>` + ( item . order_id && item . price_lock_id ? `<div class="small"> ${ button ( '原锁价单' , 'open-price-lock' , 'link-button' , `data-id=" ${ e ( item . price_lock_id ) } "` ) } </div>` : '' );
}
function reportRecipientDetailsHTML ( person , kind = 'receipt' ){
const items = person . items . filter ( item => item . kind === kind ), name = kind === 'receipt' ? '收款' : '退款' ;
2026-11-03 01:15:41 +08:00
return `<details class="report-receipt-detail"><summary aria-label=" ${ e ( person . name + name + '明细' ) } "> ${ name } 明细 <span class="small muted"> ${ items . length } 笔 ${ items . some ( item => item . amount < 0 ) ? ',含冲回' : '' } </span></summary><div class="table-wrap" tabindex="0" role="region" aria-label=" ${ e ( person . name + name + '明细表' ) } "><table class="report-receipt-table" aria-label=" ${ e ( person . name + name + '逐笔明细' ) } "><thead><tr><th>实际 ${ name } 日/归集口径</th><th>订单/客户</th><th> ${ name } 账户/说明</th><th class="number">金额</th></tr></thead><tbody> ${ items . map ( item => `<tr ${ item . amount < 0 ? ' class="report-receipt-reversal"' : '' } ><td> ${ e ( item . date ) } <div class="small muted"> ${ e ( reportReceiptBasis ( item )) } </div></td><td> ${ reportReceiptIdentityHTML ( item ) } </td><td> ${ e ( accountDisplayName ( item . account )) } <div class="small ${ item . amount < 0 ? ' danger-text' : ' muted' } "> ${ e ( reportReceiptLabel ( item )) } </div> ${ item . reference || item . note ? `<div class="small muted report-receipt-note"> ${ e ( item . reference || item . note ) } </div>` : '' } </td><td class="number ${ item . amount < 0 ? ' danger-text' : '' } ">¥ ${ yuan ( item . amount ) } </td></tr>` ). join ( '' ) || `<tr><td colspan="4" class="muted">所选范围没有 ${ e ( person . name ) }${ name } 记录。</td></tr>` } </tbody><tfoot><tr><td colspan="3"> ${ name } 明细合计</td><td class="number">¥ ${ yuan ( person [ kind ]) } </td></tr></tfoot></table></div></details>` ;
2026-10-23 09:49:36 +08:00
}
function reportRecipientReceiptsHTML ( r , range ){
2026-10-25 14:19:24 +08:00
return `<section class="report-receipts" aria-label="按收款人汇总"><p class="small muted report-receipt-scope"> ${ e ( reportPeriod ( range )) } :普通订单按开单日归集当前收付,锁价按实际收付日归集。明细显示实际收退款日,负数为冲回。</p><div class="report-recipient-grid"> ${ teamDataKeys ( r . recipientReceipts ). map ( key =>{
2026-10-23 09:49:36 +08:00
const person = r . recipientReceipts [ key ];
2026-10-28 00:22:04 +08:00
return `<article class="panel report-recipient" aria-labelledby="report-recipient- ${ key } -title"><header class="report-recipient-summary"><h2 id="report-recipient- ${ key } -title"> ${ e ( person . name ) } 净收款</h2><div class="report-recipient-total">¥ ${ yuan ( person . net ) } </div><p class="report-recipient-net"><span>退款 ¥ ${ yuan ( person . refund ) } </span><span>总收款 ¥ ${ yuan ( person . receipt ) } </span></p></header> ${ reportRecipientDetailsHTML ( person ) }${ person . items . some ( item => item . kind === 'refund' ) ? reportRecipientDetailsHTML ( person , 'refund' ) : '' } </article>` ;
2026-10-23 09:49:36 +08:00
} ).join('')}</div></section>` ;
}
2026-10-28 00:22:04 +08:00
function reportActiveAccounts ( r ){
const recorded = new Set ( teamDataKeys ( r . recipientReceipts ). flatMap ( key => r . recipientReceipts [ key ]. items . map ( item => item . account )));
return r . accounts . filter ( account => account . receipt !== 0 || account . refund !== 0 || account . net !== 0 || account . entryCount > 0 || recorded . has ( account . account ));
}
function reportOwnershipKeys ( r ){
const keys = teamDataKeys ( r . ownershipReceipts );
2026-11-07 00:30:02 +08:00
return state . user . role === 'owner' &&! reportMember ? keys . filter ( key =>{ const person = r . ownershipReceipts [ key ]; return person . items . length || person . receipt !== 0 || person . refund !== 0 || person . net !== 0 || r . ownershipBusiness [ key ]. recordCount || r . ownershipBusiness [ key ]. currentAccount . days . length ;}) : keys ;
2026-10-28 00:22:04 +08:00
}
function reportOwnershipAccountsHTML ( person ){
const ownAccounts = person . accounts . filter ( account => account . recipient === person . member ), otherAccounts = person . accounts . filter ( account => account . recipient !== person . member ), net = accounts => accounts . reduce (( total , account )=> total + account . net , 0 );
2026-11-03 01:15:41 +08:00
const group = ( title , rows )=> `<section class="report-ownership-account-group"><h3> ${ title } </h3> ${ rows . length ? `<ul> ${ rows . map ( account => `<li><div><span> ${ e ( accountDisplayName ( account . account )) } </span><small>实收 ¥ ${ yuan ( account . receipt ) } · 实退 ¥ ${ yuan ( account . refund ) } </small></div><strong>¥ ${ yuan ( account . net ) } </strong></li>` ). join ( '' ) } </ul>` : '<p class="small muted">本期暂无记录。</p>' } </section>` ;
return `<p class="report-ownership-equation"><span>本人收款净额 <b>¥ ${ yuan ( net ( ownAccounts )) } </b></span><span aria-hidden="true">+ </span><span> ${ otherAccounts . length === 1 ? e ( accountDisplayName ( otherAccounts [ 0 ]. account )) + '代收' : '他人代收' } 净额 <b>¥ ${ yuan ( net ( otherAccounts )) } </b></span><span aria-hidden="true">= </span><strong>¥ ${ yuan ( person . net ) } </strong></p><div class="report-ownership-accounts"> ${ group ( '本人收款' , ownAccounts ) }${ group ( '他人代收' , otherAccounts ) } </div>` ;
2026-10-28 00:22:04 +08:00
}
function reportBusinessAmount ( value , known ){ return ( value === null ? '已知 ' : '' ) + '¥' + yuan ( value === null ? known : value );}
2026-11-06 01:29:35 +08:00
function reportPoolMaterialSourceLabel ( source ){
return ( source . kind === 'personal_recovery' ? teamMemberName ( source . member ) + '个人回收料' : '公共料' ) + ( source . priceLocked ? '(含锁价原料)' : '' );
}
2026-11-02 21:13:10 +08:00
function reportPoolMaterialFormula ( day ){
2026-11-06 01:29:35 +08:00
if ( day . sources ) return day . sources . map ( source => ` ${ reportPoolMaterialSourceLabel ( source ) } ${ grams ( source . mg ) } g × ${ source . averageRate === null ? '待补料价' : '¥' + yuan ( source . averageRate ) + '/g' } ` ). join ( ' + ' ) + ` = ${ day . amount === null ? '料费待补(已知 ¥' + yuan ( day . knownAmount ) + ') ' : '¥' + yuan ( day . amount ) } ` ;
2026-11-02 21:13:10 +08:00
return ` ${ grams ( day . mg ) } g × ${ day . averageRate === null ? '待补料价' : '¥' + yuan ( day . averageRate ) + '/g' } = ${ day . amount === null ? '料费待补(已知 ¥' + yuan ( day . knownAmount ) + ') ' : '¥' + yuan ( day . amount ) } ` ;
}
2026-11-06 01:29:35 +08:00
function reportPoolMaterialDayHTML ( day ){
if ( ! day . sources ) return `<li><span> ${ e ( day . date ) } 料池</span><strong> ${ e ( reportPoolMaterialFormula ( day )) } </strong></li>` ;
return `<li class="report-pool-material-day"><div class="report-pool-material-day-total"><span> ${ e ( day . date ) } 料池</span><b>已用 ${ e ( grams ( day . mg )) } g · 料费 ${ e ( reportBusinessAmount ( day . amount , day . knownAmount )) } </b></div><div class="report-pool-material-sources"> ${ day . sources . map ( source => `<p><span> ${ e ( reportPoolMaterialSourceLabel ( source )) } </span><strong> ${ e ( reportPoolMaterialFormula ( source )) } </strong></p>` ). join ( '' ) } </div></li>` ;
}
function reportPoolMaterialPendingNote ( pool ){
return pool . days . some ( day => day . sources && day . sources . reduce (( total , source )=> total + source . knownAmount , 0 ) > day . knownAmount ) ? '部分来源已可核对,料费待补的订单尚未计入已知料费。' : '' ;
}
2026-11-02 21:34:17 +08:00
function reportOwnerAdvanceAmount ( value , known ){ return value === null ? '待补(已知 ¥' + yuan ( known ) + ') ' : '¥' + yuan ( value );}
function reportOwnerAdvanceFormula ( business , day ){
return ` ${ business . member === 'owner' ? '麦麦付款合计' : '麦麦垫付合计' } :料池料费 ${ reportOwnerAdvanceAmount ( day . poolAmount , day . knownPoolAmount ) } + 其他成本 ${ reportOwnerAdvanceAmount ( day . otherAmount , day . knownOtherAmount ) } = ${ reportOwnerAdvanceAmount ( day . amount , day . knownAmount ) } ` ;
}
function reportOwnerAdvanceItemAmount ( item ){
if ( item . status === 'pending' ) return '待核对' + ( item . estimatedAmount === null ? '(金额待补)' : '(预估 ¥' + yuan ( item . estimatedAmount ) + ') ' ) + ',未计垫付' ;
return item . amount === null ? '待补齐' : '¥' + yuan ( item . amount );
}
function reportOwnerAdvanceIdentity ( item ){
return item . kind === 'order' ? `<button class="link-button" data-action="open-order" data-id=" ${ e ( item . id ) } "> ${ e ( item . customer || '未填客户' ) } </button><small class="muted"> ${ e ( item . paperNumber || item . number ) } </small>` : ` ${ e ( item . customer || '未填客户' ) } <small class="muted">售后记录</small>` ;
}
function reportOwnerAdvancesHTML ( business ){
const advances = business . ownerAdvances , single = advances . from === advances . date , label = business . member === 'owner' ? '麦麦付款明细' : '麦麦垫付明细' ;
const days = advances . days . length ? advances . days : single ? [{ date : advances . date , amount : 0 , knownAmount : 0 , missingCount : 0 , pendingCount : 0 , items : []}] : [];
2026-11-07 00:30:02 +08:00
return `<details class="report-owner-advances" aria-label=" ${ e ( business . name + label ) } "><summary> ${ single ? '当日' : '按日核对' }${ label } </summary><p class="small muted">按所属订单开单日、售后记录日归集;仅列所选日期,不累计历史垫付。当日往来另列利润与麦麦代收,未扣实际转账。</p> ${ days . map ( day => `<div class="report-owner-advance-day"><header><h4> ${ e ( day . date ) } </h4><span> ${ day . missingCount ? '已知' : '' }${ business . member === 'owner' ? '付款' : '垫付' } 小计 <strong> ${ e ( reportOwnerAdvanceAmount ( day . amount , day . knownAmount )) } </strong></span></header> ${ day . items . some ( item => item . poolMaterial ) ? `<p class="report-owner-advance"> ${ e ( reportOwnerAdvanceFormula ( business , day )) } </p>` : '' }${ day . items . length ? `<div class="table-wrap"><table class="report-owner-advance-table" aria-label=" ${ e ( day . date + ' ' + label ) } "><thead><tr><th>日期</th><th>客户/单号</th><th>成本项目</th><th class="number">麦麦承担金额</th></tr></thead><tbody> ${ day . items . map ( item => `<tr ${ item . status === 'recorded' ? '' : ' class="report-pending-cost"' } ><td> ${ e ( item . date ) } </td><td> ${ reportOwnerAdvanceIdentity ( item ) } </td><td> ${ e ( item . name ) }${ item . source ? `<small class="muted"> ${ e ( item . source ) } </small>` : '' } </td><td class="number"> ${ e ( reportOwnerAdvanceItemAmount ( item )) } </td></tr>` ). join ( '' ) } </tbody></table></div>` : '<p class="small muted">当天没有已登记的' + ( business . member === 'owner' ? '麦麦付款' : '麦麦垫付' ) + '明细。</p>' }${ day . pendingCount ? '<p class="small muted">待核对项目尚未入账,预估金额不计垫付小计。</p>' : '' } </div>` ). join ( '' ) || '<p class="small muted">所选月份暂无已登记的' + label + '。</p>' } </details>` ;
2026-11-02 21:34:17 +08:00
}
function reportOwnerAdvancesText ( business ){
const advances = business . ownerAdvances , label = business . member === 'owner' ? '麦麦付款明细' : '麦麦垫付明细' ;
return [ label + '(按所属订单开单日/售后记录日逐日核对,不累计历史;预估未付不计实付)' ,...( advances . days . length ? advances . days . flatMap ( day =>[ ` ${ day . date } ${ business . member === 'owner' ? '付款' : '垫付' } 小计: ${ reportOwnerAdvanceAmount ( day . amount , day . knownAmount ) } ` ,...( day . items . some ( item => item . poolMaterial ) ? [ reportOwnerAdvanceFormula ( business , day )] : []),... day . items . map ( item => ` ${ item . date } / ${ item . customer || '未填客户' } / ${ item . paperNumber || item . number } / ${ item . name } / ${ reportOwnerAdvanceItemAmount ( item ) } ` )]) : [ advances . from === advances . date ? advances . date + ' 当日已登记垫付 ¥0.00,无明细。' : '所选月份暂无已登记明细。' ])];
2026-11-02 21:13:10 +08:00
}
function reportPoolMaterialHTML ( business ){
const pool = business . poolMaterial ; if ( ! pool ? . days . length ) return '' ;
2026-11-02 21:34:17 +08:00
const owner = pool . byPayer . owner ;
2026-11-07 00:30:02 +08:00
return `<div class="report-pool-material" aria-label=" ${ e ( business . name ) } 所属订单料池用料"><div class="report-pool-material-heading"><span>已用料合计</span><strong> ${ e ( grams ( pool . mg )) } g</strong><span>料池已用料费</span><strong> ${ e ( reportBusinessAmount ( pool . amount , pool . knownAmount )) } </strong> ${ pool . missingCount ? '<span class="badge warn">料费待补</span>' : '' } </div><ul> ${ pool . days . map ( reportPoolMaterialDayHTML ). join ( '' ) } </ul> ${ reportPoolMaterialPendingNote ( pool ) ? `<p class="small muted"> ${ e ( reportPoolMaterialPendingNote ( pool )) } </p>` : '' } <p>其中麦麦垫付 <b> ${ e ( reportBusinessAmount ( owner . amount , owner . knownAmount )) } </b></p><p>其他成本 <b> ${ e ( reportBusinessAmount ( pool . otherCosts . amount , pool . otherCosts . knownAmount )) } </b><small class="muted">(其余商品成本、工费与费用)</small></p><p class="small muted">料费已计入总成本;当日往来只取麦麦垫付部分,公式中计入一次。按未四舍五入均价逐单核算,显示料价相乘可能有分币差。 ${ pool . hasPriceLocks ? '锁价已用料费在交付日的当日往来中列示,不重复记实际采购支出。' : '' } </p></div>` ;
2026-11-02 21:13:10 +08:00
}
function reportPoolMaterialText ( business ){
const pool = business . poolMaterial ; if ( ! pool ? . days . length ) return [];
2026-11-02 21:34:17 +08:00
const owner = pool . byPayer . owner ;
2026-11-07 00:30:02 +08:00
return [ `已用料合计: ${ grams ( pool . mg ) } g` , `料池已用料费: ${ reportBusinessAmount ( pool . amount , pool . knownAmount ) } (已计入总成本;当日往来只取麦麦垫付部分,公式中计入一次)` ,... pool . days . map ( day => ` ${ day . date } 料池(已用 ${ grams ( day . mg ) } g): ${ reportPoolMaterialFormula ( day ) } ` ),...( reportPoolMaterialPendingNote ( pool ) ? [ reportPoolMaterialPendingNote ( pool )] : []), `其中麦麦垫付: ${ reportBusinessAmount ( owner . amount , owner . knownAmount ) } ` , `其他成本: ${ reportBusinessAmount ( pool . otherCosts . amount , pool . otherCosts . knownAmount ) } (其余商品成本、工费与费用)` , '料费按未四舍五入均价逐单核算,显示料价相乘可能有分币差。' ,...( pool . hasPriceLocks ? [ '锁价已用料费在交付日的当日往来中列示,不重复记实际采购支出。' ] : [])];
2026-11-02 21:13:10 +08:00
}
2026-10-28 00:22:04 +08:00
function reportOwnershipCostHTML ( business ){
const showPayers = business . knownTotalCost !== 0 || business . totalCost === null , others = teamMemberKeys . filter ( key => key !== business . member ). map ( key => business . costByPayer [ key ]). filter ( payer => payer . knownTotalCost !== 0 || payer . totalCost === null );
2026-11-02 21:13:10 +08:00
return `<section class="report-business-cost" aria-label=" ${ e ( business . name ) } 所属订单成本"><div class="report-business-heading"><h3>所属订单总成本 ${ business . afterSaleCount ? `<span class="small muted">含售后 ${ business . afterSaleCount } 笔</span>` : '' } </h3><strong> ${ e ( reportBusinessAmount ( business . totalCost , business . knownTotalCost )) } </strong> ${ business . totalCost === null ? '<span class="badge warn">成本待补齐</span>' : '' } </div> ${ reportPoolMaterialHTML ( business ) }${ showPayers ? `<div class="report-business-paid"><span>本人付款 <b> ${ e ( reportBusinessAmount ( business . selfCost , business . knownSelfCost )) } </b></span><span>他人付款 <b> ${ e ( reportBusinessAmount ( business . otherCost , business . knownOtherCost )) } </b> ${ others . length ? `<small> ${ others . map ( payer => ` ${ e ( payer . name ) } ${ e ( reportBusinessAmount ( payer . totalCost , payer . knownTotalCost )) } ` ). join ( '; ' ) } </small>` : '' } </span></div>` : '' } </section>` ;
2026-10-28 00:22:04 +08:00
}
function reportOwnershipProfitHTML ( business , range ){
const equation = business . equation , title = reportMonth || range . from !== range . date ? '本期利润' : '当日利润' , complete = equation . complete &&! business . incomplete && business . totalCost !== null && business . profit !== null , revenue = equation . basis === 'netReceipts' ? '所属订单净收入' : '销售净额' , difference = business . difference ;
return `<section class="report-business-profit" aria-label=" ${ e ( business . name + title ) } "><h3> ${ title } </h3> ${ complete ? `<p class="report-business-profit-equation"><span> ${ revenue } <b>¥ ${ yuan ( equation . revenue ) } </b></span><span aria-hidden="true">− </span><span>订单总成本 <b>¥ ${ yuan ( equation . totalCost ) } </b></span><span aria-hidden="true">= </span><strong class=" ${ business . profit < 0 ? 'danger-text' : '' } ">¥ ${ yuan ( business . profit ) } </strong></p>` : '<strong class="report-business-profit-pending">待核算</strong><p class="small muted">成本或利润资料尚未完整,先核对原单;完整利润暂不显示。</p>' }${ difference . amount !== 0 ||! difference . reconciled ? `<div class="report-business-difference"><p>所属净收款 ¥ ${ yuan ( business . netReceipts ) } ,销售净额 ¥ ${ yuan ( business . sales ) } ,差额 ¥ ${ yuan ( difference . amount ) } 。</p> ${ difference . reasons . length ? `<ul> ${ difference . reasons . map ( reason => `<li> ${ e ( reason . text ) } </li>` ). join ( '' ) } </ul>` : '<p>按原账销售与成本核对利润。</p>' } </div>` : '' } </section>` ;
}
2026-11-07 00:30:02 +08:00
function reportCurrentAccountDays ( business ){
const account = business . currentAccount ;
return account . days . length ? account . days : account . from === account . date ? [{ date : account . date , materialCost : 0 , knownMaterialCost : 0 , otherCost : 0 , knownOtherCost : 0 , profit : 0 , knownProfit : 0 , ownerNetReceipts : 0 , amount : 0 , incomplete : false }] : [];
2026-10-28 00:22:04 +08:00
}
2026-11-07 00:30:02 +08:00
function reportCurrentAccountDirection ( business , day ){
return day . amount === null ? '应转金额待核算' : day . amount > 0 ? business . name + '应转麦麦' : day . amount < 0 ? '麦麦应转' + business . name : '当日无需转款' ;
}
function reportCurrentAccountFormula ( day ){
return `麦麦垫付已用料费 ${ reportOwnerAdvanceAmount ( day . materialCost , day . knownMaterialCost ) } + 麦麦垫付其他订单成本 ${ reportOwnerAdvanceAmount ( day . otherCost , day . knownOtherCost ) } + 本人当日订单净利润 ${ reportDailyProfitAmount ( day . profit , day . knownProfit , true ) } − 麦麦代收净额 ¥ ${ yuan ( day . ownerNetReceipts ) } = ${ day . amount === null ? '待核算' : '¥' + yuan ( day . amount ) } ` ;
}
function reportOwnershipCurrentAccountHTML ( business ){
if ( business . member === 'owner' ) return '' ;
const account = business . currentAccount , days = reportCurrentAccountDays ( business );
return `<section class="report-business-settlement report-business-current" aria-label=" ${ e ( business . name ) } 当日往来账"><h3>当日往来账</h3><p class="small muted"> ${ account . from === account . date ? '仅核对所选单日。' : '按所选范围逐日核对,不将月合计当作日金额。' } 普通订单按开单日、锁价成单按交付日、售后按记录日归集;锁价代收按实际收付日。此处不含历史余额,也未扣实际转账。</p> ${ days . map ( day => `<div class="report-current-day" data-date=" ${ e ( day . date ) } "><header><h4> ${ e ( day . date ) } </h4><span> ${ e ( reportCurrentAccountDirection ( business , day )) } </span> ${ day . amount === null ? '<strong class="danger-text">待核算</strong>' : `<strong>¥ ${ yuan ( Math . abs ( day . amount )) } </strong>` } </header><p class="report-business-balance-equation"> ${ e ( reportCurrentAccountFormula ( day )) } </p> ${ day . incomplete ? '<p class="small danger-text">成本或利润尚未补齐,暂不显示完整应转金额;预估未付项目不计垫付。</p>' : '' } </div>` ). join ( '' ) || '<p class="small muted">所选范围暂无当日往来记录。</p>' } </section>` ;
}
function reportCurrentAccountText ( business ){
if ( business . member === 'owner' ) return [];
return [ '当日往来账(逐日核对,不含历史余额,未扣实际转账)' ,... reportCurrentAccountDays ( business ). flatMap ( day =>[ ` ${ day . date } / ${ reportCurrentAccountDirection ( business , day ) }${ day . amount === null ? '' : ' ¥' + yuan ( Math . abs ( day . amount )) } ` , reportCurrentAccountFormula ( day ),...( day . incomplete ? [ '成本或利润尚未补齐,暂不显示完整应转金额;预估未付项目不计垫付。' ] : [])])];
}
function reportOwnershipBusinessHTML ( business , range ){ return reportOwnershipCostHTML ( business ) + reportOwnerAdvancesHTML ( business ) + reportOwnershipProfitHTML ( business , range ) + reportOwnershipCurrentAccountHTML ( business );}
2026-10-28 00:22:04 +08:00
function reportOwnershipReceiptsHTML ( r , range ){
const keys = reportOwnershipKeys ( r );
2026-11-07 00:30:02 +08:00
return `<section class="report-receipts report-ownership-receipts" aria-label="按订单归属汇总净收入"><p class="small muted report-receipt-scope"> ${ e ( reportPeriod ( range )) } :所属订单净收入=收款−退款,已包含他人代收。成本含售后,料池仅计已耗用部分;麦麦垫付和当日往来逐日核对。</p><div class="report-recipient-grid"> ${ keys . length ? keys . map ( key =>{ const person = r . ownershipReceipts [ key ], details = {... person , name : person . name + '所属订单' } ;return ` < article class = "panel report-recipient report-ownership-recipient" data - member = "${e(key)}" aria - labelledby = "report-ownership-${key}-title" >< header class = "report-recipient-summary" >< h2 id = "report-ownership-${key}-title" > $ { e ( person . name )} 所属订单净收入 < /h2><div class="report-recipient-total">¥${yuan(person.net)}</div><p class="report-recipient-net"><span>实收 ¥${yuan(person.receipt)}</span><span>实退 ¥${yuan(person.refund)}</span></p></header>${person.items.length?reportOwnershipAccountsHTML(person):''}${reportOwnershipBusinessHTML(r.ownershipBusiness[key],range)}${person.items.length?reportRecipientDetailsHTML(details)+(person.items.some(item=>item.kind==='refund')?reportRecipientDetailsHTML(details,'refund'):''):'<p class="small muted report-ownership-empty">所选范围暂无收退款记录。</p>'}</article>`;}).join(''):'<div class="panel report-ownership-empty"><p class="muted">所选范围暂无所属订单收入、成本或当日往来记录。</p></div>'}</div></section>`;
2026-10-28 00:22:04 +08:00
}
function reportOwnershipBusinessText ( business ){
2026-11-07 00:30:02 +08:00
return [ `所属订单总成本: ${ reportBusinessAmount ( business . totalCost , business . knownTotalCost ) } ;本人付款 ${ reportBusinessAmount ( business . selfCost , business . knownSelfCost ) } ;他人付款 ${ reportBusinessAmount ( business . otherCost , business . knownOtherCost ) } ` ,... reportPoolMaterialText ( business ),... reportOwnerAdvancesText ( business ),... teamMemberKeys . filter ( key => key !== business . member ). map ( key => business . costByPayer [ key ]). filter ( payer => payer . knownTotalCost || payer . totalCost === null ). map ( payer => ` ${ payer . name } 付款: ${ reportBusinessAmount ( payer . totalCost , payer . knownTotalCost ) } ` ), `本期利润: ${ business . equation . complete &&! business . incomplete && business . profit !== null ? '¥' + yuan ( business . profit ) : '待核算,完整利润暂不显示' } ` ,... business . difference . reasons . map ( reason => reason . text ),... reportCurrentAccountText ( business )];
2026-10-28 00:22:04 +08:00
}
function reportOwnershipReceiptsText ( r ){
2026-11-03 01:15:41 +08:00
return [ '按订单归属核对净收入(收款减退款,已含他人代收,尚未扣成本与费用)' ,... reportOwnershipKeys ( r ). flatMap ( key =>{ const person = r . ownershipReceipts [ key ]; return [ ` ${ person . name } 所属订单净收入:¥ ${ yuan ( person . net ) } ;实收 ¥ ${ yuan ( person . receipt ) } ;实退 ¥ ${ yuan ( person . refund ) } ` ,... person . accounts . map ( account => ` ${ account . recipient === person . member ? '本人收款' : '他人代收' } / ${ accountDisplayName ( account . account ) } :实收 ¥ ${ yuan ( account . receipt ) } ,实退 ¥ ${ yuan ( account . refund ) } ,净额 ¥ ${ yuan ( account . net ) } ` ),... reportOwnershipBusinessText ( r . ownershipBusiness [ key ]), '' ];})];
2026-10-28 00:22:04 +08:00
}
2026-10-23 09:49:36 +08:00
function reportRecipientReceiptsText ( r ){
2026-10-25 14:19:24 +08:00
return [ '按收款人汇总(普通订单按开单日归集当前收付,锁价按实际收付日归集;负数为冲回)' ,... teamDataKeys ( r . recipientReceipts ). flatMap ( key =>{
2026-10-23 09:49:36 +08:00
const person = r . recipientReceipts [ key ];
return [ ` ${ person . name } 总收款:¥ ${ yuan ( person . receipt ) } ;退款 ¥ ${ yuan ( person . refund ) } ;净收款 ¥ ${ yuan ( person . net ) } ` ,...[ 'receipt' , 'refund' ]. flatMap ( kind =>{
const items = person . items . filter ( item => item . kind === kind ), name = kind === 'receipt' ? '收款' : '退款' ;
2026-11-03 01:15:41 +08:00
return [ ` ${ person . name }${ name } 明细(日期为实际 ${ name } 日):` ,...( items . length ? items . map ( item => ` ${ item . date } / ${ reportReceiptBasis ( item ) } / ${ item . paper_number || item . number || ( item . price_lock_id ? '锁价记录' : '订单记录' ) } / 客户 ${ item . customer || '未填客户称呼' } / ${ accountDisplayName ( item . account ) } / ${ reportReceiptLabel ( item ) } ¥ ${ yuan ( item . amount ) }${ item . reference || item . note ? ' / ' + ( item . reference || item . note ) : '' } ` ) : [ '所选范围没有' + person . name + name + '记录。' ]), ` ${ name } 明细合计:¥ ${ yuan ( person [ kind ]) } ` ];
2026-10-23 09:49:36 +08:00
}), '' ];
})];
2026-10-17 19:50:24 +08:00
}
function reportQueryState ( range , error = '' ){
const body = $ ( '#report-content' ); if ( ! body ) return ;
2026-11-03 00:29:34 +08:00
const profits = $ ( '#report-daily-profits-content' ); if ( profits ) profits . innerHTML = '' ;
2026-10-17 19:50:24 +08:00
currentReport = null ; reportLoadedUser = '' ; body . setAttribute ( 'aria-busy' , String ( ! error ));
body . innerHTML = `<div class="cards report-cards"> ${ [ '销售净额' , '累计实收' , '累计实退' , '订单净利润' ]. map ( title => card ( title , '—' , error ? '尚未取得数据' : '正在读取' )). join ( '' ) } </div><section class="panel report-query-message ${ error ? ' error' : '' } "><p> ${ error ? e ( error ) : '正在读取' + e ( reportPeriod ( range )) + '订单与售后的当前结果…' } </p> ${ error ? button ( '重新读取' , 'report-retry' ) : '' } </section>` ;
}
2026-11-03 00:29:34 +08:00
function reportDailyProfitAmount ( value , known , profit = false ){ return value === null ? ( profit ? '待核算(已核算 ¥' : '待补齐(已知 ¥' ) + yuan ( known ) + ') ' : '¥' + yuan ( value );}
function reportDailyProfitsHTML ( r ){
const table = r . dailyProfits , amounts = row => `<td class="number">¥ ${ yuan ( row . sales ) } </td><td class="number"> ${ e ( reportDailyProfitAmount ( row . totalCost , row . knownTotalCost )) } </td><td class="number ${ ( row . profit ?? row . knownProfit ) < 0 ? ' danger-text' : '' } "> ${ e ( reportDailyProfitAmount ( row . profit , row . knownProfit , true )) } </td>` ;
return `<section class="panel report-daily-profits" aria-label="每日利润表"><h2>每日利润表</h2><p class="small muted"> ${ e ( reportPeriod ( table )) } · 按日期、订单归属人核对。勾选“汇总当月”可查看当月逐日利润。</p><div class="table-wrap"><table aria-label="每日利润明细"><thead><tr><th scope="col">日期</th><th scope="col">归属人</th><th scope="col" class="number">销售净额</th><th scope="col" class="number">成本</th><th scope="col" class="number">利润</th></tr></thead><tbody> ${ table . rows . map ( row => `<tr data-date=" ${ e ( row . date ) } " data-member=" ${ e ( row . member ) } "><td> ${ e ( row . date ) } </td><td> ${ e ( row . name ) } <small class="muted">销售 ${ row . orderCount } 单 ${ row . afterSaleCount ? ' · 售后 ' + row . afterSaleCount + ' 笔' : '' }${ row . draftCount ? ' · 旧草稿 ' + row . draftCount + ' 单未计金额' : '' } </small></td> ${ amounts ( row ) } </tr>` ). join ( '' ) || '<tr><td colspan="5" class="muted">所选范围暂无订单或售后记录。</td></tr>' } </tbody><tfoot><tr><td colspan="2">所选范围合计</td> ${ amounts ( table . summary ) } </tr></tfoot></table></div><p class="small muted report-daily-profit-note">普通订单按开单日、锁价成单按交付日、售后按记录日归集。成本含实际耗用料费和费用;退货、作废沿原账冲回。 ${ table . summary . unknownProfitCount ? '待核算项目不按0计作完整利润,括号内仅为已核算部分。' : '' } </p></section>` ;
}
function reportDailyProfitsText ( r ){
const table = r . dailyProfits , rowText = row => `销售净额 ¥ ${ yuan ( row . sales ) } / 成本 ${ reportDailyProfitAmount ( row . totalCost , row . knownTotalCost ) } / 利润 ${ reportDailyProfitAmount ( row . profit , row . knownProfit , true ) } ` ;
return [ '每日利润表(按日期与订单归属人;普通订单按开单日、锁价成单按交付日、售后按记录日)' ,...( table . rows . length ? table . rows . map ( row => ` ${ row . date } / ${ row . name } / ${ rowText ( row ) } ` ) : [ '所选范围暂无订单或售后记录。' ]), `所选范围合计: ${ rowText ( table . summary ) } ` , '' ];
}
2026-10-17 19:50:24 +08:00
function validateReport ( r , range ){
if ( r . basis !== 'orderDate' || r . date !== range . date || r . from !== range . from ) throw new Error ( '返回口径或日期与当前选择不一致,请重新读取。' );
2026-10-25 14:19:24 +08:00
if ( ! r . summary ||! Array . isArray ( r . orderRows ) ||! Array . isArray ( r . accounts ) ||! r . receiptsByOrderDate ||! teamDataKeys ( r . payerCosts ). length ||! teamDataKeys ( r . payerCosts ). every ( key =>{
2026-10-17 19:50:24 +08:00
const c = r . payerCosts ? .[ key ]; return c && Array . isArray ( c . items ) && [ 'goods' , 'paidFees' , 'total' , 'missingCount' , 'pendingCount' ]. every ( name => Number . isSafeInteger ( c [ name ]));
})) throw new Error ( '对账数据尚未完整返回,请重新读取。' );
2026-10-25 14:19:24 +08:00
const recipientKeys = teamDataKeys ( r . recipientReceipts ), recipients = recipientKeys . map ( key => r . recipientReceipts ? .[ key ]);
if ( ! recipientKeys . length ||! recipients . every (( person , index )=> person && person . recipient === recipientKeys [ index ] && typeof person . name === 'string' && person . name && Array . isArray ( person . items ) && [ 'receipt' , 'refund' , 'net' ]. every ( key => Number . isSafeInteger ( person [ key ])) && person . items . every ( item => item && [ 'receipt' , 'refund' ]. includes ( item . kind ) && Number . isSafeInteger ( item . amount ) && typeof item . account === 'string' && validOrderDate ( item . date )) && person . net === person . receipt - person . refund && [ 'receipt' , 'refund' ]. every ( kind => person . items . filter ( item => item . kind === kind ). reduce (( sum , item )=> sum + item . amount , 0 ) === person [ kind ])) ||! [ 'receipt' , 'refund' , 'net' ]. every ( key => recipients . reduce (( sum , person )=> sum + person [ key ], 0 ) === r . receiptsByOrderDate [ key ])) throw new Error ( '收款人汇总与明细未完整返回或金额不一致,请重新读取。' );
2026-10-28 00:22:04 +08:00
validateOwnershipReceipts ( r );
validateOwnershipBusiness ( r );
2026-11-03 00:29:34 +08:00
validateDailyProfits ( r );
}
function validateDailyProfits ( r ){
const fail = ()=>{ throw new Error ( '每日利润表未完整返回或与当前对账金额不一致,请重新读取。' );}, table = r . dailyProfits , money = Number . isSafeInteger , count = value => money ( value ) && value >= 0 , nullable = value => value === null || money ( value ), members = teamDataKeys ( r . ownershipReceipts );
const amounts = [ 'sales' , 'knownTotalCost' , 'knownProfit' ], counts = [ 'recordCount' , 'orderCount' , 'afterSaleCount' , 'draftCount' , 'unknownCostCount' , 'unknownProfitCount' ];
const valid = row => row && amounts . every ( key => money ( row [ key ])) && counts . every ( key => count ( row [ key ])) && nullable ( row . totalCost ) && nullable ( row . profit ) && typeof row . incomplete === 'boolean' && row . recordCount === row . orderCount + row . afterSaleCount && row . draftCount <= row . orderCount && row . unknownCostCount <= row . recordCount && row . unknownProfitCount <= row . recordCount && row . totalCost === ( row . unknownCostCount ? null : row . knownTotalCost ) && row . profit === ( row . unknownProfitCount ? null : row . knownProfit ) && (( row . unknownCostCount || row . unknownProfitCount ) ? row . incomplete : true ) && ( row . profit === null || row . totalCost !== null && row . sales - row . totalCost === row . profit );
if ( ! table || table . basis !== 'orderDate' || table . from !== r . from || table . date !== r . date ||! Array . isArray ( table . rows ) ||! valid ( table . summary )) fail ();
let previous = '' ; for ( const row of table . rows ){
if ( ! valid ( row ) ||! row . recordCount ||! members . includes ( row . member ) || typeof row . name !== 'string' ||! row . name ||! validOrderDate ( row . date ) || row . date < r . from || row . date > r . date ) fail ();
const key = row . date + ':' + teamMemberKeys . indexOf ( row . member ); if ( key <= previous ) fail (); previous = key ;
}
if ([... amounts ,... counts ]. some ( key => table . rows . reduce (( sum , row )=> sum + row [ key ], 0 ) !== table . summary [ key ]) || table . rows . some ( row => row . incomplete ) !== table . summary . incomplete || table . summary . sales !== r . summary . sale || table . summary . knownTotalCost !== r . summary . totalCost || table . summary . knownProfit !== r . summary . profit || table . summary . recordCount !== r . orderRows . length || table . summary . unknownProfitCount !== ( r . summary . unknownProfitCount || 0 ) + ( r . summary . draftCount || 0 ) || table . summary . unknownCostCount !== ( r . summary . unknownCostCount || 0 ) + ( r . summary . draftCount || 0 )) fail ();
2026-10-28 00:22:04 +08:00
}
function validateOwnershipReceipts ( r ){
const fail = ()=>{ throw new Error ( '所属订单净收入与账户明细未完整返回或金额不一致,请重新读取。' );}, keys = teamDataKeys ( r . ownershipReceipts ), selected = teamMode () ? ( state . user . role === 'owner' ? reportMember : currentMember ()) : '' , expected = selected ? [ selected ] : teamMode () ? teamMemberKeys : teamDataKeys ( r . recipientReceipts );
if ( ! r . ownershipReceipts || typeof r . ownershipReceipts !== 'object' || Array . isArray ( r . ownershipReceipts ) || Object . keys ( r . ownershipReceipts ). length !== expected . length || keys . length !== expected . length ||! expected . every ( key => keys . includes ( key ))) fail ();
const receipts = [], owned = [], sum = ( items , kind )=> items . filter ( item => item . kind === kind ). reduce (( total , item )=> total + item . amount , 0 );
for ( const key of keys ){
const person = r . ownershipReceipts [ key ]; if ( ! person || person . member !== key || typeof person . name !== 'string' ||! person . name ||! Array . isArray ( person . accounts ) ||! Array . isArray ( person . items ) ||! [ 'receipt' , 'refund' , 'net' ]. every ( name => Number . isSafeInteger ( person [ name ])) || person . net !== person . receipt - person . refund ) fail ();
if ( ! person . items . every ( item => item && [ 'receipt' , 'refund' ]. includes ( item . kind ) && Number . isSafeInteger ( item . amount ) && typeof item . account === 'string' && validOrderDate ( item . date )) ||! [ 'receipt' , 'refund' ]. every ( kind => sum ( person . items , kind ) === person [ kind ])) fail ();
const accounts = new Set ();
for ( const account of person . accounts ){
if ( ! account || typeof account . account !== 'string' ||! account . account || accounts . has ( account . account ) ||! teamMemberKeys . includes ( account . recipient ) ||! [ 'wechat' , 'alipay' , 'cash' , 'credit_card' ]. includes ( account . channel ) ||! [ 'receipt' , 'refund' , 'net' , 'entryCount' ]. every ( name => Number . isSafeInteger ( account [ name ])) || account . entryCount < 1 || account . net !== account . receipt - account . refund ) fail ();
const items = person . items . filter ( item => item . account === account . account ); if ( items . length !== account . entryCount ||! [ 'receipt' , 'refund' ]. every ( kind => sum ( items , kind ) === account [ kind ])) fail (); accounts . add ( account . account );
}
if ( person . items . some ( item => ! accounts . has ( item . account )) ||! [ 'receipt' , 'refund' , 'net' ]. every ( name => person . accounts . reduce (( total , account )=> total + account [ name ], 0 ) === person [ name ])) fail ();
receipts . push ( person ); owned . push (... person . items );
}
if ( ! [ 'receipt' , 'refund' , 'net' ]. every ( name => receipts . reduce (( total , person )=> total + person [ name ], 0 ) === r . receiptsByOrderDate [ name ])) fail ();
const identity = item => JSON . stringify ([ item . id , item . kind , item . amount , item . account , item . date , item . order_id , item . price_lock_id ]), actual = teamDataKeys ( r . recipientReceipts ). flatMap ( key => r . recipientReceipts [ key ]. items ). map ( identity ). sort (), copies = owned . map ( identity ). sort ();
if ( actual . length !== copies . length || actual . some (( value , index )=> value !== copies [ index ])) fail ();
}
2026-11-02 21:13:10 +08:00
function validatePoolMaterialCosts ( b , fail ){
const count = value => Number . isSafeInteger ( value ) && value >= 0 , nullable = value => value === null || count ( value ), pool = b . poolMaterial ;
const valid = value => value && [ 'mg' , 'knownAmount' , 'missingCount' ]. every ( key => count ( value [ key ])) && nullable ( value . amount ) && value . amount === ( value . missingCount ? null : value . knownAmount ) && value . byPayer && Object . keys ( value . byPayer ). length === teamMemberKeys . length && teamMemberKeys . every ( key =>{
const payer = value . byPayer [ key ]; return payer && count ( payer . knownAmount ) && nullable ( payer . amount ) && payer . amount === ( value . missingCount ? null : payer . knownAmount );
}) && teamMemberKeys . reduce (( sum , key )=> sum + value . byPayer [ key ]. knownAmount , 0 ) === value . knownAmount ;
if ( ! valid ( pool ) || typeof pool . hasPriceLocks !== 'boolean' ||! Array . isArray ( pool . days ) || pool . missingCount > b . missingCostCount ||! pool . otherCosts ||! count ( pool . otherCosts . knownAmount ) ||! nullable ( pool . otherCosts . amount ) || pool . otherCosts . amount !== null && pool . otherCosts . amount !== pool . otherCosts . knownAmount ) fail ();
const seen = new Set (); for ( const day of pool . days ){
if ( ! valid ( day ) || day . mg <= 0 ||! /^\d{4}-\d{2}-\d{2}$/ . test ( day . poolId ) || day . date !== day . poolId ||! nullable ( day . averageRate )) fail ();
2026-11-06 01:29:35 +08:00
if ( day . sources !== undefined ){
if ( ! Array . isArray ( day . sources ) ||! day . sources . length || day . sources . some ( source => ! source ||! [ 'public' , 'personal_recovery' ]. includes ( source . kind ) || ( source . kind === 'personal_recovery' ?! teamMemberKeys . includes ( source . member ) : source . member !== null ) || typeof source . priceLocked !== 'boolean' ||! count ( source . mg ) || source . mg <= 0 ||! nullable ( source . averageRate ) ||! count ( source . knownAmount ) ||! count ( source . missingCount ) ||! nullable ( source . amount ) || source . amount !== ( source . missingCount ? null : source . knownAmount )) || day . sources . reduce (( sum , source )=> sum + source . mg , 0 ) !== day . mg || day . sources . reduce (( sum , source )=> sum + source . knownAmount , 0 ) < day . knownAmount ||! day . missingCount && ( day . sources . some ( source => source . missingCount ) || day . sources . reduce (( sum , source )=> sum + source . knownAmount , 0 ) !== day . knownAmount ) || day . averageRate !== ( day . sources . length === 1 ? day . sources [ 0 ]. averageRate : null )) fail ();
}
const key = day . poolId + ':' + ( day . sources ? 'sources' : day . averageRate ); if ( seen . has ( key )) fail (); seen . add ( key );
2026-11-02 21:13:10 +08:00
}
if ([ 'mg' , 'knownAmount' , 'missingCount' ]. some ( key => pool . days . reduce (( sum , day )=> sum + day [ key ], 0 ) !== pool [ key ]) || teamMemberKeys . some ( key => pool . days . reduce (( sum , day )=> sum + day . byPayer [ key ]. knownAmount , 0 ) !== pool . byPayer [ key ]. knownAmount || pool . byPayer [ key ]. knownAmount > b . costByPayer [ key ]. knownTotalCost ) || pool . knownAmount + pool . otherCosts . knownAmount !== b . knownTotalCost || b . totalCost !== null && ( pool . amount === null || pool . otherCosts . amount === null || pool . amount + pool . otherCosts . amount !== b . totalCost )) fail ();
}
2026-11-02 21:34:17 +08:00
function validateOwnerAdvances ( b , fail ){
const count = value => Number . isSafeInteger ( value ) && value >= 0 , nullable = value => value === null || count ( value ), advances = b . ownerAdvances ;
if ( ! advances || advances . basis !== 'orderDate' || advances . from !== b . from || advances . date !== b . date ||! Array . isArray ( advances . days )) fail ();
let previous = '' , knownTotal = 0 ;
for ( const day of advances . days ){
if ( ! day || typeof day . date !== 'string' || day . date < b . from || day . date > b . date || day . date <= previous ||! /^\d{4}-\d{2}-\d{2}$/ . test ( day . date ) ||! Array . isArray ( day . items ) ||! day . items . length ||! [ 'knownAmount' , 'missingCount' , 'pendingCount' , 'knownPoolAmount' , 'knownOtherAmount' ]. every ( key => count ( day [ key ])) ||! [ 'amount' , 'poolAmount' , 'otherAmount' ]. every ( key => nullable ( day [ key ]))) fail ();
for ( const item of day . items ){
if ( ! item || item . date !== day . date ||! [ 'order' , 'afterSale' ]. includes ( item . kind ) ||! [ 'id' , 'number' , 'paperNumber' , 'customer' , 'name' , 'source' , 'component' ]. every ( key => typeof item [ key ] === 'string' ) ||! item . id ||! item . name || typeof item . poolMaterial !== 'boolean' || typeof item . allocationPending !== 'boolean' || item . poolMaterial !== ( item . poolId !== null ) || item . poolId !== null &&! /^\d{4}-\d{2}-\d{2}$/ . test ( item . poolId ) ||! [ 'recorded' , 'missing' , 'pending' ]. includes ( item . status ) ||! nullable ( item . amount ) ||! nullable ( item . estimatedAmount )) fail ();
if ( item . status === 'recorded' ? ( item . amount === null || item . amount <= 0 || item . estimatedAmount !== null || item . allocationPending ) : ( item . amount !== null || item . status === 'missing' && item . estimatedAmount !== null || item . allocationPending && ( ! item . poolMaterial || item . status !== 'missing' ))) fail ();
}
const recorded = day . items . filter ( item => item . status === 'recorded' ), missing = day . items . filter ( item => item . status === 'missing' ), total = rows => rows . reduce (( sum , item )=> sum + item . amount , 0 ), poolMissing = missing . some ( item => item . poolMaterial ), otherMissing = missing . some ( item => ! item . poolMaterial );
if ( day . knownAmount !== total ( recorded ) || day . knownPoolAmount !== total ( recorded . filter ( item => item . poolMaterial )) || day . knownOtherAmount !== day . knownAmount - day . knownPoolAmount || day . missingCount !== missing . length || day . pendingCount !== day . items . filter ( item => item . status === 'pending' ). length || day . amount !== ( missing . length ? null : day . knownAmount ) || day . poolAmount !== ( poolMissing ? null : day . knownPoolAmount ) || day . otherAmount !== ( otherMissing ? null : day . knownOtherAmount )) fail ();
previous = day . date ; knownTotal += day . knownAmount ;
}
if ( knownTotal > b . costByPayer . owner . knownTotalCost ) fail ();
}
2026-10-28 00:22:04 +08:00
function validateOwnershipBusiness ( r ){
const fail = ()=>{ throw new Error ( '所属订单成本、利润或待转资料未完整返回,请重新读取。' );}, money = value => Number . isSafeInteger ( value ), nullable = value => value === null || money ( value ), count = value => money ( value ) && value >= 0 , keys = teamDataKeys ( r . ownershipReceipts );
if ( ! r . ownershipBusiness || typeof r . ownershipBusiness !== 'object' || Array . isArray ( r . ownershipBusiness ) || Object . keys ( r . ownershipBusiness ). length !== keys . length ||! keys . every ( key => Object . hasOwn ( r . ownershipBusiness , key ))) fail ();
for ( const member of keys ){
const b = r . ownershipBusiness [ member ]; if ( ! b || b . member !== member || typeof b . name !== 'string' ||! b . name || b . basis !== 'orderDate' || b . from !== r . from || b . date !== r . date || b . netReceipts !== r . ownershipReceipts [ member ]. net ||! [ 'sales' , 'netReceipts' , 'knownTotalCost' , 'knownSelfCost' , 'knownOtherCost' , 'knownProfit' ]. every ( key => money ( b [ key ])) ||! [ 'totalCost' , 'selfCost' , 'otherCost' , 'profit' ]. every ( key => nullable ( b [ key ])) ||! [ 'missingCostCount' , 'pendingCostCount' , 'unknownProfitCount' , 'draftCount' , 'recordCount' , 'orderCount' , 'afterSaleCount' ]. every ( key => count ( b [ key ])) || typeof b . incomplete !== 'boolean' || typeof b . hasActivity !== 'boolean' ) fail ();
if ( b . knownSelfCost + b . knownOtherCost !== b . knownTotalCost || b . totalCost !== null && b . totalCost !== b . knownTotalCost || b . selfCost !== null && b . selfCost !== b . knownSelfCost || b . otherCost !== null && b . otherCost !== b . knownOtherCost ) fail ();
if ( ! b . costByPayer || Object . keys ( b . costByPayer ). length !== teamMemberKeys . length ) fail ();
for ( const payer of teamMemberKeys ){ const row = b . costByPayer [ payer ]; if ( ! row || row . member !== payer || typeof row . name !== 'string' ||! row . name ||! nullable ( row . totalCost ) ||! money ( row . knownTotalCost ) ||! count ( row . missingCount ) ||! count ( row . pendingCount ) || row . totalCost !== null && row . totalCost !== row . knownTotalCost ) fail ();}
if ( teamMemberKeys . reduce (( total , key )=> total + b . costByPayer [ key ]. knownTotalCost , 0 ) !== b . knownTotalCost || b . costByPayer [ member ]. knownTotalCost !== b . knownSelfCost || teamMemberKeys . reduce (( total , key )=> total + b . costByPayer [ key ]. missingCount , 0 ) !== b . missingCostCount || teamMemberKeys . reduce (( total , key )=> total + b . costByPayer [ key ]. pendingCount , 0 ) !== b . pendingCostCount ) fail ();
2026-11-02 21:13:10 +08:00
validatePoolMaterialCosts ( b , fail );
2026-11-02 21:34:17 +08:00
validateOwnerAdvances ( b , fail );
2026-11-07 00:30:02 +08:00
validateCurrentAccount ( b , r . ownershipReceipts [ member ], fail );
2026-10-28 00:22:04 +08:00
const difference = b . difference , equation = b . equation , settlement = b . settlement ;
if ( ! difference || difference . amount !== b . netReceipts - b . sales || typeof difference . reconciled !== 'boolean' ||! Array . isArray ( difference . reasons ) ||! difference . reasons . every ( reason => reason && typeof reason . code === 'string' && typeof reason . text === 'string' )) fail ();
if ( ! equation ||! [ 'netReceipts' , 'sales' ]. includes ( equation . basis ) || equation . revenue !== ( equation . basis === 'netReceipts' ? b . netReceipts : b . sales ) || equation . totalCost !== b . totalCost || equation . profit !== b . profit || typeof equation . complete !== 'boolean' || equation . complete && ( ! money ( equation . totalCost ) ||! money ( equation . profit ) || equation . revenue - equation . totalCost !== equation . profit )) fail ();
if ( ! settlement || typeof settlement . available !== 'boolean' || settlement . basis !== 'cumulative-through-date' || settlement . from !== r . from || settlement . date !== r . date || typeof settlement . partial !== 'boolean' ||! count ( settlement . pendingCount ) ||! count ( settlement . legacyCount ) || typeof settlement . notice !== 'string' ||! Array . isArray ( settlement . counterparts )) fail ();
if ( settlement . available ? ( ! count ( settlement . dueOut ) ||! count ( settlement . dueIn )) : ( settlement . dueOut !== null || settlement . dueIn !== null )) fail ();
const seen = new Set (); for ( const row of settlement . counterparts ){ if ( ! row ||! teamMemberKeys . includes ( row . member ) || row . member === member || seen . has ( row . member ) || typeof row . name !== 'string' ||! row . name ||! [ 'dueOut' , 'dueIn' , 'offset' ]. every ( key => count ( row [ key ])) ||! [ 'openingDue' , 'periodNew' , 'periodTransferred' , 'closingDue' ]. every ( key => money ( row [ key ])) || row . openingDue + row . periodNew - row . periodTransferred !== row . closingDue || row . dueOut !== Math . max ( 0 , row . closingDue ) || row . dueIn !== Math . max ( 0 , - row . closingDue ) ||! row . period || row . period . obligationNet !== row . periodNew || row . period . transferred !== row . periodTransferred ||! money ( row . period . receivedForNet ) ||! money ( row . period . advancedNet ) || row . period . receivedForNet + row . period . advancedNet !== row . periodNew ) fail (); seen . add ( row . member );}
if ( settlement . available && [ 'dueOut' , 'dueIn' ]. some ( key => settlement . counterparts . reduce (( total , row )=> total + row [ key ], 0 ) !== settlement [ key ])) fail ();
}
2026-10-17 19:50:24 +08:00
}
2026-11-07 00:30:02 +08:00
function validateCurrentAccount ( b , income , fail ){
const account = b . currentAccount , money = Number . isSafeInteger , count = value => money ( value ) && value >= 0 , nullable = value => value === null || money ( value );
if ( ! account || account . basis !== 'orderDate' || account . from !== b . from || account . date !== b . date ||! Array . isArray ( account . days )) fail ();
const ownerAccounts = new Set ( income . accounts . filter ( row => row . recipient === 'owner' ). map ( row => row . account )), received = new Map ();
for ( const item of income . items ){
const date = item . price_lock_id ? item . date : item . order_date ;
if ( ! date || date < b . from || date > b . date ) continue ;
if ( ownerAccounts . has ( item . account )) received . set ( date ,( received . get ( date ) || 0 ) + ( item . kind === 'receipt' ? item . amount :- item . amount ));
}
const seen = new Set (); let previous = '' ;
for ( const day of account . days ){
if ( ! day ||! validOrderDate ( day . date ) || day . date < b . from || day . date > b . date || day . date <= previous ||! [ 'recordCount' , 'missingCostCount' , 'pendingCostCount' , 'unknownProfitCount' ]. every ( key => count ( day [ key ])) ||! [ 'knownMaterialCost' , 'knownOtherCost' , 'knownProfit' , 'ownerNetReceipts' , 'knownAmount' ]. every ( key => money ( day [ key ])) ||! [ 'materialCost' , 'otherCost' , 'profit' , 'amount' ]. every ( key => nullable ( day [ key ])) || typeof day . incomplete !== 'boolean' ) fail ();
if ( day . materialCost !== null && day . materialCost !== day . knownMaterialCost || day . otherCost !== null && day . otherCost !== day . knownOtherCost || day . profit !== ( day . unknownProfitCount ? null : day . knownProfit ) || day . knownAmount !== day . knownMaterialCost + day . knownOtherCost + day . knownProfit - day . ownerNetReceipts || day . amount !== ( day . incomplete ? null : day . knownAmount ) || ( day . missingCostCount || day . pendingCostCount || day . unknownProfitCount ) &&! day . incomplete || day . ownerNetReceipts !== ( received . get ( day . date ) || 0 )) fail ();
const advance = b . ownerAdvances . days . find ( row => row . date === day . date ), items = advance ? . items || [], recorded = items . filter ( item => item . status === 'recorded' );
const material = rows => rows . filter ( item => item . component === 'material' ), other = rows => rows . filter ( item => item . component !== 'material' ), sum = rows => rows . reduce (( total , item )=> total + item . amount , 0 ), missing = items . filter ( item => item . status === 'missing' );
if ( day . knownMaterialCost !== sum ( material ( recorded )) || day . knownOtherCost !== sum ( other ( recorded )) || day . materialCost !== ( material ( missing ). length ? null : day . knownMaterialCost ) || day . otherCost !== ( other ( missing ). length ? null : day . knownOtherCost ) || day . missingCostCount !== ( advance ? . missingCount || 0 ) || day . pendingCostCount !== ( advance ? . pendingCount || 0 )) fail ();
seen . add ( day . date ); previous = day . date ;
}
if ([... received . keys (),... b . ownerAdvances . days . map ( day => day . date )]. some ( date => ! seen . has ( date )) || account . days . reduce (( sum , day )=> sum + day . knownProfit , 0 ) !== b . knownProfit || account . days . reduce (( sum , day )=> sum + day . unknownProfitCount , 0 ) !== b . unknownProfitCount || account . days . reduce (( sum , day )=> sum + day . recordCount , 0 ) !== b . recordCount || account . days . some ( day => day . incomplete ) !== b . incomplete ) fail ();
}
2026-10-17 19:50:24 +08:00
async function renderReport (){
if ( ! reportDateInitialized ){ reportDate = reportDate || state . today ; reportDateInitialized = true ;}
invalidateReport (); const request = reportRequest , user = state . user . id || state . user . name ; let range ;
2026-11-03 00:29:34 +08:00
$ ( '#main' ). innerHTML = heading ( 'DAILY CHECK' , '每日对账' , '核对本人或所选成员的所属订单收入、实际支出与收款账户。' , `<div class="report-controls"> ${ memberFilterHTML ( 'report-member-filter' , reportMember ) } <label>对账日期<input type="date" id="report-date" value=" ${ e ( reportDate ) } " max=" ${ e ( state . today ) } " aria-label="对账日期"></label><label class="check"><input type="checkbox" id="report-month" ${ reportMonth ? 'checked' : '' } >汇总当月</label></div>` ) + `<p class="small muted report-scope">普通订单按开单日期、售后按记录日期筛选。锁价收付按实际发生日期,销售和完整利润在交付日计入;原锁付款不会重复计入交付日支出。</p><div id="report-content" aria-live="polite"></div><div id="daily-funds-content" aria-live="polite"></div><div id="report-daily-profits-content" aria-live="polite"></div>` ;
2026-10-17 19:50:24 +08:00
try { range = reportRange ();} catch ( err ){ reportQueryState ( null , err . message ); return ;}
reportQueryState ( range );
2026-10-23 09:49:36 +08:00
if ( typeof prepareDailyFundsReport === 'function' ) prepareDailyFundsReport ({... range , month : reportMonth });
2026-10-17 19:50:24 +08:00
try {
2026-10-25 14:19:24 +08:00
const r = await api ( '/api/report?' + new URLSearchParams ({ basis : 'orderDate' , from : range . from , date : range . date ,...( state . user . role === 'owner' && reportMember ? { member : reportMember } : {})}));
2026-10-17 19:50:24 +08:00
if ( request !== reportRequest || tab !== 'report' ||! $ ( '#report-content' ) || ( state . user . id || state . user . name ) !== user ) return ;
validateReport ( r , range ); renderReportContent ( r , range ); currentReport = r ; reportLoadedUser = user ;
2026-10-23 09:49:36 +08:00
if ( typeof acceptDailyFundsReport === 'function' ){ try { acceptDailyFundsReport ( r ,{... range , month : reportMonth });} catch ( err ){ dailyFundsReportError ( range , err );}}
} catch ( err ){ if ( request === reportRequest && tab === 'report' && $ ( '#report-content' )){ reportQueryState ( range , err . name === 'AbortError' ? '读取超时,请重新读取。' : err . message ); if ( typeof dailyFundsReportError === 'function' ) dailyFundsReportError ( range , err );}}
2026-10-17 19:50:24 +08:00
}
function reportOrderNetHTML ( r , range ){
const s = r . summary ;
2026-10-21 01:32:49 +08:00
return `<section class="panel report-order-net"><h2>订单与售后净额明细</h2><p class="small muted"> ${ e ( reportPeriod ( range )) } 范围内,普通订单按开单日、锁价成单按交付日、售后按记录日期归集。这里显示订单完整耗用成本,与上方实际付款分开核对;旧草稿不计金额。</p><div class="table-wrap"><table class="report-order-table" aria-label="订单与售后净额明细"><thead><tr><th>日期/单号或售后项目</th><th>类型/状态</th><th class="number">销售净额</th><th class="number">货品成本</th><th class="number">已付费用</th><th class="number">成本合计</th><th class="number">订单净利润</th></tr></thead><tbody> ${ r . orderRows . map ( row => `<tr><td> ${ e ( row . date ) } <br> ${ orderBookIdentity ( row ) }${ row . kind === 'afterSale' ? `<div class="small muted"> ${ e ( afterSalePayerName ( row )) } 支付</div>` : '' }${ row . costHint ? `<div class="small muted"> ${ e ( row . costHint ) } </div>` : '' } </td><td> ${ badge ( row ) } </td> ${ [ 'sale' , 'goods' , 'paidFees' , 'totalCost' , 'profit' ]. map ( key => `<td class="number"> ${ e ( reportRowAmount ( row , key )) } </td>` ). join ( '' ) } </tr>` ). join ( '' ) || '<tr><td colspan="7" class="muted">所选日期没有订单或售后记录。</td></tr>' } </tbody><tfoot><tr><td colspan="2">销售 ${ s . orderCount } 单 · 售后 ${ s . afterSaleCount || 0 } 笔</td><td class="number"> ${ e ( reportSummaryAmount ( s , 'sale' )) } </td><td class="number"> ${ e ( reportCostAmount ( r . goods , s . missingCosts )) } </td><td class="number">¥ ${ yuan ( r . expense ) } </td><td class="number"> ${ e ( reportSummaryAmount ( s , 'totalCost' )) } </td><td class="number"> ${ e ( reportSummaryAmount ( s , 'profit' )) } </td></tr></tfoot></table></div></section>` ;
2026-10-17 19:50:24 +08:00
}
function reportGlobalHTML ( r ){
2026-11-08 03:30:58 +08:00
if ( teamMode ()) return `<section class="panel"><h2>客户待收款与库存</h2><p>客户待收款 <strong>¥ ${ yuan ( r . customerBalance ) } </strong></p><div class="grid three"> ${ r . inventory . map ( i => `<div> ${ e ( pocketLabel ( i . pocket )) } <strong> ${ grams ( i . mg ) } g</strong></div>` ). join ( '' ) } </div></section>` ;
return `<div class="split report-secondary"><section class="panel"><h2>截至现在的未结事项</h2><p class="small muted">所有订单的当前未结情况,不受上方日期筛选。</p><p>客户待收款:<strong>¥ ${ yuan ( r . customerBalance ) } </strong></p><p> ${ r . materialPoolSettlement ? '订单与剩余料款' : '所有订单' } 待结算净额:<strong> ${ r . settlementDue == null ? '料费待补(已核算部分 ¥' + yuan ( r . knownSettlementDue ) + ') ' : '¥' + yuan ( r . settlementDue ) } </strong></p><div class="note">净额仅供总览,不把不同订单的返款与交款互相抵扣。货款按单交,利润月底交。</div></section><section class="panel"><h2> ${ e ( r . date ) } 账面库存</h2><p class="small muted">按所选日及此前的库存流水计算;月汇总仍显示所选日库存。已复核历史值从库存页每日快照查询。</p><div class="grid two"> ${ r . inventory . map ( i => `<div> ${ e ( pocketLabel ( i . pocket )) } <strong> ${ grams ( i . mg ) } g</strong></div>` ). join ( '' ) } </div></section></div>` ;
2026-10-17 19:50:24 +08:00
}
function reportUnsettledHTML ( r ){
2026-11-03 01:15:41 +08:00
return `<section class="panel report-unsettled"><h2>逐单交款与返款(截至现在)</h2><p class="small muted">所有订单,不受日期筛选。负数表示麦麦需转回娜娜。含麦麦直收款的订单,先复核货款与利润归属。</p><div class="table-wrap"><table><thead><tr><th>订单</th><th class="number">货款待结</th><th class="number">利润待结</th><th class="number">麦麦直收净额</th><th class="number">总待结</th></tr></thead><tbody> ${ r . unsettled . map ( o => `<tr><td><button class="link-button" data-action="open-order" data-id=" ${ e ( o . id ) } "> ${ e ( o . number ) } </button></td><td class="number"> ${ materialReportMoney ( o . costDue ) } </td><td class="number"> ${ materialReportMoney ( o . profitDue ) } </td><td class="number">¥ ${ yuan ( o . ownerDirect ) } </td><td class="number"> ${ materialReportMoney ( o . total ) } </td></tr>` ). join ( '' ) || '<tr><td colspan="5">目前没有待结款项。</td></tr>' } </tbody></table></div></section>` ;
2026-10-17 19:50:24 +08:00
}
function renderReportContent ( r , range ){
const body = $ ( '#report-content' ), s = r . summary , receipts = r . receiptsByOrderDate , profitMissing = s . unknownProfitCount || 0 ;
const countHints = [ `销售 ${ s . orderCount } 单` , `售后 ${ s . afterSaleCount || 0 } 笔` , ` ${ s . completedCount } 单完成` , s . returnedCount ? ` ${ s . returnedCount } 单退货` : '' , s . cancelledCount ? ` ${ s . cancelledCount } 单取消` : '' , s . draftCount ? ` ${ s . draftCount } 单旧草稿未计金额` : '' ]. filter ( Boolean ). join ( ' · ' );
const close = r . close , closeStatus = reportMonth ? '月汇总显示月初至所选日的订单与售后;单日核对快照请取消“汇总当月”后保存。' : close ? ` ${ close . date } 已由 ${ close . actor } 保存快照。 ${ close . stale ? ( close . staleReason || '之后有补录,请重新核对。' ) : '快照保留,不等于支付平台账单已核实。' } ` : '尚未保存所选日对账快照(含当日售后)。' ;
body . setAttribute ( 'aria-busy' , 'false' );
2026-11-03 01:15:41 +08:00
body . innerHTML = ` ${ reportOwnershipReceiptsHTML ( r , range ) } <div class="order-people-strip report-people-strip"> ${ peopleCountHTML ( r . peopleCount ) } </div><div class="cards report-cards"> ${ card ( '所选' + ( reportMonth ? '月' : '日' ) + '销售净额' , e ( reportSummaryAmount ( s , 'sale' )), e ( countHints )) }${ card ( '本期实收' , '¥' + yuan ( receipts . receipt ), '普通订单累计收款+本期锁价实收' ) }${ card ( '本期实退' , '¥' + yuan ( receipts . refund ), '普通订单累计退款+本期锁价实退' ) }${ card ( '本期净利润' + ( profitMissing ? '(已核算部分)' : '' ), e ( reportSummaryAmount ( s , 'profit' )), profitMissing ? profitMissing + ' 单利润待补齐' + ( r . pendingMaterialCount ? ',其中 ' + r . pendingMaterialCount + ' 单料费待补' : '' ) : '销售净额 − 订单耗用成本 − 实际费用(含售后)' , true ) } </div><div class="report-primary"><section class="panel report-accounts"><h2>按收款账户核对</h2><p class="small muted"> ${ e ( reportPeriod ( range )) } 普通订单当前收付,加上同期锁价实际收付。</p><div class="table-wrap"><table aria-label="按收款账户核对"><thead><tr><th>账户</th><th class="number">实收</th><th class="number">实退</th><th class="number">净额</th></tr></thead><tbody> ${ reportActiveAccounts ( r ). map ( a => `<tr><td> ${ e ( accountDisplayName ( a . account )) } </td><td class="number">¥ ${ yuan ( a . receipt ) } </td><td class="number">¥ ${ yuan ( a . refund ) } </td><td class="number">¥ ${ yuan ( a . net ) } </td></tr>` ). join ( '' ) || '<tr><td colspan="4" class="muted">所选范围没有收退款活动账户。</td></tr>' } </tbody><tfoot><tr><td>合计</td><td class="number">¥ ${ yuan ( receipts . receipt ) } </td><td class="number">¥ ${ yuan ( receipts . refund ) } </td><td class="number">¥ ${ yuan ( receipts . net ) } </td></tr></tfoot></table></div><p class="small muted report-cost-note">请按这些订单的收退款记录与微信、支付宝、现金、信用卡核对;系统尚未接入支付平台账单。</p></section> ${ reportPayerCostsHTML ( r ) } </div>` ;
2026-11-07 00:30:02 +08:00
body . insertAdjacentHTML ( 'beforeend' , priceLockActivityHTML ( r . priceLockActivity ) + materialPoolActivityHTML ( r . materialPoolActivity ) + reportOrderNetHTML ( r , range ) + reportGlobalHTML ( r ) + `<section class="panel"><div class="panel-title"><h2>需要查看 ${ r . warnings . length } 项</h2><span class="small muted">截至现在所有订单,不受日期筛选</span></div> ${ r . warnings . length ? `<ul> ${ r . warnings . map ( w => `<li> ${ w . id ? `<button class="link-button" data-action="open-order" data-id=" ${ e ( w . id ) } "> ${ e ( w . number ) } </button> ` : '' }${ e ( w . message ) } </li>` ). join ( '' ) } </ul>` : '<p class="ok">系统内未发现待补成本、待退款和待复核项。实际到账仍需核对。</p>' } <div class="form-actions"><div class="small ${ close ? . stale ? 'danger-text' : 'muted' } "> ${ e ( closeStatus ) } </div><div class="actions"> ${ button ( '下载对账报告' , 'download-report' ) }${ state . user . role === 'owner' &&! reportMonth ? button ( '保存核对快照' , 'close-day' , 'primary' ) : '' } </div></div></section>` + ( teamMode () ? '' : reportUnsettledHTML ( r ) + materialPoolGlobalSettlementHTML ( r . materialPoolSettlement )));
2026-11-03 00:29:34 +08:00
$ ( '#report-daily-profits-content' ). innerHTML = reportDailyProfitsHTML ( r );
2026-10-17 19:50:24 +08:00
}
function requireCurrentReport (){
const range = reportRange (), r = currentReport ;
if ( tab !== 'report' ||! $ ( '#report-content' ) ||! r || reportLoadedUser !== ( state . user . id || state . user . name )) throw new Error ( '对账数据正在读取或已失效,请读取完成后再操作。' );
if ( $ ( '#report-date' ) ? . value !== range . date || $ ( '#report-month' ) ? . checked !== reportMonth ) throw new Error ( '对账日期已改变,请读取完成后再操作。' );
validateReport ( r , range ); return r ;
}
function reportDownloadText ( r ){
2026-10-25 14:19:24 +08:00
if ( teamMode () && typeof reportTeamDownloadText === 'function' ) return reportTeamDownloadText ( r );
const s = r . summary , receipts = r . receiptsByOrderDate , people = teamDataKeys ( r . payerCosts ). map ( key => r . payerCosts [ key ]), missing = people . reduce (( sum , c )=> sum + c . missingCount , 0 ), pending = people . reduce (( sum , c )=> sum + c . pendingCount , 0 );
2026-10-17 19:50:24 +08:00
const costs = people . flatMap ( c =>[ ` ${ c . name } 支出成本:货品成本 ${ reportCostAmount ( c . goods , c . missingCount ) } ;已付费用 ¥ ${ yuan ( c . paidFees ) }${ c . items . some ( item => item . kind === 'afterSale' ) ? '(其中售后 ¥' + yuan ( reportAfterSaleAmount ( c )) + ') ' : '' } ;支出合计 ${ reportCostAmount ( c . total , c . missingCount + c . pendingCount ) } ` , reportPayerHints ( c ), ` ${ c . name } 逐项明细(货品成本为 0 的分项省略,已核实为 0 的费用保留):` ,... reportCostItems ( c ). map ( item => ` ${ item . date } / ${ reportCostIdentity ( item ) } / ${ item . name } / ${ item . source }${ item . calculation ? ' / ' + reportCostFormula ( item ) : '' } / ${ reportCostItemAmount ( item ) }${ item . kind === 'pending' ? '(未计入实际成本与合计)' : '' } ` ), '' ]);
const orders = r . orderRows . map ( row => ` ${ row . date } / ${ row . kind === 'afterSale' ? '售后 · ' + row . project + ' / 客户 ' + row . customer + ' / ' + afterSalePayerName ( row ) + '支付' : row . paper_number || row . number } / ${ label [ row . status ] || row . status } / 销售净额 ${ reportRowAmount ( row , 'sale' ) } / 货品成本 ${ reportRowAmount ( row , 'goods' ) } / 已付费用 ${ reportRowAmount ( row , 'paidFees' ) } / 成本合计 ${ reportRowAmount ( row , 'totalCost' ) } / 净利润 ${ reportRowAmount ( row , 'profit' ) }${ row . costHint ? ' / ' + row . costHint : '' } ` );
2026-11-08 03:30:58 +08:00
return [ `麦麦珠宝新账 · ${ reportPeriod ( r ) } 对账报告` , '口径:普通订单按开单日期、售后按记录日期;锁价收付款按实际发生日期,销售与完整利润按交付日期。原锁料费不会重复计入交付日实际支出。' , `销售订单: ${ s . orderCount } 单;售后 ${ s . afterSaleCount || 0 } 笔;完成 ${ s . completedCount } 单;退货 ${ s . returnedCount } 单;取消 ${ s . cancelledCount } 单;旧草稿 ${ s . draftCount } 单(未计金额)` ,... peopleCountReportLines ( r . peopleCount ), `销售净额: ${ reportSummaryAmount ( s , 'sale' ) } ` , `累计实收:¥ ${ yuan ( receipts . receipt ) } ` , `累计实退:¥ ${ yuan ( receipts . refund ) } ` , `客户收款净额:¥ ${ yuan ( receipts . net ) } ` , `订单耗用货品成本: ${ reportCostAmount ( r . goods , s . missingCosts ) } ` , `订单已付费用:¥ ${ yuan ( r . expense ) }${ s . afterSaleCount ? '(其中售后 ¥' + yuan ( people . reduce (( sum , c )=> sum + reportAfterSaleAmount ( c ), 0 )) + ') ' : '' } ` , `各人实际货品支出: ${ reportCostAmount ( r . outlayGoods ?? r . goods , missing ) } ` , `各人实际费用支出:¥ ${ yuan ( r . outlayExpense ?? r . expense ) } ` , `各人实际支出合计: ${ reportCostAmount ( r . outlayTotal ?? r . goods + r . expense , missing + pending ) } ` , `本期净利润 ${ s . unknownProfitCount ? '(已核算部分)' : '' } : ${ reportSummaryAmount ( s , 'profit' ) }${ s . unknownProfitCount ? '; ' + s . unknownProfitCount + ' 单利润待补齐' : '' } ` , '' ,... reportDailyProfitsText ( r ),... reportOwnershipReceiptsText ( r ),...( typeof dailyFundsDownloadText === 'function' ? dailyFundsDownloadText ( r ) : []),... reportRecipientReceiptsText ( r ), '按收款账户核对(普通订单累计收付+同期锁价实际收付)' ,... reportActiveAccounts ( r ). map ( a => ` ${ accountDisplayName ( a . account ) } :实收 ¥ ${ yuan ( a . receipt ) } ,实退 ¥ ${ yuan ( a . refund ) } ,净额 ¥ ${ yuan ( a . net ) } ` ), '' ,( teamMode () ? '各人支出成本(未入账费用不计合计)' : '双方支出成本(未入账费用不计合计)' ),... costs ,... priceLockActivityText ( r . priceLockActivity ),...( r . materialPoolActivity ? . purchases ? . length ? [ '本期实际购料(已计入各人实际支出,不再加总)' ,... r . materialPoolActivity . purchases . map ( item => ` ${ item . date } / ${ grams ( item . mg ) } g / ¥ ${ yuan ( item . amount ) } / ${ materialPayerName ( item . payer ) } / ${ item . note || '' } ` ), '' ] : []), '订单与售后净额明细(订单按开单日期、售后按售后日期)' ,... orders , '' , ` ${ r . date } 账面库存(按所选日及此前流水计算,月汇总仍显示所选日)` ,... r . inventory . map ( i => ` ${ pocketLabel ( i . pocket ) } : ${ grams ( i . mg ) } g` ), '' , '截至现在的全局未结事项(不受日期筛选)' , `客户待收款:¥ ${ yuan ( r . customerBalance ) } ` , `订单与剩余料款待结净额: ${ materialReportMoney ( r . settlementDue ) } ` ,... r . unsettled . map ( o => ` ${ o . number } :货款待结 ${ materialReportMoney ( o . costDue ) } ,利润待结 ${ materialReportMoney ( o . profitDue ) } ,麦麦直收净额 ¥ ${ yuan ( o . ownerDirect ) } ,总待结 ${ materialReportMoney ( o . total ) } ` ), '' , '当前待处理(所有订单,不受日期筛选)' ,... r . warnings . map ( w => ` ${ w . number || '' } ${ w . message } ` ), '' ,...( r . materialPoolSettlement ? . pools ? . length ? [ '剩余料款与娜娜结算(正数娜娜交麦麦,负数麦麦转回助理)' ,... r . materialPoolSettlement . pools . map ( item => ` ${ item . date } :娜娜剩余料款 ${ materialReportMoney ( item . assistantInventoryCredit ) } ,实际已交净额 ¥ ${ yuan ( item . transferred ) } ,待结 ${ materialReportMoney ( item . settlementDue ) } ` ), '' ] : []), '收款由经办人登记,不代表支付平台自动核验。各人实际付款与订单耗用成本分别核对;退货冲回耗用成本,锁价实际进货付款保留。净利润不含房租、工资、水电。' ]. join ( '\n' );
2026-10-17 19:50:24 +08:00
}
function printSettingsDirty ( form = $ ( '#print-settings' )){
if ( ! form ) return false ;
return Object . entries ( state . printing ). some (([ key , value ])=>{
const input = form . elements . namedItem ( key ); if ( ! input ) return false ;
return typeof value === 'number' ? ( input . value . trim () === '' || Number ( input . value ) !== value ) : input . value !== String ( value ?? '' );
});
}
function syncPrintSettingsPreview ( saved = false ){
const form = $ ( '#print-settings' ); if ( ! form ) return ;
if ( saved ) form . dataset . saved = 'true' ;
for ( const key of [ 'store' , 'subtitle' , 'contact' ]){
const preview = $ ( '#print-mini-' + key ), input = form . elements . namedItem ( key ); if ( ! preview ||! input ) continue ;
preview . textContent = input . value ; if ( key === 'contact' ) preview . hidden =! input . value ;
}
const status = $ ( '#print-settings-status' ), dirty = printSettingsDirty ( form ), owner = state . user . role === 'owner' ;
if ( status ){ status . className = 'small ' + ( dirty ? 'danger-text' : 'muted' ); status . textContent =! owner ? '只读;由麦麦账号修改并保存打印设置。' : printSettingsSaving ? '正在保存打印设置…' : dirty ? '修改后未保存,请点击“保存打印设置”。' : form . dataset . saved === 'true' ? '已保存,打印使用当前设置。' : '当前生效设置;修改后请点击保存。' ;}
document . querySelectorAll ( 'button[form="print-settings"]' ). forEach ( button => button . disabled =! owner || printSettingsSaving || busy );
}
async function savePrintSettings ( form , data ){
if ( state . user . role !== 'owner' ) throw new Error ( '打印设置由麦麦账号修改。' );
if ( printSettingsSaving ) throw new Error ( '正在保存打印设置,请稍候。' );
const fields = form . querySelector ( '.print-settings-fields' ); let committed = false ;
printSettingsSaving = true ; fields . disabled = true ; $ ( '#print-settings-error' ). innerHTML = '' ; syncPrintSettingsPreview ();
try {
await mutate ( '/api/printing' , data ); committed = true ; syncPrintSettingsPreview (); await refresh ();
syncPrintSettingsPreview ( true ); toast ( '打印设置已保存,预览和后续打印使用新设置' );
} catch ( err ){ if ( committed ) err . message = '打印设置已保存,但最新设置暂未读到。请刷新页面核对。' ; throw err ;}
finally { printSettingsSaving = false ; if ( $ ( '#print-settings' ) === form ) fields . disabled = state . user . role !== 'owner' ; syncPrintSettingsPreview ();}
}
function renderSettings (){ const s = state . printing , canEdit = state . user . role === 'owner' ;
2026-10-25 14:19:24 +08:00
$ ( '#main' ). innerHTML = heading ( 'PRINT & SETTINGS' , '打印与设置' , '先把单据做好,选好纸张和打印机后再校准位置。' ) + `<div class="split"><section class="panel"><div class="panel-title print-settings-title"><div><h2>客户打印模板</h2><p id="print-settings-status" class="small muted" aria-live="polite"></p></div> ${ canEdit ? '<button type="submit" form="print-settings" class="primary">保存打印设置</button>' : '<span class="small muted">由麦麦账号修改</span>' } </div><form id="print-settings"><fieldset class="print-settings-fields" ${ canEdit ? '' : 'disabled' } ><div class="grid two"> ${ field ( '店名' , 'store' , s . store , 'text' , 'maxlength="80" required' ) }${ field ( '单据标题' , 'subtitle' , s . subtitle , 'text' , 'maxlength="80"' ) }${ field ( '客户联系信息(选填)' , 'contact' , s . contact , 'text' , 'maxlength="80"' ) }${ field ( '表格最少行数' , 'rows' , s . rows , 'number' , 'min="3" max="12" required' ) }${ field ( '左右偏移(mm,正数向右)' , 'offsetX' , s . offsetX , 'number' , 'min="-30" max="30" step="0.1" required' ) }${ field ( '上下偏移(mm,正数向下)' , 'offsetY' , s . offsetY , 'number' , 'min="-30" max="30" step="0.1" required' ) }${ field ( '内容距顶部(mm) ' , 'contentTop' , s . contentTop , 'number' , 'min="5" max="40" step="0.1" required' ) }${ field ( '商品行高(mm) ' , 'rowHeight' , s . rowHeight , 'number' , 'min="7" max="16" step="0.1" required' ) } </div></fieldset><div class="form-actions"> ${ state . orders [ 0 ] ? button ( '打开最近一单预览' , 'print' , '' , `data-id=" ${ state . orders [ 0 ]. id } "` ) : '' } </div><div id="print-settings-error" aria-live="polite"></div></form></section><section class="panel print-settings-preview"><p class="small muted">填写效果示意;保存后用于实际打印。</p><div class="print-preview-mini"><div class="paper-mini"><strong id="print-mini-store"> ${ e ( s . store ) } </strong><p id="print-mini-subtitle"> ${ e ( s . subtitle ) } </p><p id="print-mini-contact" ${ s . contact ? '' : 'hidden' } > ${ e ( s . contact ) } </p><table><tr><td>商品名称</td><td>克重</td><td>成交金额</td></tr><tr><td>足金手链</td><td>1.200g</td><td>1,200.00</td></tr><tr><td> </td><td></td><td></td></tr></table><p>合计金额 ¥1,200.00</p><p>大写:壹仟贰佰元整</p><p>注意事项 · 珠宝首饰保养须知</p><p>经办人 ______</p></div></div><div class="note">固定241× 140mm横版,明细多时自动缩小到一页。打印窗口也选241×140mm,关闭页眉页脚。表格最少行数只用于补空行;套打按实物纸样校准偏移。</div><p class="small muted">补打沿用同一订单号,不会重复出库或收入。客户预览接口不返回成本、垫资人、利润及内部操作日志。</p></section></div><div class="grid two"><section class="panel"><h2>数据库与备份</h2><p> ${ state . mode === 'production' ? '主账保存在部署服务器的独立SQLite数据库。' : '现在运行在本机试用环境,云端正式数据库尚未部署。' } </p><p class="small muted">启动时和运行期间每6小时生成完整数据库备份。本机同盘备份不能防电脑损坏,正式部署还需异地备份。</p> ${ state . backup ? . last ? `<p class="small">本次运行最近备份: ${ e ( state . backup ? . last . time ) } </p>` : '' }${ state . backup ? . error ? `<p class="error"> ${ e ( state . backup ? . error ) } </p>` : '' }${ state . user . role === 'owner' ? button ( '生成并下载完整备份' , 'backup' ) : '<p class="muted">由麦麦账号下载备份。</p>' } </section><section class="panel"><h2>飞书查看副本</h2><p><span class="badge ${ state . sync . enabled ? '' : 'warn' } "> ${ state . sync . enabled ? '已配置' : '尚未连接' } </span></p><p class="small muted">使用新账专用表单向同步。修改和复核在本系统完成;同步失败不重开订单、不影响本地账务保存。</p> ${ state . sync . enabled ? `<p>待同步 ${ state . sync . pending } 项 · 失败 ${ state . sync . failed } 项</p> ${ state . sync . error ? `<p class="error"> ${ e ( state . sync . error ) } </p>` : '' }${ state . user . role === 'owner' ? button ( '立即重试同步' , 'sync' ) : '' } ` : '<p class="note">已预留应用API同步通道。正式连接时再配置新表,未连接原销售表,未试写真实账务。</p>' } </section></
2026-10-17 19:50:24 +08:00
syncPrintSettingsPreview();
2026-10-25 14:19:24 +08:00
if(teamMode()){$('#main').insertAdjacentHTML('afterbegin',teamAccountsSettingsHTML());loadTeamMembers();}
2026-10-17 19:50:24 +08:00
}
function markFeeEdited(target){const row=target.closest('#fee-rows .fee-row');if(row)row.dataset.edited='true';}
// 防止滚轮、上下键误改数字;仍保留数字校验与手机数字键盘。
document.addEventListener('keydown',ev=>{if(ev.target instanceof HTMLInputElement&&ev.target.type==='number'&&['ArrowUp','ArrowDown'].includes(ev.key))ev.preventDefault();});
document.addEventListener('wheel',ev=>{if(ev.target instanceof HTMLInputElement&&ev.target.type==='number'&&document.activeElement===ev.target)ev.preventDefault();},{passive:false});
2026-10-28 00:22:04 +08:00
for(const type of ['input','change'])document.addEventListener(type,ev=>{if(ev.target.closest('#after-sale-edit-form'))syncAfterSaleEditMode();if(ev.target.closest('#print-settings'))syncPrintSettingsPreview();if(typeof syncOrderOwnershipSelection==='function'&&ev.target.closest('#order-ownership-form'))syncOrderOwnershipSelection(ev.target);});
2026-10-25 14:19:24 +08:00
document.addEventListener('input',ev=>{if(ev.target.id==='people-count-date')loadPeopleCount();else if(ev.target.closest('#people-count-form'))syncPeopleCountPreview();});
2026-11-08 02:22:58 +08:00
document.addEventListener('input',ev=>{if(typeof dailyFundsInput==='function')dailyFundsInput(ev.target);if(ev.target.closest('#price-lock-create-form[data-price-lock-edit-id]')&&!['pending_edit_verified','pending_edit_reason'].includes(ev.target.name)){const checked=$('#price-lock-create-form [name="pending_edit_verified"]');if(checked)checked.checked=false;}if(ev.target.closest('#order-form,#price-lock-create-form,#price-lock-delivery-form')){markFeeEdited(ev.target);syncChargePrice(ev.target);updateTotal();}if(ev.target.closest('#action-form[data-kind="cost"]'))syncCostEditor();if(ev.target.closest('#action-form')){syncActionCreditCardFee();if(typeof syncOrderActionChangeMode==='function')syncOrderActionChangeMode();}if(ev.target.id==='order-search')filterOrders(180);if(['order-date','order-from','order-to'].includes(ev.target.id))return updateOrderBookDate(ev.target);});
2026-11-08 03:30:58 +08:00
document.addEventListener('change',async ev=>{try{if(ev.target.name==='pocket'){const note=ev.target.closest('label')?.nextElementSibling;if(note?.classList?.contains('pocket-selection-note'))note.hidden=!ev.target.value||activePocketKeys().includes(ev.target.value);}if(ev.target.closest('#price-lock-create-form[data-price-lock-edit-id]')&&!['pending_edit_verified','pending_edit_reason'].includes(ev.target.name)){const checked=$('#price-lock-create-form [name="pending_edit_verified"]');if(checked)checked.checked=false;}if(ev.target.closest('#price-lock-create-form,#price-lock-delivery-form')){markFeeEdited(ev.target);syncChargePrice(ev.target);updateTotal();}if(ev.target.closest('#order-form')){markFeeEdited(ev.target);syncChargePrice(ev.target);const row=ev.target.closest('.line-item');if(row&&ev.target.name==='nameType'&&['足银999','纯银925'].includes(ev.target.value))row.querySelector('[name="pocket"]').value='';if(row&&ev.target.name==='unit'&&ev.target.value==='件'){row.querySelector('[name="pricingMode"]').value='manual';row.querySelector('[name="pocket"]').value='';}updateTotal();if(ev.target.name==='date')updatePaperNumber();if(ev.target.name==='member'&&teamMode()){const prefix={owner:'麦麦',assistant:'助理',assistant2:'助理2'}[ev.target.value];const recipient=$('#order-form [name="payment_recipient"]');if(recipient){recipient.dataset.nonCardRecipient=prefix;if($('#order-form [name="payment_method"]')?.value!=='信用卡')recipient.value=prefix;}for(const fee of document.querySelectorAll('#fee-rows .fee-row'))if(fee.dataset.edited!=='true'&&FeeEstimates.normalize(fee.querySelector('.fee-name')?.textContent)!=='包装')fee.querySelector('[name="feePayer"]').value=ev.target.value;resetOrderTemplates();loadOrderTemplates();updateTotal();}}if(ev.target.closest('#action-form[data-kind="cost"]'))syncCostEditor();if(ev.target.closest('#action-form')){syncActionCreditCardFee();if(typeof syncOrderActionChangeMode==='function')syncOrderActionChangeMode();}if(ev.target.closest('#inventory-change-form')&&ev.target.name==='kind')syncInventoryChangeForm();if(ev.target.closest('#stock-form')&&ev.target.name==='kind')syncStockForm();if(ev.target.id==='inventory-history-date'){inventoryHistoryMode='date';inventoryHistoryDate=ev.target.value;await loadInventorySnapshots();}if(ev.target.id==='inventory-movements-pocket'||ev.target.id==='inventory-movements-kind'){if(ev.target.id==='inventory-movements-pocket')inventoryMovementPocket=ev.target.value;else inventoryMovementKind=ev.target.value;inventoryMovementPage=1;await loadInventoryMovements();}if(ev.target.closest('#people-count-history-form'))await loadPeopleCountHistory();if(ev.target.id==='order-filter'||ev.target.id==='order-member-filter'||ev.target.id==='order-pocket-filter')filterOrders();if(ev.target.id==='report-member-filter'){reportMember=ev.target.value;await renderReport();}if(ev.target.id==='report-month'){reportMonth=ev.target.checked;await renderReport();}if(ev.target.id==='report-date'){reportDate=ev.target.value;await renderReport();}}catch(err){toast(err.message,true);}});
2026-10-17 19:50:24 +08:00
document.addEventListener('click',async ev=>{
2026-11-04 22:18:56 +08:00
const b=ev.target.closest('button');if(!b||b.disabled)return;if(b.dataset.tab){if(typeof invalidateRecoveryChangeViews==='function')invalidateRecoveryChangeViews();invalidateAfterSaleViews();invalidateInventoryMovementViews();if(typeof invalidateInventoryChangeViews==='function')invalidateInventoryChangeViews();closePeopleCountHistory();invalidateOrderDetailView(true);invalidateOrderBookDetailList();++orderBookRequest;clearTimeout(orderBookTimer);if(typeof invalidateOrderCancellationViews==='function')invalidateOrderCancellationViews();if(typeof invalidateOrderChangeViews==='function')invalidateOrderChangeViews();if(typeof invalidateOrderOwnershipViews==='function')invalidateOrderOwnershipViews();if(tab==='order-edit')leaveOrderEdit();invalidateReport();invalidatePriceLockViews();tab=b.dataset.tab;priceLockDeliveryId='';editDraft=null;if(tab==='report'&&$('#report-content')){let range;try{range=reportRange();}catch{}if(range)reportQueryState(range);}try{await refresh();}catch(err){if(tab==='report'&&$('#report-content'))reportQueryState(null,err.message);toast(err.message,true);}return;}
2026-10-17 19:50:24 +08:00
const a=b.dataset.action;if(!a)return;
try{
2026-11-08 03:30:58 +08:00
if(typeof pocketManagerAction==='function'&&a.startsWith('pocket-manager-'))return await pocketManagerAction(a,b);
2026-10-28 00:22:04 +08:00
if(a==='after-sale-edit')return await openAfterSaleEdit(b.dataset.id);
if(a==='after-sale-changes-open')return await openAfterSaleChanges();
if(a==='after-sale-changes-close')return closeAfterSaleChanges();
if(a==='after-sale-changes-reload')return await loadAfterSaleChanges();
if(a==='after-sale-changes-filter'){if(['pending','approved','rejected','all'].includes(b.dataset.status))afterSaleChangesStatus=b.dataset.status;return await loadAfterSaleChanges();}
if(a==='after-sale-change-open')return await openAfterSaleChange(b.dataset.id);
if(a==='after-sale-review-decision')return showAfterSaleReviewForm(b.dataset.kind);
if(a==='after-sale-review-cancel'){if(afterSaleReviewEntry)afterSaleReviewEntry.kind=null;return renderAfterSaleReview();}
2026-10-26 17:07:26 +08:00
if(typeof handleMaterialRollingAction==='function'&&(a.startsWith('material-rolling-')||a.startsWith('material-change-')))return await handleMaterialRollingAction(a,b);
2026-10-25 14:19:24 +08:00
if(typeof inventoryChangeAction==='function'&&a.startsWith('inventory-change-'))return await inventoryChangeAction(a,b);
2026-10-23 09:49:36 +08:00
if(typeof dailyFundsAction==='function'&&(a.startsWith('daily-')||a.startsWith('reimbursement-')))return await dailyFundsAction(a,b);
if(orderDetailLoad&&b.closest('#order-dialog')&&a!=='close-dialog')throw new Error('正在读取订单,请稍候再操作。');
2026-10-26 20:25:31 +08:00
if(typeof orderOwnershipAction==='function'&&a.startsWith('order-ownership-'))return await orderOwnershipAction(a,b);
2026-10-23 09:49:36 +08:00
if(a==='open-order-changes')return await openOrderChanges();
if(a==='close-order-changes'){closeOrderChanges();return;}
if(a==='filter-order-changes'){orderChangeListStatus=b.dataset.status;return await loadOrderChanges();}
if(a==='retry-order-changes')return await loadOrderChanges();
if(a==='open-change-order'){closeOrderChanges();return await openOrder(b.dataset.id);}
if(a==='approve-order-change')return showOrderChangeForm('approve');
if(a==='reject-order-change')return showOrderChangeForm('reject');
if(a==='close-order-change-form'){closeOrderChangeForm();return;}
2026-10-23 11:58:19 +08:00
if(a==='reload-order-change')return orderDetailRetry?.savedContext&&orderDetailRetry.id===b.dataset.id?await retryOrderDetail():await refreshOrderDetailAfterSave(b.dataset.id);
2026-10-23 00:38:04 +08:00
if(a==='open-order-cancellations')return await openOrderCancellations();
if(a==='close-order-cancellations'){closeOrderCancellations();return;}
if(a==='filter-order-cancellations'){orderCancellationListStatus=b.dataset.status;return await loadOrderCancellations();}
if(a==='retry-order-cancellations')return await loadOrderCancellations();
if(a==='open-cancellation-order'){closeOrderCancellations();return await openOrder(b.dataset.id);}
if(a==='request-order-cancellation')return showOrderCancellationForm('request');
if(a==='approve-order-cancellation')return showOrderCancellationForm('approve');
if(a==='reject-order-cancellation')return showOrderCancellationForm('reject');
if(a==='close-order-cancellation-form'){closeOrderCancellationForm();return;}
2026-10-23 11:58:19 +08:00
if(a==='reload-order-cancellation')return orderDetailRetry?.savedContext&&orderDetailRetry.id===b.dataset.id?await retryOrderDetail():await refreshOrderDetailAfterSave(b.dataset.id);
2026-10-21 01:32:49 +08:00
if(a==='refresh-material-pools'){await refresh(false);return await renderMaterialPools();}
if(a==='new-material-purchase'){ $('#main').innerHTML=materialPoolsPageHTML(materialPoolsCache);return;}
if(a==='toggle-material-pool'){materialPoolsOpenDate=materialPoolsOpenDate===b.dataset.id?'':b.dataset.id;if(materialPoolsCache&&$('#material-pools-content'))$('#material-pools-content').innerHTML=materialPoolListHTML(materialPoolsCache);return;}
if(a==='reload-material-choices')return await loadMaterialPoolChoices(true);
2026-11-02 19:30:28 +08:00
if(a==='reload-price-lock-pool')return await loadPriceLockPoolChoices(true);
2026-11-08 02:22:58 +08:00
if(a==='add-lock-line'||a==='remove-lock-line')return changePriceLockLines(a,b);
if(typeof priceLockPendingActionClick==='function'&&(['edit-price-lock','cancel-price-lock','leave-lock-edit','reset-lock-edit'].includes(a)||a.startsWith('price-lock-change')||a==='price-lock-list-status'))return await priceLockPendingActionClick(a,b);
2026-10-21 01:32:49 +08:00
if(a==='edit-material-purchase'||a==='delete-material-purchase')return await showMaterialPurchaseChange(b.dataset.id,a==='delete-material-purchase'?'delete':'edit');
if(a==='reload-material-purchase')return await showMaterialPurchaseChange(b.dataset.id,b.dataset.kind);
if(a==='close-material-purchase'){closeMaterialPurchaseDialog();return;}
if(a==='refresh-changed-material-purchase'){closeMaterialPurchaseDialog();invalidateMaterialPools();invalidateReport();await refresh(false);return await renderMaterialPools();}
if(a==='goto-material-pools'){$('#order-dialog')?.close();currentOrder=null;if(b.dataset.id)materialPoolsOpenDate=b.dataset.id;tab='material-pools';return await refresh();}
if(a==='material-pool-settlement'){if(pending())throw new Error('请先恢复上次未确认的操作,再登记实际交款。');return showMaterialPoolSettlement(b.dataset.id);}
if(a==='close-material-settlement'){$('#material-settlement-dialog')?.close();return;}
if(a==='reload-material-settlement'){$('#material-settlement-dialog')?.close();return await renderMaterialPools();}
2026-10-22 17:06:32 +08:00
if(a==='edit-order')return await startOrderEdit(b.dataset.id,b);
if(a==='cancel-order-edit')return await cancelOrderEdit();
if(a==='leave-order-edit'){leaveOrderEdit();tab='orders';return await refresh();}
if(a==='reload-order-edit')return await reloadOrderEdit(b.dataset.id);
if(a==='keep-order-edit')return await reloadOrderEdit(b.dataset.id,'keep');
if(a==='reset-order-edit')return await reloadOrderEdit(b.dataset.id,'reset');
2026-10-21 01:32:49 +08:00
if(a==='create-mode'){createMode=b.dataset.mode==='lock'?'lock':'direct';return renderCreate();}
2026-11-08 02:22:58 +08:00
if(a==='new-price-lock'){if(typeof priceLockEditEntry!=='undefined')priceLockEditEntry=null;invalidatePriceLockViews();priceLockDeliveryId='';createMode='lock';tab='create';return await refresh();}
2026-10-21 01:32:49 +08:00
if(a==='refresh-price-locks'){invalidatePriceLockViews();priceLockDeliveryId='';return await renderPriceLocks();}
if(a==='open-price-lock')return await openPriceLock(b.dataset.id);
if(a==='close-price-lock'){invalidatePriceLockViews();$('#price-lock-dialog')?.close();return;}
if(a==='deliver-price-lock'){if(pending())throw new Error('请先恢复上次未确认的操作,再办理交付。');$('#price-lock-dialog')?.close();invalidateReport();priceLockDeliveryId=b.dataset.id;tab='price-locks';return await refresh();}
if(a==='open-lock-order'){$('#price-lock-dialog')?.close();return await openOrder(b.dataset.id);}
2026-10-26 22:46:55 +08:00
if(a.startsWith('demo-')){invalidateInventoryMovementViews(true);if(typeof invalidateInventoryChangeViews==='function')invalidateInventoryChangeViews();await api('/api/demo-login',{member:a==='demo-owner'?'owner':a==='demo-assistant2'?'assistant2':'assistant'});return init();}
if(a==='logout'){invalidateInventoryMovementViews(true);if(typeof invalidateInventoryChangeViews==='function')invalidateInventoryChangeViews();++orderDetailRequest;if(typeof invalidateOrderCancellationViews==='function')invalidateOrderCancellationViews();if(typeof invalidateOrderChangeViews==='function')invalidateOrderChangeViews();if(typeof invalidateOrderOwnershipViews==='function')invalidateOrderOwnershipViews();invalidatePriceLockViews();if(pending())throw new Error('请先恢复上次未确认的操作,再退出');closePeopleCountHistory();if(tab==='order-edit')leaveOrderEdit();invalidateReport();invalidateMaterialPools();await api('/api/logout',{});resetOrderTemplates();localStorage.removeItem('mm-draft-'+session.user.id);return init();}
2026-10-17 19:50:24 +08:00
if(a==='refresh'){
if(tab==='orders'){clearTimeout(orderBookTimer);++orderBookRequest;let range;try{range=orderBookRange();}catch{}orderBookLoading(range);try{return await refresh();}catch(err){orderBookError(err.message);throw err;}}
return refresh();
}
2026-11-01 23:40:44 +08:00
if(a==='order-period')return await selectOrderBookPeriod(b.dataset.period);
2026-10-17 19:50:24 +08:00
if(a==='new-after-sale'){if(pending())throw new Error('请先恢复上次未确认的操作,再新增售后。');await refresh(false);if(tab==='orders')showAfterSaleForm();return;}
2026-10-28 00:22:04 +08:00
if(a==='close-after-sale'){closeAfterSaleDialog();return;}
2026-10-17 19:50:24 +08:00
if(a==='people-count'){if(pending())throw new Error('请先恢复上次未确认的操作,再记录人数。');await refresh(false);if(tab==='orders')return await showPeopleCountForm();return;}
if(a==='close-people-count'){invalidatePeopleEntry();$('#people-count-dialog')?.close();return;}
if(a==='people-count-retry')return await loadPeopleCount();
2026-10-24 16:09:45 +08:00
if(a==='people-history')return await openPeopleCountHistory();
if(a==='close-people-history'){closePeopleCountHistory();return;}
if(a==='people-history-retry')return await loadPeopleCountHistory();
if(a==='people-history-month')return await peopleCountHistoryMonth(b.dataset.period==='previous');
2026-10-17 19:50:24 +08:00
if(a==='order-book-retry')return await loadOrderBook();
if(a==='report-retry')return await renderReport();
if(a==='inventory-retry')return await renderStock();
2026-10-23 09:49:36 +08:00
if(a==='inventory-movements-retry')return await loadInventoryMovements();
2026-10-31 14:59:30 +08:00
if(a==='inventory-movements-export')return await exportInventoryMovements();
2026-10-26 22:46:55 +08:00
if(a==='inventory-movements-page')return await moveInventoryMovementPage(b.dataset.direction);
2026-10-17 19:50:24 +08:00
if(a==='inventory-history'){
if(!inventoryPage)return;
inventoryHistoryOpen=!inventoryHistoryOpen;$('#inventory-history').hidden=!inventoryHistoryOpen;b.textContent=inventoryHistoryOpen?'收起每日快照':'查看每日快照';b.setAttribute('aria-expanded',String(inventoryHistoryOpen));
if(inventoryHistoryOpen)await loadInventorySnapshots();else ++inventoryHistoryRequest;
return;
}
if(a==='inventory-history-period'){inventoryHistoryMode=b.dataset.period;return await loadInventorySnapshots();}
if(a==='inventory-history-retry')return await loadInventorySnapshots();
if(a==='inventory-review'){
2026-10-26 22:46:55 +08:00
const page=inventoryPage;if(!page)throw new Error('请先重新读取库存,再核对保存。');if(state.user.role!=='owner'||!page.canReview)throw new Error('手动复核库存由麦麦操作。');
2026-10-17 19:50:24 +08:00
try{await mutate('/api/inventory/review',{date:page.date,verified:true,revision:page.revision});}
catch(err){if(err.status===409){await renderStock();err.message='库存已有变动,页面已更新。请核对当前数量后再次保存。';}throw err;}
await refresh();return toast('今日库存复核快照已保存');
}
if(a==='retry'){
2026-11-08 03:30:58 +08:00
const p=pending();if(!p)return;let r;const recoveryContext=captureOrderDetailReload(currentOrder?.id);const detailAction=p.url.match(/^\/api\/orders\/([^/]+)\/(?:review|receipt|refund|expense|fees|cost|return|settlement|correct|complete|confirm|deliver)$/),detailContext=detailAction?captureOrderDetailReload(decodeURIComponent(detailAction[1])):null;const orderEdit=p.url.match(/^\/api\/orders\/([^/]+)\/edit$/);const ownership=typeof orderOwnershipOperation==='function'?orderOwnershipOperation(p.url):null;const cancellation=typeof orderCancellationOperation==='function'?orderCancellationOperation(p.url):null;const change=typeof orderChangeOperation==='function'?orderChangeOperation(p.url):null;const materialChange=p.url.match(/^\/api\/material-purchases\/([^/]+)\/(edit|delete)$/);const fundsOperation=typeof dailyFundsOperation==='function'?dailyFundsOperation(p.url):null;const inventoryChange=typeof inventoryChangeOperation==='function'?inventoryChangeOperation(p.url):null;const materialRolling=typeof materialRollingOperation==='function'?materialRollingOperation(p.url):null;const pocketOperation=typeof pocketManagementOperation==='function'&&pocketManagementOperation(p.url);
2026-10-26 20:25:31 +08:00
const ownershipContext=ownership?captureOrderOwnershipView(ownership.orderId||currentOrder?.id):null;
2026-11-04 22:18:56 +08:00
const afterSale=afterSaleOperation(p.url),afterSaleView=afterSale?captureAfterSaleView(afterSale):null;const recoveryChange=typeof recoveryChangeOperation==='function'?recoveryChangeOperation(p.url):null,recoveryChangeView=recoveryChange?captureRecoveryChangeView():null;
2026-11-08 03:30:58 +08:00
try{r=await mutate(p.url,p.data,p);}catch(err){if(pocketOperation)return pocketManagerError(err);if(recoveryChange){if(recoveryChangeView.user===recoveryChangeUser())recoveryChangeError(err,recoveryChange);return;}if(afterSale){if(afterSaleView.user===orderDetailUser())afterSaleOperationError(err,afterSale);return;}if(materialRolling)return materialRollingRetryError(p,err);if(inventoryChange)return inventoryChangeError(err,inventoryChange);if(fundsOperation)return await dailyFundsError(err,fundsOperation);if(ownership)return orderOwnershipError(err,ownership,ownershipContext);if(cancellation)return orderCancellationError(err);if(change)return change.kind==='request'&&typeof orderEditEntry!=='undefined'&&orderEditEntry?.id===change.orderId?orderEditError(err,change.orderId):orderChangeError(err,change);if(orderEdit)return orderEditError(err,decodeURIComponent(orderEdit[1]));if(detailAction&& $('#action-form[data-order-change="true"]')&&orderActionChangeEntry?.id===decodeURIComponent(detailAction[1]))return orderActionChangeError(err,{kind:'direct',orderId:decodeURIComponent(detailAction[1])});if(materialChange)return materialPurchaseChangeError($('#material-purchase-'+materialChange[2]+'-form'),err,{id:decodeURIComponent(materialChange[1]),kind:materialChange[2]});if(p.url==='/api/people-count'&&err.status===409){await refresh(false);await showPeopleCountForm(p.data.date,'人数已被更新,已显示当前值,请核对后再保存。');return toast('人数已被更新,请核对当前值后再保存。',true);}throw err;}
if(pocketOperation)return await finishPocketManagementSave(p.url,p.data,r);
2026-11-04 22:18:56 +08:00
if(recoveryChange)return await finishRecoveryChangeSave(p.url,p.data,r,recoveryChangeView);
2026-10-28 00:22:04 +08:00
if(afterSale)return await finishAfterSaleSave(p.url,p.data,r,afterSaleView);
2026-10-26 17:07:26 +08:00
if(materialRolling)return await finishMaterialRollingMutation(p.url,p.data,r);
2026-10-25 14:19:24 +08:00
if(inventoryChange)return await finishInventoryChangeSave(p.url,p.data,r);
if(p.url==='/api/team-funds/transfers')return await finishTeamTransferSave(r);
2026-10-23 09:49:36 +08:00
if(fundsOperation)return await finishDailyFundsSave(p.url,p.data,r,dailyFundsRecoveryOrigin(p));
2026-10-26 20:25:31 +08:00
if(ownership)return await finishOrderOwnershipSave(p.url,p.data,r,recoveryContext?.id===(r.id||r.order?.id||ownership.orderId)?recoveryContext:null,ownershipContext);
2026-10-23 11:58:19 +08:00
if(cancellation)return await finishOrderCancellationSave(p.url,p.data,r,recoveryContext?.id===(r.id||r.order?.id||cancellation.orderId)?recoveryContext:null);
if(change)return await finishOrderChangeSave(p.url,p.data,r,recoveryContext?.id===(r.id||r.order?.id||change.orderId)?recoveryContext:null);
2026-10-22 17:06:32 +08:00
if(orderEdit)return await finishOrderEditSave(p.data,r,decodeURIComponent(orderEdit[1]));
2026-11-08 02:22:58 +08:00
if(typeof priceLockPendingOperation==='function'&&priceLockPendingOperation(p.url))return await finishPendingPriceLockSave(p.url,p.data,r);
2026-10-21 01:32:49 +08:00
if(p.url==='/api/price-locks'||/^\/api\/price-locks\/[^/]+\/deliver$/.test(p.url))return await finishPriceLockSave(p.url,p.data,r);
2026-10-26 14:44:07 +08:00
if(p.url==='/api/recoveries'&&typeof finishRecoverySave==='function')return await finishRecoverySave(p.data,r);
2026-10-21 01:32:49 +08:00
if(p.url==='/api/material-purchases')return await finishMaterialPurchaseSave(p.data,r);
if(materialChange)return await finishMaterialPurchaseChange(p.data,r,decodeURIComponent(materialChange[1]),materialChange[2]);
const poolSettlement=p.url.match(/^\/api\/material-pools\/([^/]+)\/settlement$/);if(poolSettlement)return await finishMaterialSettlementSave(p.data,r,decodeURIComponent(poolSettlement[1]));
2026-10-17 19:50:24 +08:00
if(p.url==='/api/after-sales'){await showSavedAfterSale(p.data.date);return toast('原售后已确认,不会重复记账');}
if(p.url==='/api/people-count'){await showSavedPeopleCount(p.data.date);return toast('原人数记录已确认,不会重复记账');}
if(p.url==='/api/printing'){await refresh();syncPrintSettingsPreview(true);return toast('打印设置已保存,预览和后续打印使用新设置');}
2026-10-22 04:21:26 +08:00
if(/^\/api\/order-templates(?:\/[^/]+\/(?:update|delete))?$/.test(p.url))return await finishOrderTemplateSave(p.url,p.data,r);
2026-10-21 01:32:49 +08:00
if(p.url==='/api/orders/issue')return await finishIssuedOrderSave(p.data,r);
2026-10-23 11:58:19 +08:00
toast('原操作已确认,不会重复记账');if(detailAction)return await refreshOrderDetailAfterSave(r.id||decodeURIComponent(detailAction[1]),detailContext);await refresh();if(r.id)await openOrder(r.id);return;
2026-10-17 19:50:24 +08:00
}
2026-10-21 01:32:49 +08:00
if(a==='split-cost'){const row=b.closest('.line-item'),unit=row.querySelector('[name="unit"]').value,payer=row.querySelector('[name="payer"]');row.dataset.legacy='false';payer.closest('label').remove();row.querySelector('.cost-fields').innerHTML=costFields({material:'',labor:'',accessories:'0',other:'0'},'cost-',true,{}, {mode:unit==='g'?'gram':'total'},{},unit,costPayerInput({payer:payer.value}),{compact:true,payer:payer.value,...(row.closest('#order-form')?{poolLine:{payer:payer.value}}:{})});updateTotal();return loadMaterialPoolChoices();}
2026-10-25 14:19:24 +08:00
if(a==='add-fee'){$('#fee-rows').insertAdjacentHTML('beforeend',feeRowHTML({key:'manual:'+crypto.randomUUID(),note:'其他费用',amount:'',payer:teamDefaultPayer(),status:'estimated',edited:true}));return updateTotal();}
2026-10-17 19:50:24 +08:00
if(a==='remove-fee'){b.closest('.fee-row').remove();return updateTotal();}
if(a==='add-charge'){const list=b.closest('.line-item').querySelector('.charge-list');if(list.children.length>=100)throw new Error('每行最多填写100项附加项目');list.insertAdjacentHTML('beforeend',chargeHTML());return updateTotal();}
if(a==='remove-charge'){b.closest('.charge-row').remove();return updateTotal();}
2026-10-21 01:32:49 +08:00
if(a==='add-line'){$('#lines').insertAdjacentHTML('beforeend',lineHTML({},$('#lines').children.length+1,{materialPool:!!b.closest('#order-form')}));return updateTotal();}
2026-10-17 19:50:24 +08:00
if(a==='remove-line'){if($('#lines').children.length<=1)throw new Error('请至少保留一行商品');b.closest('.line-item').remove();return updateTotal();}
2026-10-22 17:06:32 +08:00
if(a==='clear-draft'){if(tab==='order-edit')throw new Error('请用“取消修改”退出订单修改。');editDraft=null;orderTemplateSelection='';localStorage.removeItem('mm-draft-'+session.user.id);return renderCreate();}
2026-10-22 04:21:26 +08:00
if(a==='copy-order')return await copyOrder(b.dataset.id,b);
2026-11-02 18:55:10 +08:00
if(a==='view-saved-order-edit')return await viewSavedOrderEdit(b.dataset.id,b);
2026-10-23 09:49:36 +08:00
if(a==='open-order')return await openOrder(b.dataset.id,{source:b});
if(a==='order-detail-prev')return await navigateOrderDetail(-1);
if(a==='order-detail-next')return await navigateOrderDetail(1);
if(a==='order-detail-retry')return await retryOrderDetail();
if(a==='close-dialog'){invalidateOrderDetailView();if(typeof closeOrderCancellationForm==='function')closeOrderCancellationForm();$('#order-dialog').close();currentOrder=null;return;}
if(a==='edit'){if(state.user.role!=='owner')throw new Error('已有草稿由麦麦继续填写并开单;资料更正请从原单申请修改。');createMode='direct';orderTemplateSelection='';editDraft=draftInputs(currentOrder);$('#order-dialog').close();tab='create';return render();}
2026-10-17 19:50:24 +08:00
if(a.startsWith('show-'))return showAction(a.slice(5));
2026-10-23 09:49:36 +08:00
if(a==='hide-action'){$('#detail-form').innerHTML='';orderDetailSwitchError='';updateOrderDetailNavigation();return;}
2026-10-17 19:50:24 +08:00
if(a==='print'){
if(b.closest('#print-settings')){
if(printSettingsSaving)throw new Error('打印设置正在保存,请保存完成后再打开预览。');
if(printSettingsDirty()){syncPrintSettingsPreview();$('#print-settings-status')?.scrollIntoView({block:'center'});throw new Error('打印设置已修改但尚未保存,请先点击“保存打印设置”,再打开预览。');}
}
const id=b.dataset.id;const popup=window.open('/print/'+id+'?mode=full','_blank','noopener');
await mutate('/api/orders/'+id+'/print',{mode:'full'});toast('客户打印页已打开;若未出现,请允许此网站打开新窗口');return;
}
if(a==='close-day'){const r=requireCurrentReport();if(reportMonth)throw new Error('保存单日核对快照前,请取消“汇总当月”。');await mutate('/api/close',{date:r.date,basis:'orderDate'});toast(r.date+' 对账与库存快照已保存');if(tab==='report')return renderReport();return;}
if(a==='download-report'){
const r=requireCurrentReport(),content=reportDownloadText(r),link=document.createElement('a');link.href=URL.createObjectURL(new Blob(['\ufeff'+content],{type:'text/plain;charset=utf-8'}));link.download=` 麦麦对账 - $ { r . from === r . date ? r . date : r . from + '至' + r . date }. txt `;link.click();setTimeout(()=>URL.revokeObjectURL(link.href),1000);return;
}
if(a==='backup'){const r=await api('/api/backup',{});const link=document.createElement('a');link.href='/api/backup/'+r.name;link.download=r.name;link.click();toast('完整备份已生成');return refresh();}
if(a==='sync'){const r=await api('/api/sync',{});toast(r.error||'同步重试完成,请查看状态',!!r.error);return refresh();}
}catch(err){toast(err.message,true);if($('#detail-error')&¤tOrder)$('#detail-error').innerHTML=` < div class = "error" > $ { e ( err . message )} < /div>`;}
});
document . addEventListener ( 'submit' , async ev =>{
ev . preventDefault (); const form = ev . target ; const data = Object . fromEntries ( new FormData ( form ));
try {
2026-11-08 03:30:58 +08:00
if ( typeof submitPocketManagement === 'function' && ( form . id === 'pocket-create-form' || form . classList ? . contains ? .( 'pocket-rename-form' ))) return await submitPocketManagement ( form );
2026-10-26 17:07:26 +08:00
if ([ 'material-rolling-enable-form' , 'material-change-review-form' ]. includes ( form . id )) return await submitMaterialRollingForm ( form );
2026-10-25 14:19:24 +08:00
if ( form . id === 'inventory-change-form' ) return await submitInventoryChange ( form );
if ( form . id === 'inventory-change-review-form' ) return await submitInventoryChangeReview ( form );
2026-10-23 09:49:36 +08:00
if ([ 'daily-outlay-form' , 'reimbursement-form' , 'reimbursement-review-form' ]. includes ( form . id ) && typeof submitDailyFundsForm === 'function' ) return await submitDailyFundsForm ( form );
2026-10-28 00:22:04 +08:00
if ( form . id === 'after-sale-edit-form' ) return await submitAfterSaleEdit ( form );
if ( form . id === 'after-sale-review-form' ) return await submitAfterSaleReview ( form );
2026-10-26 20:25:31 +08:00
if ( form . id === 'order-ownership-form' ) return await submitOrderOwnership ( form );
2026-10-23 09:49:36 +08:00
if ( form . id === 'order-change-form' ) return await submitOrderChange ( form );
2026-10-23 00:38:04 +08:00
if ( form . id === 'order-cancellation-form' ) return await submitOrderCancellation ( form );
2026-10-17 19:50:24 +08:00
if ( form . id === 'setup-form' || form . id === 'login-form' ){ await api ( form . id === 'setup-form' ? '/api/setup' : '/api/login' , data ); return init ();}
2026-10-21 01:32:49 +08:00
if ( form . id === 'material-purchase-form' ) return await submitMaterialPurchase ( form );
if ( form . id === 'material-purchase-edit-form' || form . id === 'material-purchase-delete-form' ) return await submitMaterialPurchaseChange ( form );
if ( form . id === 'material-settlement-form' ) return await submitMaterialSettlement ( form );
2026-10-24 16:09:45 +08:00
if ( form . id === 'people-count-history-form' ) return await loadPeopleCountHistory ();
2026-10-17 19:50:24 +08:00
if ( form . id === 'people-count-form' ){
if ( ! peopleEntry || peopleEntry . date !== data . date || peopleEntryUser !== ( state . user . id || state . user . name )) throw new Error ( '请等人数记录读取完成后再保存。' );
2026-10-25 14:19:24 +08:00
const counts = Object . fromEntries ( peopleParts (). map (([ part , label ])=>[ part + 'Count' , peopleCountInput ( data [ part + 'Count' ], label , true )]));
$ ( '#people-count-error' ). innerHTML = '' ; await mutate ( '/api/people-count' ,{ date : data . date ,... counts , revision : peopleEntry . revision }); return await showSavedPeopleCount ( data . date );
2026-10-17 19:50:24 +08:00
}
if ( form . id === 'after-sale-form' ){
const input = { date : data . date , project : String ( data . project || '' ). trim (), customer : String ( data . customer || '' ). trim (), amount : String ( data . amount || '' ). trim (), payer : data . payer };
if ( ! validOrderDate ( input . date ) || input . date > state . today ) throw new Error ( '售后日期请选择今天或之前的有效日期。' );
if ( ! input . project || input . project . length > 100 ) throw new Error ( '售后项目请填写1~ 100字。' );
if ( ! input . customer || input . customer . length > 60 ) throw new Error ( '客户请填写1~60字的称呼或代号。' );
2026-10-25 14:19:24 +08:00
if ( ! [ 'owner' , 'assistant' , 'assistant2' ]. includes ( input . payer )) throw new Error ( '请选择这笔售后由谁支付。' );
LedgerCalc . cents ( input . amount , '售后金额' ); if ( teamMode ()) input . member = form . querySelector ( '[name="member"]' ) ? . value || currentMember (); $ ( '#after-sale-error' ). innerHTML = '' ;
2026-10-17 19:50:24 +08:00
await mutate ( '/api/after-sales' , input ); return await showSavedAfterSale ( input . date );
}
2026-11-08 02:22:58 +08:00
if ( form . id === 'price-lock-cancel-form' ) return await submitPriceLockCancel ( form );
if ( form . id === 'price-lock-review-form' ) return await submitPriceLockReview ( form , ev . submitter );
2026-10-21 01:32:49 +08:00
if ( form . id === 'price-lock-create-form' || form . id === 'price-lock-delivery-form' ) return await submitPriceLockForm ( form );
2026-10-22 17:06:32 +08:00
if ( form . id === 'order-edit-meta-form' || form . id === 'order-form' && form . dataset . orderEdit === 'true' ) return await submitOrderEdit ( form );
2026-11-08 03:30:58 +08:00
if ( form . id === 'order-form' ){ validateNewPocketSelections ( form ); updateTotal (); const draft = validateIssueDraft ( collectDraft ()); if ( draft . id && state . user . role !== 'owner' ) throw new Error ( '已有草稿由麦麦继续填写并开单;无单号的新开单流程照常使用。' ); $ ( '#order-error' ). innerHTML = '' ; const r = await mutate ( '/api/orders/issue' , draft ); return await finishIssuedOrderSave ( draft , r );}
2026-10-17 19:50:24 +08:00
if ( form . id === 'stock-form' ){
const input = { kind : data . kind , date : data . date , pocket : data . pocket , grams : String ( data . grams || '' ). trim (), note : data . note || '' };
2026-11-08 03:30:58 +08:00
if ( ! [ 'increase' , 'decrease' , 'transfer' ]. includes ( input . kind ) ||! activePocketKeys (). includes ( input . pocket )) throw new Error ( '请选择库存动作和货盘。' );
2026-10-17 19:50:24 +08:00
if ( ! /^\d+(?:\.\d{1,3})?$/ . test ( input . grams ) || Number ( input . grams ) <= 0 ) throw new Error ( '数量请填写大于0的数字,最多保留3位小数。' );
2026-11-08 03:30:58 +08:00
if ( input . kind === 'transfer' ){ input . to = data . to ; if ( ! activePocketKeys (). includes ( input . to ) || input . to === input . pocket ) throw new Error ( '平移请选择两个不同的货盘。' );}
2026-10-17 19:50:24 +08:00
$ ( '#stock-error' ). innerHTML = '' ; await mutate ( '/api/stock' , input ); await refresh (); return toast ( '库存' + ({ increase : '增加' , decrease : '减少' , transfer : '平移' })[ input . kind ] + '已登记' );
}
if ( form . id === 'print-settings' ) return await savePrintSettings ( form , data );
if ( form . id === 'password-form' ){ await mutate ( '/api/password' , data ); return init ();}
if ( form . id === 'action-form' ){
const kind = form . dataset . kind ; const input = {... data , date : data . date || state . today , verified : data . verified === 'on' , feesVerified : data . feesVerified === 'on' };
if ( kind === 'fees' ){ input . revision = currentOrder . revision ; input . fee_items = [... form . querySelectorAll ( '.fee-verify-row' )]. map ( row =>({... currentOrder . pendingFees . find ( f => f . key === row . dataset . key ), status : 'estimated' , amount : row . querySelector ( '[name="verifiedAmount"]' ). value , payer : row . querySelector ( '[name="verifiedPayer"]' ). value }));}
if ( kind === 'correct' ){ const [ type , target ] = data . entry . split ( ':' ); input . type = type ; input . target = target ;}
if ( kind === 'cost' ) input . costs = [... form . querySelectorAll ( '.cost-editor' )]. map ( row =>{ const value = readPurchaseCost ( row ); return { parts : value . costParts , costMaterial : value . costMaterial , costLabor : value . costLabor , costPayers : value . costPayers , payer : row . querySelector ( '[name="goodsPayer"]' ). value };});
2026-10-25 14:19:24 +08:00
if ( kind === 'receipt' || kind === 'refund' ) input . account = readPaymentAccount ( form ); if ( kind === 'correct' && input . account ) input . account = normalizePaymentAccount ( input . account );
2026-11-08 03:30:58 +08:00
if ( kind === 'return' ) input . returnPockets = currentOrder . lines . map (( _ , i )=> form . querySelector ( '[name="return-' + i + '"]' ) ? . value ?? data [ 'return-' + i ]);
2026-10-17 19:50:24 +08:00
if ([ 'review' , 'complete' ]. includes ( kind )) input . revision = currentOrder . revision ;
2026-10-23 11:58:19 +08:00
if ( typeof orderActionUsesChangeForm === 'function' && orderActionUsesChangeForm ( kind )) return await submitOrderActionChange ( form , input );
const id = currentOrder . id , detailContext = captureOrderDetailReload ( id ); await mutate ( '/api/orders/' + id + '/' + kind , input ); invalidateMaterialPools (); await refreshOrderDetailAfterSave ( id , detailContext ); return toast ( actionName [ kind ] + '已保存' );
2026-10-17 19:50:24 +08:00
}
2026-11-08 02:22:58 +08:00
} catch ( err ){ if ( typeof priceLockPendingError === 'function' && ( form . id === 'price-lock-cancel-form' || form . id === 'price-lock-review-form' || form . dataset . priceLockEditId )) return priceLockPendingError ( err , form ); if ([ 'after-sale-edit-form' , 'after-sale-review-form' ]. includes ( form . id )) return afterSaleOperationError ( err ); if ([ 'material-rolling-enable-form' , 'material-change-review-form' ]. includes ( form . id )) return materialRollingError ( form , err ); if ([ 'inventory-change-form' , 'inventory-change-review-form' ]. includes ( form . id )) return inventoryChangeError ( err , inventoryChangeReview ? { id : inventoryChangeReview . request . id , review : true } : inventoryChangeEntry ? { id : inventoryChangeEntry . id , kind : inventoryChangeEntry . kind } : null ); if ( form . id === 'action-form' && form . dataset . orderChange === 'true' ) return orderActionChangeError ( err ); if ( form . id === 'order-ownership-form' ) return orderOwnershipError ( err ); if ( form . id === 'order-change-form' ) return orderChangeError ( err ); if ( form . id === 'order-cancellation-form' ) return orderCancellationError ( err ); if ( form . id === 'order-edit-meta-form' || form . id === 'order-form' && form . dataset . orderEdit === 'true' ) return orderEditError ( err ); if ( form . id === 'material-purchase-edit-form' || form . id === 'material-purchase-delete-form' ) return materialPurchaseChangeError ( form , err ); if ( form . id . startsWith ( 'material-' )){ err . message = err . message . replace ( '不要重新开单' , '不要重复登记' ); toast ( err . message , true ); const target = form . id === 'material-purchase-form' ? $ ( '#material-purchase-error' ) : $ ( '#material-settlement-error' ); if ( target ) target . innerHTML = `<div class="error"> ${ e ( err . message ) }${ err . status === 409 ? ' ' + button ( '关闭并重新读取该日购料' , 'reload-material-settlement' , 'quiet' ) : '' } </div>` ; return ;} if ( form . id === 'people-count-form' && err . status === 409 ){ await loadPeopleCount ( '人数已被更新,已显示当前值,请核对后再保存。' ); return toast ( '人数已被更新,请核对当前值后再保存。' , true );} if ( form . id === 'people-count-form' ) err . message = err . message . replace ( '不要重新开单' , '不要重复记录人数' ); if ( form . id === 'after-sale-form' ) err . message = err . message . replace ( '不要重新开单' , '不要重复新增售后' ); if ( form . id . startsWith ( 'price-lock-' )) err . message = err . message . replace ( '不要重新开单' , '不要重复锁价或交付' ); toast ( err . message , true ); if ( form . id . startsWith ( 'price-lock-' ) && $ ( '#price-lock-error' )) $ ( '#price-lock-error' ). innerHTML = `<div class="error"> ${ e ( err . message ) }${ err . status === 409 ? ( form . dataset . id ? ' ' + button ( '重新读取锁价单' , 'deliver-price-lock' , '' , `data-id=" ${ e ( form . dataset . id ) } "` ) : [... form . querySelectorAll ( '[name="material_source"]' )]. some ( input => input . value === 'pool' ) ? ' ' + button ( '刷新料池后重新核对' , 'reload-price-lock-pool' , 'quiet' ) : '' ) : '' } </div>` ; else if ( form . id === 'people-count-form' && $ ( '#people-count-error' )) $ ( '#people-count-error' ). innerHTML = `<div class="error"> ${ e ( err . message ) } </div>` ; else if ( form . id === 'after-sale-form' && $ ( '#after-sale-error' )) $ ( '#after-sale-error' ). innerHTML = `<div class="error"> ${ e ( err . message ) } </div>` ; else if ( form . id === 'print-settings' && $ ( '#print-settings-error' )) $ ( '#print-settings-error' ). innerHTML = `<div class="error"> ${ e ( err . message ) } </div>` ; else if ( form . id . endsWith ( 'login-form' ) || form . id === 'setup-form' ) $ ( '#login-error' ). innerHTML = `<div class="error"> ${ e ( err . message ) } </div>` ; else if ( form . id === 'order-form' ) $ ( '#order-error' ). innerHTML = `<div class="error"> ${ e ( err . message ) } </div>` ; else if ( form . id === 'stock-form' && $ ( '#stock-error' )) $ ( '#stock-error' ). innerHTML = `<div class="error"> ${ e ( err . message ) } </div>` ; else if ( $ ( '#detail-error' ) && form . id === 'action-form' ) $ ( '#detail-error' ). innerHTML = `<div class="error"> ${ e ( err . message ) }${ pending () ? ' ' + button ( '恢复原操作' , 'retry' , 'danger' ) : '' } </div>` ;}
2026-10-17 19:50:24 +08:00
});
init ();