@davoodmehraban89 / Factor-easy-2 Mirror · read-only / commits / 4288e4a
Fork 0

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

Mirrored from https://github.com/davoodmehraban89/Factor-easy.git

Synced Dec 3, 17:00 UTC

Fix test-account lifetime license mislabel caused by async organization bootstrap (#145)

* docs: record verified test-account lifetime entitlement and suspected org-context load race * fix: defer account license read until organization context is installed * fix: signal organization account context availability after module loads * fix: bust cached core/bootstrap versions for organization license readiness * fix: ensure fresh organization adapter is fetched for cached authenticated browsers * test: force delayed organization loader and verify lifetime license never snapshots placeholder * docs: record org-license race fix, synthetic regression and required release gates * test: align cache assertions with new organzation-aware startup versions * test: wait for org-context adapter before legacy expired-license fixture

davoodmehraban89 committed Oct 15, 2026 at 00:03 UTC 4288e4a0473f7b58d4e7ac5865d3396825a34d00
8 files changed +121 -11
PROJECT_STATE.md
+10
@@ -697,3 +697,13 @@ Owner reports login blocked with generic 'check internet/VPN' network error on l
697 - Owner environment: Supabase organization now `Finora – Production`, project `Finora ERP – Production`, project ref `hcsixhqbyuhpshfwqpjx` (matches `js/core.js`). Supabase Free scheduled backup unavailable; Cloudflare R2 activation requires a valid card and was not completed, so this solution uses no paid subscription.
698 - **Exact next work:** owner powers on authorized Windows computer and brings Desktop Commander online; obtain Direct or Session-pooler DB endpoint without disclosing password; locally generate/secure an age identity; install matching PostgreSQL 17 client and age; run first encrypted backup with password entered privately; verify archive, copy to a second device, restore to *empty localhost disposable DB*, independently validate recovered rows/config, then plan time-based Windows Task Scheduler with OS-protected credentials and log rotation. Keep status `PRODUCTION_BACKUP_NOT_RUN / RECOVERY_NOT_VERIFIED` until each test is evidenced.
699 - Historical continuity from superseded documentation PR #142: [PR #141](https://github.com/davoodmehraban89/Factor-easy/pull/141) head `c33a6a89dccfe2558c4cc77b041ef3910a4e4f77`, Quality `38605198345` SUCCESS, Security `38605198098` SUCCESS, protected main squash `9693b342670915271e3b471cf68da44b2530d99a`. Company-form Save state respects `canWrite()`; lifetime organization license discrepancy still unverified and must not be overridden.
700 +
701 +
702 +### 2026-10-14 test-account lifetime license rendered expired — ORGANIZATION BOOTSTRAP RACE CONFIRMED IN SOURCE / FIX IN PROGRESS
703 +- **Owner-provided READ-ONLY production SQL:** both owner and test account separately have exactly one active organization ownership, with a `public.licenses` organization record `plan=lifetime, status=active, ends_at=2099-01-01`; the test account's organization is `davood_mehraban`. Do not change licenses or confuse the two identities. Screenshots are evidence of DB state; production browser account matching is still an independent acceptance gate.
704 +- **Reproduced source ordering concern:** `js/core.js` calls `initAuthSystem()` while HTML is parsing; a saved session triggers `enterApp()`, which currently starts `fetchCurrentUser()` in parallel with `window.FinoraAppAssetsReady`. The original core `fetchCurrentUser` returns placeholder `type=none,status=unavailable`; `js/organization-rbac.js` arrives later through asynchronous ordered extension loading (`js/bootstrap.js`) and **then** wraps `fetchCurrentUser` to load the real org license. If auth lookup starts earlier, the app retains an unavailable placeholder and `updateLicenseDisplay()` treats missing end date as expired. This is a plausible deterministic race; a mocked Chromium interleaving must be added to prove it.
705 +- **Authorized minimal fix:** signal when organization-context wrapper is installed; gate profile entitlement fetch on that signal while keeping the login form interactive and all existing bounded aborts; retain parallel wait for remaining app assets; distinguish genuinely expired/cancelled subscription from unavailable/unknown in the read-only badge. No Supabase schema, RLS, Auth, role, entitlement, financial data or migration changes. Synthetic Playwright race/regression tests, Quality/Security/Pages gates and real owner/test-account production acceptance are required separately. Rollback: revert scoped PR and guarded redeploy.
706 +- **Status before implementation:** branch `fix/finora-org-license-bootstrap-race-20261014` created from protected `main`; code fix/CI/merge/release all PENDING.
707 +
708 +- **Scoped code/test implemented (CI PENDING):** `js/core.js` now creates `FinoraOrganizationContextReady`, keeps auth controls independent, and waits for organization adapter readiness before starting entitlement/profile fetch; asset loading still runs concurrently and inherits existing abort timeout. `js/organization-rbac.js` signals after its full module/wrapper installation. `updateLicenseDisplay` differentiates unavailable/unknown from truly expired/cancelled without loosening `canWrite()`. `index.html` and `js/bootstrap.js` cache-bust updated core, loader and org adapter for previously cached browser sessions. New synthetic Chromium test in `scripts/phase0-startup-performance.spec.js` delays organization module 1600ms while starting a fake authenticated transition and asserts no premature placeholder fetch, correct lifetime badge, non-expiry for unavailable state and preserved no-write-to-production behavior. No real account credentials or SQL changes.
709 +- **Evidence needed:** exact head static/build/browser + disposable DB and security CI; protected main merge; guarded Pages deploy + owner test-account hard reload should show `وضعیت اشتراک : نامحدود` if same verified organization context. If not, inspect browser account/organization/version rather than changing entitlements.
index.html
+3 -3
@@ -13,7 +13,7 @@
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=20261013-static-pages-guard-v2" />
16 +<link rel="preload" as="script" href="js/core.js?v=20261014-org-license-readiness-v1" />
17 <link rel="preload" as="script" href="js/login-connectivity.js?v=20261012-data-probe-v3" />
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>
@@ -893,7 +893,7 @@ body{background:#f6f9fc}
893 <!-- The credential-free connectivity action must be loaded before core declares
894 login actions interactive. Hardened Pages binds static handlers just before core. -->
895 <script src="js/login-connectivity.js?v=20261012-data-probe-v3"></script>
896 -<script src="js/core.js?v=20261013-static-pages-guard-v2"></script>
896 +<script src="js/core.js?v=20261014-org-license-readiness-v1"></script>
897 <script src="js/admin.js?v=20261012-provision-error-v1"></script>
898 <script src="js/sync.js?v=20261012-login-read-cancel-v1"></script>
899 <script src="js/ui.js?v=20261002-shell-scroll-ownership-v2"></script>
@@ -906,7 +906,7 @@ body{background:#f6f9fc}
906 <script src="js/companies.js?v=20260928-integrity-v4"></script>
907 <script src="js/backup.js?v=20260928-data-v3"></script>
908 <script src="js/words.js"></script>
909 -<script src="js/bootstrap.js?v=20261013-ordered-bundle-v1"></script>
909 +<script src="js/bootstrap.js?v=20261014-org-license-readiness-v1"></script>
910
911 <style>
912 .form-control, textarea, select { direction: rtl; }
js/bootstrap.js
+1 -1
@@ -3,7 +3,7 @@
3 // browsers may download in parallel but preserve script execution/dependencies.
4 // Auth starts only once all extensions have finished loading or failed.
5 const FINORA_EXTENSION_SCRIPTS=[
6 - "js/organization-rbac.js?v=20261012-login-scoped-read-v1",
6 + "js/organization-rbac.js?v=20261014-org-license-readiness-v1",
7 "js/organization-invitations.js?v=20260930-eli3-v1",
8 "js/organization-enterprise-ux.js?v=20260930-eli4-v1",
9 "js/platform-modules.js?v=20261001-platform-c6-v1",
js/core.js
+19 -3
@@ -62,6 +62,11 @@ let authBusy=false;
62 let finoraAppAssetsResolve,finoraAppAssetsReject;
63 window.FinoraAppAssetsReady=new Promise((resolve,reject)=>{finoraAppAssetsResolve=resolve;finoraAppAssetsReject=reject;});
64 window.FinoraAppAssetsReady.catch(()=>{});
65 +// The account entitlement lookup MUST NOT race the organization module's
66 +// fetchCurrentUser wrapper. Do not stall the separate interactive login form.
67 +let finoraOrganizationContextResolve;
68 +window.FinoraOrganizationContextReady=new Promise(resolve=>{finoraOrganizationContextResolve=resolve;});
69 +window.finoraMarkOrganizationContextReady=()=>finoraOrganizationContextResolve();
70 window.finoraMarkAppAssetsReady=()=>finoraAppAssetsResolve();
71 window.finoraMarkAppAssetsFailed=()=>finoraAppAssetsReject(new Error('FINORA_APP_ASSETS_UNAVAILABLE'));
72
@@ -321,8 +326,15 @@ async function enterApp(authUser,{timeoutMs=25000}={}){
326 },timeoutMs);
327 try{
328 setAuthLoginStatus('در حال بازیابی نشست و آماده‌سازی محیط کار...','loading');
329 + // Waiting for ALL assets in parallel was not sufficient: the old account
330 + // lookup could resolve BEFORE organization-rbac.js installed its wrapper,
331 + // leaving a placeholder 'unavailable' license until the next login.
332 + const organizationAccount=window.FinoraOrganizationContextReady.then(()=>{
333 + if(controller.signal.aborted)throw new Error('FINORA_LOGIN_READ_TIMEOUT');
334 + return fetchCurrentUser(authUser,{signal:controller.signal});
335 + });
336 const [profile]=await Promise.all([
325 - finoraTrackLoginRead('ACCOUNT_CONTEXT',finoraAbortableRead(fetchCurrentUser(authUser,{signal:controller.signal}),controller.signal)),
337 + finoraTrackLoginRead('ACCOUNT_CONTEXT',finoraAbortableRead(organizationAccount,controller.signal)),
338 finoraTrackLoginRead('APP_ASSETS',finoraAbortableRead(window.FinoraAppAssetsReady,controller.signal))
339 ]);
340 if(controller.signal.aborted)throw new Error('FINORA_LOGIN_READ_TIMEOUT');
@@ -395,9 +407,13 @@ function updateLicenseDisplay(user){
407 if(hasActiveLicense){
408 badge.className='badge badge-success';
409 badge.innerText=(sub.type==='lifetime')?'وضعیت اشتراک : نامحدود':`وضعیت اشتراک : تا تاریخ ${formatToJalali(sub.endDate)}`;
398 - }else if(isExpired||sub.status==='cancelled'){
410 + }else if(sub.status==='cancelled'||sub.status==='expired'||(sub.status==='active'&&isExpired)){
411 badge.className='badge badge-danger';badge.innerText='وضعیت اشتراک : منقضی شده';
400 - }else{
412 + }else if(sub.status==='trial'||sub.type==='trial'){
413 badge.className='badge badge-warning';badge.innerText=`وضعیت اشتراک : آزمایشی تا تاریخ ${formatToJalali(sub.endDate)}`;
414 + }else{
415 + // A failed/unfinished organization lookup is NOT evidence of expiry.
416 + // Fail closed for writes via canWrite(), but label the cause truthfully.
417 + badge.className='badge badge-warning';badge.innerText='وضعیت اشتراک : قابل بررسی نیست';
418 }
419 }
js/organization-rbac.js
+2
@@ -217,4 +217,6 @@ function ensureOrgAccessButton(){
217 }
218 const baseEnterAppOrg=enterApp;
219 enterApp=async function(authUser){const r=await baseEnterAppOrg(authUser);ensureOrgAccessButton();return r};
220 +// Signal only after the full organization module and its account wrapper exist.
221 +window.finoraMarkOrganizationContextReady?.();
222 })();
\ No newline at end of file
scripts/dom-smoke.spec.js
+1 -1
@@ -3,7 +3,7 @@ const {PDFDocument}=require('pdf-lib');
3 test('real DOM shell and post-login smoke',async({page})=>{const errs=[];page.on('pageerror',e=>errs.push(String(e)));await page.goto('http://127.0.0.1:4173/index.html',{waitUntil:'domcontentloaded'});await expect(page.locator('#auth-screen')).toBeVisible();await expect(page.locator('[data-module="projects"]')).toHaveCount(1);await expect(page.locator('[data-module="dashboard"]')).toContainText('داشبورد');await expect(page.locator('[data-module="home"]')).toHaveCount(0);await expect(page.locator('[data-module="catalog"]')).toHaveCount(0);await expect(page.locator('[data-module="erp"]')).toHaveCount(0);await expect(page.locator('#view-contracting')).toHaveCount(1);await expect(page.locator('[data-module="inventory"]')).toHaveCount(1);await expect(page.locator('[data-module="assets"]')).toHaveCount(1);await expect(page.locator('[data-module="enterprise"]')).toHaveCount(1);await page.waitForFunction(()=>typeof enterpriseRender==='function');await expect(page.locator('[data-module="enterprise"]')).toHaveCount(1);for(const id of ['view-inventory','view-assets','view-currency','view-data-center','view-integrations'])await expect(page.locator('#'+id)).toHaveCount(1);expect(await page.evaluate(()=>{const a=[...document.querySelectorAll('[id]')].map(x=>x.id),s=new Set(),d=[];for(const id of a){if(s.has(id))d.push(id);s.add(id)}return d})).toEqual([]);await page.evaluate(async()=>{fetchCurrentUser=async()=>({id:'smoke-user',email:'smoke@example.test',fullName:'Smoke Admin',username:'smoke',role:'admin',maxCompanies:1,subscription:{type:'lifetime',status:'active',endDate:'2099-01-01'}});pullAll=async()=>{datastore.settings=[{ownerUserId:'smoke-user',user_display_name:'Smoke Admin',professional_role:'accountant'}]};refreshAllSurfaces=()=>{window.__smokeRefresh=true};maybeMigrateLegacyData=()=>{window.__smokeMigrate=true};await enterApp({id:'smoke-user'});});await expect(page.locator('#auth-screen')).toBeHidden();await expect(page.locator('body')).toHaveClass(/is-admin/);await expect(page.locator('#logged-user-label')).toContainText('Smoke Admin');await expect(page.locator('#module-panel-handle')).toBeVisible();await expect(page.locator('[data-module="projects"] b')).toHaveText('پیمان‌ها');await expect(page.locator('.module-panel-head .panel-collapse')).toHaveCount(0);await page.evaluate(()=>toggleModulePanel());await expect(page.locator('body')).toHaveClass(/shell-panel-collapsed/);await expect(page.locator('#module-panel-handle')).toBeVisible();await expect(page.locator('#module-panel-handle')).toHaveAttribute('aria-expanded','false');await page.click('#module-panel-handle');await expect(page.locator('body')).not.toHaveClass(/shell-panel-collapsed/);await page.evaluate(()=>openModule('accounting','view-accounting-foundation','accounts'));await expect(page.locator('#module-panel-links')).toContainText('ساختار مالی');await expect(page.locator('#module-panel-links')).toContainText('ثبت و عملیات');await expect(page.locator('#module-panel-links')).toContainText('دفاتر و کنترل');await expect(page.locator('#module-panel-links')).toContainText('صورت‌های مالی و تحلیل');await expect(page.locator('#module-panel-links [data-task="accounts"]')).toHaveClass(/active/);await page.fill('#global-command-search','تراز آزمایشی');await expect(page.locator('#command-search-results')).toContainText('تراز آزمایشی');await expect(page.locator('#view-accounting-foundation [data-finora-task="accounts"]')).toBeVisible();await expect(page.locator('#view-accounting-foundation [data-finora-task="dimensions"]')).toBeHidden();await page.evaluate(()=>switchView('view-accounting-foundation'));await expect(page.locator('#view-accounting-foundation [data-finora-task="dimensions"]')).toBeVisible();await page.evaluate(()=>navigateShell('accounting','view-accounting-foundation','accounts'));await page.evaluate(()=>navigateShell('settings','view-settings','company'));await expect(page.locator('#view-settings [data-finora-task="company"]')).toBeVisible();await expect(page.locator('#view-settings [data-finora-task="account"]')).toBeHidden();await expect(page.locator('#company-legal-form')).toContainText('سهامی خاص');await expect(page.locator('#company-legal-form')).toContainText('با مسئولیت محدود');await page.selectOption('#company-entity-type','legal');await page.fill('#company-reg-input','SHOULD_CLEAR');await page.selectOption('#company-organization-role','holding_parent');await page.selectOption('#company-entity-type','natural');await page.evaluate(()=>handleCompanyEntityTypeChange());await expect(page.locator('#company-legal-form-box')).toBeHidden();await expect(page.locator('#company-sector-box')).toBeHidden();await expect(page.locator('#company-organization-box')).toBeHidden();await expect(page.locator('#company-registration-box')).toBeHidden();await expect(page.locator('#company-national-label')).toHaveText('کد ملی');expect(await page.inputValue('#company-reg-input')).toBe('');expect(await page.inputValue('#company-organization-role')).toBe('standalone');await page.selectOption('#company-entity-type','legal');await page.evaluate(()=>handleCompanyEntityTypeChange());await expect(page.locator('#company-legal-form-box')).toBeVisible();await expect(page.locator('#company-organization-box')).toBeVisible();await expect(page.locator('#company-registration-box')).toBeVisible();await expect(page.locator('#company-national-label')).toHaveText('شناسه ملی');await expect(page.locator('#company-organization-role')).toContainText('شرکت مادر / هلدینگ');await expect(page.locator('#company-organization-role')).toContainText('شرکت تابعه');await page.evaluate(()=>switchView('view-contacts'));await page.selectOption('#contact-entity-type','legal');await page.fill('#contact-economic-input','LEGAL-ONLY');await page.fill('#contact-reg-input','REG-ONLY');await page.selectOption('#contact-entity-type','natural');await expect(page.locator('#box-contact-economic')).toBeHidden();await expect(page.locator('#box-contact-reg')).toBeHidden();await expect(page.locator('#label-contact-national')).toHaveText('کد ملی');expect(await page.inputValue('#contact-economic-input')).toBe('');expect(await page.inputValue('#contact-reg-input')).toBe('');await page.evaluate(()=>navigateShell('enterprise','view-enterprise','compliance'));await expect(page.locator('#view-enterprise')).toContainText('رجیستری انطباق ایران');await expect(page.locator('#view-enterprise')).toContainText('IR-LABOR-24');await page.evaluate(()=>navigateShell('enterprise','view-enterprise','payroll'));await expect(page.locator('#view-enterprise')).toContainText('حقوق، بیمه و مالیات حقوق');await page.evaluate(()=>navigateShell('enterprise','view-enterprise','costing'));await expect(page.locator('#view-enterprise')).toContainText('ABC');await page.evaluate(()=>navigateShell('enterprise','view-enterprise','group'));await expect(page.locator('#view-enterprise')).toContainText('کنترل مدیریتی گروه');await page.evaluate(()=>navigateShell('accounting','view-journal','new'));await expect(page.locator('#view-journal [data-finora-task="new"]')).toBeVisible();await expect(page.locator('#view-journal [data-finora-task="register"]')).toBeHidden();await page.evaluate(()=>navigateShell('accounting','view-journal','register'));await expect(page.locator('#view-journal [data-finora-task="register"]')).toBeVisible();await expect(page.locator('#view-journal [data-finora-task="new"]')).toBeHidden();await page.evaluate(()=>navigateShell('accounting','view-accounting-reports','trial'));await expect(page.locator('#p6-reporting-root [data-finora-task="trial"]')).toBeVisible();await expect(page.locator('#p6-reporting-root [data-finora-task="ledger"]')).toBeHidden();expect(await page.evaluate(()=>({refresh:window.__smokeRefresh,migrate:window.__smokeMigrate,admin:canShowShellCommand({guard:'admin'})}))).toEqual({refresh:true,migrate:true,admin:true});await page.evaluate(()=>{saveDatastore=()=>{};datastore.companies=[{id:'C1',ownerUserId:'smoke-user',name:'Smoke Co'}];datastore.settings=[{ownerUserId:'smoke-user',default_company_id:'C1'}];datastore.products=[{id:'P1',ownerUserId:'smoke-user',companyId:'C1',code:'1',name:'Smoke Product',type:'good',unit:'عدد',buy_price:100,sale_price:150,stock:0}];for(const k of ['warehouses','stockMovements','inventoryCounts','fixedAssets','assetDepreciations','currencies','exchangeRates','costCenters','importBatches','integrationConnections','integrationOutbox','phase5Audit'])datastore[k]=[];switchView('view-inventory');p5Render('view-inventory');});await expect(page.locator('#view-journal')).toBeHidden();await page.evaluate(()=>{switchView('view-dashboard');renderDashboard();});await expect(page.locator('#kpi-assets-sum')).toHaveCount(1);await expect(page.locator('#dashboard-cashflow-chart svg')).toHaveCount(1);await expect(page.locator('#dashboard-recent-journals')).toHaveCount(1);await page.evaluate(()=>{switchView('view-accounting-foundation');renderAccountingFoundation();});await expect(page.locator('#view-accounting-foundation')).toContainText('ورود کدینگ از Excel');await expect(page.locator('#view-accounting-foundation')).toContainText('شناور ۴ قرارداد/پیمان');await page.evaluate(()=>navigateShell('enterprise','view-enterprise','compliance'));await expect(page.locator('#view-enterprise')).toContainText('رجیستری انطباق ایران');await expect(page.locator('#view-enterprise')).toContainText('IR-LABOR-24');await page.evaluate(()=>navigateShell('enterprise','view-enterprise','leave'));await expect(page.locator('#view-enterprise')).toContainText('حداکثر ۹ روز');await expect(page.locator('#af-account-type')).toHaveCount(1);await expect(page.locator('#af-account-search')).toHaveCount(1);await expect(page.locator('#af-account-level-filter')).toHaveCount(1);await expect(page.locator('#af-account-role')).toHaveCount(1);await expect(page.locator('#af-dim-source option[value="contract"]')).toHaveCount(1);await page.evaluate(()=>{switchView('view-inventory');p5Render('view-inventory');});await expect(page.locator('#p5-inventory-root')).toContainText('انبار اصلی');await expect(page.locator('#p5-inventory-root')).toContainText('Smoke Product');await page.evaluate(()=>{switchView('view-accounting-reports');P6Reports.render();});await expect(page.locator('#p6-reporting-root')).toContainText('تراز آزمایشی');await expect(page.locator('#p6-reporting-root')).toContainText('صورت جریان وجوه نقد');expect(await page.evaluate(()=>{const a=[...document.querySelectorAll('[id]')].map(x=>x.id),s=new Set(),d=[];for(const id of a){if(s.has(id))d.push(id);s.add(id)}return d})).toEqual([]);await page.evaluate(()=>{window.__FINORA_PRINT_TEST_MODE=true;window.print=()=>{};const items=Array.from({length:25},(_,i)=>({prodName:'Item '+(i+1),qty:1,unit:'عدد',price:100,lineTotal:100}));datastore.invoices=[{id:'PRINT_FORMAL',ownerUserId:'smoke-user',companyId:'C1',contactId:'',kind:'formal',number:'F-1',date:'1405/07/07',items,subtotal:2500,discount:0,vat:250,grandTotal:2750,paymentMethod:'cash'}];renderAndPrintDirect('PRINT_FORMAL');});await expect(page.locator('#printable-invoice .invoice-a4-page')).toHaveCount(3);expect(await page.locator('#dynamic-print-orientation').evaluate(el=>el.innerHTML.includes('A4 landscape'))).toBe(true);await expect(page.locator('#finora-print-frame')).toHaveCount(1);expect(await page.locator('#finora-print-frame').evaluate(f=>({paper:f.contentDocument.querySelector('#finora-print-document')?.dataset.paper,orientation:f.contentDocument.querySelector('#finora-print-document')?.dataset.orientation,appUi:f.contentDocument.querySelectorAll('.view-pane,.app-shell-nav,.module-panel,.topbar').length,pages:f.contentDocument.querySelectorAll('.invoice-a4-page').length}))).toEqual({paper:'A4',orientation:'landscape',appUi:0,pages:3});await page.emulateMedia({media:'print'});expect(await page.locator('#printable-invoice .invoice-a4-page').first().evaluate(el=>getComputedStyle(el).breakAfter)).toBe('page');await page.emulateMedia({media:'screen'});await page.evaluate(()=>{datastore.invoices[0].id='PRINT_NONFORMAL';datastore.invoices[0].kind='informal';renderAndPrintDirect('PRINT_NONFORMAL');});await expect(page.locator('#printable-invoice .invoice-a4-page')).toHaveCount(3);expect(await page.locator('#dynamic-print-orientation').evaluate(el=>el.innerHTML.includes('A5 landscape'))).toBe(true);expect(await page.locator('#finora-print-frame').evaluate(f=>({paper:f.contentDocument.querySelector('#finora-print-document')?.dataset.paper,orientation:f.contentDocument.querySelector('#finora-print-document')?.dataset.orientation,appUi:f.contentDocument.querySelectorAll('.view-pane,.app-shell-nav,.module-panel,.topbar').length,pages:f.contentDocument.querySelectorAll('.invoice-a4-page').length}))).toEqual({paper:'A5',orientation:'landscape',appUi:0,pages:3});expect(errs.filter(x=>!x.includes('ResizeObserver'))).toEqual([]);});
4
5
6 -test('expired license browser enforcement',async({page})=>{const errs=[];page.on('pageerror',e=>errs.push(String(e)));await page.goto('http://127.0.0.1:4173/index.html',{waitUntil:'domcontentloaded'});await page.evaluate(async()=>{window.__licenseAlerts=[];window.alert=m=>window.__licenseAlerts.push(String(m));fetchCurrentUser=async()=>({id:'expired-user',email:'expired@example.test',fullName:'Expired User',username:'expired',role:'user',subscription:{type:'monthly',status:'active',startDate:'2025-01-01',endDate:'2025-01-31'}});pullAll=async()=>{};refreshAllSurfaces=()=>{updateLicenseDisplay(currentUser)};maybeMigrateLegacyData=()=>{};await enterApp({id:'expired-user'});});await expect(page.locator('#auth-screen')).toBeHidden();await expect(page.locator('#user-license-status-badge')).toContainText('منقضی شده');expect(await page.evaluate(()=>canWrite())).toBe(false);expect(await page.evaluate(()=>requireWrite())).toBe(false);expect(await page.evaluate(()=>window.__licenseAlerts.some(x=>x.includes('منقضی')&&x.includes('امکان ثبت یا ویرایش')))).toBe(true);expect(errs.filter(x=>!x.includes('ResizeObserver'))).toEqual([]);});
6 +test('expired license browser enforcement',async({page})=>{const errs=[];page.on('pageerror',e=>errs.push(String(e)));await page.goto('http://127.0.0.1:4173/index.html',{waitUntil:'domcontentloaded'});await expect.poll(()=>page.evaluate(()=>window.FinoraStartupStatus?.authChecked),{timeout:15000}).toBe(true);await page.evaluate(async()=>{window.__licenseAlerts=[];window.alert=m=>window.__licenseAlerts.push(String(m));fetchCurrentUser=async()=>({id:'expired-user',email:'expired@example.test',fullName:'Expired User',username:'expired',role:'user',subscription:{type:'monthly',status:'active',startDate:'2025-01-01',endDate:'2025-01-31'}});pullAll=async()=>{};refreshAllSurfaces=()=>{updateLicenseDisplay(currentUser)};maybeMigrateLegacyData=()=>{};await enterApp({id:'expired-user'});});await expect(page.locator('#auth-screen')).toBeHidden();await expect(page.locator('#user-license-status-badge')).toContainText('منقضی شده');expect(await page.evaluate(()=>canWrite())).toBe(false);expect(await page.evaluate(()=>requireWrite())).toBe(false);expect(await page.evaluate(()=>window.__licenseAlerts.some(x=>x.includes('منقضی')&&x.includes('امکان ثبت یا ویرایش')))).toBe(true);expect(errs.filter(x=>!x.includes('ResizeObserver'))).toEqual([]);});
7
8
9 test('isolated print document honors CSS paper size in Chromium PDF',async({page,context})=>{await page.goto('http://127.0.0.1:4173/index.html',{waitUntil:'domcontentloaded'});const docs=await page.evaluate(()=>({a4:buildIsolatedPrintDocument('<div class="invoice-a4-page">FORMAL_ONLY</div>',{paper:'A4',orientation:'landscape',widthMm:297,heightMm:210,marginMm:5}),a5:buildIsolatedPrintDocument('<div class="invoice-a4-page">NONFORMAL_ONLY</div>',{paper:'A5',orientation:'landscape',widthMm:210,heightMm:148,marginMm:5})}));for(const [kind,html] of Object.entries(docs)){const p=await context.newPage();await p.setContent(html,{waitUntil:'domcontentloaded'});expect(await p.locator('body').innerText()).toContain(kind==='a4'?'FORMAL_ONLY':'NONFORMAL_ONLY');expect(await p.locator('.view-pane,.app-shell-nav,.module-panel,.topbar').count()).toBe(0);const pdf=await p.pdf({preferCSSPageSize:true,printBackground:true});const parsed=await PDFDocument.load(pdf);expect(parsed.getPageCount()).toBe(1);const {width:w,height:h}=parsed.getPage(0).getSize();expect(w).toBeGreaterThan(h);if(kind==='a4'){expect(w).toBeGreaterThan(830);expect(h).toBeGreaterThan(580);}else{expect(w).toBeGreaterThan(580);expect(w).toBeLessThan(620);expect(h).toBeGreaterThan(400);expect(h).toBeLessThan(440);}await p.close();}});
scripts/login-connectivity-check.mjs
+4 -3
@@ -7,11 +7,12 @@ 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=20261012-data-probe-v3'),'Missing versioned script');
10 -assert(html.includes('js/core.js?v=20261013-static-pages-guard-v2'),'Production login controls must use new cache version');
11 -assert(html.indexOf('<script src="js/login-connectivity.js?v=20261012-data-probe-v3"')<html.indexOf('<script src="js/core.js?v=20261013-static-pages-guard-v2"'),'Connectivity handler script must execute before core (not just preload)');
12 -assert(html.includes('js/bootstrap.js?v=20261013-ordered-bundle-v1'),'Parallel bootstrap must also be cache-busted');
10 +assert(html.includes('js/core.js?v=20261014-org-license-readiness-v1'),'Production login controls must use new cache version');
11 +assert(html.indexOf('<script src="js/login-connectivity.js?v=20261012-data-probe-v3"')<html.indexOf('<script src="js/core.js?v=20261014-org-license-readiness-v1"'),'Connectivity handler script must execute before core (not just preload)');
12 +assert(html.includes('js/bootstrap.js?v=20261014-org-license-readiness-v1'),'Parallel bootstrap must also be cache-busted');
13 assert(html.includes('id="auth-login-button"')&&html.includes('id="auth-login-status"'),'Login control requires real readiness/progress feedback');
14 assert(core.includes('window.FinoraAppAssetsReady'),'Authenticated workspace must remain gated until all module scripts settle');
15 +assert(core.includes('window.FinoraOrganizationContextReady')&&core.includes('organizationAccount'),'Profile and license lookup must wait for the organization account adapter');
16 assert(core.includes('FinoraLoginActionsBound'),'Production CSP action readiness must require installed event listeners');
17 assert(core.includes('FINORA_LOGIN_READ_TIMEOUT'),'Restored-session reads must have bounded wait and visible fallback');
18 assert(core.includes('isAuthNetworkError(err)'),'Network error diagnostic not wired');
scripts/phase0-startup-performance.spec.js
+81
@@ -200,6 +200,87 @@ test('F0 organization-scoped record hydration respects abort and tenant boundary
200 expect(observed).toEqual({selectedTenant:'org-fixture',preserved:true,noLeakedDummy:true,noStaleSnapshot:true});
201 });
202
203 +
204 +test('F0 test-account lifetime entitlement waits for delayed organization adapter, not placeholder profile',async({page})=>{
205 + // The account and license below are synthetic; no real login or customer data.
206 + // Deliberately restore a "session" BEFORE the organization extension executes.
207 + await page.route('**/js/organization-rbac.js*',async route=>{
208 + await new Promise(resolve=>setTimeout(resolve,1600));
209 + await route.continue();
210 + });
211 + await page.goto(BASE,{waitUntil:'domcontentloaded'});
212 + const observed=await page.evaluate(async()=>{
213 + window.finoraFixtureLegacyProfileCalls=0;
214 + // This is the original profile-only loader, captured by the later wrapper.
215 + window.fetchCurrentUser=async authUser=>{
216 + window.finoraFixtureLegacyProfileCalls++;
217 + return {id:authUser.id,email:'synthetic@example.test',role:'accountant',
218 + subscription:{type:'none',status:'unavailable',endDate:null}};
219 + };
220 + const rows={
221 + organization_members:[{
222 + id:'fixture-membership',user_id:'synthetic-session',organization_id:'fixture-org',
223 + status:'active',is_owner:true,unit_id:null,position_title:null
224 + }],
225 + organizations:[{id:'fixture-org',name:'Fixture Company',status:'active'}],
226 + licenses:[{
227 + organization_id:'fixture-org',plan:'lifetime',status:'active',
228 + starts_at:'2026-01-01',ends_at:'2099-01-01',
229 + max_companies:5,max_users:5,modules:['full_suite']
230 + }],
231 + member_module_permissions:[],
232 + organization_roles:[],
233 + organization_role_permissions:[],
234 + organization_member_roles:[],
235 + records:[]
236 + };
237 + const originalFrom=sb.from;
238 + const originalPullAll=pullAll;
239 + const originalFetch=fetchCurrentUser;
240 + sb.from=table=>({
241 + select(){return this;},
242 + eq(){return this;},
243 + in(){return this;},
244 + order(){return this;},
245 + range(){return this;},
246 + abortSignal(){return this;},
247 + then(resolve){resolve({data:rows[table]||[],error:null});}
248 + });
249 + // No real Supabase requests or writes.
250 + pullAll=async()=>{};
251 + const pending=enterApp({id:'synthetic-session'},{timeoutMs:8500});
252 + await new Promise(resolve=>setTimeout(resolve,90));
253 + const profileFetchedBeforeOrgAdapter=window.finoraFixtureLegacyProfileCalls;
254 + await pending;
255 + const selected=currentUser?.subscription||null;
256 + const selectedOrganization=currentUser?.organizationName||null;
257 + const licenseBadge=document.getElementById('user-license-status-badge')?.innerText||'';
258 + const allowWrite=canWrite();
259 + // Verify that an unavailable snapshot is NEVER presented as expired.
260 + updateLicenseDisplay({subscription:{type:'none',status:'unavailable',endDate:null}});
261 + const unavailableBadge=document.getElementById('user-license-status-badge')?.innerText||'';
262 + updateLicenseDisplay(currentUser);
263 + return {
264 + profileFetchedBeforeOrgAdapter,
265 + finalFetches:window.finoraFixtureLegacyProfileCalls,
266 + selected,selectedOrganization,licenseBadge,allowWrite,
267 + unavailableBadge,finalBadge:document.getElementById('user-license-status-badge')?.innerText||'',
268 + authHidden:getComputedStyle(document.getElementById('auth-screen')).display==='none'
269 + };
270 + });
271 + expect(observed.profileFetchedBeforeOrgAdapter).toBe(0);
272 + expect(observed.finalFetches).toBe(1);
273 + expect(observed.selected).toMatchObject({type:'lifetime',status:'active',endDate:'2099-01-01'});
274 + expect(observed.selectedOrganization).toBe('Fixture Company');
275 + expect(observed.allowWrite).toBe(true);
276 + expect(observed.licenseBadge).toContain('نامحدود');
277 + expect(observed.unavailableBadge).toContain('قابل بررسی نیست');
278 + expect(observed.unavailableBadge).not.toContain('منقضی');
279 + expect(observed.finalBadge).toContain('نامحدود');
280 + expect(observed.authHidden).toBe(true);
281 +});
282 +
283 +
284 test('F0 bootstrap timeout reports ACCOUNT_CONTEXT without email, token or private profile',async({page})=>{
285 await page.goto(BASE,{waitUntil:'domcontentloaded'});
286 await expect.poll(()=>page.evaluate(()=>window.FinoraStartupStatus?.authChecked),{timeout:15000}).toBe(true);