diff --git a/新账系统/public/app.js b/新账系统/public/app.js
index 4c3be1d..af4d647 100644
--- a/新账系统/public/app.js
+++ b/新账系统/public/app.js
@@ -93,6 +93,33 @@ function retryableMutation(url){
/^\/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))$/
].some(pattern=>pattern.test(url));
}
+const loginSteps={
+ '/api/login':'提交登录',
+ '/api/setup':'建立账号',
+ '/api/session':'检查登录状态',
+ '/api/state':'读取账本'
+};
+function loginErrorHTML(error,fallbackStep){
+ const diagnostic=error.loginDiagnostic;
+ const step=diagnostic?loginSteps[diagnostic.path]:fallbackStep;
+ let message;
+ if(!diagnostic)message='页面处理出错,请刷新后重试。';
+ else if(error.status)message=error.message;
+ else if(diagnostic.timedOut)message='等待超过 25 秒,浏览器已停止等待。';
+ else if(diagnostic.status)message='已收到服务器响应,但未能读取完整的账本系统数据。';
+ else message='浏览器未收到 HTTP 响应,具体中断原因还需对照服务器日志。';
+ const time=new Date().toLocaleString('zh-CN',{timeZone:'Asia/Shanghai',hour12:false});
+ const lines=['步骤:'+step,'北京时间:'+time];
+ if(diagnostic){
+ lines.push('接口:'+diagnostic.method+' '+diagnostic.path,'HTTP 状态:'+(diagnostic.status||'未收到'));
+ lines.push('本次请求耗时:'+(diagnostic.elapsed/1000).toFixed(1)+' 秒');
+ }
+ // 只摘录已知浏览器错误,响应原文和表单内容不进入可复制的诊断信息。
+ const browserMessages=['Load failed','Failed to fetch','fetch is aborted','Fetch is aborted','NetworkError when attempting to fetch resource.','The operation was aborted.'];
+ if(browserMessages.includes(error.message))lines.push('浏览器提示:'+error.message);
+ const details=lines.join('\n');
+ return `${e(step)}失败${e(message)}
${e(details)}
${button('复制诊断信息','copy-login-diagnostic','quiet')}`;
+}
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()):'';
@@ -102,9 +129,11 @@ async function api(url,data,operation,retryContext){
try{
for(let attempt=0;;attempt++){
if(!active())throw accountChangedError();
- const controller=new AbortController(),timer=setTimeout(()=>controller.abort(),25000);
+ const started=Date.now(),controller=new AbortController(),timer=setTimeout(()=>controller.abort(),25000);
+ let responseStatus;
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});
+ responseStatus=r.status;
// 网关可能返回HTML,先按状态识别,不能让JSON解析失败掩盖502等。
if([408,502,503,504].includes(r.status))throw Object.assign(new Error('服务器暂时没有响应('+r.status+')'),{status:r.status,retryable:true});
const binary=r.ok&&retryContext?.responseType==='xlsx';
@@ -116,7 +145,10 @@ async function api(url,data,operation,retryContext){
}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;
+ if(!retry||!transient||attempt>=requestBackoffs.length){
+ if(loginSteps[url])err.loginDiagnostic={path:url,method:write?'POST':'GET',status:responseStatus,timedOut:controller.signal.aborted,elapsed:Date.now()-started};
+ throw err;
+ }
showRequestProgress(token,'连接暂时中断,正在自动'+(write?'确认':'重连')+'('+(attempt+1)+'/2)…');
await new Promise(resolve=>setTimeout(resolve,requestBackoffs[attempt]));
}finally{clearTimeout(timer);}
@@ -158,7 +190,17 @@ async function init(){
if(typeof invalidateInventoryChangeViews==='function')invalidateInventoryChangeViews();++inventoryRequest;++inventoryHistoryRequest;inventoryPage=null;invalidateInventoryMovementViews(true);
closePeopleCountHistory();
invalidateOrderDetailView(true);orderBookDetailList=null;++orderBookRequest;clearTimeout(orderBookTimer);
- try{session=await api('/api/session');if(!session.user)return login();$('#login').innerHTML='';$('#shell').hidden=false;restoreOrderEditTab();await refresh();showPending();}catch(err){$('#login').innerHTML=`
系统暂时没有连接上
${e(err.message)}
请保持启动窗口打开,再刷新页面。
`;}
+ let step='检查登录状态';
+ try{
+ session=await api('/api/session');
+ if(!session.user)return login();
+ $('#login').innerHTML='';$('#shell').hidden=false;
+ step='打开账本页面';
+ restoreOrderEditTab();await refresh();showPending();
+ }catch(err){
+ $('#shell').hidden=true;
+ $('#login').innerHTML=`${loginErrorHTML(err,step)}${button('重新读取','retry-login-load')}
`;
+ }
}
function login(){
$('#shell').hidden=true;
@@ -1985,6 +2027,13 @@ document.addEventListener('click',async ev=>{
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;}
const a=b.dataset.action;if(!a)return;
try{
+ if(a==='retry-login-load')return init();
+ if(a==='copy-login-diagnostic'){
+ const details=b.parentElement.querySelector('[data-login-diagnostic]');
+ try{await navigator.clipboard.writeText(details.innerText);b.textContent='已复制';}
+ catch{b.textContent='请长按或选中上方文字复制';}
+ return;
+ }
if(typeof orderAfterSaleAction==='function'&&a.startsWith('order-after-sale-'))return await orderAfterSaleAction(a,b);
if(typeof pocketManagerAction==='function'&&a.startsWith('pocket-manager-'))return await pocketManagerAction(a,b);
if(a==='after-sale-edit')return await openAfterSaleEdit(b.dataset.id);
@@ -2172,7 +2221,13 @@ document.addEventListener('submit',async ev=>{
if(form.id==='order-after-sale-form')return await submitOrderAfterSale(form);
if(form.id==='order-change-form')return await submitOrderChange(form);
if(form.id==='order-cancellation-form')return await submitOrderCancellation(form);
- if(form.id==='setup-form'||form.id==='login-form'){await api(form.id==='setup-form'?'/api/setup':'/api/login',data);return init();}
+ if(form.id==='setup-form'||form.id==='login-form'){
+ const url=form.id==='setup-form'?'/api/setup':'/api/login';
+ const target=$('#login-error');
+ target.textContent='';
+ try{await api(url,data);}catch(err){target.innerHTML=loginErrorHTML(err,loginSteps[url]);return;}
+ return init();
+ }
if(form.id==='material-purchase-form')return await submitMaterialPurchase(form);
if(form.id==='material-purchase-edit-form'||form.id==='material-purchase-delete-form')return await submitMaterialPurchaseChange(form);
if(form.id==='material-settlement-form')return await submitMaterialSettlement(form);
diff --git a/新账系统/test/request-retry.test.js b/新账系统/test/request-retry.test.js
index 3273d27..67a50cd 100644
--- a/新账系统/test/request-retry.test.js
+++ b/新账系统/test/request-retry.test.js
@@ -89,3 +89,25 @@ test('二进制Excel读取沿用账号校验与有限GET重试,HTML成功页
const html=harness(()=>new Response('login',{headers:{'Content-Type':'text/html'}}));await assert.rejects(html.run("api('/api/inventory/movements/export.xlsx',undefined,undefined,{responseType:'xlsx'})"),/文件格式异常/);assert.equal(html.calls.length,1);
const denied=harness(()=>httpError(403,'仅用于明确权限拒绝'));await assert.rejects(denied.run("api('/api/inventory/movements/export.xlsx',undefined,undefined,{responseType:'xlsx'})"),/明确权限拒绝/);assert.equal(denied.calls.length,1);
});
+
+test('登录诊断区分传输中断、超时、服务端拒绝和读取响应失败,隐藏提交内容',async()=>{
+ const cases=[
+ {fetcher:()=>{throw new TypeError('Load failed');},text:['提交登录失败','HTTP 状态:未收到','浏览器提示:Load failed']},
+ {fetcher:(_url,{signal})=>new Promise((_,reject)=>signal.addEventListener('abort',()=>reject(new Error('fetch is aborted')))),timeout:true,text:['等待超过 25 秒','HTTP 状态:未收到']},
+ {fetcher:()=>httpError(401,'账号或密码不正确'),text:['账号或密码不正确','HTTP 状态:401']},
+ {fetcher:()=>new Response('private-response-content'),text:['未能读取完整','HTTP 状态:200']}
+ ];
+ for(const c of cases){
+ const h=harness(c.fetcher,{timeout:c.timeout});
+ const html=await h.run("api('/api/login',{password:'secret-input'}).catch(err=>loginErrorHTML(err,'提交登录'))");
+ for(const text of [...c.text,'北京时间','POST /api/login','复制诊断信息'])assert.ok(html.includes(text),text);
+ assert.doesNotMatch(html,/secret-input|private-response-content/);
+ assert.equal(h.calls.length,1);
+ }
+ for(const [route,stage] of [['/api/session','检查登录状态'],['/api/state','读取账本']]){
+ const h=harness(()=>{throw new TypeError('Load failed');});
+ const html=await h.run(`api('${route}').catch(err=>loginErrorHTML(err,'打开账本页面'))`);
+ assert.ok(html.includes(stage+'失败'));
+ assert.ok(html.includes('GET '+route));
+ }
+});