سامانه صدور فاکتور و حسابداری
Mirrored from https://github.com/davoodmehraban89/Factor-easy.git
Synced Dec 3, 23:15 UTC
Fix redundant enterprise module load on startup (#158)
* docs: record scoped Phase 0 slow-dispatcher regression plan * test: reproduce slow Pages dispatcher without delaying login controls * docs: record failed slow-startup baseline and request-initiator next check * test: capture exact Chromium initiator of unexpected legacy Pages request * docs: identify duplicate enterprise loader and scope one-line repair * fix: stop dynamically loading enterprise module already in Pages accounting bundle * docs: record passing 123 Chromium and security gates for duplicate-loader repair
davoodmehraban89 committed
Oct 16, 2026 at 01:46 UTC
612998edb51274ac1e6136a31265cd17b9abd265
3 files changed
+73
-1
PROJECT_STATE.md
+9
@@ -797,3 +797,12 @@ Owner reports login blocked with generic 'check internet/VPN' network error on l
797
- **Prior independent LIVE product filter:** TinyFish [run `341e1f6d-a792-4b5e-b0b9-69908056b460`](https://agent.tinyfish.ai/runs/341e1f6d-a792-4b5e-b0b9-69908056b460) with same Test/Work profile reached invoice and filtered `بلوک` to **3 matching product options**, without selecting/saving. Later run `a31d48d6-34ea-4b6d-91b3-7d28a0c817f5` was inconclusive for navigation, but the new run confirms navigation and buyer search in a separate successful session. Generic TinyFish agent claims about absent `data-module=commerce` contradicted source HTML and should not be treated as a root cause.
798
- **Acceptance:** Phase 0 **F0-02 interactive product and buyer filtering PASS for observed authorized test account**; opening the invoice and reverting transient search state also PASS. Combined with 122/122 synthetic Playwright and protected Pages release, this closes the *two lookup UI acceptance checks only*. It does NOT prove committed invoice persistence, financial posting, cross-company data isolation, cold login performance on owner's affected ISP, or all user devices.
799
- **Next safe work:** Phase 0 F0-01 affected-network fresh login needs owner-device evidence; F0-03 actual invoice persistence/print cannot be certified by no-write TinyFish test; live backup and isolated restore remain `PRODUCTION_BACKUP_NOT_RUN / RECOVERY_NOT_VERIFIED` due missing secure authorized machine and owner-held age identity. Continue source-side audit/tests without operating on live financial records. This PR updates documentation only; rollback by reverting doc PR.
800
+
801
+### 2026-10-16 Owner continuation — F0-01 delayed Pages dispatcher / legacy-request differential (PLANNED, QA ONLY)
802
+- **Owner direction:** «ادامه بده». Rechecked current protected main `69e0721d7004e8497cf43aaf6ab259b49ac97681`, open login Issue #106 and latest buyer/product acceptance #157. Main Quality `38793466628`, Security `38793466635`, Release `38793944702`, Pages `38794031181` all SUCCESS; 122/122 controlled Chromium PASS, not owner-ISP cold-login acceptance.
803
+- **Evidence and hypothesis:** owner Chrome waterfall on prior affected hotspot had unusually slow `generated-dynamic-handlers.js` (~43s) and accounting Pages group (~15s), plus an unexpected pending standalone `enterprise-iran.js`. Current `scripts/build-pages.mjs` inserts the CSP-safe dynamic dispatcher as a bottom classic blocking script. This can delay `DOMContentLoaded` and therefore extension bootstrap; the network/initiator root cause and live current release remain unproven. Current bundler intentionally consolidates 38 core scripts into three ordered groups and 14 extensions into one bundle.
804
+- **Scoped plan:** add an isolated Playwright regression for generated `_site` Pages, with delayed dynamic dispatcher and a request ledger asserting early credential controls, expected DOM readiness sequencing, no premature workspace, complete later module readiness and no unexpected standalone legacy ERP request. Do not alter runtime/Auth/schema/RLS/roles/financial records/permissions; do not hide missing assets, bypass readiness or assume 304 is a failed response. If test reveals source defect, stop and separately review minimum fix; do not assume this QA proves owner affected-network performance.
805
+- **Acceptance / rollback:** exact PR-head Quality (122+ Chromium, Golden, three disposable DB) and Security PASS; docs and test-only branch, no production writes. Restore by reverting isolated PR. Live first signed-out login on owner's impacted Chrome/ISP remains F0-01 P0 OPEN; no invoice persistence/real backup signoff.
806
+- **First independent CI result on PR #158 head `926a44321daf56f989a595b74048145e155451cc`:** Security `38813224607` SUCCESS; Quality `38813224500` FAIL, **122/123 Chromium PASS**. The one new synthetic hardened-Pages test confirmed early login remains available during deliberately delayed bottom dynamic dispatcher, but detected a standalone `enterprise-iran.js` network request, contrary to expected bundling. Three disposable DB jobs, Golden and other financial invariants passed. Do not merge or deploy this test-only PR while failing. Next: capture request resource type + Chromium Network initiator on this isolated fixture to distinguish duplicate executed script, speculative preload, or diagnostic fetch. This is an actual test failure, not yet proven runtime financial corruption or a confirmed owner-ISP fix.
807
+- **CDP root cause evidence / bounded implementation decision, before code edit:** PR #158 head `6dc91cddf403a2d482c30795f2b32e20cd6b82d2`, Quality `38814011317` 122/123 Chromium with same intentional test FAIL, Security `38814011321` PASS. Chromium `Network.requestWillBeSent` identifies a real **Script** request to `/_site/js/enterprise-iran.js`, initiator `finora-pages-foundation.js` line 565. Source mapping through ordered foundation bundle reveals `js/ui.js` line 218: a `DOMContentLoaded` listener injects a second `<script src=js/enterprise-iran.js>`. This duplicates the same ERP module already in the required accounting Pages bundle; raw development `index.html` also separately includes it statically at line 941. **Authorized narrow fix:** delete ONLY this dynamic redundant script insertion from `js/ui.js`, retain enterprise module in original static index and Pages accounting bundle and preserve module rail rendering; keep strict fail-closed gating and test full Chromium/Golden/DB/Security. Do not combine unrelated CSP handler files in this fix. Rollback by reverting ui.js one-line change.
808
+- **One-line repair controlled CI VERIFIED on PR #158 code HEAD `6dfdf41b7694ef6397c19bce8613f68cd6b724d4`:** [Quality `38814776887`](https://github.com/davoodmehraban89/Factor-easy/actions/runs/38814776887) SUCCESS; static job logs **123/123 Chromium PASS**, including the delayed CSP handler + no redundant source-script fetch regression; Golden sale→receipt→purchase→payment→reversal→trial balance→statements and accounting P0 invariants PASS; **three disposable DB jobs SUCCESS**. [Security `38814776751`](https://github.com/davoodmehraban89/Factor-easy/actions/runs/38814776751) SUCCESS. Production source change is only removal of redundant DOMContentLoaded dynamic load in `js/ui.js` (enterprise module remains in built accounting group). **PENDING:** after this evidence-only documentation append, recheck exact final PR head CI before merge; protected-main Release/Pages and actual owner-ISP cold login are NOT VERIFIED at this checkpoint. Phase 0/Issue #106 remain OPEN.
js/ui.js
+1
-1
@@ -215,7 +215,7 @@ function syncShellForView(viewId){
215
}
216
document.addEventListener('click',e=>{if(!e.target.closest('.global-search'))closeCommandSearch();if(!e.target.closest('.quick-create'))closeQuickCreateMenu();});
217
document.addEventListener('keydown',e=>{if(e.key==='Escape')closeQuickCreateMenu();if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='k'){e.preventDefault();const s=document.getElementById('global-command-search');if(s){s.focus();s.select();}}});
218
-document.addEventListener('DOMContentLoaded',()=>{const rail=document.getElementById('module-rail');if(rail&&!rail.querySelector('[data-module="enterprise"]')){const b=document.createElement('button');b.className='module-tab';b.dataset.module='enterprise';b.dataset.view='view-enterprise';b.title='سازمان و منابع انسانی';b.innerHTML='<span>♙</span><b>سازمان</b>';b.onclick=()=>openModule('enterprise','view-enterprise','employees');const reports=rail.querySelector('[data-module="reports"]');rail.insertBefore(b,reports||null)}const s=document.createElement('script');s.src='js/enterprise-iran.js?v=20260930-iran-erp-v1';s.defer=true;document.body.appendChild(s);
218
+document.addEventListener('DOMContentLoaded',()=>{const rail=document.getElementById('module-rail');if(rail&&!rail.querySelector('[data-module="enterprise"]')){const b=document.createElement('button');b.className='module-tab';b.dataset.module='enterprise';b.dataset.view='view-enterprise';b.title='سازمان و منابع انسانی';b.innerHTML='<span>♙</span><b>سازمان</b>';b.onclick=()=>openModule('enterprise','view-enterprise','employees');const reports=rail.querySelector('[data-module="reports"]');rail.insertBefore(b,reports||null)}
219
try{if(localStorage.getItem('finora.shell.panelCollapsed')==='1')document.body.classList.add('shell-panel-collapsed');}catch(_){}
220
syncModulePanelHandle();
221
renderModulePanel('dashboard','view-dashboard','overview');updateShellContext('dashboard','view-dashboard','overview');
scripts/pages-artifact.spec.js
+63
@@ -56,6 +56,69 @@ test('Production CSP login and connectivity actions work while later ERP JS is s
56
expect(delayedModuleFinished).toBe(false);
57
});
58
59
+test('Slow final CSP dispatcher keeps login usable without loading legacy ERP scripts',async({page})=>{
60
+ let delayedDispatcherReleased=false;
61
+ const unexpectedLegacyRequests=[];
62
+ const initiatorTrace=[];
63
+ const session=await page.context().newCDPSession(page);
64
+ await session.send('Network.enable');
65
+ session.on('Network.requestWillBeSent',event=>{
66
+ if(!/\/enterprise-iran(?:-v2)?\.js(?:\?|$)/.test(event.request.url))return;
67
+ initiatorTrace.push({
68
+ path:new URL(event.request.url).pathname,
69
+ type:event.type||'unknown',
70
+ initiatorType:event.initiator?.type||'unknown',
71
+ stack:(event.initiator?.stack?.callFrames||[]).slice(0,3).map(frame=>({
72
+ file:String(frame.url||'').split('?')[0].replace(/^https?:\/\/[^/]+/,''),
73
+ line:frame.lineNumber,
74
+ name:frame.functionName
75
+ }))
76
+ });
77
+ });
78
+ const standaloneScripts=new Set([
79
+ 'enterprise-iran.js','enterprise-iran-v2.js','accounting-foundation.js',
80
+ 'journal-engine.js','admin.js','organization-rbac.js','taxpayer-print.js'
81
+ ]);
82
+ page.on('request',req=>{
83
+ const filename=new URL(req.url()).pathname.split('/').at(-1);
84
+ if(standaloneScripts.has(filename))unexpectedLegacyRequests.push({filename,type:req.resourceType()});
85
+ });
86
+ // The owner's Chrome waterfall showed this bottom-of-body CSP dispatcher
87
+ // unusually slow. A delayed response is used; an HTTP 304 is not treated
88
+ // as a failed script, and no authenticated account or finance data is used.
89
+ await page.route('**/js/generated-dynamic-handlers.js',async route=>{
90
+ await new Promise(resolve=>setTimeout(resolve,4500));
91
+ delayedDispatcherReleased=true;
92
+ await route.continue();
93
+ });
94
+ await page.goto(base,{waitUntil:'commit'});
95
+ await expect(page.locator('#auth-login-button')).toBeEnabled({timeout:3500});
96
+ const early=await page.evaluate(()=>({
97
+ documentState:document.readyState,
98
+ authReady:window.FinoraStartupStatus?.authFormReady,
99
+ staticHandlers:window.FinoraLoginActionsBound,
100
+ authVisible:getComputedStyle(document.getElementById('auth-screen')).display!=='none'
101
+ }));
102
+ expect(early).toMatchObject({
103
+ documentState:'loading',
104
+ authReady:true,
105
+ staticHandlers:true,
106
+ authVisible:true
107
+ });
108
+ expect(delayedDispatcherReleased,'The auth form must not await the bottom dispatcher').toBe(false);
109
+ const prompt=page.waitForEvent('dialog').then(async dialog=>{
110
+ expect(dialog.message()).toContain('ایمیل');
111
+ await dialog.dismiss();
112
+ });
113
+ await Promise.all([page.locator('#auth-login-button').click(),prompt]);
114
+ await page.waitForLoadState('domcontentloaded',{timeout:15000});
115
+ await expect.poll(()=>page.evaluate(()=>window.FinoraStartupStatus?.extensionsReady),{timeout:15000}).toBe(true);
116
+ expect(delayedDispatcherReleased).toBe(true);
117
+ if(unexpectedLegacyRequests.length)console.log('LEGACY_PAGES_REQUEST_TRACE='+JSON.stringify(initiatorTrace));
118
+ expect(unexpectedLegacyRequests,'Published Pages must not refetch already bundled ERP source modules; CDP '+JSON.stringify(initiatorTrace)).toEqual([]);
119
+ expect(await page.locator('#auth-screen').isVisible()).toBe(true);
120
+});
121
+
122
test('Built Pages uses exactly one SHA-pinned local bundle for all 14 ERP extensions',async({page})=>{
123
const requested=[];
124
page.on('request',req=>{