سامانه صدور فاکتور و حسابداری

fix(phase0): make login responsive before ERP startup (#104)

* docs(state): record critical login readiness regression before implementation * fix(login): start auth early, gate app hydration and surface pending state * fix(login): release authenticated modules without holding login form * perf(login): parallel ordered deferred scripts and initially disabled login until auth handler ready * fix(login): prevent inert Google and OTP clicks before handlers initialize * fix(login): activate all auth actions only when handler functions exist * test(login): delayed static script and duplicate slow sign-in browser regressions * test(login): update cache invariant and require explicit login readiness gate * fix(login): bound stalled Supabase Auth network requests to unblock retries * test(login): auth network timeout and unchanged records transport * fix(startup): load shared monetary parser before deferred module initialization * fix(startup): preserve original synchronous ERP script execution contract * fix(startup): restore baseline global formatter dependency order * fix(login): enable password form immediately after core, before the 39 ERP scripts * test(login): verify early auth readiness against delayed optional extension * perf(login): prioritize downloading core auth and read-only connectivity scripts * fix(login): keep live feedback without conflicting global status role * docs(state): register tested login-ready fix, failures, and owner acceptance boundary

davoodmehraban89 committed Oct 12, 2026 at 20:01 UTC 8217f7ebb3cb66f4be471cadd62e70a9991524cf
6 files changed +180 -28
PROJECT_STATE.md
+13
@@ -27,6 +27,19 @@ The latest user message is the sole source of new instructions. Read AGENTS.md t
27 - **Exact PR-head verification:** Quality `38263379525` SUCCESS, static job `114859322898` logs **89/89 actual Chromium DOM PASS**, Accounting P0, double-entry, Golden and posted-history invariant PASS; disposable DB jobs `114859322415`, `114859323040`, `114859323233` SUCCESS. Security `38263379761` SUCCESS, CodeQL job `114859321621` and release safety job `114859321310` SUCCESS; Dependency Review `114859324783` SKIPPED. The post-merge main exact-SHA workflows for `4be48f74...` remain **NOT VERIFIED**, as do any owner-authenticated production F0-01/F0-02/F0-03/F0-04/F0-07, complete migration SQL parity and true adversarial RLS checks; these must not be inferred from CI or documented as COMPLETED.
28 - **Outcome and rollback:** state reconciliation recorded and merged, **PHASE 0 STILL OPEN**; no application runtime, production ledger, Supabase schema/RLS/Auth/roles/migrations, or destructive data changed. Documentation-only rollback is a targeted revert; next independent safe task is read-only PR #58 archive-parity assessment, then owner-authorized browser acceptance against legitimate existing data with no confidential credentials in chat.
29
30 +## 2026-10-12 Phase 0 owner escalation — login screen looks ready but ignores interaction (PLANNED / NOT FIXED)
31 +- **User symptom and P0 priority:** the email/password form becomes visible while login resources/session initialization are still loading; entering credentials and clicking login can appear to do nothing, sometimes never reaching the application. This is distinct from the previously shipped 14-extension download optimization PR #100 and must not be declared resolved by its CI.
32 +- **Baseline:** protected main `3445a87592341512dea56745e291c10e5225d8b4`; no Auth/DB/account changes authorized. Source investigation found 40+ synchronous parser-blocking local JS tags, auth init delayed until the 14 extension scripts settle, and `handleLogin()` silently returns when `authBusy` while `enterApp()` awaits full account-record download with no visible per-step status.
33 +- **Narrow intended correction:** preserve ordered script dependencies while fetching parser-blocking app JS in parallel; initialize the login form before non-auth extensions finish; keep authenticated app transition gated on complete scripts and tenant-scoped data loading; make login-in-progress/busy/error state visible rather than leaving an apparently inert form. Add Chromium network-throttled before/after regression and preserve all accounting/Golden/Security/DB gates. No mutation of real accounts, RLS, schema, roles, financial data or Auth server settings.
34 +- **Acceptance:** fresh login form becomes actionable before intentionally delayed optional app module, mocked/unauthenticated negative tests show no credential disclosure or duplicate sign-in, restored session never renders partial app, app status never silently ignores a second click. Gate release on same-SHA Quality/Security/Release/Deploy; owner affected-network authenticated acceptance remains separately OPEN. Rollback: revert single scoped PR and gated redeploy.
35 +
36 +### 2026-10-12 Phase 0 login interactivity repair — PR #104 CONTROLLED QA PASS / MERGE PENDING
37 +- **Verified baseline and root cause:** pre-fix email/password controls painted before the application finished downloading numerous parser-blocking scripts. Core login initialization also previously waited for all 14 extension scripts to settle. Once clicked, `authBusy` silently ignored repeat clicks while authenticated `enterApp()` awaited account + `pullAll()` with no inline stage status. This matches a plausible mechanism for the owner's reported unresponsive/spinning login; **affected ISP production session not reproduced**.
38 +- **Patch in [PR #104](https://github.com/davoodmehraban89/Factor-easy/pull/104):** priority preload of versioned `js/core.js` and `js/login-connectivity.js` in HTML; explicit disabled-until-handler-ready auth controls; immediate `initAuthSystem()` after core runs and the auth DOM exists, without waiting for 14 optional ordered extension requests. Restored and newly authenticated sessions wait `FinoraAppAssetsReady` before tenant-scoped hydration; the original 41 classic ERP script execution order remains unchanged (trial `defer` was rolled back after browser regressions). Login now reports ready / authenticating / waiting for modules / loading company records / slow network / error, and duplicate clicks never trigger duplicate Auth calls. Auth HTTP requests have a bounded 12s abort using the Supabase client fetch adapter; record/ledger writes and reads are unchanged.
39 +- **Actual Chromium regressions added:** optional extension held 3.5 seconds while password form was enabled at **379ms** in one controlled runner sample; mocked incomplete hydration retains progress and suppresses duplicate sign-in; synthetic hung Auth transport aborts without modifying records endpoint behavior; optional CDN outage and ordered extensions still covered. Synthetic times are **not** owner workstation benchmarks.
40 +- **Exact tested feature-head SHA `872d26e144aab81dc6c04a5eae536f02e15ec1b3`:** [Quality `38277314941`](https://github.com/davoodmehraban89/Factor-easy/actions/runs/38277314941) SUCCESS; static quality job **92/92 actual Chromium Playwright PASS (53.7s)**, 55 JS / 52 MJS syntax PASS, Golden accounting + immutable posted-history PASS; disposable PostgreSQL C8/D1/identity jobs all SUCCESS. [Security `38277315134`](https://github.com/davoodmehraban89/Factor-easy/actions/runs/38277315134) SUCCESS. Earlier full-defer attempt failed regression (16/92), rolled back; next failure 91/92 arose from duplicate role=status and was corrected without weakening the test. **This documentation follow-up commit has not yet received same-head CI.**
41 +- **Acceptance boundaries:** coded fix and controlled QA verified; protected-main merge, exact-SHA Release/Deploy and live domain readback are **PENDING**. Owner-authenticated sign-in on affected ISP, latency after tenant `pullAll()`, real user/password and device-specific stability remain **NOT VERIFIED / F0-01 OPEN**. Phase 0 remains OPEN. No accounts, Auth server config, schema, RLS, permissions, production data or financial history modified. Rollback: revert #104 and gated Pages redeploy.
42 +
43 ## Current change ledger
44 | 2026-10-07 | Owner requested accounting/product usability refinement from live screenshots: automatic non-user-entered floating-detail codes, contextual in-product guides (especially accounting/chart/dimensions), remove duplicate product internal tax ID and use product code as internal item ID, strengthen in-control product/person search, introduce hierarchical product group/subgroup coding with deterministic 6-digit product codes, and keep sale/purchase commercial-document workspace layout stable while only semantic fields change. | **IMPLEMENTED / LOCAL VERIFICATION PASSED / CI PENDING** | Baseline main = `7e58c75f7d754f378d94ca3f356c1ae580aa7ee3`. Automatic dimension type/value codes, contextual guides, product-code-as-internal-ID, normalized multi-token search, and additive six-digit product coding implemented. Existing historical codes preserved. Commercial sale/purchase workspaces now share a stable `صدور سند تجاری` header/actions layout; duplicate purchase sidebar injection removed; the public selector is the single document-type selector and the legacy internal invoice-kind control is hidden. Local syntax/static/commerce/UX/accounting phases 2–6/Golden checks passed; protected-branch CI remains pending. |
45
index.html
+15 -11
@@ -13,6 +13,8 @@
13 <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; font-src 'self' https://cdn.jsdelivr.net data:; img-src 'self' data: blob:; connect-src 'self' https://hcsixhqbyuhpshfwqpjx.supabase.co; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests" />
14 <meta name="apple-mobile-web-app-capable" content="yes" />
15 <meta name="theme-color" content="#071a48" />
16 +<link rel="preload" as="script" href="js/core.js?v=20261012-login-ready-v2" />
17 +<link rel="preload" as="script" href="js/login-connectivity.js?v=20261011-login-triage-v1" />
18 <script src="vendor/supabase.js"></script>
19 <script async src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
20 <link id="finora-optional-font" rel="stylesheet" media="print" href="https://cdn.jsdelivr.net/gh/rastikerdar/vazirmatn@v33.003/misc/Farsi-Digits/Vazirmatn-FD-font-face.css" />
@@ -228,31 +230,32 @@ body{background:#f6f9fc}
230 <div><h1>نرم‌افزار ERP سازمانی فینورا</h1><p>ورود یا ثبت‌نام امن در محیط سازمانی</p></div>
231 </div>
232 <div id="auth-form-container">
231 - <button class="btn auth-google" onclick="signInWithGoogle()"><span class="auth-google-mark">G</span><span>ادامه با Google</span></button>
233 + <button disabled class="btn auth-google" onclick="signInWithGoogle()"><span class="auth-google-mark">G</span><span>ادامه با Google</span></button>
234 <div class="auth-divider">یا با ایمیل</div>
235 <div class="form-group"><label>ایمیل</label><input type="email" id="auth-email" class="form-control" placeholder="name@example.com" autocomplete="email" autocapitalize="none" dir="ltr" /></div>
236 <div class="form-group"><label>رمز عبور</label><input type="password" id="auth-password" class="form-control" placeholder="رمز عبور" autocomplete="current-password" dir="ltr" /></div>
237 <div class="auth-actions">
236 - <button class="btn btn-primary" onclick="handleLogin()">ورود با رمز</button>
237 - <button class="btn btn-secondary" onclick="startEmailOtp(false,false)">ورود با کد ایمیل</button>
238 + <button id="auth-login-button" class="btn btn-primary" onclick="handleLogin()" disabled>ورود با رمز</button>
239 + <button disabled class="btn btn-secondary" onclick="startEmailOtp(false,false)">ورود با کد ایمیل</button>
240 </div>
239 - <button type="button" id="auth-connectivity-check" class="btn btn-secondary" style="width:100%;margin-top:10px" onclick="checkAuthConnectivity()">بررسی اتصال به سرور ورود</button>
241 + <p id="auth-login-status" aria-live="polite" data-state="loading" style="font-size:12px;line-height:1.9;margin-top:8px;min-height:24px;color:#475569">در حال آماده‌سازی فرم ورود...</p>
242 + <button disabled type="button" id="auth-connectivity-check" class="btn btn-secondary" style="width:100%;margin-top:10px" onclick="checkAuthConnectivity()">بررسی اتصال به سرور ورود</button>
243 <p id="auth-connectivity-result" aria-live="polite" style="font-size:12px;line-height:1.9;margin-top:8px;overflow-wrap:anywhere"></p>
241 - <button class="btn auth-signup" onclick="startEmailOtp(false,true)">ثبت‌نام با کد ایمیل</button>
244 + <button disabled class="btn auth-signup" onclick="startEmailOtp(false,true)">ثبت‌نام با کد ایمیل</button>
245 <p class="auth-note">ورود با کد ایمیل برای حساب موجود است. ایجاد حساب جدید فقط از مسیر «ثبت‌نام با کد ایمیل» انجام می‌شود.</p>
246 </div>
247 <div id="auth-otp-container" style="display:none">
248 <p style="font-size:13px;line-height:1.9;margin-bottom:12px">کد یک‌بارمصرف به <strong dir="ltr" id="auth-otp-email-label"></strong> ارسال شد. پوشه‌ی هرزنامه را هم ببینید.</p>
249 <div class="form-group"><label>کد تأیید</label><input type="text" id="auth-otp" class="form-control" inputmode="numeric" autocomplete="one-time-code" placeholder="------" dir="ltr" /></div>
247 - <div class="auth-actions"><button class="btn btn-primary" onclick="verifyEmailOtp()">تأیید کد</button><button class="btn btn-secondary" onclick="startEmailOtp(true)">ارسال دوباره</button></div>
248 - <button class="btn btn-secondary" style="width:100%;margin-top:10px" onclick="backToAuthMain()">بازگشت</button>
250 + <div class="auth-actions"><button disabled class="btn btn-primary" onclick="verifyEmailOtp()">تأیید کد</button><button disabled class="btn btn-secondary" onclick="startEmailOtp(true)">ارسال دوباره</button></div>
251 + <button disabled class="btn btn-secondary" style="width:100%;margin-top:10px" onclick="backToAuthMain()">بازگشت</button>
252 </div>
253 <div id="auth-setpass-container" style="display:none">
254 <p style="font-size:13px;line-height:1.9;margin-bottom:12px">ایمیل شما تأیید شد. برای ورودهای بعدی می‌توانید یک رمز عبور تعیین کنید.</p>
255 <div class="form-group"><label>رمز عبور جدید</label><input type="password" id="auth-newpass" class="form-control" placeholder="حداقل ۸ کاراکتر" autocomplete="new-password" dir="ltr" /></div>
256 <div class="form-group"><label>تکرار رمز عبور</label><input type="password" id="auth-newpass2" class="form-control" placeholder="تکرار رمز" autocomplete="new-password" dir="ltr" /></div>
254 - <button class="btn btn-primary" style="width:100%;margin-top:16px" onclick="saveNewPassword()">ذخیره رمز و ورود</button>
255 - <button class="btn btn-secondary" style="width:100%;margin-top:10px" onclick="skipSetPassword()">فعلاً بدون رمز ادامه بده</button>
257 + <button disabled class="btn btn-primary" style="width:100%;margin-top:16px" onclick="saveNewPassword()">ذخیره رمز و ورود</button>
258 + <button disabled class="btn btn-secondary" style="width:100%;margin-top:10px" onclick="skipSetPassword()">فعلاً بدون رمز ادامه بده</button>
259 </div>
260 </div>
261 <aside class="auth-visual" aria-label="معرفی فینورا">
@@ -887,7 +890,7 @@ body{background:#f6f9fc}
890 <div class="dock-tab" data-view="view-settings" onclick="switchView('view-settings')"><span>⚙️</span><span>تنظیمات</span></div>
891 </nav>
892
890 -<script src="js/core.js?v=20261011-login-triage-v1"></script>
893 +<script src="js/core.js?v=20261012-login-ready-v2"></script>
894 <script src="js/login-connectivity.js?v=20261011-login-triage-v1"></script>
895 <script src="js/admin.js?v=20261012-provision-error-v1"></script>
896 <script src="js/sync.js?v=20260928-data-v4"></script>
@@ -901,7 +904,7 @@ body{background:#f6f9fc}
904 <script src="js/companies.js?v=20260928-integrity-v4"></script>
905 <script src="js/backup.js?v=20260928-data-v3"></script>
906 <script src="js/words.js"></script>
904 -<script src="js/bootstrap.js?v=20261012-startup-parallel-v1"></script>
907 +<script src="js/bootstrap.js?v=20261012-login-ready-v2"></script>
908
909 <style>
910 .form-control, textarea, select { direction: rtl; }
@@ -910,6 +913,7 @@ body{background:#f6f9fc}
913 <script src="js/patches.js"></script>
914 <script src="js/idle-and-reports.js?v=20260928-phase3-v5"></script>
915 <script src="js/money-format.js"></script>
916 +
917 <script src="js/projects.js?v=20260928-projects-v7"></script>
918 <script src="js/invoice-excel-import.js"></script>
919 <script src="js/purchases.js?v=20261011-persian-print-v1"></script>
js/bootstrap.js
+8 -8
@@ -41,15 +41,15 @@ window.addEventListener('DOMContentLoaded',async()=>{
41 const started=performance.now();
42 const results=await Promise.allSettled(FINORA_EXTENSION_SCRIPTS.map(finoraLoadScript));
43 const failed=results.flatMap((r,i)=>r.status==='rejected'?[FINORA_EXTENSION_SCRIPTS[i]]:[]);
44 - window.FinoraStartupStatus={
44 + Object.assign(window.FinoraStartupStatus,{
45 extensionCount:FINORA_EXTENSION_SCRIPTS.length,
46 failedExtensionCount:failed.length,
47 - extensionLoadMs:Math.round(performance.now()-started)
48 - };
47 + extensionLoadMs:Math.round(performance.now()-started),
48 + extensionsReady:true
49 + });
50 if(failed.length)console.error('Finora platform extension assets unavailable:',failed);
50 - // Never start a restored user session against half-loaded application modules.
51 - if(!currentUser)await initAuthSystem();
52 - // UI fixtures and diagnostics may now wait for the completed session check.
53 - // This flag contains no session/identity information.
54 - window.FinoraStartupStatus.authChecked=true;
51 + // A successful sign-in/restored session must wait for these modules, but
52 + // rendering the interactive email/password form never waits for them.
53 + window.finoraMarkAppAssetsReady();
54 + if(window.FinoraStartupStatus.authSessionChecked)window.FinoraStartupStatus.authChecked=true;
55 });
js/core.js
+73 -8
@@ -32,7 +32,24 @@ function addDaysToDate(baseDateStr,days){
32
33 const SUPABASE_URL='https://hcsixhqbyuhpshfwqpjx.supabase.co';
34 const SUPABASE_KEY='sb_publishable_2y8IsGdhqeLDPkEp7mBF4w_X4yji16D'; // publishable (public by design); access is enforced by RLS on the server
35 -const sb=window.supabase.createClient(SUPABASE_URL,SUPABASE_KEY,{auth:{persistSession:true,autoRefreshToken:true,detectSessionInUrl:true,flowType:'pkce'}});
35 +// Browser fetch otherwise may hang indefinitely on unstable ISPs. Bound only
36 +// Auth transport requests; financial record requests keep their own semantics.
37 +// This abort releases the Auth SDK lock and permits a clear, retryable error.
38 +function finoraBoundedAuthFetch(input,init={},timeoutMs=12000){
39 + const url=typeof input==='string'?input:String(input?.url||input||'');
40 + if(!url.includes('/auth/v1/'))return fetch(input,init);
41 + const controller=new AbortController();
42 + const upstream=init?.signal||input?.signal;
43 + const abortFromUpstream=()=>controller.abort();
44 + if(upstream?.aborted)controller.abort();
45 + else if(upstream)upstream.addEventListener('abort',abortFromUpstream,{once:true});
46 + const timeout=setTimeout(()=>controller.abort(),timeoutMs);
47 + return fetch(input,{...init,signal:controller.signal}).finally(()=>{
48 + clearTimeout(timeout);
49 + if(upstream)upstream.removeEventListener('abort',abortFromUpstream);
50 + });
51 +}
52 +const sb=window.supabase.createClient(SUPABASE_URL,SUPABASE_KEY,{global:{fetch:finoraBoundedAuthFetch},auth:{persistSession:true,autoRefreshToken:true,detectSessionInUrl:true,flowType:'pkce'}});
53 const ID_RE=/^[A-Za-z0-9_-]{1,64}$/;
54 const COLLS=['companies','contacts','products','invoices','purchases','cheques','expenses','payments','settings','fiscalYears','accounts','dimensionTypes','dimensionValues','accountDimensionRules','branches','projects','projectLinks','postingProfiles','journalVouchers','journalLines','journalLineDimensions','contracts','contractAmendments','contractParties','contractDeductions','guarantees','guaranteeEvents','contractStatements','phase4Audit','warehouses','stockMovements','inventoryCounts','fixedAssets','assetDepreciations','currencies','exchangeRates','costCenters','importBatches','integrationConnections','integrationOutbox','phase5Audit','employees','employmentContracts','employeeLeave','cashboxes','pettyCashFunds','complianceRules','payrollRuns','payrollLines','employeeBenefitAccruals','pettyCashTransactions','budgets','costDrivers','costAllocations','intercompanyTransactions','enterpriseAudit'];
55
@@ -41,6 +58,16 @@ function todayISO(){return new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Tehra
58
59 let currentUser=null;
60 let authBusy=false;
61 +// Authentication starts independently of the optional ERP modules.
62 +let finoraAppAssetsResolve;
63 +window.FinoraAppAssetsReady=new Promise(resolve=>{finoraAppAssetsResolve=resolve;});
64 +window.finoraMarkAppAssetsReady=()=>finoraAppAssetsResolve();
65 +window.FinoraStartupStatus={authFormReady:false,authSessionChecked:false,authChecked:false,extensionsReady:false};
66 +function setAuthLoginStatus(message,state){
67 + const el=document.getElementById('auth-login-status');
68 + if(el){el.textContent=message;el.dataset.state=state||'ready';}
69 +}
70 +
71
72 const EMAIL_RE=/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
73 const OTP_RE=/^[0-9]{6,10}$/;
@@ -104,7 +131,16 @@ function reportOAuthReturnError(){
131 }
132 }catch(e){}
133 }
134 +let finoraAuthInitStarted=false;
135 async function initAuthSystem(){
136 + if(finoraAuthInitStarted)return;
137 + finoraAuthInitStarted=true;
138 + const screen=document.getElementById('auth-screen');
139 + if(screen)screen.style.display='flex';
140 + showAuthPanel('main');
141 + if(screen)screen.querySelectorAll('button').forEach(button=>{button.disabled=false;});
142 + window.FinoraStartupStatus.authFormReady=true;
143 + setAuthLoginStatus('فرم ورود آماده است.','ready');
144 // Remove the legacy plaintext user database that older versions kept in this browser.
145 try{localStorage.removeItem(AUTH_KEY);}catch(e){}
146 try{sessionStorage.removeItem('easy_factor_session_v4_7');}catch(e){}
@@ -112,24 +148,39 @@ async function initAuthSystem(){
148 sb.auth.onAuthStateChange(ev=>{if(ev==='SIGNED_OUT'&&currentUser){window.location.reload();}});
149 try{
150 const {data}=await sb.auth.getSession();
115 - if(data&&data.session){await enterApp(data.session.user);return;}
151 + if(data&&data.session&&!authBusy){await enterApp(data.session.user);return;}
152 }catch(e){console.error(e);}
117 - document.getElementById('auth-screen').style.display='flex';
118 - showAuthPanel('main');
153 + finally{
154 + window.FinoraStartupStatus.authSessionChecked=true;
155 + if(window.FinoraStartupStatus.extensionsReady)window.FinoraStartupStatus.authChecked=true;
156 + }
157 }
158 async function handleLogin(){
121 - if(authBusy)return;
159 + if(authBusy){
160 + setAuthLoginStatus('درخواست ورود قبلی هنوز در حال انجام است؛ لطفاً منتظر نتیجه بمانید.','busy');
161 + return;
162 + }
163 const email=normalizeEmail(document.getElementById('auth-email').value);
164 const pass=document.getElementById('auth-password').value;
165 if(!EMAIL_RE.test(email)){alert('آدرس ایمیل معتبر وارد کنید.');return;}
166 if(!pass){alert('رمز عبور را وارد کنید؛ یا «ادامه با کد ایمیل» را بزنید.');return;}
167 authBusy=true;
168 + setAuthLoginStatus('در حال بررسی اطلاعات ورود...','loading');
169 + const slowNotice=setTimeout(()=>setAuthLoginStatus('پاسخ سرور ورود طولانی شده است. اگر ادامه یافت از «بررسی اتصال به سرور ورود» استفاده کنید.','slow'),9000);
170 try{
171 const {data,error}=await sb.auth.signInWithPassword({email,password:pass});
172 if(error)throw error;
173 + if(!data?.user)throw new Error('No authenticated user was returned');
174 + setAuthLoginStatus('ورود تأیید شد؛ در حال آماده‌سازی محیط و اطلاعات شرکت...','loading');
175 await enterApp(data.user);
131 - }catch(err){alert(authMsg(err));if(typeof isAuthNetworkError==='function'&&isAuthNetworkError(err)&&typeof checkAuthConnectivity==='function')void checkAuthConnectivity();}
132 - finally{authBusy=false;}
176 + }catch(err){
177 + setAuthLoginStatus('ورود انجام نشد؛ پیام خطا را بررسی و دوباره تلاش کنید.','error');
178 + alert(authMsg(err));
179 + if(typeof isAuthNetworkError==='function'&&isAuthNetworkError(err)&&typeof checkAuthConnectivity==='function')void checkAuthConnectivity();
180 + }finally{
181 + clearTimeout(slowNotice);
182 + authBusy=false;
183 + }
184 }
185 async function signInWithGoogle(){
186 if(authBusy)return;
@@ -202,12 +253,16 @@ async function skipSetPassword(){
253 }
254 async function enterApp(authUser){
255 try{
205 - currentUser=await fetchCurrentUser(authUser);
256 + setAuthLoginStatus('در حال آماده‌سازی محیط کار...','loading');
257 + const [profile]=await Promise.all([fetchCurrentUser(authUser),window.FinoraAppAssetsReady]);
258 + currentUser=profile;
259 + setAuthLoginStatus('در حال دریافت اطلاعات شرکت...','loading');
260 await pullAll();
261 const prefs=typeof getMySettings==='function'?getMySettings():null;if(prefs?.user_display_name&&!currentUser.fullName)currentUser.fullName=prefs.user_display_name;if(prefs?.professional_role)currentUser.professionalRole=prefs.professional_role;
262 }catch(err){
263 console.error(err);
264 currentUser=null;
265 + setAuthLoginStatus('دریافت اطلاعات حساب ناموفق بود؛ اتصال را بررسی و دوباره تلاش کنید.','error');
266 alert('خطا در بارگذاری اطلاعات حساب. اتصال اینترنت را بررسی کنید و دوباره وارد شوید.');
267 document.getElementById('auth-screen').style.display='flex';
268 showAuthPanel('main');
@@ -233,6 +288,16 @@ async function handleLogout(){
288 window.location.reload();
289 }
290
291 +// This classic core script sits AFTER the auth DOM, but BEFORE the heavy
292 +// ERP scripts. Enable sign-in now while the parser continues fetching modules.
293 +if(document.getElementById('auth-screen')){
294 + void initAuthSystem();
295 +}else if(document.readyState==='loading'){
296 + document.addEventListener('DOMContentLoaded',()=>{void initAuthSystem();},{once:true});
297 +}else{
298 + void initAuthSystem();
299 +}
300 +
301 function updateLicenseDisplay(user){
302 if(!user)return;
303 const badge=document.getElementById('user-license-status-badge');
scripts/login-connectivity-check.mjs
+4 -1
@@ -7,7 +7,10 @@ assert(html.includes('id="auth-connectivity-check"'),'Missing diagnostic action'
7 assert(html.includes('id="auth-connectivity-result"'),'Missing accessible result');
8 assert(html.includes('id="auth-connectivity-result" aria-live="polite"'),'Diagnostic must announce updates without adding a conflicting global role=status');
9 assert(html.includes('js/login-connectivity.js?v=20261011-login-triage-v1'),'Missing versioned script');
10 -assert(html.includes('js/core.js?v=20261011-login-triage-v1'),'Core.js cache version not bumped');
10 +assert(html.includes('js/core.js?v=20261012-login-ready-v2'),'New login core must have a distinct production cache version');
11 +assert(html.includes('js/bootstrap.js?v=20261012-login-ready-v2'),'Parallel bootstrap must also be cache-busted');
12 +assert(html.includes('id="auth-login-button"')&&html.includes('id="auth-login-status"'),'Login control requires real readiness/progress feedback');
13 +assert(core.includes('window.FinoraAppAssetsReady'),'Authenticated workspace must remain gated until all module scripts settle');
14 assert(core.includes('isAuthNetworkError(err)'),'Network error diagnostic not wired');
15 assert(!core.includes('اتصال اینترنت/VPN را بررسی کنید'),'Misleading VPN-only error text remains');
16 assert(diagnostic.includes("'/auth/v1/health'"),'Must test the real GoTrue health path');
scripts/phase0-startup-performance.spec.js
+67
@@ -43,3 +43,70 @@ test('F0 startup is independent of optional spreadsheet CDN and keeps on-demand
43 expect(await page.evaluate(()=>typeof window.finoraDownloadConfiguredTemplate)).toBe('function');
44 expect(await page.evaluate(()=>typeof window.XLSX)).toBe('undefined');
45 });
46 +
47 +test('F0 login controls are actionable before a delayed non-auth extension completes',async({page})=>{
48 + const late='office-workflow.js';
49 + let lateFinished=false;
50 + await page.route('**/js/'+late+'*',async route=>{
51 + await new Promise(resolve=>setTimeout(resolve,3500));
52 + lateFinished=true;
53 + await route.continue();
54 + });
55 + const start=Date.now();
56 + await page.goto(BASE,{waitUntil:'domcontentloaded'});
57 + await expect(page.locator('#auth-login-button')).toBeEnabled({timeout:3000});
58 + const readyMs=Date.now()-start;
59 + console.info('F0 login form enabled before late ERP script, elapsed ms:',readyMs);
60 + expect(lateFinished,'Login should not wait on optional ERP extension').toBe(false);
61 + await page.locator('#auth-email').fill('nobody@example.test');
62 + await page.locator('#auth-password').fill('qa-fixture-only');
63 + await expect(page.locator('#auth-email')).toHaveValue('nobody@example.test');
64 + await expect(page.locator('#auth-login-status')).toHaveAttribute('data-state','ready');
65 + // Never submit this fake identity to a real server in a startup smoke.
66 +});
67 +
68 +test('F0 login visibly reports a pending mocked sign-in and suppresses duplicate requests',async({page})=>{
69 + await page.goto(BASE,{waitUntil:'domcontentloaded'});
70 + await expect.poll(()=>page.evaluate(()=>window.FinoraStartupStatus?.authChecked),{timeout:15000}).toBe(true);
71 + await page.evaluate(()=>{
72 + window.finoraFixtureLoginCalls=0;
73 + sb.auth.signInWithPassword=async()=>{
74 + window.finoraFixtureLoginCalls+=1;
75 + return {data:{user:{id:'fixture-nonreal'}},error:null};
76 + };
77 + window.fetchCurrentUser=async()=>({id:'fixture-nonreal',email:'fixture@example.test',role:'accountant'});
78 + window.pullAll=()=>new Promise(()=>{}); // intentionally stalled fixture, zero DB activity
79 + });
80 + await page.locator('#auth-email').fill('fixture@example.test');
81 + await page.locator('#auth-password').fill('synthetic-fixture-only');
82 + await page.locator('#auth-login-button').click();
83 + await expect(page.locator('#auth-login-status')).toHaveAttribute('data-state','loading');
84 + await page.locator('#auth-login-button').click();
85 + await expect(page.locator('#auth-login-status')).toHaveAttribute('data-state','busy');
86 + expect(await page.evaluate(()=>window.finoraFixtureLoginCalls)).toBe(1);
87 + await expect(page.locator('#auth-screen')).toBeVisible();
88 +});
89 +
90 +test('F0 auth transport times out stalled requests without affecting other Supabase endpoints',async({page})=>{
91 + await page.goto(BASE,{waitUntil:'domcontentloaded'});
92 + const result=await page.evaluate(async()=>{
93 + const original=window.fetch,called=[];
94 + window.fetch=(input,init={})=>new Promise((resolve,reject)=>{
95 + called.push({url:String(input),signal:!!init.signal});
96 + if(!String(input).includes('/auth/v1/'))return resolve({ok:true});
97 + init.signal.addEventListener('abort',()=>reject(new DOMException('aborted','AbortError')),{once:true});
98 + });
99 + try{
100 + let timedOut=false;
101 + try{await finoraBoundedAuthFetch('https://example.test/auth/v1/token',{},40);}
102 + catch(err){timedOut=err.name==='AbortError';}
103 + await finoraBoundedAuthFetch('https://example.test/rest/v1/records',{},40);
104 + return {timedOut,called};
105 + }finally{window.fetch=original;}
106 + });
107 + expect(result.timedOut).toBe(true);
108 + expect(result.called).toEqual([
109 + {url:'https://example.test/auth/v1/token',signal:true},
110 + {url:'https://example.test/rest/v1/records',signal:false}
111 + ]);
112 +});