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-11-14 01:16:35 +08:00
const actionName = { confirm : '蝖株恕霈W� ' , receipt : '� 餉扇� 嗆狡' , refund : '� 餉扇� � 甈� ' , expense : '� 湔𦻖韐寧鍂' , fees : '銵亥扇� 批� 韐寧鍂' , cost : '銵仿� 韐批� � 鞉𧋦' , deliver : '摰峕� � � � 株扇韐� ' , complete : '銵仿� � 批� 韐血𦛚' , cancel : '� 𡝗� 霈W� ' , return : '� 游� � � 韐� ' , settlement : '摰鮋� 鈭斗狡' , review : '摨𦯀蜓憭齿瓲' , correct : '� 湔迤瘚� 偌' , ownership : '靽格㺿霈W� 敶鍦� ' };
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-14 01:16:35 +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 ( name === value ? accountDisplayName ( value ) : name ) } </option>` ;}). join ( '' );
2026-11-08 03:30:58 +08:00
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 ?? '' );}
2026-11-08 15:47:07 +08:00
function pocketCountsEnabled ( key ){ return !! key && state ? . pocketCatalog ? . some ( row => row . key === key && row . countUnit === 'pair' ) === true ;}
function stockCountValue ( value ,{ zero = false , optional = false , signed = false , title = '摨枏� � 圈� 嚗� 笆嚗� ' } = {}){
const text = String ( value ?? '' ). trim (); if ( ! text && optional ) return null ;
if ( signed ){ if ( ! /^-?\d+$/ . test ( text ) ||! Number . isSafeInteger ( Number ( text )) || Math . abs ( Number ( text )) > 1000000000 || Number ( text ) === 0 ) throw new Error ( title + '霂瑕‵� 䠷� 0� 湔㺭嚗� � � 惩‵甇� 㺭嚗� � 撠穃‵韐� 㺭� � ' ); return Number ( text );}
if ( ! /^\d+$/ . test ( text ) ||! Number . isSafeInteger ( Number ( text )) || Number ( text ) > ( 1000000000 ) || Number ( text ) < ( zero ? 0 : 1 )) throw new Error ( title + '霂瑕‵� � ' + ( zero ? '� 噼� ' : '憭找� 0� � ' ) + '� 湔㺭嚗䔶� 撖孵‵1� � ' );
return Number ( text );
}
function stockCountField ( pocket , value = '' ,{ name = 'stockCount' , title = '� 箏� � 圈� 嚗� 笆嚗� ' , optional = false , visible = pocketCountsEnabled ( pocket ), help } = {}){
const hint = help ?? ( optional ? '� � 蟮� 芾扇敶訫笆� 堆� � 臭� � 嗵征� 踝� 銝舘恣撌亥晶隞嗆㺭� � � 憛怠� � � ' : '銝舘恣撌亥晶隞嗆㺭� � � 憛怠� � � ' );
return `<label class="stock-count-field" data-stock-count-field ${ visible ? '' : 'hidden' } > ${ e ( title ) } <input name=" ${ e ( name ) } " value=" ${ e ( value ?? '' ) } " type="number" min="1" max="1000000000" step="1" inputmode="numeric" ${ visible ? '' : 'disabled' } ${ visible &&! optional ? 'required' : '' } placeholder="銝� 撖孵‵1"> ${ hint ? '<small class="muted">' + e ( hint ) + '</small>' : '' } </label>` ;
}
function syncStockCountField ( root ,{ pocket , name = 'stockCount' , visible = pocketCountsEnabled ( pocket ), optional = false } = {}){
const input = root ? . querySelector ? .( '[name="' + name + '"]' ); if ( ! input ) return ;
const label = input . closest ( 'label' ); if ( label ) label . hidden =! visible ;
input . disabled =! visible || busy ||!! pending () || root . dataset ? . stale === 'true' ; input . required = visible &&! optional ;
}
function stockCountText ( value ,{ signed = false , unknown = '� 芾扇敶訫笆� � ' } = {}){ return Number . isSafeInteger ( value ) ? ( signed && value > 0 ? '+' : '' ) + value + '撖� ' : unknown ;}
function inventoryCountHTML ( item ,{ signed = false } = {}){ return Number . isSafeInteger ( item ? . stockCount ) ? `<div class="small stock-count-number"> ${ e ( stockCountText ( item . stockCount ,{ signed } ))}</div>` : pocketCountsEnabled ( item ? . pocket ) ? '<div class="small muted">� 芾扇敶訫笆� � </div>' : '' ;}
function inventoryBalanceCountHTML ( item ){ return item ? . countUnit === 'pair' || pocketCountsEnabled ( item ? . pocket ) ? `<div class="stock-count-number"> ${ e ( stockCountText ( item ? . count )) } </div>` : '' ;}
function legacyCountConfirmationHTML ( value ){ return value ? . requiresLegacyCountVerified ? `<div class="note"> ${ e ( value . legacyCountNotice || '餈嗵� � � 蟮霈啣� � 芾扇敶訫笆� 堆� 敶枏� 撖寞㺭� 匧� � � � � 孵抅� � � � 踺� � 𧋦甈⊥唂� 漤� � 脣� 銝滩䌊� 冽凒� 孵� � 滚笆� 堆� 憒� � � 拇� � 睃� 霂瑕𡖂� 𡁜� 憭拙笆� 啗� � 氬� � ' ) } </div><label class="check"><input name="legacyCountVerified" type="checkbox" required>撌脫瓲撖孵� � 滚笆� 啣抅� � � � � 圾� 祆活� 湔迤撖孵� � 脣笆� 啁� 憭� � </label>` : '' ;}
function requireLegacyCountConfirmation ( form , value ){ if ( ! value ? . requiresLegacyCountVerified ) return {}; if ( ! form . querySelector ( '[name="legacyCountVerified"]' ) ? . checked ) throw new Error ( '霂瑟瓲撖孵� � 滚笆� 啣抅� � � 撟嗅㗲� 匧� � 脣笆� 啁&霈扎� � ' ); return { legacyCountVerified : true };}
2026-11-08 03:30:58 +08:00
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>` ;
2026-11-14 01:16:35 +08:00
const choice = ( title , name , values , selected )=>{
// 靽格㺿� � 蟮霈啣� � 嗡� � 坔� � 𦦵鍂� 睃極嚗𥟇鰵憓鮋� 㗇𥋘� 𡑒”� 芸� � 怠鍳� 典� 撌乓� �
if ( selected && teamMemberKeys (). includes ( selected ) &&! teamMemberEnabled ( selected ) && values . some ( value => teamMemberKeys (). includes ( Array . isArray ( value ) ? value [ 0 ] : value )) &&! values . some ( value =>( Array . isArray ( value ) ? value [ 0 ] : value ) === selected )) values = [... values ,[ selected , teamMemberName ( selected ) + '嚗� 歇� 𦦵鍂 繚 � 蠘扇敶𤏪� ' ]];
return `<label> ${ e ( title ) } <select name=" ${ name } "> ${ opts ( values , selected ) } </select></label>` ;
};
2026-10-17 19:50:24 +08:00
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 ( '� 餃� 韐血噡撌脣� � g� 霂瑕� � 啣� 蝏抒賒嚗𥕦� � 滢� 撌脫� � 栶� � ' ),{ 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-14 01:16:35 +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' , '/api/shop-settings' , '/api/employees' ]. includes ( url ) || [
2026-11-08 03:30:58 +08:00
/^\/api\/pockets\/[^/]+\/update$/ ,
2026-11-14 01:16:35 +08:00
/^\/api\/employees\/[^/]+\/(?:update|deactivate|reactivate|delete)$/ ,
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嚗� � � 厩𠶖� � � � 恬� 銝滩� 霈咐SON閫� � 憭梯揖� 拍� 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 ( '� W � � � � 雿� ' , '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 = '� 餃� 撌脰� � � � 霂瑕� � 啣僎� 餃� 嚗� � � W� � � � 雿栶� � ' ;
else if ( ! err . confirmed && ( ! err . status || err . retryable )) err . message = '餈墧𦻖銝剜鱏嚗峕� 鈭斤� � 𨅯� 蝖株恕� � 窈� 嫖� 𨀣� 憭滚� � 滢� � 嘅� 銝滩� � 齿鰵撘� � 𨰻� � ' ;
else if ( ! err . confirmed ) err . message += ' � 𣂷漱蝏𤘪� 隞滚� 蝖株恕嚗諹窈靽萘� � � � 雿栶� � ' ;
}
throw err ;
2026-11-14 01:16:35 +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 (); if ( typeof applyEmployeeRestrictions === 'function' ) applyEmployeeRestrictions ();}
2026-10-17 19:50:24 +08:00
}
async function init (){
2026-11-14 01:16:35 +08:00
if ( typeof invalidateEmployees === 'function' ) invalidateEmployees ();
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 ;
2026-11-14 01:16:35 +08:00
if ( typeof applyShopBrand === 'function' ) applyShopBrand ();
2026-10-17 19:50:24 +08:00
const intro = session . mode === 'demo' ? '� 刻� � � 恥� 閧� 銋惩� � 湔� 蝔页� 瞍𠉛內� 唳旿銝擧鰵韐阡� 蝳颯� � ' : '� � 挽蝵株揭� 瑯� � � � 齿糓� 祆㦤霂閧鍂嚗峕迤撘譍� 蝡臬� 韐血𡖂銵屸� 蝵柴� � ' ;
2026-11-14 01:16:35 +08:00
const options = session . loginOptions || [{ member : 'owner' , loginName : '暻阡漲' , label : '暻阡漲' },{ member : 'assistant' , loginName : '� 拍� 1' , label : '憡𨅯� ' },{ member : 'assistant2' , loginName : '� 拍� 2' , label : '撠𤩺� ' }];
$ ( '#login' ). innerHTML = `<section class="login-wrap"><div class="brand-mark"> ${ e ( Array . from ( shopBrandName ())[ 0 ] || '摨� ' ) } </div><h1> ${ e ( shopBrandName ()) } 繚 � 啗揭蝟餌� </h1><p class="muted"> ${ session . setup || session . mode === 'demo' ? intro : '敶訫� � � 𤣰甈曆� 憭齿瓲嚗䔶� � 䔶� 撘㰘恥� 訫� 憪卝� � ' } </p><div id="login-error"></div> ${ session . mode === 'demo' ? options . map ( row => button ( e ( '隞� ' + row . label + '頨思遢餈𥕦� 瞍𠉛內' ), 'demo-' + row . member , row . member === 'owner' ? 'primary' : '' )). join ( '' ) : 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' , options . map ( row =>[ row . loginName , row . label + '嚗� ' + row . loginName + '嚗� ' ]), options [ 0 ] ? . loginName ) }${ 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-14 01:16:35 +08:00
async function refresh ( renderPage = true , stillCurrent ){ const latest = await api ( '/api/state' ); if ( stillCurrent &&! stillCurrent ()) return ; state = latest ; if ( typeof applyShopBrand === 'function' ) applyShopBrand (); $ ( '#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
}
2026-11-14 01:16:35 +08:00
const legacyTeamMembers = [{ member : 'owner' , label : '暻阡漲' },{ member : 'assistant' , label : '憡𨅯� ' },{ member : 'assistant2' , label : '撠𤩺� ' }];
function teamMemberCatalog (){ const rows = state ? . members ? . length ? state . members : state ? . shopSettings ? . members ? . length ? state . shopSettings . members : legacyTeamMembers ; return rows . filter ( row => row && typeof row . member === 'string' );}
function teamMemberKeys (){ return teamMemberCatalog (). map ( row => row . member );}
function teamMemberEnabled ( member ){ return teamMemberCatalog (). find ( row => row . member === member ) ? . enabled !== false && teamMemberKeys (). includes ( member );}
function activeTeamMemberKeys (){ return teamMemberKeys (). filter ( teamMemberEnabled );}
function assistantMemberKeys (){ return teamMemberKeys (). filter ( member => member !== 'owner' );}
2026-10-25 14:19:24 +08:00
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-14 01:16:35 +08:00
function teamMemberName ( member ){ return state ? . shopSettings ? . members ? . find ( row => row . member === member ) ? . label || state ? . members ? . find ( row => row . member === member ) ? . label || session ? . loginOptions ? . find ( row => row . member === member ) ? . label || ({ owner : '暻阡漲' , assistant : '憡𨅯� ' , assistant2 : '撠𤩺� ' })[ member ] || '敺� &霈� ' ;}
function shopBrandName (){ return state ? . shopSettings ? . storeName || state ? . printing ? . store || session ? . brand ? . storeName || '� 惩� � 啗揭' ;}
function shopFeeDefaults (){ return { certificate : '4' , packaging : '3' , shipping : '6' , packagingPayer : 'owner' ,... state ? . shopSettings ? . feeDefaults };}
function configuredCreditCardRate (){ return state ? . shopSettings ? . creditCardRatePermille ?? 6 ;}
function creditCardPreviewRate ( root ){
if (( root ? . id === 'order-credit-card-fee' || tab === 'order-edit' ) && tab === 'order-edit' && typeof orderEditEntry !== 'undefined' ) return orderEditEntry ? . order ? . credit_card_rate_permille ?? configuredCreditCardRate ();
if ( root ? . id === 'order-credit-card-fee' && editDraft ? . id ) return editDraft . credit_card_rate_permille ?? configuredCreditCardRate ();
if ( root ? . id === 'action-credit-card-fee' ) return currentOrder ? . credit_card_rate_permille ?? configuredCreditCardRate ();
if ( root ? . id === 'lock-create-card-fee' && typeof priceLockEditEntry !== 'undefined' && priceLockEditEntry ) return priceLockEditEntry . lock ? . credit_card_rate_permille ?? configuredCreditCardRate ();
if ( root ? . id === 'lock-delivery-card-fee' && typeof currentPriceLock !== 'undefined' ) return currentPriceLock ? . credit_card_rate_permille ?? configuredCreditCardRate ();
return configuredCreditCardRate ();
}
function currentSalesperson (){ return state ? . shopSettings ? teamMemberName ( currentMember ()) : session ? . user ? . name || state ? . user ? . name || state ? . user ? . label || session ? . user ? . label || teamMemberName ( currentMember ());}
function memberAccountPrefix ( member ){ return ({ owner : '暻阡漲' , assistant : '� 拍� ' , assistant2 : '� 拍� 2' })[ member ] || member ;}
function accountIdentity ( value ){ const text = String ( value ?? '' ); for ( const member of teamMemberKeys ()){ const prefixes = member === 'assistant' ? [ '� 拍� ' , '� 拍� 1' ] : [ memberAccountPrefix ( member )]; for ( const prefix of prefixes ) if ( text === prefix ) return { member , prefix , channel : '' }; else if ( text . startsWith ( prefix ) && [ '敺桐縑' , '� 臭� 摰� ' , '� 圈� ' , '靽∠鍂� � ' ]. includes ( text . slice ( prefix . length ))) return { member , prefix , channel : text . slice ( prefix . length )};} return null ;}
function accountDisplayName ( value ){ const account = accountIdentity ( value ); return account ? teamMemberName ( account . member ) + account . channel : value ;}
function activePaymentAccounts ( selected = '' ){ const values = [... new Set (( state ? . accounts || []). map ( normalizePaymentAccount ))]. filter ( value =>{ const member = accountIdentity ( value ) ? . member ; return ! member || teamMemberEnabled ( member ) || value === selected ;}); if ( selected &&! values . includes ( selected )) values . push ( selected ); return values ;}
2026-11-10 22:29:17 +08:00
function actorDisplayName ( value ){ return [ '� 拍� ' , '� 拍� 1' , '� 拍� 2' ]. includes ( value ) ? accountDisplayName ( value ) : value ;}
2026-11-14 01:16:35 +08:00
function teamMemberOptions ( assistantFirst = false ,{ historical = false , selected = '' } = {}){ let keys = ( historical ? teamMemberKeys () : activeTeamMemberKeys ()). filter ( member => teamMode () || member !== 'assistant2' ); if ( assistantFirst ) keys = [... keys . filter ( member => member !== 'owner' ),... keys . filter ( member => member === 'owner' )]; const options = keys . map ( member =>[ member , teamMemberName ( member ) + ( historical &&! teamMemberEnabled ( member ) ? '嚗� 歇� 𦦵鍂嚗� ' : '' )]); if ( selected && teamMemberKeys (). includes ( selected ) &&! keys . includes ( selected )) options . push ([ selected , teamMemberName ( selected ) + '嚗� 歇� 𦦵鍂 繚 � 蠘扇敶𤏪� ' ]); return options ;}
function teamDataKeys ( data ){ return [... assistantMemberKeys (), 'owner' ]. filter ( member => data && Object . hasOwn ( data , member ));}
2026-10-25 14:19:24 +08:00
function teamDefaultPayer (){ return teamMode () ? orderFormMember () : 'assistant' ;}
function orderMemberField ( member = currentMember (), locked = false ){
if ( ! teamMode ()) return '' ;
2026-11-14 01:16:35 +08:00
const selected = teamMemberKeys (). includes ( member ) ? member : currentMember ();
2026-10-25 14:19:24 +08:00
return state . user . role === 'owner' &&! locked ? choice ( '霈W� 敶鍦� 嚗� � � 交狡銝𦒘� 蝏抬� ' , 'member' , teamMemberOptions (), selected ) : `<label>霈W� 敶鍦� 嚗� � � 交狡銝𦒘� 蝏抬� <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-14 01:16:35 +08:00
function peoplePartMember ( part ){ return part === 'assistant1' ? 'assistant' : part ;}
function peopleParts ( historical = false ){ const keys = assistantMemberKeys (). filter ( member => historical || teamMemberEnabled ( member )), parts = keys . map ( member =>[ member === 'assistant' ? 'assistant1' : member , teamMemberName ( member ) + '鈭箸㺭' ]); return state ? . user ? . role === 'assistant' && teamMode () ? parts . filter (([ key ])=> peoplePartMember ( key ) === currentMember ()) : parts ;}
function memberFilterHTML ( id , selected = '' ){ return state . user . role === 'owner' && teamMode () ? `<label class="member-filter">霈W� 敶鍦� <select id=" ${ e ( id ) } "> ${ opts ([[ '' , '� 券� � 𣂼� ' ],... teamMemberOptions ( false ,{ historical : true } )],selected)}</select></label>` : '' ;}
2026-10-25 14:19:24 +08:00
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 );}
2026-11-14 01:16:35 +08:00
function defaultPaymentRecipient (){ const member = teamMode () ? orderFormMember () : 'assistant' ; return memberAccountPrefix ( teamMemberEnabled ( member ) ? member : 'owner' );}
2026-10-25 14:19:24 +08:00
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 () + '敺桐縑' );
2026-11-14 01:16:35 +08:00
const card = isCreditCardAccount ( account ), identity = accountIdentity ( account ), prefix = identity ? memberAccountPrefix ( identity . member ) : defaultPaymentRecipient ();
const recipients = teamMemberOptions ( ! teamMode ()). map (([ member , name ])=>[ memberAccountPrefix ( member ), name ]);
if ( identity &&! teamMemberEnabled ( identity . member )) recipients . push ([ prefix , teamMemberName ( identity . member ) + '嚗� 歇� 𦦵鍂 繚 � 蠘扇敶𤏪� ' ]);
return choice ( '� 嗆狡� 孵� ' , 'payment_method' , methods , identity ? . channel || '敺桐縑' ) + `<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' } >靽∠鍂� ∠� 銝� � � ${ e ( teamMemberName ( 'owner' )) } � 嗆狡� � </small>`: '' } </label>` ;
2026-10-25 14:19:24 +08:00
}
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 = '摰X� 隞䀹狡� 煾� ' ){
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">� 芸𢆡霈∠� 繚 摰X� � 閙旿銝齿遬蝷� </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 || '摰X� 隞䀹狡� 煾� ' , 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-11-14 01:16:35 +08:00
try { const rate = creditCardPreviewRate ( root ), amount = CreditCardFees . amount ( cents , rate ); field . value = ( amount / 100 ). toFixed ( 2 ); note . textContent = ` ${ basis } 瞼 ${ yuan ( cents ) } � ${ rate } � � = 瞼${ yuan ( amount ) } � � 恣� 亙� � 冽� � 穿� 摰X� 隞䀹狡� 煾� 銝滚� 嚗偦� � 甈曆� � � � 𧼮歇� 𤑳� � � � 蝏剛晶� � ;return amount;}
catch{field.value='';note.textContent=` 憛怠 � 摰X � 隞䀹狡 � 煾 � � 舘䌊 � 刻恣蝞 � $ { creditCardPreviewRate ( root )} � 唳 � 蝏剛晶嚗𥕢 � 甈曆犖暺䁅恕$ { teamMemberName ( 'owner' )} 嚗 � 虾 � 匧 � � � 耨 � 嫘 � � ; 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' )};}
2026-11-14 01:16:35 +08:00
function purchasePayerField ( title , name , value ){ return `<label class="purchase-payer"> ${ e ( title ) } <select name=" ${ e ( name ) } " required> ${ teamMemberKeys (). includes ( value ) ? '' : '<option value="" disabled selected>霂琿� 㗇𥋘</option>' }${ opts ( teamMemberOptions ( false ,{ selected : value } ),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 } � � � � � � 煾� 銝滢� 敶𤘪� 瘥誩� � 嗘遠嚗𥕦� � X� � 见� 霂瑕‵� 坔� � � � 韐扳� 隞瑯� � ;
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 !== '' ? '嚗𥟇� � 𧢲� 隞瑕歇靽萘� 嚗� � � 宐� 舀� 憭� ' : '' } � � ) : '� 湔𦻖憛怠� � 祈� � 餃極韐嫘� � ' ; 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
// � 折△� Z䌊� 冽� 摮条� 蝛箇蒾銵𣬚凒� 乩蝙� 冽鰵銵典� 嚗𥕦歇蝏誩‵� 嗵� � 扳𥁒隞瑚� � 坔� � 煾� � �
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 15:47:07 +08:00
return `<div class="line-item" data-legacy=" ${ legacy ? 'true' : 'false' } " data-historical-pocket=" ${ options . historicalPocket ? 'true' : 'false' } " data-count-original-pocket=" ${ e ( options . historicalPocket ? l . pocket || '' : '' ) } " data-count-original-quantity=" ${ e ( options . historicalPocket ? l . quantity ?? '' : '' ) } " data-count-historical-unknown=" ${ options . historicalPocket && l . stockCount == null ? '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 ( '� � � 桀� 隞瑁秩� 𠬍� 摰X� � 航� 嚗� ' , '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-10 02:54:58 +08:00
<div class="internal"><div class="internal-title">� � � � 鞉𧋦 繚 摰X� � 閙旿銝齿遬蝷� </div><div class="grid two cost-source-fields"> ${ pocketChoice ( '� 箏� 韐抒� 嚗� � 暺� � 嚗� ' , 'pocket' , l . pocket ?? ( name === '頞喲� 999' ? '� 啗揮' : '' ),{ historical :!! options . historicalPocket } )} ${ stockCountField ( l . pocket ?? ( name === '頞喲� 999' ? '� 啗揮' : '' ), l . stockCount ,{ optional :!! options . historicalPocket && l . stockCount == null } )} ${ legacy ? choice ( '韐批� � 鞉𧋦� 梯� � 思� ' , 'payer' , teamMemberOptions (), l . payer || 'owner' ) : '' } </div> ${ options . materialPool &&! options . historicalPocket && typeof returnedStockLotChoiceHTML === 'function' ? returnedStockLotChoiceHTML ( l ) : '' }
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-11-14 01:16:35 +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' , shopDefaults : shopFeeDefaults ()}),... 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-11-14 01:16:35 +08:00
if ( ! draft . id &&! draft . fee_auto_initialized &&! items . some ( f => f . key === 'shipping' )) items . unshift ({ key : 'shipping' , note : '敹恍� 坿晶' , amount : shopFeeDefaults (). shipping , payer : teamDefaultPayer (), status : 'estimated' , edited : false });
return '<section class="panel internal"><div class="panel-title"><h2>摰鮋� 韐寧鍂嚗� � � 剁� </h2>' + button ( '嚗� 瘛餃� � 嗡� � 鞉𧋦' , 'add-fee' ) + '</div><p class="small muted">' + ( tab === 'order-edit' ? '隞乩� � 匧� � 齿� � � 晶� 刻扇敶閖� 憛恬� 瘥讐� 靽萘� � � 𣈲隞䀹𠯫� 麄� � 芦� 朞晶� 典虾� 匧鐯� 桐耨� 對� 靽∠鍂� ⊥� 蝏剛晶� 煾� � 峕𠯫� 蠘䌊� 函輕� 歹� � 芸虾靽格㺿隞䀹狡鈭箝� � ' : '' ) + '銝𦠜䲮� � � 憿寧𤌍� 芸𢆡撣血� � 鞉𧋦� � � 銋阡� 霈� ' + e ( shopFeeDefaults (). certificate ) + '� � � � � 鋆� ' + e ( shopFeeDefaults (). packaging ) + '� � � � � � 暺䁅恕� � ' + e ( teamMemberName ( shopFeeDefaults (). packagingPayer )) + '隞䀹狡嚗𥕦翰� 埝� � 游� 暺䁅恕' + e ( shopFeeDefaults (). shipping ) + '� � � � � 虾靽格㺿� � 窈憛怠� 摰鮋� 撌脖� � 煾� 嚗峕瓷� 㗇� � 砍‵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="隞� � � � � 頝蠘� 嚗䔶� 隡𡁜枂� 啣銁摰X� � � � 桀� � 𡝗� � 唬辣銝� "> ${ 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-11-08 15:47:07 +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 . stockCount &&! 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-14 01:16:35 +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' ? '撌脣� � 嗡蛹� 芯� 摮条� � 桅� 朞恥� 𤏪� 摰X� 蝘啣鐤撌脩� 蝛箝� � � � � 遠� 嗡� 甈曆� � 烐� � 唾� 銝滚蒂� 伐� 霂琿� � 啣‵� 蹱𧋦甈⊥芦� 𡁻� � 桃� � 躰晶撟園� 㗇𥋘隞䀹狡鈭綽� � 齿瓲撖寞𥁒隞瑕� 韐寧鍂� � ' : '撌脣� � 嗡蛹� 芯� 摮条� � 啗恥� 𤏪� 摰X� 蝘啣鐤撌脩� 蝛箝� � 瓲撖寞𧋦甈∪� � 溻� � 𥁒隞瑯� � 晶� 典� � 嗆狡韐行� � 𠬍� � 滨� � 鞾� � 桀� � 柴� � ' ) + '</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>摰X� 銝𤾸� � � </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 ( '摰X� 蝘啣鐤嚗譍誨� 瘀� 敹� ‵嚗� ' , 'customer' , draft . customer || '' , 'text' , 'required maxlength="60" placeholder="� 嫣噶� 曉� 霈W� � 喳虾"' ) }${ field ( '撘� � 蓥犖嚗� � 憛恬� ' , 'salesperson' , draft . salesperson || currentSalesperson (), '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>摰X� � 訫� 瘜� <textarea name="note" maxlength="240" rows="2" placeholder="� 芸� � 航悟摰X� � 见� � � � 摰� "> ${ 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 loadReturnedStockLots === 'function' ) loadReturnedStockLots ( true ); 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 ;
2026-11-08 15:47:07 +08:00
if ( ! pocketCountsEnabled ( values . pocket ) || values . unit !== 'g' ) delete values . stockCount ;
else if ( String ( values . stockCount ?? '' ). trim () === '' ) values . stockCount = null ;
2026-10-17 19:50:24 +08:00
if ( row . dataset . legacy !== 'true' ) Object . assign ( values , readPurchaseCost ( row . querySelector ( '.cost-fields' )));
2026-11-10 02:54:58 +08:00
return typeof returnedStockLineInput === 'function' && row . querySelector ( '[name="returnedStockId"]' ) ? . value ? returnedStockLineInput ( row , values ) : values ;
2026-10-17 19:50:24 +08:00
}
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 );
2026-11-08 15:47:07 +08:00
const historicalUnknown = row . dataset . countHistoricalUnknown === 'true' && row . dataset . countOriginalPocket === el ( 'pocket' ). value && Number ( row . dataset . countOriginalQuantity ) === Number ( el ( 'quantity' ). value );
syncStockCountField ( row ,{ pocket : el ( 'pocket' ). value , visible : el ( 'unit' ). value === 'g' && pocketCountsEnabled ( el ( 'pocket' ). value ), optional : historicalUnknown });
2026-10-17 19:50:24 +08:00
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 );
2026-11-10 02:54:58 +08:00
if ( typeof syncReturnedStockCost === 'function' ) syncReturnedStockCost ( row );
2026-10-17 19:50:24 +08:00
}
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 ( '摰X� 蝘啣鐤嚗譍誨� 瑕� 憛恬� 霂瑕‵� � 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 + '� � � � 㵪� � 圈� ' );
2026-11-08 15:47:07 +08:00
if ( pocketCountsEnabled ( l . pocket ) && l . unit === 'g' ){
const original = typeof orderEditEntry !== 'undefined' && $ ( '#order-form' ) ? . dataset . orderEdit === 'true' ? orderEditEntry ? . originalInputs ? . lines ? .[ i ] : null ;
const historicalUnknown = original && original . stockCount == null && original . pocket === l . pocket && Number ( original . quantity ) === Number ( l . quantity );
stockCountValue ( l . stockCount ,{ optional :!! historicalUnknown , title : item + '� 箏� � 圈� 嚗� 笆嚗� ' });
}
2026-10-17 19:50:24 +08:00
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-11-14 01:16:35 +08:00
if ( ! [ 'material' , 'labor' ]. every ( key => teamMemberKeys (). 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 ( '� 齿鰵霂餃� 霈W� ' , '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 : '摰鮋� 霈W� � 拇隋' , value : '� 批� 敺� ‘朣� ' , hint : '� 唳� � 批� 撠𡁏𧊋摰峕� � � � 株扇韐佗� 銵仿� 甈暸★� � 揮� � � � 砌� 韐寧鍂� 舘恣蝞堒� � � ⏚瘨艾� � ' };
2026-10-21 01:32:49 +08:00
return { title : o . status === 'delivered' ? '摰鮋� 霈W� � 拇隋' : '霈W� � � � 拇隋' , 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 ;
}
2026-11-14 01:16:35 +08:00
const orderEntryTimeFormatter = new Intl . DateTimeFormat ( 'zh-CN' ,{ timeZone : 'Asia/Shanghai' , year : 'numeric' , month : '2-digit' , day : '2-digit' , hour : '2-digit' , minute : '2-digit' , hourCycle : 'h23' });
function orderEntryTime ( value ){
// created � 舫� 甈∪� � 亥恥� 閧� � 笔� � 園𡢿嚗𥟇唂� 厩阮銵仿� � 𦒘� 靽萘� � 厩阮� 園𡢿嚗䔶� � 鍦� 甇� � 撘� � 閙𧒄� 氬� �
if ( typeof value !== 'string' ||! /^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d{1,3})?)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/ . test ( value ) ||! validOrderDate ( value . slice ( 0 , 10 ))) return '� 芾扇敶� ' ;
const date = new Date ( value ); if ( Number . isNaN ( date . getTime ())) return '� 芾扇敶� ' ;
const parts = Object . fromEntries ( orderEntryTimeFormatter . formatToParts ( date ). map ( part =>[ part . type , part . value ]));
return ` ${ parts . year } - ${ parts . month } - ${ parts . day } ${ parts . hour } : ${ parts . minute } ` ;
}
function orderEntryTimeHTML ( order ){ return `<div class="small muted order-entry-time">敶訫� � 園𡢿嚗� � 鈭祆𧒄� 湛� 嚗� ${ e ( orderEntryTime ( order . created )) } </div>` ;}
2026-10-17 19:50:24 +08:00
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-14 01:16:35 +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 '� � � 桐� � 拇隋� 匧� � 𤏪� 鈭支� � 交� 嚗� 睸� 𦒘� � 墧𤣰� 㕑扇敶閙𠯫� 毺� � 剹� � 芦� 朞恥� 閙𤣰甈暹遬蝷箏� � 滨敞霈∴� � � 遠� 園� � 甈暹� 摰鮋� � 𤑳� � 交� 霈∪� 嚗� � 鈭支� 銝滩恣� � � 桀� � 拇隋� � 歇� 𡝗� 霈W� 銝滩恣� 祇△� � � 格� � 鳴� � 湔𦻖� 墧𤣰隞䀹狡霈∪� 瘥𤩺𠯫韐剜� 嚗䔶� 霈⊿� � 桀� � 拇隋� � ' ;}
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 ( '摰X� ' , 'customer' , '' , 'text' , 'required maxlength="60" placeholder="摰X� 蝘啣鐤� 碶誨� � "' ) }${ 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 ){
2026-11-14 01:16:35 +08:00
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 );
2026-10-28 00:22:04 +08:00
}
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 ;
2026-11-14 01:16:35 +08:00
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 ( '� 桀� 霈啣� 韏� � � 芸� � 渲� � 痹� 霂琿� � 啗粉� 硋� � 滢耨� 嫘� � ' );
2026-10-28 00:22:04 +08:00
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 ;
}
2026-11-14 01:16:35 +08:00
function afterSaleStatus ( request ){ return { pending : '敺� � 銝餃恣� � ' , approved : '撌脣� � � ' , rejected : '撌脤底� � ' }[ request . status ] || '� 嗆� � � 蝖株恕' ;}
2026-10-28 00:22:04 +08:00
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 ( '摰X� ' , '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 ],[ '摰X� ' , record . customer ],[ '� 煾� ' , '瞼' + yuan ( record . amount )],[ '靚� 𣈲隞� ' , teamMemberName ( record . payer )],[ '霈W� 敶鍦� ' , 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 ? '� 𣂷漱靽格㺿� 唾窈' : '� 湔𦻖靽嘥� 靽格㺿' ;
2026-11-14 01:16:35 +08:00
if ( mode ) mode . textContent = approval ? '� 祆活靽格㺿� � 摨𦯀蜓摰⊥鸌� � � � 誩� � 齿凒� 啣睸� 舘晶� 典� � 拇隋嚗𥕦� 摰⊥鸌� 罸𡢿隞齿� � 蠘扇敶閗恣韐艾� � ' : state . user . role === 'owner' ? '靽嘥� � 𡒊凒� 交凒� 啗� 蝚𥪜睸� 𠬍� 韐寧鍂銝𤾸⏚瘨行� 靽格㺿� 𡒊� � 交� � 滨� � � ' : '� � 𠯫� 煺� 靽格㺿� 擧𠯫� 笔� 銝箔� 憭抬� � 湔𦻖靽嘥� 嚗𥟇㺿銝箏� 隞𡝗𠯫� 罸◆� 𣂷漱摨𦯀蜓摰⊥鸌� � ' ;
2026-10-28 00:22:04 +08:00
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 ();
2026-11-14 01:16:35 +08:00
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>` : '' ;
2026-10-28 00:22:04 +08:00
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 ( '摰X� ' , '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 ( '� W � � � � 雿� ' , '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 ( '� 桀� � 交� 霂琿� 㗇𥋘隞𠰴予� 碶� � 滨� � 㗇� � 交� � � ' );
2026-11-14 01:16:35 +08:00
if ( ! input . project || input . project . length > 100 ) throw new Error ( '� 桀� 憿寧𤌍霂瑕‵� � 1嚚� 100摮𨰜� � ' ); if ( ! input . customer || input . customer . length > 60 ) throw new Error ( '摰X� 霂瑕‵� � 1嚚� 60摮㛖� 蝘啣鐤� 碶誨� 瑯� � ' ); if ( ! teamMemberKeys (). includes ( input . payer )) throw new Error ( '霂琿� 㗇𥋘餈嗵� � 桀� � 梯� � 臭� � � ' ); if ( input . reason . length > 200 ) throw new Error ( '靽格㺿霂湔� � � 憭� 200摮𨰜� � ' ); LedgerCalc . cents ( input . amount , '� 桀� � 煾� ' );
2026-10-28 00:22:04 +08:00
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 ();
2026-11-14 01:16:35 +08:00
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">霈W� 敶鍦� 嚗� ${ 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>` ;
2026-10-28 00:22:04 +08:00
}
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 ){
2026-11-14 01:16:35 +08:00
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 ( '� 蠘扇敶訫歇� 匧� � 剁� 霂琿� � 啗粉� 硋僎� 詨笆� � ' );
2026-10-28 00:22:04 +08:00
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 ){
2026-11-14 01:16:35 +08:00
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 ( '霂琿� 㗇𥋘� 峕� � 㚚底� 𠺶� � ' );
2026-10-28 00:22:04 +08:00
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 ){
2026-11-14 01:16:35 +08:00
const operation = afterSaleOperation ( url ), update = operation . kind === 'update' , applied = update && result . applied === true , message = update ? ( applied ? '� 桀� 靽格㺿撌脖� 摮� ' : '� 桀� 靽格㺿� 唾窈撌脫� 鈭歹� 敺� � 銝餃恣� � ' ) : operation . kind === 'approve' ? '撌脣� � 誩睸� 𦒘耨� � ' : '撌脤底� 𧼮睸� 𦒘耨� 寧𤚗霂� ' ;
2026-10-28 00:22:04 +08:00
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-11-14 01:16:35 +08:00
return peopleParts ( true ). map (([ part , name ])=> `<div class="people-count-item"><strong> ${ e ( peopleCountDisplayName ( name , period )) } </strong><span> ${ e ( peopleCountText ( count , part )) } </span></div>` ). join ( '' ) + `<small> ${ period ? '� 祆� � � 憓痹� 蝏𤘪� � 交� 颱犖� 堆� � � 䌊撘� 憪𧢲𠯫� 齿� 餈𤏸扇敶閙� 颱犖� 堆� 蝻箔遙銝� 蝡臬� � 芰䰻嚗峕� � 交� 颱犖� 唬� 蝝臬� � � ' : '� � 䌊銝𦒘� 甈⊥� 霈啣� � 交� 瘥磰� 嚗峕𧊋霈啣� � 亥䌊� 刻歲餈� � 0銝箸� � � 扇敶𨰻� � ' } 銝漤� 霈W� � 𦦵揣銝𡒊𠶖� � � � 匧� � 硔� � </small>` ;
2026-10-25 14:19:24 +08:00
}
2026-11-14 01:16:35 +08:00
function peopleCountReportLines ( count ){ const period = count ? . from !== count ? . date ; return peopleParts ( true ). map (([ part , name ])=> ` ${ peopleCountDisplayName ( name , period ) } 嚗� ${ peopleCountText ( count , part ) }${ period ? '嚗� � � � ' + ( count ? . date || '� 芰䰻' ) + '嚗𥕦� 憪𧢲𠯫� 齿� 餈𤏸扇敶� ' + ( count ? .[ part ] ? . baselineDate || '� � � ' ) + '嚗� ' : '' } ` );}
2026-10-29 00:27:36 +08:00
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-11-14 01:16:35 +08:00
const parts = peopleParts ( true ), rows = result . rows . filter ( row => parts . some (([ part ])=> row [ part + 'Count' ] !== null && row [ part + 'Count' ] !== undefined ));
2026-10-26 14:44:07 +08:00
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 ( '瘥𤩺𠯫鈭箸㺭韏� � � 芸� � 渲� � 痹� 霂琿� � 唳䰻霂U� � ' );
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-11-14 01:16:35 +08:00
const parts = peopleParts ( true ), names = parts . map (([ part ])=> part + 'Count' ), previous = {};
2026-10-29 00:27:36 +08:00
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 ( '瘥𤩺𠯫� 颱犖� 唳� � 睃� 韏� � 銝滚� � 湛� 霂琿� � 唳䰻霂U� � ' );
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-14 01:16:35 +08:00
function afterSalePayerName ( row ){ return row . costItems ? .[ 0 ] ? . payer ? teamMemberName ( 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-11-10 02:54:58 +08:00
if ( row . kind === 'orderAfterSale' ) return `<button class="link-button order-book-link order-book-customer-first" data-action="open-order" data-id=" ${ e ( row . order_id || row . id ) } "><strong class="order-book-customer-name"> ${ e ( row . customer || '� 芸‵蝘啣鐤' ) } </strong><span class="order-book-secondary muted">霈W� � 桀� 繚 ${ e ( row . paper_number || row . number ) } </span><span class="small muted">� 亦� � 笔� � 桀� 蝏𤘪� </span></button>` ;
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 || '摰X� ' ) } � � � � 嗅� "` ) } ` ;
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-11-10 02:54:58 +08:00
function orderIsReviewed ( row ){ return ! [ 'afterSale' , 'orderAfterSale' , '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-10 02:54:58 +08:00
$ ( '#main' ). innerHTML = heading ( 'ORDER BOOK' , '霈W� ' , '� 㗇𠯫� � 䰻� 钅� � 株恥� 𨰻� � � � 嗡� � 桀� 嚗𣬚� � 餃恥� 瑟䰻� 𧢲� 蝏� � � ' , 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="霈W� � 交� "> ${ 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="� � � 霈W� � 交� "></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="霈W� 撘� 憪𧢲𠯫� � "></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="霈W� 蝏𤘪� � 交� "></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="� 𦦵揣霈W� 嚗� � � 瑯� � 恥� 瑯� � � � � � � 钅� 嚗� " 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' } >� � 鉄� � � 㕑揮� 条� 霈W� 嚗屸� 憸脲� � 游� 瘙� � 颯� � � 隞瑕� � � 𤣰隞睃躹隞齿� � 交� � 曄內� � </p><div id="order-list" aria-live="polite"></div><p class="small muted order-book-footnote">� � � 格� � 蠘扇韐行𠯫靽萘� 嚗諹恥� 訫睸� 舘� � 游� � 祉� � 桀� 韐寧鍂� 匧睸� 擧𠯫� 蠘恣� 亙⏚瘨艾� � 歇� 𡝗� 霈W� 銝滩恣瘙� � 鳴� � � 𤣰� � 甈整� � 晶� 典� 雿𨅯� � 脣� � 𡒊� 靽萘� � 冽� � 亙笆韐艾� � � � 桀� � 滚� 霈∩� � 恍𣂎擖啣� � 湔𦻖� 墧𤣰嚗� � 銵䔶� � 曄內摰鮋� � 钅� 嚗𥕢辣� 啁� 撣詨� 霈~� � 唂� 厩阮� 乩遠銝滩恣� 亙� 霈~� � </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 = [ '霈W� � 圈� ' , '� 拇隋' , '� 嗆狡' , '� 鞉𧋦' ]. 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 || '� � � 㗇𠯫� � ' ) + '霈W� � � </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 = [ '霈W� � 圈� ' , '� 拇隋' , '� 嗆狡' , '� 鞉𧋦' ]. 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>' ;
2026-11-10 02:54:58 +08:00
if ( row . kind === 'orderAfterSale' ) return '<div class="order-fee-parts"><span>� 笔� � 桀� � 鞉𧋦靚� 㟲</span></div>' ;
2026-10-17 19:50:24 +08:00
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 ( '霈W� 瘙� � 餅㺭� 桀� � 芸� � 渲� � 痹� 霂瑕� � 啣� � 齿鰵霂餃� � � ' );
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-11-10 02:54:58 +08:00
const detailList = { version :++ orderBookDetailVersion , request : orderBookRequest , user : orderDetailUser (), scope : orderDetailFilterScope (), element : $ ( '#order-list' ), ids : [... new Set ( book . rows . filter ( row => ! [ 'afterSale' , 'orderAfterSale' ]. includes ( row . kind ) && 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-14 01:16:35 +08:00
const costDetails = `<div class="order-stat-lines"> ${ ( teamMode () ? teamMemberKeys () : [ 'owner' , 'assistant' ]). map ( member => `<span><b> ${ e ( teamMemberName ( member )) } </b><span> ${ orderBookSummaryAmount ( s , member + 'Cost' ) } </span></span>` ). join ( '' ) } </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 ;}
2026-11-14 01:16:35 +08:00
$ ( '#order-list' ). innerHTML = `<div class="table-wrap order-book-table-wrap"><table class="order-book-table" aria-label=" ${ e ( range . name ) } 霈W� 韐行𧋦"><thead><tr><th class="order-index">摨誩噡</th><th>摰X� 嚗誯� � 柴� � � � 嗆� � 桀� </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=" ${ [ 'afterSale' , 'orderAfterSale' ]. includes ( row . kind ) ? '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> ${ ! [ 'afterSale' , 'orderAfterSale' , 'recovery' ]. includes ( row . kind ) ? orderEntryTimeHTML ( row ) : '' }${ showOrderCopyEntry &&! [ 'afterSale' , 'orderAfterSale' , '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 ) } 銝箸鰵霈W� "` ) : '' }${ 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 ){
2026-11-10 02:54:58 +08:00
if ( typeof invalidateOrderAfterSaleForm === 'function' ) invalidateOrderAfterSaleForm ();
2026-10-23 09:49:36 +08:00
++ 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 ? '霈W� � 𡑒”撌脣� � 吔� 霂瑁� � 𧼮� 銵券� � 唳� 撘� � � ' : loading ? '甇� 銁霂餃� 霈W� 嚗� � � 滚� � 格� � 嗡� � 踺� � ' : busy ? '甇� 銁靽嘥� 嚗諹窈摰峕� � 𤾸� � U� � ' : pending () ? '霂瑕� � W� � � � 雿頣� � 滚� � Z恥� 𨰻� � ' : '� 匧� � 滨� � 匧� � � � � 株恥� 閖◇摨𤩺䰻� � ' ;
const retryBlocked = busy ||!! pending () || loading ||!! orderDetailRetry ? . navigation &&! orderDetailNavigationValid ( orderDetailRetry . navigation );
return `<div class="order-detail-navigation-row" role="group" aria-label="� � 揢霈W� "> ${ 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 + '� ∟恥� � ' : '瘝⊥� � 臬� � Y � 霈W� � 𡑒”' } "> ${ 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 ) } 敶枏� 霈W� 撌脖� � 踺� � ${ 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 ( '甇� 銁靽嘥� 嚗諹窈摰峕� � 𤾸� � � 揢霈W� � � ' );
if ( pending ()) refuse ( '霂瑕� � 孵稬憿園� � 𨀣� 憭滚� � 滢� � 嘅� 蝖株恕銝𦠜活� 𣂷漱蝏𤘪� � 𤾸� � � 揢霈W� � � ' );
if ( orderCopyLoading || typeof orderEditLoading !== 'undefined' && orderEditLoading ) refuse ( '甇� 銁憭� � 霈W� 嚗諹窈蝔滚� 坔� � � 揢� � ' );
if ( $ ( '#detail-form' ) ? . querySelector ? .( 'form' )) refuse ( '敶枏� � 㗇𧊋� 嗉絲� � ‵� 坔� 摰對� 霂瑕� 靽嘥� � 𡝗𤣰韏瘀� � 滚� � Z恥� 𨰻� � ' );
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 ( '� 毺� � 厩� 霈W� � 𡑒”撠𡁏𧊋霂餃� ' );
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 = '敶枏� 霈W� 撌脖� � 典� 蝑偦� 厩� � 靝葉嚗諹窈餈𥪜� � 𡑒”� 㗇𥋘� 嗡� � 閙旿� � ' ; 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 ();
// � 芣� 霈W� 韐行𧋦� 𣬚� � 曉� � 亙藁蝏穃� � 𡑒”嚗𥕦恣� 嫘� � 𥁒銵典� � � 遠� 亙藁銝齿窒� 其� � 滨� 憿箏� � �
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' ? '霈W� 霂餃� 頞� 𧒄嚗諹窈� 滩� � � ' : 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 ( '甇� 銁憭� � 霈W� 嚗諹窈蝔滚� 坔� 憭滚� � � ' );
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 ( '撌脫� � 𣂷漱甇� 銁憭� � � 𣇉� � 𨅯� 蝖株恕嚗諹窈� W� � � � 雿𨅯� � 滚� � 嗚� � ' );
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-11-14 01:16:35 +08:00
if (( unreadable || OrderCopy . hasDraftContent ( saved ,{ today : latest . today , salesperson : currentSalesperson ()})) &&! 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 ;
2026-11-14 01:16:35 +08:00
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 => teamMemberKeys (). includes ( part . payer ) && Number . isSafeInteger ( part . amount ) && part . amount >= 0 ) && ( value . materialAmount === null || value . allocations . reduce (( sum , part )=> sum + part . amount , 0 ) === value . materialAmount );
2026-11-02 19:30:28 +08:00
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">摰X� � 訫� 瘜剁� </span>${e(o.note)}</p>`:''}</section>`;
}
function orderCostRowsHTML ( rows , label ){
2026-11-14 01:16:35 +08:00
const names = Object . fromEntries ( teamMemberKeys (). map ( member =>[ member , teamMemberName ( member )]));
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 } = {}){
2026-11-10 02:54:58 +08:00
if ( typeof orderAfterSaleRecord === 'function' && orderAfterSaleRecord ( o )) return orderAfterSaleCostsHTML ( o );
2026-10-23 09:49:36 +08:00
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 );
// � � 恣雿輻鍂霈W� � � � � 鞉𧋦� � 唂� 訫� 憿嫣� � 駁� 銝滢� � 湔𧒄嚗峕� 靽嘥� � � 揮� � � 韐寧鍂� � 恣撅閧內� �
const terms = rowTotal === knownTotal ? numbers : [ knownGoods , paidFees ]. filter ( amount => amount !== 0 );
const equation = ( terms . length ? terms : [ 0 ]). map ( amount => '瞼' + yuan ( amount )). join ( ' 嚗� ' );
2026-11-14 01:16:35 +08:00
const payerTotals = Object . fromEntries ( teamMemberKeys (). map ( member =>[ member , 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 } = {}){
2026-11-10 02:54:58 +08:00
if ( typeof orderAfterSaleRecord === 'function' && orderAfterSaleRecord ( o )) return orderAfterSaleProfitHTML ( o );
2026-10-23 09:49:36 +08:00
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' ? '� 𡝗� � 𤾸� 憸� ' : '摰鮋� 霈W� � 拇隋' ;
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">� � � 鈭日� 憸苷� 霈⊥� � � � � 殷� � 芷� � 皜� � 摰X� 甈曉𡖂� 冽𤣰� � 甈曇扇敶蓥葉� 詨笆� � </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 ) ? '� 笔枂摨栞揮� � ' : '� 餉扇韐抒� ' ;
2026-11-08 15:47:07 +08:00
return `<span class="detail-line-pocket"> ${ e ( title ) } 嚗� ${ e ( pocket ) }${ Number . isSafeInteger ( line . stockCount ) ? ' 繚 ' + e ( stockCountText ( line . stockCount )) : pocketCountsEnabled ( line . pocket ) ? ' 繚 � 芾扇敶訫笆� � ' : '' } </span>` ;
2026-10-25 14:19:24 +08:00
}
2026-11-08 15:47:07 +08:00
function syncReturnCounts ( form = $ ( '#action-form' )){ if ( ! form || form . dataset . kind !== 'return' ) return ; currentOrder ? . lines ? . forEach (( line , index )=>{ const pocket = form . querySelector ( '[name="return-' + index + '"]' ) ? . value , input = form . querySelector ( '[name="returnCount-' + index + '"]' ); syncStockCountField ( form ,{ pocket , name : 'returnCount-' + index }); if ( input ){ input . readOnly = Number . isSafeInteger ( line . stockCount ); if ( input . readOnly ) input . value = String ( line . stockCount );}});}
function readReturnCounts ( form , pockets ){ return pockets . map (( pocket , index )=>{ if ( ! pocketCountsEnabled ( pocket )) return null ; const count = stockCountValue ( form . querySelector ( '[name="returnCount-' + index + '"]' ) ? . value ,{ title : '� � � ' + ( index + 1 ) + '摰鮋� � � � 墧㺭� 𧶏� 撖對� ' }), original = currentOrder ? . lines ? .[ index ] ? . stockCount ; if ( Number . isSafeInteger ( original ) && count !== original ) throw new Error ( '� � � ' + ( index + 1 ) + '� 游� � � � 墧㺭� 誯◆銝𤾸� � 箏� � � ' + original + '撖嫣� � 氬� � ' ); return count ;});}
2026-10-25 17:50:26 +08:00
2026-10-17 19:50:24 +08:00
function renderDetail (){
2026-11-10 02:54:58 +08:00
if ( typeof invalidateOrderAfterSaleForm === 'function' ) invalidateOrderAfterSaleForm ();
2026-10-23 09:49:36 +08:00
const o = currentOrder , done = [ 'delivered' , 'returned' , 'cancelled' ]. includes ( o . status );
2026-11-10 02:54:58 +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 , afterSaleDone = typeof orderAfterSaleRecord === 'function' &&!! orderAfterSaleRecord ( o ), voided = typeof orderCancellationApproved === 'function' ? orderCancellationApproved ( o ) : o . cancellationApproved , financialBlocked = approvalPending ||!! voided || afterSaleDone , owner = state . user . role === 'owner' ;
2026-10-22 04:21:26 +08:00
let actions = button ( '摰X� 憸� � 嚗𤩺� � � ' , 'print' , 'primary' , `data-id=" ${ o . id } "` ) + ( showOrderCopyEntry ? button ( '<span aria-hidden="true">嚗� </span>憭滚� � 啣� ' , 'copy-order' , 'order-copy-button' , `data-id=" ${ e ( o . id ) } "` ) : '' );
2026-11-10 02:54:58 +08:00
if (( o . status !== 'draft' ||! owner ) &&! approvalPending &&! afterSaleDone ) actions = button ( owner || o . date === state . today ? '靽格㺿霈W� ' : '� 唾窈靽格㺿' , '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-11-10 02:54:58 +08:00
if ( typeof orderAfterSaleActionHTML === 'function' ) actions += orderAfterSaleActionHTML ( o ,{ blocked : financialBlocked });
if ( o . status === 'delivered' &&! financialBlocked ) actions += typeof orderAfterSaleLegacyActionHTML === 'function' ? orderAfterSaleLegacyActionHTML ( o , needsApproval ( 'return' )) : button ( needsApproval ( 'return' ) ? '� 唾窈� 游� � � 韐� ' : '� 游� � � 韐� ' , 'show-return' , 'quiet' );
if ([ 'cancelled' , 'returned' ]. includes ( o . status ) && o . netReceived > 0 &&! financialBlocked &&! ( typeof orderAfterSaleRecord === 'function' && orderAfterSaleRecord ( o ))) 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-11-10 02:54:58 +08:00
if ( owner &&! approvalPending && (( ! voided &&! afterSaleDone && ( o . payments . some ( p => ! p . price_lock_event_id ) || o . expenses . length )) || o . settlements . length )) actions += button ( '� 湔迤霈圈� � � � 瘞� ' , 'show-correct' );
2026-11-14 01:16:35 +08:00
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-11-14 01:16:35 +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>' : '' ;
$ ( '#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 () || '� 芸‵摰X� 蝘啣鐤' ) } </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> ${ orderEntryTimeHTML ( o ) } </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> ${ typeof orderAfterSaleDetailHTML === 'function' ? orderAfterSaleDetailHTML ( o ) : '' }${ 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 () ? '� � 蟮銝支犖蝏梶� 嚗� 蘨靘𥡝蕭皞荔� 銝滩恣� 亙𣪧� 笔� � 伐� ' : ( "銝� " + e ( teamMemberName ( "assistant" )) + "� � � 蝞� " ) } </summary><div class="grid three"><div> ${ e ( teamMemberName ( "owner" )) } � 怨� 摨𥪜� � � <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 ? ( e ( teamMemberName ( "owner" )) + "敺� 蓮� � " + e ( teamMemberName ( "assistant" ))) : ( e ( teamMemberName ( "assistant" )) + "敺� 漱" + e ( teamMemberName ( "owner" ))) } <strong> ${ o . settlementDue == null ? '� 躰晶敺� ‘ ' : '瞼' + yuan ( Math . abs ( o . settlementDue )) } </strong><br><small class="muted"> ${ o . materialCostPending ? '銵亥雲韐剜� � 舘䌊� 刻恣蝞梹� 敶枏� 銝滩� � 餉扇鈭斗狡' : done ? '� 急𧋦� 閗揮甈曆� � 拇隋嚗諹砲� 亥揚� 嗵� 蝞堒𡖂銵峕瓲撖� ' : '� 批� 摰峕� � � � 株扇韐血� 敶X� 摨𥪯漱甈� ' } </small></div></div> ${ priceLockInventoryCreditHTML ( o ) }${ o . ownerDirect ? afterSaleDone ? `<div class="note"> ${ e ( teamMemberName ( "owner" )) } 韐行� 摰鮋� � 坔� 摰X� 甈� 瞼 ${ yuan ( o . ownerDirect ) } 嚗� 歇蝥喳� � 桀� � � � 甈曆� � � 蝏� ⏚瘨佗� 霂瑟� 摰鮋� 韐行� � 詨笆蝏梶� � � </div>` : `<div class="note"> ${ e ( teamMemberName ( "owner" )) } � 湔𦻖� 嗅恥� 瑕� 憸� 瞼${ yuan ( o . ownerDirect ) } 嚗� ${ o . status === 'delivered' ? '撌脖� � 餃� 蝏㯄� 憸脲緍� 歹� 韐扳狡嚗誩⏚瘨行� � � � � 閧𡠺憭齿瓲� � ' : o . price_lock_id && o . status === 'returned' && o . netReceived === 0 ? '摰X� 撌脤� � 皜� � 頝刻揭� 瑟𤣰� � 甈曉耦� 鞟� 撌桅� 撌脰恣� 亙� � 寧� 蝞𨰜� � ' : '餈䠷� � � � 鈭𤾸恥� 瑟狡嚗� � 瘨� � � � 韐批� 憿颱� � 蠘揭� 琿� � 摰X� 嚗䔶� 蝞堒� 餈𥪜𨭌� � � � ' } </div>` : '' } <p class="small muted" style="margin:14px 0 0">撘� � 訫� � 匧� 鈭方揮甈橘� � 拇隋� � � 鈭扎� � � � 韐扯� 甈曉� � 祈扇敶𤏪� 銝齿𠽌銝衤� 蝚𢛵� � � � 諹扇敶訫� � � 蓮韐佗� 銝滢� � 𤏸絲隞䀹狡� � </p></details>` } <details class="panel"><summary>� 園� � 甈曆� �
2026-10-23 00:38:04 +08:00
}
2026-11-14 01:16:35 +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'?'摰X� � 嗆狡':'摰X� � � 甈� ',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?(teamMemberName("owner")+"餈� "+teamMemberName("assistant")):(teamMemberName("assistant")+"鈭� "+teamMemberName("owner")))+' 繚 '+(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>${e(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 );
2026-11-10 02:54:58 +08:00
if ([ 'return' , 'refund' ]. includes ( action ) && typeof orderAfterSaleRecord === 'function' && orderAfterSaleRecord ( o )) throw new Error ( '� 砍� 撌脣� � � 睸� 𠬍� 霂瑟䰻� 见睸� 𤾸� � � 扇敶𤏪� 銝滩� � 滚� � � 韐折� � 甈整� � ' );
2026-10-23 11:58:19 +08:00
if ( action === 'cancel' ) throw new Error ( '霂琿� � 啗粉� 𤥁恥� 訫� 嚗䔶� � 𨅯� 瘨� 恥� 𨰝� 脲� � 𦦵𤚗霂瑕� 瘨� � 脲瓲撖孵� � � � � ' );
2026-11-14 01:16:35 +08:00
if ( o . ownershipPending || typeof orderOwnershipPending === 'function' && orderOwnershipPending ( o )) throw new Error ( '敶鍦� � 唾窈敺� � 銝餃� � 賂� 敶枏� � � � � 砍� � 嗡� 靽格㺿� 諹扇韐艾� � ' );
if ( o . cancellationPending || typeof orderCancellationPending === 'function' && orderCancellationPending ( o )) throw new Error ( '� 𡝗� � 唾窈敺� � 銝餃� � 賂� 敶枏� � � � � 砍� 靽格㺿� 屸� � 韐扼� � ' );
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-11-14 01:16:35 +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' ? '� 啗揭' : '� � 甈暹� � � ' } 嚗䔶� � 臭� � 嗅� 摰X� � 芸㦛� � </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-11-08 15:47:07 +08:00
if ( action === 'complete' ) html = ` ${ dt }${ o . lines . map (( line , index )=> line . unit === 'g' && pocketCountsEnabled ( line . pocket ) && line . stockCount == null ? stockCountField ( line . pocket , '' ,{ name : 'completeCount-' + index , title : line . name + ' 繚 摰鮋� � 箏� � 圈� 嚗� 笆嚗� ' , help : '' } ):'').join('')}<p>銵仿� 餈坔� � 批� � � � � 株扇韐佗� � 匧‵� 䠷� 憸肽扇敶訫� � � 晶� 具� � � � 蠘揮� 䀹緍� 誯� � 穃僎霈∪� � � � 桐� � 拇隋� � 狡憿寞𧊋� 園� � 𡝗� � 祇� 憸脲� 蝛箇蒾� 塚� 霂瑕� 銵仿� � � </p><label class="check"><input type="checkbox" name="verified" required>撌脫瓲摰𧼮� 憸脲𤣰甈整� � � � � 歇鈭支� 嚗峕� 憛怨晶� 其蛹摰鮋� 撌脖� � 煾� 嚗峕瓷� 匧� � 毺� 撌脣‵0� � </label>` ;
if ( action === 'return' ) html = ` ${ dt }${ field ( '� � 韐批� � � ' , 'reason' , '' , 'text' , 'required maxlength="200"' ) } <div class="grid two"> ${ o . lines . map (( l , i )=> '<div class="return-stock-item">' + 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 ] : '' )) + stockCountField ( l . pocket , l . stockCount ,{ name : 'returnCount-' + i , title : '摰鮋� � � � 墧㺭� 𧶏� 撖對� ' , help : '' } )+'</div>').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-14 01:16:35 +08:00
if ( action === 'settlement' ) html = `<div class="grid three"> ${ dt }${ choice ( '頧祆狡� 孵� ' , 'direction' ,[[ 'toOwner' ,( teamMemberName ( "assistant" ) + " � � " + teamMemberName ( "owner" ))],[ 'toAssistant' ,( teamMemberName ( "owner" ) + " � � " + teamMemberName ( "assistant" ))]], 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 ? ( e ( teamMemberName ( "owner" )) + "撌脩凒� 交𤣰� 圈� � � 恥� 瑟狡嚗� � � 匧� � � � � 菜瓲皜� � 撅𠺶� � " ) : `韐扳狡敺� � 瞼 ${ yuan ( o . costDue ) } 嚗𥕦⏚瘨血� 蝏� 瞼 ${ yuan ( o . profitDue ) } 嚗� � � 唬蛹 ${ e ( teamMemberName ( "owner" )) } � � 頧砍� 嚗剹� � }</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-14 01:16:35 +08:00
const entries = [...(( o . cancellationApproved || typeof orderAfterSaleRecord === 'function' && orderAfterSaleRecord ( o )) ? [] : o . payments . filter ( valid )). map ( r =>[ 'payment:' + r . id , r . date + ' ' + ( r . kind === 'receipt' ? '摰X� � 嗆狡' : '摰X� � � 甈� ' ) + ' ' + yuan ( r . amount ) + '� � ' + accountDisplayName ( r . account )]),...(( o . cancellationApproved || typeof orderAfterSaleRecord === 'function' && orderAfterSaleRecord ( o )) ? [] : 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 ? ( teamMemberName ( "owner" ) + "餈娍狡" ) : ( teamMemberName ( "assistant" ) + "鈭斗狡" )) + ' ' + 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' , activePaymentAccounts (), '� 拍� 敺桐縑' ) }${ choice ( '� 湔迤� 𦒘� 甈曆犖嚗� � 韐寧鍂嚗� ' , 'payer' , teamMemberOptions ( true ), 'assistant' ) }${ choice ( '� 湔迤� 舘蓮甈暹䲮� 𡢅� 隞� 漱甈橘� ' , 'direction' ,[[ 'toOwner' ,( teamMemberName ( "assistant" ) + " � � " + teamMemberName ( "owner" ))],[ 'toAssistant' ,( teamMemberName ( "owner" ) + " � � " + teamMemberName ( "assistant" ))]], '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-11-08 15:47:07 +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(action==='return')syncReturnCounts();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 );
2026-11-14 01:16:35 +08:00
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>靽∠鍂� ∠� 銝� � � ${ e ( teamMemberName ( 'owner' )) } � 嗆狡� � </small>`); note = form . querySelector ( '.correction-card-note' );} if ( note ) note . hidden =! isCreditCardAccount ( correction ? . value );
2026-10-25 14:19:24 +08:00
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' ;}
2026-11-14 01:16:35 +08:00
function stockSnapshotLabel ( snapshot ){ return { automatic : '蝟餌� � 芸𢆡靽嘥� ' , manual : '摨𦯀蜓憭齿瓲' , unknown : '撌脖� 摮� ' }[ stockSnapshotSource ( snapshot )];}
2026-10-26 22:46:55 +08:00
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' ;
2026-11-10 22:29:17 +08:00
const saved = snapshot ? `<span class="badge ${ snapshot . stale ? ' warn' : '' } "> ${ stockSnapshotLabel ( snapshot ) } </span> ${ manual && snapshot . actor ? e ( actorDisplayName ( snapshot . actor )) + ' 繚 ' : '' } 摰鮋� 靽嘥� ${ e ( stockTime ( snapshot . updated || snapshot . created )) } ` : '' ;
2026-10-26 22:46:55 +08:00
const status =! snapshot ? '隞𠰴予撠𡁏𧊋靽嘥� 敹怎� � � ' : ` ${ saved }${ snapshot . stale ? ' 繚 靽嘥� � 擧� 摨枏� � 睃𢆡嚗䔶� � 坔� � 嗡� 摮睃� 潦� � ' + ( manual ? '� � � 齿鰵憭齿瓲� � ' : '' ) : manual ? ' 繚 隞𠰴予撌脣� � � ' : '' } ` ;
2026-11-14 01:16:35 +08:00
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 15:47:07 +08:00
const previous = page . yesterday ? . inventory ? . find ( row => row . pocket === pocket );
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> ${ inventoryBalanceCountHTML ( item ) }${ item . reserved ? `<div class="small muted stock-reserved">� 批� � 删鍂 ${ grams ( item . reserved ) } g 繚 � 舐鍂 ${ grams ( item . available ) } g</div>` : '' }${ item . unknownReservedCount ? '<div class="small danger-text">� � ' + e ( item . unknownReservedCount ) + ' 蝚娍唂� 閙𧊋霈啣� 撖寞㺭嚗� � 銵仿� � 批� 撖寞㺭� 滚枂摨瓐� � </div>' : '' }${ Number . isSafeInteger ( item . reservedCount ) && item . reservedCount ? `<div class="small muted stock-reserved">� 批� � 删鍂 ${ item . reservedCount } 撖� 繚 � 舐鍂 ${ stockCountText ( item . availableCount ) } </div>` : '' } <div class="stock-yesterday"><span>� 典予敹怎� <small> ${ e ( page . yesterdayDate . slice ( 5 )) } </small></span><b class=" ${ yesterday ? '' : 'muted' } "> ${ yesterday || ( page . yesterday ? '� 芾扇敶閗砲韐抒� ' : '� 芯� 摮睃翰� � ' ) } </b> ${ pocketCountsEnabled ( pocket ) ? `<small> ${ e ( stockCountText ( previous ? . count ,{ unknown : page . yesterday ? '� 芾扇敶訫笆� � ' : '� 芯� 摮睃笆� 啣翰� � ' } ))}</small>` : '' }${ 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-11-14 01:16:35 +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 15:47:07 +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' , '撟喟宏' ],...( state . user . role === 'owner' ? [[ 'adjustment' , '� 芾� � 游笆� � ' ]] : [])], '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 ( '� 圈� 嚗ā嚗� ' , 'grams' , '' , 'number' , 'min="0.001" step="0.001" required inputmode="decimal" placeholder="憛怠� 甇� 㺭"' ) }${ stockCountField ( '' , '' ,{ title : '摨枏� � 圈� 嚗� 笆嚗� ' , help : '' } )} ${ dateField () } </div><p class="small muted" data-stock-count-note hidden>撟喟宏瘨匧� 撖寞㺭韐抒� � 嗅‵� 蹱𧋦甈∪� � � 笆� 堆� 銝方器� 質扇敶訫笆� 唳𧒄� 峕郊憓𧼮� � 詨� � 圈� � � </p><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-11-08 15:47:07 +08:00
const adjustment = kind === 'adjustment' , counted = pocketCountsEnabled ( form . elements . pocket . value ) || transfer && pocketCountsEnabled ( target . value ), quantity = form . querySelector ( '[name="grams"]' ), count = form . querySelector ( '[name="stockCount"]' );
if ( quantity ){ if ( adjustment && quantity . dataset . previousGrams === undefined ){ quantity . dataset . previousGrams = quantity . value ; quantity . value = '0' ;} else if ( ! adjustment && quantity . dataset . previousGrams !== undefined ){ quantity . value = quantity . dataset . previousGrams ; delete quantity . dataset . previousGrams ;} quantity . readOnly = adjustment ; quantity . min = adjustment ? '0' : '0.001' ;}
syncStockCountField ( form ,{ visible : counted }); if ( count ){ count . min = adjustment ? '-1000000000' : '1' ; count . placeholder = adjustment ? '憓𧼮� 憛急迤� 堆� � 誩� 憛怨� � � ' : '銝� 撖孵‵1' ;}
const note = form . querySelector ( '[data-stock-count-note]' ); if ( note ){ note . hidden =! counted ||! adjustment &&! transfer ; note . textContent = adjustment ? '� 芯耨甇� 歇� 条� � � 笆� 堆� 銝齿㺿� 睃� � 溻� � � � 惩‵甇� 㟲� 堆� � 誩� 憛怨� � 湔㺭� � ' : transfer ? '撟喟宏瘨匧� 撖寞㺭韐抒� � 嗅‵� 蹱𧋦甈∪� � � 笆� 堆� 銝方器� 質扇敶訫笆� 唳𧒄� 峕郊憓𧼮� � 詨� � 圈� � � ' : '� 祆活� 漤� 銝𤾸� � � 笆� 啣� � 怎蒈霈堆� 銝� 撖孵‵1� � ' ;}
$ ( '#stock-submit' ). textContent = adjustment ? '靽嘥� 撖寞㺭靚� 㟲' : '� 餉扇' + ({ increase : '憓𧼮� ' , decrease : '� 誩� ' , transfer : '撟喟宏' })[ kind ]; $ ( '#stock-error' ). innerHTML = '' ;
2026-10-17 19:50:24 +08:00
}
function stockMovements (){
2026-11-08 03:30:58 +08:00
const pockets = inventoryMovementPockets . length ? inventoryMovementPockets : activePocketKeys (). map ( pocket =>({ pocket , active : true }));
2026-11-14 01:16:35 +08:00
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 = '� � � 㕑揮� 䀝� 蝐餃� � � xcel撌脩� � 琜� � � 鉄� 券� � 寥� 霈啣� � � ' ; toast ( '� � � 㕑揮� 䀝� 蝐餃� � � � 摮䀹� 瘞媧xcel撌脩� � � ' );
} 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-11-08 15:47:07 +08:00
const names = { increase : '憓𧼮� ' , decrease : '� 誩� ' , transfer : '撟喟宏' , opening : '撘� 韐� ' , purchase : '� 亙� ' , adjustment : '靚� 㟲' , manual : '� 见𢆡� 睃𢆡' , sale : '� � � 桀枂摨� ' , return : '� � 韐批� 摨� ' , manual_reversal : '� 湔迤� 脣� ' , lock_purchase : '� � 遠暺� � � 亙� ' , lock_finished : '� � 遠� 𣂼� � 亙� ' , count_opening : '撖寞㺭� 条� � 箏� ' , order_edit_reverse : '� 孵� � 箏� � 脣� ' , order_edit_sale : '� 孵� � 箏� ' , order_cancel_reverse : '霈W� 雿𨅯� � 脣� ' , recovery : '� 墧𤣰� 扳� � 亙� ' };
2026-11-10 22:29:17 +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 ${ inventoryCountHTML ( r ,{ signed : true } )}</td><td> ${ e ( names [ r . kind ] || r . kind ) } </td><td> ${ r . reversal || r . kind === 'manual_reversal' ? '� 文� � 扯扇敶閧� 摨枏� 敶勗� ' : e ( r . note ) || '� � ' } </td><td> ${ e ( actorDisplayName ( 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' ;
2026-11-08 15:47:07 +08:00
return kind === 'increase' ? ( row . mg > 0 || row . mg === 0 && row . stockCount > 0 ) && [ 'increase' , 'purchase' , 'adjustment' , 'manual' ]. includes ( row . kind ) : ( row . mg < 0 || row . mg === 0 && row . stockCount < 0 ) && [ 'decrease' , 'adjustment' , 'manual' ]. includes ( row . kind );
2026-10-26 22:46:55 +08:00
}
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 15:47:07 +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> ${ inventoryBalanceCountHTML ( i ) }${ 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 ( '敹怎� � 交� 銝擧䰻霂V� 銝� � 湛� 霂琿� � 啗粉� 硔� � ' );
$ ( '#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 15:47:07 +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 )) } 嚗ā ${ pocketCountsEnabled ( p ) ? '嚗誩笆' : '' } 嚗� </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 || i . count || i . reservedCount ));
2026-11-10 22:29:17 +08:00
return `<tr><td> ${ e ( snapshot . date ) } </td> ${ activePocketKeys (). map ( p => `<td class="number"> ${ stockQuantity ( snapshot . inventory , p ) ? . replace ( /g$/ , '' ) || '<span class="muted">� 芾扇敶� </span>' }${ pocketCountsEnabled ( p ) ? '<div class="small">' + e ( stockCountText ( snapshot . inventory ? . find ( row => row . pocket === p ) ? . count )) + '</div>' : '' } </td>` ). join ( '' ) } <td> ${ stockSnapshotLabel ( snapshot ) }${ stockSnapshotSource ( snapshot ) === 'manual' && snapshot . actor ? `<div class="small muted"> ${ e ( actorDisplayName ( 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 ${ i . countUnit === 'pair' || pocketCountsEnabled ( i . pocket ) ? ' / ' + e ( stockCountText ( i . count )) : '' } ` ). 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 || '� 芸‵摰X� ' ) : ( 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>� 交� 嚗誩� � 瑟� 摰X� </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-11-14 01:16:35 +08:00
return `<section class="panel report-costs"><h2>� 劐� 甈曆犖� 詨笆� 鞉𧋦</h2><p class="small muted">� 桅� 朞恥� 閙� 撘� � 閙𠯫敶㘾� 嚗𥟇� � 亥揚� 蹱� 摰鮋� 韐凋僭� 交� 敶㘾� 嚗諹恥� 閗� 㛖鍂� 躰晶銝滚� 霈∩� 甈⊥𣈲� 綽� � � 遠� 躰晶� � 極韐嫣� 韐寧鍂� 匧� � � � 甈暹𠯫敶㘾� 嚗� � � � � 韐嫣� � 其漱隞䀹𧒄� 滚� 霈∪� � � � � � 𣈲� 箏虾� 賭� � 祆� 霈W� � 㛖鍂� 鞉𧋦銝滚� � � 蓮韐西窈隞交瓲摰𧼮� � � � � 游� � � 𣈲� 箔蛹� � � � </p><div class="table-wrap"><table class="report-payer-table" aria-label="� 拍� 銝� ${ e ( teamMemberName ( "owner" )) } � 臬枂� 鞉𧋦"><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 ? '� 脣� ' : '' );}
2026-11-10 22:29:17 +08:00
function reportReceiptBasis ( item ){ return item . order_after_sale ? '霈W� � 桀� 繚 � 匧� � � 𤣰隞䀹𠯫' : item . price_lock_id ? '� � 遠 繚 � 匧� � � 𤣰隞䀹𠯫' : '� 桅� 朞恥� � 繚 撘� � � ' + ( item . order_date || '� 交� � 芣� 靘� ' );}
2026-10-23 09:49:36 +08:00
function reportReceiptIdentityHTML ( item ){
const number = item . paper_number || item . number || ( item . price_lock_id ? '� � 遠霈啣� ' : '霈W� 霈啣� ' );
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 || '� 芸‵摰X� 蝘啣鐤' ) } </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>霈W� 嚗誩恥� � </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 ) ? '� 典� � 交� 撌脣虾� 詨笆嚗峕� 韐孵� 銵亦� 霈W� 撠𡁏𧊋霈∪� 撌脩䰻� 躰晶� � ' : '' ;
}
2026-11-02 21:34:17 +08:00
function reportOwnerAdvanceAmount ( value , known ){ return value === null ? '敺� ‘嚗� 歇� � 瞼' + yuan ( known ) + '嚗� ' : '瞼' + yuan ( value );}
function reportOwnerAdvanceFormula ( business , day ){
2026-11-14 01:16:35 +08:00
return ` ${ business . member === 'owner' ? ( teamMemberName ( "owner" ) + "隞䀹狡� � 恣" ) : ( teamMemberName ( "owner" ) + "� 思� � � 恣" ) } 嚗𡁏� 瘙䭾� 韐� ${ reportOwnerAdvanceAmount ( day . poolAmount , day . knownPoolAmount ) } 嚗� � 嗡� � 鞉𧋦 ${ reportOwnerAdvanceAmount ( day . otherAmount , day . knownOtherAmount ) } 嚗� ${ reportOwnerAdvanceAmount ( day . amount , day . knownAmount ) } ` ;
2026-11-02 21:34:17 +08:00
}
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 || '� 芸‵摰X� ' ) } </button><small class="muted"> ${ e ( item . paperNumber || item . number ) } </small>` : ` ${ e ( item . customer || '� 芸‵摰X� ' ) } <small class="muted">� 桀� 霈啣� </small>` ;
}
function reportOwnerAdvancesHTML ( business ){
2026-11-14 01:16:35 +08:00
const advances = business . ownerAdvances , single = advances . from === advances . date , label = business . member === 'owner' ? ( teamMemberName ( "owner" ) + "隞䀹狡� 𡒊� " ) : ( teamMemberName ( "owner" ) + "� 思� � 𡒊� " );
2026-11-02 21:34:17 +08:00
const days = advances . days . length ? advances . days : single ? [{ date : advances . date , amount : 0 , knownAmount : 0 , missingCount : 0 , pendingCount : 0 , items : []}] : [];
2026-11-14 01:16:35 +08:00
return `<details class="report-owner-advances" aria-label=" ${ e ( business . name + label ) } "><summary> ${ single ? '敶𤘪𠯫' : '� 㗇𠯫� 詨笆' }${ e ( label ) } </summary><p class="small muted">� 㗇� 撅噼恥� 訫� � 閙𠯫� � 睸� 舘扇敶閙𠯫敶㘾� 嚗𥕢� � 埈� � 㗇𠯫� � � 銝滨敞霈∪� � 脣𠿭隞塩� � � � 亙� � 亙𡖂� 堒⏚瘨虫� ${ e ( teamMemberName ( "owner" )) } 隞� 𤣰嚗峕𧊋� � � � � 蓮韐艾� � </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>摰X� 嚗誩� � � </th><th>� 鞉𧋦憿寧𤌍</th><th class="number"> ${ e ( teamMemberName ( "owner" )) } � 踵� � 煾� </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' ? ( e ( teamMemberName ( "owner" )) + "隞䀹狡" ) : ( e ( teamMemberName ( "owner" )) + "� 思� " )) + '� 𡒊� � � </p>' }${ day . pendingCount ? '<p class="small muted">敺� 瓲撖寥★� 桀� � 芸� 韐佗� 憸� 摯� 煾� 銝滩恣� 思� 撠讛恣� � </p>' : '' } </div>` ). join ( '' ) || '<p class="small muted">� � � 㗇� 隞賣� � 惩歇� 餉扇� � ' + e ( label ) + '� � </p>' } </details>` ;
2026-11-02 21:34:17 +08:00
}
function reportOwnerAdvancesText ( business ){
2026-11-14 01:16:35 +08:00
const advances = business . ownerAdvances , label = business . member === 'owner' ? ( teamMemberName ( "owner" ) + "隞䀹狡� 𡒊� " ) : ( teamMemberName ( "owner" ) + "� 思� � 𡒊� " );
2026-11-02 21:34:17 +08:00
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 || '� 芸‵摰X� ' } / ${ 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-14 01:16:35 +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>� 嗡葉 ${ e ( teamMemberName ( "owner" )) } � 思� <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">� 躰晶撌脰恣� 交� 餅� � 穿� 敶𤘪𠯫敺� � 亙蘨� � ${ e ( teamMemberName ( "owner" )) } � 思� � 典� 嚗� � 撘譍葉霈∪� 銝� 甈~� � � � 芸� � 滢� � 亙� 隞琿� 𣂼� � 貊� 嚗峕遬蝷箸� 隞瑞㮾銋睃虾� 賣� � � � 撌柴� � ${ 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-14 01:16:35 +08:00
return [ `撌脩鍂� 坔� 霈∴� ${ grams ( pool . mg ) } g` , `� 蹱� 撌脩鍂� 躰晶嚗� ${ reportBusinessAmount ( pool . amount , pool . knownAmount ) } 嚗� 歇霈∪� � 餅� � 穿� 敶𤘪𠯫敺� � 亙蘨� � ${ teamMemberName ( "owner" ) } � 思� � 典� 嚗� � 撘譍葉霈∪� 銝� 甈∴� `,... pool . days . map ( day => ` ${ day . date } � 蹱� 嚗� 歇� � ${ grams ( day . mg ) } g嚗㚁� ${ reportPoolMaterialFormula ( day ) } ` ),...( reportPoolMaterialPendingNote ( pool ) ? [ reportPoolMaterialPendingNote ( pool )] : []), `� 嗡葉 ${ teamMemberName ( "owner" ) } � 思� 嚗� ${ 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){
2026-11-14 01:16:35 +08:00
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>霈W� � 餅� � � <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 ){
2026-11-14 01:16:35 +08:00
return day . amount === null ? '摨磰蓮� 煾� 敺� 瓲蝞� ' : day . amount > 0 ? business . name + ( "摨磰蓮" + teamMemberName ( "owner" )) : day . amount < 0 ? ( teamMemberName ( "owner" ) + "摨磰蓮" ) + business . name : '敶𤘪𠯫� 𣳇� 頧祆狡' ;
2026-11-07 00:30:02 +08:00
}
function reportCurrentAccountFormula ( day ){
2026-11-14 01:16:35 +08:00
return ` ${ teamMemberName ( "owner" ) } � 思� 撌脩鍂� 躰晶 ${ reportOwnerAdvanceAmount ( day . materialCost , day . knownMaterialCost ) } 嚗� ${ teamMemberName ( "owner" ) } � 思� � 嗡� 霈W� � 鞉𧋦 ${ reportOwnerAdvanceAmount ( day . otherCost , day . knownOtherCost ) } 嚗� � 砌犖敶𤘪𠯫霈W� � � � 拇隋 ${ reportDailyProfitAmount ( day . profit , day . knownProfit , true ) } � � ${ teamMemberName ( "owner" ) } 隞� 𤣰� � 憸� 瞼 ${ yuan ( day . ownerNetReceipts ) } 嚗� ${ day . amount === null ? '敺� 瓲蝞� ' : '瞼' + yuan ( day . amount ) } ` ;
2026-11-07 00:30:02 +08:00
}
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-14 01:16:35 +08:00
return `<section class="report-receipts report-ownership-receipts" aria-label="� 㕑恥� 訫� 撅墧� � 餃� � 嗅� "><p class="small muted report-receipt-scope"> ${ e ( reportPeriod ( range )) } 嚗𡁏� 撅噼恥� 訫� � 嗅� 嚗脲𤣰甈撾� � � 甈橘� 撌脣� � 思� 鈭箔誨� 嗚� � � � 砍鉄� 桀� 嚗峕� 瘙牐� 霈∪歇� 㛖鍂� 典� 嚗� ${ e ( teamMemberName ( "owner" )) } � 思� � � � � 亙� � 仿� 鞉𠯫� 詨笆� � </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-14 01:16:35 +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 ? '� � 遠霈啣� ' : '霈W� 霈啣� ' )} / 摰X � $ { item . customer || '� 芸‵摰X� 蝘啣鐤' } / $ { 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" > $ {[ '� � � 桀� 憸� ' , '蝝航恣摰墧𤣰' , '蝝航恣摰鮋� � ' , '霈W� � � � 拇隋' ]. map ( title => card ( title , '� � ' , error ? '撠𡁏𧊋� 硋� � 唳旿' : '甇� 銁霂餃� ' )). join ( '' )} < /div><section class="panel report-query-message${error?' error':''}"><p>${error?e(error):'甇� 銁霂餃� '+e(reportPeriod(range))+'霈W� 銝𤾸睸� 𡒊� 敶枏� 蝏𤘪� � � '}</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 [ '瘥𤩺𠯫� 拇隋銵剁� � 㗇𠯫� 煺� 霈W� 敶鍦� 鈭綽� � 桅� 朞恥� 閙� 撘� � 閙𠯫� � � 隞瑟� � 閙� 鈭支� � 乓� � 睸� 擧� 霈啣� � 伐� ' ,...( 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 ();
2026-11-14 01:16:35 +08:00
let previousDate = '' , previousIndex =- 1 ; for ( const row of table . rows ){
2026-11-03 00:29:34 +08:00
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 ();
2026-11-14 01:16:35 +08:00
const index = teamMemberKeys (). indexOf ( row . member ); if ( row . date < previousDate || row . date === previousDate && index <= previousIndex ) fail (); previousDate = row . date ; previousIndex = index ;
2026-11-03 00:29:34 +08:00
}
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 ){
2026-11-14 01:16:35 +08:00
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 );
2026-10-28 00:22:04 +08:00
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 ){
2026-11-14 01:16:35 +08:00
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 ();
2026-10-28 00:22:04 +08:00
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-10 22:29:17 +08:00
function reportAfterSaleRecoveryCosts ( r , b , fail ){
2026-11-14 01:16:35 +08:00
const money = Number . isSafeInteger , count = value => money ( value ) && value >= 0 , items = [], byPayer = Object . fromEntries ( teamMemberKeys (). map ( key =>[ key , 0 ]));
2026-11-10 22:29:17 +08:00
const identity = item => JSON . stringify ([ item . component , item . payer , item . amount , item . source , item . materialPoolId ?? null ]);
for ( const row of r . orderRows . filter ( row => row . kind === 'orderAfterSale' && ( row . member ?? ( teamMode () ? null : 'assistant' )) === b . member )){
const record = row . orderAfterSale , summary = record ? . summary , original = record ? . originalOrder ?? record ? . original , expected = [];
if ( row . status !== 'after_sale' ||! validOrderDate ( row . date ) || row . date < b . from || row . date > b . date || record ? . date !== row . date || ( record . order_id ?? record . orderId ) !== ( row . order_id ?? row . id ) ||! summary ||! Array . isArray ( summary . lines ) ||! summary . lines . length ||! Array . isArray ( row . costItems ) ||! count ( summary . materialReturnedCost ) ||! count ( summary . laborRestockedCost )) fail ();
for ( const line of summary . lines ){
if ( ! line ||! count ( line . lineIndex ) || typeof line . name !== 'string' ) fail ();
for ( const [ component , key , totalKey ] of [[ 'material' , 'materialAllocations' , 'materialReturnedCost' ],[ 'labor' , 'restockedLaborAllocations' , 'laborRestockedCost' ]]){
2026-11-14 01:16:35 +08:00
const parts = line [ key ]; if ( ! Array . isArray ( parts ) ||! count ( line [ totalKey ]) || parts . some ( part => ! part ||! teamMemberKeys (). includes ( part . payer ) ||! count ( part . amount )) || parts . reduce (( sum , part )=> sum + part . amount , 0 ) !== line [ totalKey ]) fail ();
2026-11-10 22:29:17 +08:00
for ( const part of parts ) if ( part . amount ) expected . push ({ component , payer : part . payer , amount :- part . amount , source : `� � � ${ line . lineIndex + 1 } 繚 ${ line . name } ` , materialPoolId : component === 'material' ? row . date : null });
}
}
if ([ 'materialReturnedCost' , 'laborRestockedCost' ]. some ( key => summary . lines . reduce (( sum , line )=> sum + line [ key ], 0 ) !== summary [ key ])) fail ();
const recovered = row . costItems . filter ( item => item ? . nonCash === true ), actual = recovered . map ( identity ). sort (), wanted = expected . map ( identity ). sort ();
2026-11-14 01:16:35 +08:00
if ( actual . length !== wanted . length || actual . some (( value , index )=> value !== wanted [ index ]) || row . costItems . some ( item => ! item ||! teamMemberKeys (). includes ( item . payer ) ||! money ( item . amount ) || ( item . nonCash === true ? item . kind !== 'goods' || item . amount >= 0 : item . kind !== 'paid' || item . component !== 'fee' || item . afterSaleExpense !== true || item . amount < 0 )) || row . costItems . reduce (( sum , item )=> sum + item . amount , 0 ) !== row . known ? . totalCost || row . totalCost !== row . known . totalCost ||! money ( original ? . total ) ||! money ( summary . retainedAmount ) || row . sale !== summary . retainedAmount - original . total ||! money ( row . profit ) || row . profit !== summary . profitAdjustment || row . sale - row . totalCost !== row . profit ) fail ();
2026-11-10 22:29:17 +08:00
for ( const item of recovered ){ byPayer [ item . payer ] += item . amount ; items . push ({... item , id : row . id , date : row . date });}
}
return { byPayer , items };
}
function validatePoolMaterialCosts ( b , recoveries , fail ){
const money = Number . isSafeInteger , count = value => money ( value ) && value >= 0 , nullable = value => value === null || count ( value ), pool = b . poolMaterial ;
2026-11-14 01:16:35 +08:00
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 =>{
2026-11-02 21:13:10 +08:00
const payer = value . byPayer [ key ]; return payer && count ( payer . knownAmount ) && nullable ( payer . amount ) && payer . amount === ( value . missingCount ? null : payer . knownAmount );
2026-11-14 01:16:35 +08:00
}) && teamMemberKeys (). reduce (( sum , key )=> sum + value . byPayer [ key ]. knownAmount , 0 ) === value . knownAmount ;
2026-11-10 22:29:17 +08:00
if ( ! valid ( pool ) || typeof pool . hasPriceLocks !== 'boolean' ||! Array . isArray ( pool . days ) || pool . missingCount > b . missingCostCount ||! pool . otherCosts ||! money ( pool . otherCosts . knownAmount ) ||! ( pool . otherCosts . amount === null || money ( pool . otherCosts . amount )) || pool . otherCosts . amount !== null && pool . otherCosts . amount !== pool . otherCosts . knownAmount ) fail ();
2026-11-02 21:13:10 +08:00
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 ){
2026-11-14 01:16:35 +08:00
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 ();
2026-11-06 01:29:35 +08:00
}
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
}
2026-11-10 22:29:17 +08:00
// � 蹱� � 㛖鍂靽脲� 甇� 㺭嚗𥕦睸� 𤾸� 摨枏� � 誩� � 鞉𧋦嚗䔶� � 賢� � 踹� � 鞉𧋦� 𣂼� � 蠘� 㛖鍂� �
2026-11-14 01:16:35 +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 - recoveries . byPayer [ key ]) || pool . otherCosts . knownAmount - teamMemberKeys (). reduce (( sum , key )=> sum + recoveries . byPayer [ key ], 0 ) < 0 || 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:13:10 +08:00
}
2026-11-10 22:29:17 +08:00
function validateOwnerAdvances ( b , recoveries , fail ){
const money = Number . isSafeInteger , count = value => money ( value ) && value >= 0 , nullable = value => value === null || money ( value ), advances = b . ownerAdvances ;
const identity = item => JSON . stringify ([ item . id , item . date , item . component , item . source , item . poolId ?? item . materialPoolId ?? null , item . amount ]), remaining = recoveries . items . filter ( item => item . payer === 'owner' ). map ( identity );
2026-11-02 21:34:17 +08:00
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 ){
2026-11-10 22:29:17 +08:00
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' , 'knownPoolAmount' , 'knownOtherAmount' ]. every ( key => money ( day [ key ])) ||! [ 'missingCount' , 'pendingCount' ]. every ( key => count ( day [ key ])) ||! [ 'amount' , 'poolAmount' , 'otherAmount' ]. every ( key => nullable ( day [ key ]))) fail ();
2026-11-02 21:34:17 +08:00
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 ();
2026-11-10 22:29:17 +08:00
if ( item . nonCash !== undefined && typeof item . nonCash !== 'boolean' || item . estimatedAmount !== null && item . estimatedAmount < 0 || ( 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 ();
if ( item . amount < 0 || item . nonCash === true ){ const index = remaining . indexOf ( identity ( item )); if ( item . kind !== 'order' || item . status !== 'recorded' || item . nonCash !== true || item . amount >= 0 || index < 0 ) fail (); remaining . splice ( index , 1 );}
2026-11-02 21:34:17 +08:00
}
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 ;
}
2026-11-10 22:29:17 +08:00
if ( remaining . length || knownTotal > b . costByPayer . owner . knownTotalCost ) fail ();
2026-11-02 21:34:17 +08:00
}
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 ();
2026-11-14 01:16:35 +08:00
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-10 22:29:17 +08:00
const recoveries = reportAfterSaleRecoveryCosts ( r , b , fail );
validatePoolMaterialCosts ( b , recoveries , fail );
validateOwnerAdvances ( b , recoveries , 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 ();
2026-11-14 01:16:35 +08:00
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 );}
2026-10-28 00:22:04 +08:00
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 ){
2026-11-10 22:29:17 +08:00
const date = item . price_lock_id || item . order_after_sale ? item . date : item . order_date ;
2026-11-07 00:30:02 +08:00
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 );}}
2026-11-10 22:29:17 +08:00
} catch ( err ){ if ( request === reportRequest && tab === 'report' && $ ( '#report-content' )){ reportQueryState ( range , err . name === 'AbortError' ? '霂餃� 頞� 𧒄嚗諹窈� 齿鰵霂餃� � � ' : err . message ); if ( typeof dailyFundsReportError === 'function' ) dailyFundsReportError ( range , err ,{ shared : true });}}
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>霈W� 銝𤾸睸� 𤾸� 憸脲� 蝏� </h2><p class="small muted"> ${ e ( reportPeriod ( range )) } � � 凒� � � � 桅� 朞恥� 閙� 撘� � 閙𠯫� � � 隞瑟� � 閙� 鈭支� � 乓� � 睸� 擧� 霈啣� � 交� 敶㘾� � � � � 峕遬蝷箄恥� 訫� � 渲� 㛖鍂� 鞉𧋦嚗䔶� 銝𦠜䲮摰鮋� 隞䀹狡� � � � 詨笆嚗𥟇唂� 厩阮銝滩恣� 煾� � � </p><div class="table-wrap"><table class="report-order-table" aria-label="霈W� 銝𤾸睸� 𤾸� 憸脲� 蝏� "><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">霈W� � � � 拇隋</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 15:47:07 +08:00
if ( teamMode ()) return `<section class="panel"><h2>摰X� 敺� 𤣰甈曆� 摨枏� </h2><p>摰X� 敺� 𤣰甈� <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> ${ inventoryBalanceCountHTML ( i ) } </div>` ). join ( '' ) } </div></section>` ;
return `<div class="split report-secondary"><section class="panel"><h2>� 芾秐� 啣銁� � 𧊋蝏㮖� 憿� </h2><p class="small muted">� � � 㕑恥� 閧� 敶枏� � 芰� � � � 嚗䔶� � 𦯀� � 寞𠯫� 毺� � 剹� � </p><p>摰X� 敺� 𤣰甈橘� <strong>瞼 ${ yuan ( r . customerBalance ) } </strong></p><p> ${ r . materialPoolSettlement ? '霈W� 銝𤾸� 雿蹱� 甈� ' : '� � � 㕑恥� � ' } 敺� � 蝞堒� 憸嘅� <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">� 㗇� � 㗇𠯫� 𦠜迨� 滨� 摨枏� 瘚� 偌霈∠� 嚗𥟇� 瘙� � 颱� � 曄內� � � 㗇𠯫摨枏� � � 歇憭齿瓲� � 蟮� 潔� 摨枏� 憿菜� � 亙翰� 扳䰻霂U� � </p><div class="grid two"> ${ r . inventory . map ( i => `<div> ${ e ( pocketLabel ( i . pocket )) } <strong> ${ grams ( i . mg ) } g</strong> ${ inventoryBalanceCountHTML ( i ) } </div>` ). join ( '' ) } </div></section></div>` ;
2026-10-17 19:50:24 +08:00
}
function reportUnsettledHTML ( r ){
2026-11-14 01:16:35 +08:00
return `<section class="panel report-unsettled"><h2>� 𣂼� 鈭斗狡銝舘� 甈橘� � 芾秐� 啣銁嚗� </h2><p class="small muted">� � � 㕑恥� 𤏪� 銝滚� � 交� 蝑偦� 剹� � � � 啗”蝷� ${ e ( teamMemberName ( "owner" )) } � � 頧砍� ${ e ( teamMemberName ( "assistant" )) } � � 鉄${ e ( teamMemberName ( "owner" )) } � 湔𤣰甈曄� 霈W� 嚗� � 憭齿瓲韐扳狡銝𤾸⏚瘨血� 撅𠺶� � </p><div class="table-wrap"><table><thead><tr><th>霈W� </th><th class="number">韐扳狡敺� � </th><th class="number">� 拇隋敺� � </th><th class="number">${ e ( teamMemberName ( "owner" )) } � 湔𤣰� � 憸� </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+' � 閙� 韐孵� 銵� ':''):'� � � 桀� 憸� � � 霈W� � 㛖鍂� 鞉𧋦 � � 摰鮋� 韐寧鍂嚗� 鉄� 桀� 嚗� ',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">霂瑟� 餈嗘� 霈W� � � 𤣰� � 甈曇扇敶蓥� 敺桐縑� � 𣈲隞睃� � � 緵� 㻫� � 縑� 典㨃� 詨笆嚗𤤿頂蝏笔� � 芣𦻖� 交𣈲隞睃像� 啗揭� 𨰻� � </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 + ' / 摰X� ' + 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-14 01:16:35 +08:00
return [` $ { shopBrandName ()} � 啗揭 繚 $ { 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 ) } ` , `摰X� � 嗆狡� � 憸嘅� 瞼 ${ yuan ( receipts . net ) } ` , `霈W� � 㛖鍂韐批� � 鞉𧋦嚗� ${ reportCostAmount ( r . goods , s . missingCosts ) } ` , `霈W� 撌脖� 韐寧鍂嚗块� ${ 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 || '' } ` ), '' ] : []), '霈W� 銝𤾸睸� 𤾸� 憸脲� 蝏� � 霈W� � 匧� � 閙𠯫� 麄� � 睸� 擧� � 桀� � 交� 嚗� ' ,... orders , '' , ` ${ r . date } 韐阡𢒰摨枏� 嚗� � � � � 㗇𠯫� 𦠜迨� 齿� 瘞渲恣蝞梹� � � � � 颱� � 曄內� � � 㗇𠯫嚗头,...r.inventory.map(i=>` $ { pocketLabel ( i . pocket )} 嚗 � $ { grams ( i . mg )} g$ { i . countUnit === 'pair' || pocketCountsEnabled ( i . pocket ) ? ' / ' + stockCountText ( i . count ) : '' } `),'','� 芾秐� 啣銁� � � 撅� � 芰� 鈭钅★嚗� � � 埈𠯫� 毺� � 㚁� ',` 摰X � 敺 � 𤣰甈橘 � 瞼$ { yuan ( r . customerBalance )} `,` 霈W � 銝𤾸 � 雿蹱 � 甈曉 � 蝏枏 � 憸嘅 � $ { materialReportMoney ( r . settlementDue )} `,...r.unsettled.map(o=>` $ { o . number } 嚗朞揮甈曉 � 蝏 � $ { materialReportMoney ( o . costDue )} 嚗 � ⏚瘨血 � 蝏 � $ { materialReportMoney ( o . profitDue )} 嚗 � $ { teamMemberName ( "owner" )} � 湔𤣰 � � 憸 � 瞼$ { yuan ( o . ownerDirect )} 嚗峕 � 餃 � 蝏 � $ { materialReportMoney ( o . total )} `),'','敶枏� 敺� � � � � � � � 㕑恥� 𤏪� 銝滚� � 交� 蝑偦� 㚁� ',...r.warnings.map(w=>` $ { w . number || '' } $ { w . message } `),'',...(r.materialPoolSettlement?.pools?.length?[("� 拐� � 蹱狡銝� "+teamMemberName("assistant")+"蝏梶� 嚗� 迤� � "+teamMemberName("assistant")+"鈭� "+teamMemberName("owner")+"嚗諹� � � "+teamMemberName("owner")+"頧砍� � 拍� 嚗� "),...r.materialPoolSettlement.pools.map(item=>` $ { item . date } 嚗 � $ { teamMemberName ( "assistant" )} � 拐 � � 蹱狡 $ { materialReportMoney ( item . assistantInventoryCredit )} 嚗 � � � � 歇鈭文 � 憸 � 瞼$ { yuan ( item . transferred )} 嚗 � � 蝏 � $ { materialReportMoney ( item . settlementDue )} `),'']:[]),'� 嗆狡� 梁� � 硺犖� 餉扇嚗䔶� 隞� ”� 臭� 撟喳蝱� 芸𢆡� 賊� � � � 鈭箏� � � � 甈曆� 霈W� � 㛖鍂� 鞉𧋦� � � � 詨笆嚗偦� � 韐批� � 噼� 㛖鍂� 鞉𧋦嚗屸� 隞瑕� � � � 韐找� 甈曆� � 踺� � � � 拇隋銝滚鉄� 輻� � � 極韏� � � 偌� 萸� � '].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';
2026-11-14 01:16:35 +08:00
if(status){status.className='small '+(dirty?'danger-text':'muted');status.textContent=!owner?'� 芾粉嚗𤤿眏摨𦯀蜓韐血噡靽格㺿撟嗡� 摮䀹� � 啗挽蝵柴� � ':printSettingsSaving?'甇� 銁靽嘥� � 枏㫲霈曄蔭� � ':dirty?'靽格㺿� 擧𧊋靽嘥� 嚗諹窈� 孵稬� 靝� 摮䀹� � 啗挽蝵栽� 腈� � ':form.dataset.saved==='true'?'撌脖� 摮矋� � 枏㫲雿輻鍂敶枏� 霈曄蔭� � ':'敶枏� � � � 霈曄蔭嚗𥕢耨� 孵� 霂瑞� � 颱� 摮塩� � ';}
2026-10-17 19:50:24 +08:00
document.querySelectorAll('button[form="print-settings"]').forEach(button=>button.disabled=!owner||printSettingsSaving||busy);
}
async function savePrintSettings(form,data){
2026-11-14 01:16:35 +08:00
if(typeof shopSettingsDirty==='function'&&shopSettingsDirty())throw new Error('摨烾唍� 滨蔭撠𡁏𧊋靽嘥� 嚗諹窈� � � 摮睃� � 粹� 蝵殷� � 滢� 摮䀹� � 啗挽蝵柴� � ');
if(state.user.role!=='owner')throw new Error('� 枏㫲霈曄蔭� 勗� 銝餉揭� 瑚耨� 嫘� � ');
2026-10-17 19:50:24 +08:00
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{
2026-11-14 01:16:35 +08:00
await mutate('/api/printing',{...data,shopSettingsRevision:state.shopSettings?.revision});committed=true;syncPrintSettingsPreview();await refresh();
2026-10-17 19:50:24 +08:00
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-11-14 01:16:35 +08:00
$('#main').innerHTML=heading('SHOP & PRINT SETTINGS','摨烾唍銝擧� � 啗挽蝵� ','摨烾唍頨思遢� � � � 睃� 暺䁅恕� 潛� 銝� � 滨蔭嚗𥟇� � 啣� 撅� � 匧� � � 爾撘䭾嵗� � � � ')+(typeof shopSettingsHTML==='function'?shopSettingsHTML():'')+(typeof employeeManagementHTML==='function'?employeeManagementHTML():'')+` < div class = "split" >< section class = "panel" >< div class = "panel-title print-settings-title" >< div >< h2 > 摰X � � 枏㫲璅 ⊥ 踎 < /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"><p class="small muted">摨堒� � � � � 格� 憸䀝� � 𠉛頂靽⊥� � 典� � 粹� 蝵桐葉靽嘥� � � </p><fieldset class="print-settings-fields" ${canEdit?'':'disabled'}><div class="grid two">${field('摨堒� ','store',s.store,'text','maxlength="80" required readonly')}${field('� 閙旿� � � ','subtitle',s.subtitle,'text','maxlength="80" readonly')}${field('摰X� � 𠉛頂靽⊥� 嚗� � 匧‵嚗� ','contact',s.contact,'text','maxlength="80" readonly')}${field('銵冽聢� � 撠𤏸� � � ','rows',s.rows,'number','min="3" max="12" required')}${field('撌血𢰧� 讐宏嚗ém嚗峕迤� 啣� � 喉� ','offsetX',s.offsetX,'number','min="-30" max="30" step="0.1" required')}${field('銝𠹺� � 讐宏嚗ém嚗峕迤� 啣� 銝页� ','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('� � � 銵屸� 嚗ém嚗� ','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">銵交� 瘝輻鍂� 䔶� 霈W� � 瘀� 銝滢� � 滚� � 箏� � 𡝗𤣰� 乓� � 恥� 琿� 閫� 𦻖� � � 餈𥪜� � 鞉𧋦� � 𠿭韏� 犖� � ⏚瘨血� � � � � 滢� � 亙� � � </p></section></div><div class="grid two"><section class="panel"><h2>� 唳旿摨㮖� 憭� 遢</h2><p>${state.mode==='production'?'銝餉揭靽嘥� � 券� 蝵脫� � ∪膥� � 𡠺蝡喹QLite� 唳旿摨瓐� � ':'� 啣銁餈鞱� � 冽𧋦� 箄� � 函㴓憓� � 鈭𤑳垢甇� � � 唳旿摨枏� � 芷� 蝵脯� � '}</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">雿輻鍂� 啗揭銝梶鍂銵典� � 穃� 甇乓� � 耨� 孵� 憭齿瓲� 冽𧋦蝟餌� 摰峕� 嚗𥕦� 甇亙仃韐乩� � 滚� 霈W� � � � 敶勗� � 砍𧑐韐血𦛚靽嘥� � � </p>${state.sync.enabled?`<p>敺� � 甇� ${state.sync.pending} 憿� 繚 憭梯揖 ${state.sync.failed} 憿� </p>${stat
syncPrintSettingsPreview (); if ( typeof syncShopSettingsStatus === 'function' ) syncShopSettingsStatus ();
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-11-10 02:54:58 +08:00
for ( const type of [ 'input' , 'change' ]) document . addEventListener ( type , ev =>{ if ( typeof syncOrderAfterSaleForm === 'function' && ev . target . closest ( '#order-after-sale-form' )) syncOrderAfterSaleForm ( ev . target ); 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-14 01:16:35 +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' )){ if ( ev . target . name === 'returnedStockId' && typeof applyReturnedStockSelection === 'function' ) applyReturnedStockSelection ( ev . target . closest ( '.line-item' )); if ([ 'date' , 'member' ]. includes ( ev . target . name ) && typeof loadReturnedStockLots === 'function' ) loadReturnedStockLots ( true ); 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 = memberAccountPrefix ( 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' ) && [ 'kind' , 'pocket' , 'to' ]. includes ( ev . target . name )) syncInventoryChangeForm (); if ( ev . target . closest ( '#stock-form' ) && [ 'kind' , 'pocket' , 'to' ]. includes ( ev . target . name )) syncStockForm (); if ( ev . target . closest ( '#action-form[data-kind="return"]' )) syncReturnCounts (); 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-10 02:54:58 +08:00
if ( typeof orderAfterSaleAction === 'function' && a . startsWith ( 'order-after-sale-' )) return await orderAfterSaleAction ( a , b );
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 ( '甇� 銁霂餃� 霈W� 嚗諹窈蝔滚� 坔� � 滢� � � ' );
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 ( '霂瑕� � W� 銝𦠜活� 芰&霈斤� � 滢� 嚗� � � 餉扇摰鮋� 鈭斗狡� � ' ); 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 ( '霂瑕� � W� 銝𦠜活� 芰&霈斤� � 滢� 嚗� � � 䂿� 鈭支� � � ' ); $ ( '#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-11-14 01:16:35 +08:00
if ( a . startsWith ( 'demo-' )){ invalidateInventoryMovementViews ( true ); if ( typeof invalidateInventoryChangeViews === 'function' ) invalidateInventoryChangeViews (); await api ( '/api/demo-login' ,{ member : a . slice ( 'demo-' . length )}); return init ();}
2026-10-26 22:46:55 +08:00
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 ( '霂瑕� � W� 銝𦠜活� 芰&霈斤� � 滢� 嚗� � � � � � ' ); 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 ( '霂瑕� � W� 銝𦠜活� 芰&霈斤� � 滢� 嚗� � � 啣� � 桀� � � ' ); 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 ( '霂瑕� � W� 銝𦠜活� 芰&霈斤� � 滢� 嚗� � 霈啣� 鈭箸㺭� � ' ); 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-11-14 01:16:35 +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 = '摨枏� 撌脫� � 睃𢆡嚗屸△� W歇� 湔鰵� � 窈� 詨笆敶枏� � 圈� � 𤾸� 甈∩� 摮塩� � ' ;} 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-11-10 02:54:58 +08:00
const orderAfterSale = typeof orderAfterSaleOperation === 'function' && orderAfterSaleOperation ( p . url , p . data );
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-10 02:54:58 +08:00
try { r = await mutate ( p . url , p . data , p );} catch ( err ){ if ( orderAfterSale ) return orderAfterSaleError ( 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 ( orderAfterSale ) return await finishOrderAfterSaleSave ( p . url , p . data , r , detailContext || recoveryContext );
2026-11-08 03:30:58 +08:00
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 ( '� 煺犖� 啗扇敶訫歇蝖株恕嚗䔶� 隡𡁻� 憭滩扇韐� ' );}
2026-11-14 01:16:35 +08:00
if ( p . url === '/api/shop-settings' ){ await refresh (); syncShopSettingsStatus ( true ); return toast ( '摨烾唍� 滨蔭撌脖� 摮� ' );}
2026-10-17 19:50:24 +08:00
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-11-10 02:54:58 +08:00
if ( a === 'add-line' ){ $ ( '#lines' ). insertAdjacentHTML ( 'beforeend' , lineHTML ({}, $ ( '#lines' ). children . length + 1 ,{ materialPool :!! b . closest ( '#order-form' )})); if ( typeof loadReturnedStockLots === 'function' ) loadReturnedStockLots (); return updateTotal ();}
if ( a === 'remove-line' ){ if ( $ ( '#lines' ). children . length <= 1 ) throw new Error ( '霂瑁秐撠睲� � 嗘� 銵� � � � ' ); b . closest ( '.line-item' ). remove (); if ( typeof refreshReturnedStockChoices === 'function' ) refreshReturnedStockChoices (); 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 ;}
2026-11-14 01:16:35 +08:00
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' )){
2026-11-14 01:16:35 +08:00
if ( typeof shopSettingsDirty === 'function' && shopSettingsDirty ()) throw new Error ( '摨烾唍� 滨蔭撠𡁏𧊋靽嘥� 嚗諹窈� � � 摮睃� � 枏� 憸� � � � ' );
2026-10-17 19:50:24 +08:00
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 ( '摰X� � 枏㫲憿萄歇� 枏� 嚗𥡝𥅾� 芸枂� 堆� 霂瑕� 霈豢迨蝵𤑳� � 枏� � 啁� � � ' ); 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' ){
2026-11-14 01:16:35 +08:00
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 = ` ${ shopBrandName () } 撖寡揭- ${ r . from === r . date ? r . date : r . from + '� � ' + r . date } .txt` ; link . click (); setTimeout (()=> URL . revokeObjectURL ( link . href ), 1000 ); return ;
2026-10-17 19:50:24 +08:00
}
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' ) && currentOrder ) $ ( '#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-11-10 02:54:58 +08:00
if ( form . id === 'order-after-sale-form' ) return await submitOrderAfterSale ( 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-11-14 01:16:35 +08:00
const counts = Object . fromEntries ( peopleParts (). filter (([ part ])=>[ 'assistant1' , 'assistant2' ]. includes ( part )). map (([ part , label ])=>[ part + 'Count' , peopleCountInput ( data [ part + 'Count' ], label , true )]));
if ( peopleParts (). some (([ part ])=> ! [ 'assistant1' , 'assistant2' ]. includes ( part ))) counts . memberCounts = Object . fromEntries ( peopleParts (). map (([ part , label ])=>[ peoplePartMember ( part ), peopleCountInput ( data [ part + 'Count' ], label , true )]));
2026-10-25 14:19:24 +08:00
$ ( '#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 ( '摰X� 霂瑕‵� � 1嚚� 60摮㛖� 蝘啣鐤� 碶誨� 瑯� � ' );
2026-11-14 01:16:35 +08:00
if ( ! teamMemberKeys (). includes ( input . payer )) throw new Error ( '霂琿� 㗇𥋘餈嗵� � 桀� � 梯� � 臭� � � ' );
2026-10-25 14:19:24 +08:00
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-14 01:16:35 +08:00
if ( form . id === 'order-form' ){ validateNewPocketSelections ( form ); if ( typeof validateReturnedStockSelections === 'function' ) validateReturnedStockSelections ( 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 15:47:07 +08:00
if ( ! [ 'increase' , 'decrease' , 'transfer' ,...( state . user . role === 'owner' ? [ 'adjustment' ] : [])]. includes ( input . kind ) ||! activePocketKeys (). includes ( input . pocket )) throw new Error ( '霂琿� 㗇𥋘摨枏� � 其� � 諹揮� 塩� � ' );
if ( ! /^\d+(?:\.\d{1,3})?$/ . test ( input . grams ) || Number ( input . grams ) < ( input . kind === 'adjustment' ? 0 : 0.001 )) 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-11-08 15:47:07 +08:00
if ( pocketCountsEnabled ( input . pocket ) || input . kind === 'transfer' && pocketCountsEnabled ( input . to )) input . stockCount = stockCountValue ( data . stockCount ,{ signed : input . kind === 'adjustment' }); if ( input . kind === 'adjustment' && ( ! pocketCountsEnabled ( input . pocket ) || Number ( input . grams ) !== 0 )) throw new Error ( '� 芾� � 游笆� 啗窈� 㗇𥋘撌脣鍳� 典笆� 啁� 韐抒� 嚗� � � 滢� � � 0� � ' );
$ ( '#stock-error' ). innerHTML = '' ; await mutate ( '/api/stock' , input ); await refresh (); return toast ( input . kind === 'adjustment' ? '摨枏� 撖寞㺭撌脰� � � ' : '摨枏� ' + ({ increase : '憓𧼮� ' , decrease : '� 誩� ' , transfer : '撟喟宏' })[ input . kind ] + '撌脩蒈霈� ' );
2026-10-17 19:50:24 +08:00
}
2026-11-14 01:16:35 +08:00
if ( form . id === 'shop-settings-form' ) return await saveShopSettings ( form );
2026-10-17 19:50:24 +08:00
if ( form . id === 'print-settings' ) return await savePrintSettings ( form , data );
2026-11-14 01:16:35 +08:00
if ( form . id === 'password-form' ){ if ( typeof shopSettingsDirty === 'function' && ( shopSettingsDirty () || printSettingsDirty ())) throw new Error ( '霂瑕� 靽嘥� 摨烾唍銝擧� � 啗挽蝵殷� � 滢耨� 孵� � � � � ' ); await mutate ( '/api/password' , data ); return init ();}
2026-10-17 19:50:24 +08:00
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 15:47:07 +08:00
if ( kind === 'return' ){ input . returnPockets = currentOrder . lines . map (( _ , i )=> form . querySelector ( '[name="return-' + i + '"]' ) ? . value ?? data [ 'return-' + i ]); input . returnCounts = readReturnCounts ( form , input . returnPockets );}
if ( kind === 'complete' ){ input . stockCounts = {}; currentOrder . lines . forEach (( line , index )=>{ if ( line . unit === 'g' && pocketCountsEnabled ( line . pocket ) && line . stockCount == null ) input . stockCounts [ index ] = stockCountValue ( form . querySelector ( '[name="completeCount-' + index + '"]' ) ? . value ,{ title : '� � � ' + ( index + 1 ) + '摰鮋� � 箏� � 圈� 嚗� 笆嚗� ' });});} 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-14 01:16:35 +08:00
} catch ( err ){ if ( form . id === 'shop-settings-form' ) return shopSettingsError ( err ); if ( form . id === 'order-after-sale-form' && typeof orderAfterSaleError === 'function' ) return orderAfterSaleError ( 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 ( '� W � � � � 雿� ' , 'retry' , 'danger' ) : '' } </div>` ;}
2026-10-17 19:50:24 +08:00
});
init ();