سامانه صدور فاکتور و حسابداری
Mirrored from https://github.com/davoodmehraban89/Factor-easy.git
Synced Dec 4, 00:30 UTC
feat(navigation): focus daily rail and expose purchase commands
davoodmehraban89 committed
Oct 23, 2026 at 22:08 UTC
c60f1735be8d108650381953443bfbb174464961
16 files changed
+289
-36
PROJECT_STATE.md
+9
@@ -38,3 +38,12 @@
38
### 2026-10-16 Phase 0 post-merge Chromium intermittent fixture (QA-only follow-up; NOT application defect proven)
39
- **Original Phase 0 PR:** #160 merged exact-main `67be4fbfa6161156b10ce6279445266c989e97d3`. PR-head Quality `38867730181` 123/123 Chromium PASS, isolated DB and Security PASS. Protected main Quality `38868319174` attempt 1 **FAIL 122/123** at `scripts/phase0-invoice-persistence.spec.js:52`, `#auth-screen` remained visible for 5 seconds; all three DB jobs and Security `38868319200` succeeded. Same-SHA failed-job rerun attempt 2 was requested; result must be verified separately. Neither result proves actual production financial persistence or login failure.
40
- **Source-reproduced test harness race:** `authenticatedMockBrowser` waits only for `enterApp`, `commitSaveInvoice`, `pullAll` functions before installing a fake authenticated identity; asynchronously loaded `organization-rbac` wrapper can supersede the fake identity. Prior `scripts/accounting-document-workflow.spec.js:36–43` already fixes the identical fixture ordering issue by waiting for `FinoraStartupStatus.extensionsReady`, zero failed extensions, and `authChecked`. Apply the same pre-mock readiness condition **only in this synthetic invoice test**; preserve all UI, Supabase/Auth/RLS, financial accounting and live record behavior. Require Quality 123/123, Security and all three disposable DB on exact repair SHA; then controlled protected merge and same-main checks. Rollback is a test-only revert. All owner-ISP and real invoice E2E remain NOT VERIFIED.
41
+
42
+### 2026-10-23 — Owner-authorized Phase A: navigation and commands only (in progress)
43
+- New owner execution prompt uses phases **A–H**. This turn authorizes **A only**, superseding the earlier turn's Phase 0 restriction; no approval for B–H, merging, deployment, SQL, schema/RLS/Auth/roles/grants or any Supabase production access/write is inferred.
44
+- Verified remote baseline: `main` = `bccd474433b4188e43aae345773498ea6fc65209` (PR #161); clean clone, branch `feat/finora-phase-a-navigation-20261023`. Mandatory reference documents and six listed JS sources read before implementation; canonical UI image inspected.
45
+- Owner contract: retain two-tier shell; default rail order/labels **داشبورد، حسابداری، بازرگانی، خزانهداری، انبار، پیمانها، گزارشها، تنظیمات**. Explicit sales/purchase tasks reuse current views and command search. Assets/enterprise/office/requests remain licensed-launcher workspaces; their business behavior and code remain. Hide tasks whose implementation does not exist; no new accounting/reporting engine or promised workflows.
46
+- Drift reported before edits: old IA includes assets/order differs; old PROJECT_STATE restricts prior request to Phase 0; commercial QA forbids the newly requested purchase task. Main also injects organization/access utility buttons into rail; move those controls outside the daily rail while retaining handlers/permissions. Add a visible launcher entry so extra modules remain reachable. Approved JPG in repository is 384×216, not the 1536×864 size described by AGENTS; use the existing layout without inventing a replacement.
47
+- Execution/verification plan: [Phase A navigation report](docs/PHASE_A_NAVIGATION_2026-10-23.md). Pre-change syntax (55 JS + 54 MJS) and Golden accounting core PASS locally. QA/security/release results and PR-head SHA to be recorded after actual execution. NOT VERIFIED: owner-ISP login, real printing, production two-user behavior/customer acceptance. No Supabase connection is needed for A.
48
+- Local implementation checkpoint: exact eight-module rail, explicit sale/purchase panel/search routes, no advanced-module runtime rail injection; existing licensed launcher exposed by «ماژولها» footer control; organization utility handlers/permissions preserved outside the rail. Existing lazy enterprise view is ensured before entry; bootstrap/changed extension cache URLs bumped. No financial, SQL, frozen workflow or print implementation file changed.
49
+- Actually executed: 3 new DOM assertions observed RED before application edits then **3/3 PASS**; all **50** existing static/behavioral/backup/release-safety commands PASS; full existing CI browser command **126/126 Chromium PASS** (2.9m; existing 123 + 3 new), Golden and generated Pages/A4/A5 print tests PASS. Independent whole-diff review has no remaining findings. Cloud WOFF2 font configuration required a temporary process-only FONTCONFIG_FILE override; original print assertion passed without print-code edits. Remote PR-head CI and three disposable DB jobs remain pending at this checkpoint; no merge/deploy/next-phase action is authorized.
docs/PHASE_A_NAVIGATION_2026-10-23.md
new
+68
@@ -0,0 +1,68 @@
1
+# Finora Phase A — navigation and command contract
2
+
3
+## Scope and baseline
4
+
5
+Owner request dated 2026-10-23 authorizes Phase A only, on `main` baseline `bccd474433b4188e43aae345773498ea6fc65209`. The detailed execution prompt in this session is the specification. The existing IIFE/global JavaScript, HTML shell, view IDs, task selectors, entitlement guards, colors and edge handle stay in use. No dependency, SQL, production database operation, accounting calculation or frozen office/workflow/OCR/SLA behavior is changed.
6
+
7
+The direct registry/HTML adjustment is the implementation approach: a second navigation registry or replacement shell would duplicate working routing. The old commerce invoice-type selector remains usable; separate sales/purchase commands point to its existing two views. Existing combined ledger and treasury tasks remain working projections; unimplemented templates, separate daybook, closing and returns workflows are not advertised.
8
+
9
+## Implementation plan
10
+
11
+- [x] Pin the default rail to eight ordered modules: dashboard, accounting, commerce, treasury, inventory, projects, reports, settings, using the owner's exact Persian labels.
12
+- [x] Expose explicit sales/purchase commands through `FINORA_MODULES` / `FINORA_COMMANDS`; keep report deep links and existing accounting task focusing.
13
+- [x] Remove assets/enterprise static rail buttons and enterprise/office/requests runtime rail injection. Preserve licensed launcher entries, navigation guards and command search. Provide a visible launcher button and relocate organization/access utilities outside the module rail with their existing permissions and handlers.
14
+- [x] Check command availability against implemented views/renderers; omit unavailable actions without placeholder labels. Do not create new financial workflows for missing menu items.
15
+- [x] Add real-DOM regression assertions, observe failure on baseline, implement, and run existing affected checks plus CI's static/behavioral and Chromium suite. Preserve existing print tests and Golden accounting expectations. Review the complete diff independently.
16
+- [ ] Commit/push this branch, open one scoped PR, inspect exact-head Quality/Security including disposable DB jobs, and record actual PASS / NOT VERIFIED evidence. Stop before Phase B and merging.
17
+
18
+## Review focus
19
+
20
+- Rail remains eight items after delayed extension bootstrap, login and repeated refresh, including users with multiple organizations.
21
+- Licensed extras remain reachable from the visible launcher; unlicensed modules remain blocked and admin-only commands remain guarded.
22
+- Purchase click/search opens the actual purchase surface; sales stays in its existing surface, and neither navigation writes accounting records.
23
+- Accounting entry/register/trial links focus existing cards; report module uses the same reporting view/task.
24
+- Cold startup and generated Pages artifact keep the same navigation behavior, and existing A4/A5 print isolation passes.
25
+
26
+## Reported differences
27
+
28
+- Prior roadmap restrictions describe a previous Phase 0 request; the current owner explicitly authorizes A.
29
+- IA v2 lists assets in the rail and places projects before inventory. This PR follows the current eight-module list.
30
+- Old commerce checks prohibit a separate purchase item and require generic «فاکتورها». Their assertions must follow the current owner contract without weakening financial checks.
31
+- Organization utilities are injected into the rail by two extensions; their placement must change to preserve the exact eight-module contract. Their operations/permissions are retained.
32
+- Repository reference JPG is 384×216, although AGENTS describes its source as 1536×864. No replacement design is introduced.
33
+
34
+## Verification evidence
35
+
36
+Baseline remote `main` Quality [38869588407](https://github.com/davoodmehraban89/Factor-easy/actions/runs/38869588407) and Security [38869588431](https://github.com/davoodmehraban89/Factor-easy/actions/runs/38869588431) were verified successful. Remote `main` remained `bccd474433b4188e43aae345773498ea6fc65209` before this PR.
37
+
38
+Actually executed locally:
39
+
40
+| Check | Actual result |
41
+| --- | --- |
42
+| Baseline syntax / Golden | PASS (55 JS modules + 54 MJS scripts; existing Golden unchanged) |
43
+| New Phase A tests on unchanged application | 3 expected failures: extra rail buttons, missing visible launcher, missing purchase command registration |
44
+| Same Phase A tests after implementation | 3/3 PASS; exact rail after repeated organization refresh, real purchase/search/accounting/report clicks, licensed launcher and missing-implementation filtering |
45
+| All static/behavioral/backup/safety commands from Quality plus release safety | 50 commands, 0 failures, including Golden |
46
+| Exact existing CI Chromium spec list, `--reporter=line --workers=1` | **126/126 PASS** in 2.9 minutes (baseline 123 + 3 new), including isolated A4/A5 PDF, purchase/taxpayer print and generated Pages CSP navigation |
47
+| Final syntax, quality, login connectivity, generated public regression, Golden and release safety after cache fix | PASS; `git diff --check` PASS |
48
+| Synthetic 1536×864 source-shell visual inspection | Rail labels/order and sales/purchase context fit existing shell; screenshot inspected locally, no customer-data use |
49
+| Independent complete-diff review | No remaining critical/important/minor findings |
50
+
51
+Environment note: initial existing PDF test failed before application edits because this cloud image prioritizes system WOFF2 fonts that Chromium renders with zero text width. A temporary `FONTCONFIG_FILE=/tmp/finora-fontconfig-no-woff2.conf` excludes those fonts only for local browser processes; the unchanged PDF assertion then passed. No repository font, print code, dependency or CI setting was modified for this environment repair.
52
+
53
+Two issues found during test/review were fixed and verified: enterprise uses its existing lazy view factory before first launcher navigation; bootstrap and changed extension URLs use `20261023-phase-a-navigation-v1` so a cached previous manifest cannot restore removed rail items. Bootstrap cache assertion was observed RED then GREEN. Existing mixed accounting/treasury enterprise tasks remain available through their guarded command-search routes as on baseline; no duplicate launcher catalog or permission-refresh behavior was invented.
54
+
55
+Exact PR-head CI (including three disposable PostgreSQL jobs) is pending remote execution; local Chromium/fixture success does not establish production accounting or customer acceptance.
56
+
57
+## Changed files
58
+
59
+- Shell and extension URLs: `index.html`, `js/ui.js`, `js/bootstrap.js`.
60
+- Launcher and organization utility placement: `js/platform-modules.js`, `js/organization-shell.js`, `js/organization-rbac.js` (DOM placement only; permission predicates/RPCs unchanged).
61
+- DOM/static contracts: `scripts/dom-smoke.spec.js`, `scripts/platform-office.spec.js`, `scripts/phase0-modal-dashboard.spec.js`, `scripts/pages-artifact.spec.js`, `scripts/shell-scroll-ownership.spec.js`, `scripts/commercial-rnd-check.mjs`, `scripts/quality-check.mjs`, `scripts/login-connectivity-check.mjs`.
62
+- Continuity/evidence: `PROJECT_STATE.md`, this report.
63
+
64
+No `supabase/`, financial engine/source-posting or print implementation file changed. README's previously documented single-file wording is outside this navigation PR.
65
+
66
+**NOT VERIFIED:** real owner-ISP login, physical printer output, two simultaneous users on production, customer acceptance. No Supabase production access or migration is part of Phase A.
67
+
68
+Rollback: revert this navigation PR; financial data/schema remain untouched. Next phase requires a fresh owner instruction after this phase is reviewed.
index.html
+6
-7
@@ -280,16 +280,15 @@ body{background:#f6f9fc}
280
<button class="module-tab active" data-module="dashboard" data-view="view-dashboard" onclick="openModule('dashboard','view-dashboard','overview')" title="داشبورد"><span>⌂</span><b>داشبورد</b></button>
281
<button class="module-tab" data-module="accounting" data-view="view-accounting-foundation" onclick="openModule('accounting','view-accounting-foundation','accounts')" title="حسابداری"><span>▦</span><b>حسابداری</b></button>
282
<button class="module-tab" data-module="commerce" data-view="view-invoices" onclick="openModule('commerce','view-invoices')" title="بازرگانی"><span>⇄</span><b>بازرگانی</b></button>
283
- <button class="module-tab" data-module="treasury" data-view="view-payments" onclick="openModule('treasury','view-payments')" title="خزانهداری"><span>◈</span><b>خزانه</b></button>
284
- <button class="module-tab" data-module="projects" data-view="view-contracting" onclick="openModule('projects','view-contracting')" title="پیمانها"><span>▧</span><b>پیمانها</b></button>
283
+ <button class="module-tab" data-module="treasury" data-view="view-payments" onclick="openModule('treasury','view-payments')" title="خزانهداری"><span>◈</span><b>خزانهداری</b></button>
284
<button class="module-tab" data-module="inventory" data-view="view-inventory" onclick="openModule('inventory','view-inventory','stock')" title="انبار"><span>▦</span><b>انبار</b></button>
286
- <button class="module-tab" data-module="assets" data-view="view-assets" onclick="openModule('assets','view-assets','asset-register')" title="دارایی ثابت"><span>◆</span><b>دارایی</b></button>
287
- <button class="module-tab" data-module="enterprise" data-view="view-enterprise" onclick="openModule('enterprise','view-enterprise','employees')" title="سازمان"><span>♙</span><b>سازمان</b></button>
288
- <button class="module-tab" data-module="reports" data-view="view-reports" onclick="openModule('reports','view-reports')" title="گزارشها"><span>▥</span><b>گزارش</b></button>
285
+ <button class="module-tab" data-module="projects" data-view="view-contracting" onclick="openModule('projects','view-contracting')" title="پیمانها"><span>▧</span><b>پیمانها</b></button>
286
+ <button class="module-tab" data-module="reports" data-view="view-reports" onclick="openModule('reports','view-reports')" title="گزارشها"><span>▥</span><b>گزارشها</b></button>
287
<button class="module-tab" data-module="settings" data-view="view-settings" onclick="openModule('settings','view-settings')" title="تنظیمات"><span>⚙</span><b>تنظیمات</b></button>
288
</div>
289
<div class="sidebar-footer">
290
<span id="logged-user-label">کاربر</span>
291
+ <button class="shell-logout" id="finora-module-launcher-toggle" type="button" onclick="showModuleLauncher(true)" title="ماژولهای فعال لایسنس">ماژولها</button>
292
<button class="shell-logout" onclick="handleLogout()" title="خروج">خروج</button>
293
</div>
294
</aside>
@@ -896,7 +895,7 @@ body{background:#f6f9fc}
895
<script src="js/core.js?v=20261014-org-license-readiness-v1"></script>
896
<script src="js/admin.js?v=20261012-provision-error-v1"></script>
897
<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>
898
+<script src="js/ui.js?v=20261023-phase-a-navigation-v1"></script>
899
<script src="js/invoices.js?v=20261011-doc-draft-v1"></script>
900
<script src="js/print.js?v=20261012-clean-invoice-print-v1"></script>
901
<script src="js/products.js"></script>
@@ -906,7 +905,7 @@ body{background:#f6f9fc}
905
<script src="js/companies.js?v=20260928-integrity-v4"></script>
906
<script src="js/backup.js?v=20260928-data-v3"></script>
907
<script src="js/words.js"></script>
909
-<script src="js/bootstrap.js?v=20261014-org-license-readiness-v1"></script>
908
+<script src="js/bootstrap.js?v=20261023-phase-a-navigation-v1"></script>
909
910
<style>
911
.form-control, textarea, select { direction: rtl; }
js/bootstrap.js
+3
-3
@@ -3,10 +3,10 @@
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=20261014-org-license-readiness-v1",
6
+ "js/organization-rbac.js?v=20261023-phase-a-navigation-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",
9
+ "js/platform-modules.js?v=20261023-phase-a-navigation-v1",
10
"js/office-automation.js?v=20260930-c4-v1",
11
"js/request-workflow-d2.js?v=20261001-d2-v1",
12
"js/request-workflow-d3b.js?v=20261001-d3b-v1",
@@ -15,7 +15,7 @@ const FINORA_EXTENSION_SCRIPTS=[
15
"js/office-rbac.js?v=20260930-slice-b-v1",
16
"js/office-mature.js?v=20261001-c7-v2",
17
"js/office-workflow.js?v=20261001-c8-task3-v3",
18
- "js/organization-shell.js?v=20260930-eli4-v1",
18
+ "js/organization-shell.js?v=20261023-phase-a-navigation-v1",
19
"js/taxpayer-print.js?v=20261003-reference-v2"
20
];
21
const FINORA_EXTENSION_BUNDLE_URL=null;
js/organization-rbac.js
+3
-3
@@ -211,12 +211,12 @@ window.organizationSavePermissionFromUi=async function(){
211
const {error}=await sb.rpc('organization_set_member_permission',{p_organization_id:currentUser.organizationId,p_member_id:member,p_module_key:module,p_capabilities:caps,p_scope_type:scope,p_scope_id:scopeId,p_confidentiality_level:clearance});if(error)return alert('ثبت مجوز انجام نشد: '+error.message);alert('مجوز عضو ثبت شد.');await showOrganizationAccessManager();
212
};
213
function ensureOrgAccessButton(){
214
- const rail=document.getElementById('module-rail');if(!rail||document.getElementById('finora-org-access-btn'))return;
215
- const b=document.createElement('button');b.id='finora-org-access-btn';b.className='module-tab';b.title='سازمان و دسترسیها';b.innerHTML='<span>♙</span><b>دسترسیها</b>';b.onclick=showOrganizationAccessManager;rail.appendChild(b);
214
+ const footer=document.querySelector('.app-shell-nav .sidebar-footer');if(!footer||document.getElementById('finora-org-access-btn'))return;
215
+ const b=document.createElement('button');b.id='finora-org-access-btn';b.className='shell-logout';b.title='سازمان و دسترسیها';b.textContent='دسترسیها';b.onclick=showOrganizationAccessManager;footer.appendChild(b);
216
b.style.display=(finoraCanManageOrganization()||configurableModules().length)?'':'none';
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
222
+})();
js/organization-shell.js
+3
-3
@@ -7,9 +7,9 @@ window.showFinoraOrganizationSwitcher=function(){
7
el.innerHTML='<div class="modal-card" style="max-width:520px"><h3>انتخاب سازمان فعال</h3><p class="af-hint">اطلاعات، لایسنس و دسترسیها بر اساس سازمان انتخابشده بارگذاری میشوند.</p>'+finoraOrganizationSwitcherHtml()+'<div style="margin-top:14px"><button class="btn btn-secondary" onclick="document.getElementById(\'finora-org-switch-modal\').classList.remove(\'active\')">بستن</button></div></div>';el.classList.add('active');
8
};
9
function ensureOrgShell(){
10
- const rail=document.getElementById('module-rail');if(!rail||!currentUser)return;
11
- if((currentUser.organizations||[]).length>1&&!document.getElementById('finora-org-switch-btn')){const b=document.createElement('button');b.id='finora-org-switch-btn';b.className='module-tab';b.title='تغییر سازمان';b.innerHTML='<span>⇄</span><b>سازمان</b>';b.onclick=showFinoraOrganizationSwitcher;rail.appendChild(b)}
12
- if(canManage()&&!document.getElementById('finora-org-access-btn')){const b=document.createElement('button');b.id='finora-org-access-btn';b.className='module-tab';b.title='سازمان و دسترسیها';b.innerHTML='<span>♙</span><b>دسترسیها</b>';b.onclick=showOrganizationAccessManager;rail.appendChild(b)}
10
+ const footer=document.querySelector('.app-shell-nav .sidebar-footer');if(!footer||!currentUser)return;
11
+ if((currentUser.organizations||[]).length>1&&!document.getElementById('finora-org-switch-btn')){const b=document.createElement('button');b.id='finora-org-switch-btn';b.className='shell-logout';b.title='تغییر سازمان';b.textContent='سازمان';b.onclick=showFinoraOrganizationSwitcher;footer.appendChild(b)}
12
+ if(canManage()&&!document.getElementById('finora-org-access-btn')){const b=document.createElement('button');b.id='finora-org-access-btn';b.className='shell-logout';b.title='سازمان و دسترسیها';b.textContent='دسترسیها';b.onclick=showOrganizationAccessManager;footer.appendChild(b)}
13
}
14
const baseEnter=enterApp;enterApp=async function(authUser){const r=await baseEnter(authUser);ensureOrgShell();return r};
15
const baseRefresh=refreshAllSurfaces;refreshAllSurfaces=function(){const r=baseRefresh();ensureOrgShell();return r};
js/platform-modules.js
+3
-4
@@ -23,8 +23,7 @@ function registerShellModules(){
23
if(typeof FINORA_VIEW_HOME!=='undefined'){FINORA_VIEW_HOME['view-office']='office';FINORA_VIEW_HOME['view-requests']='requests'}
24
if(typeof FINORA_COMMANDS!=='undefined')[['office',FINORA_MODULES.office],['requests',FINORA_MODULES.requests]].forEach(([module,m])=>m.groups.forEach(g=>g.items.forEach(i=>{if(!FINORA_COMMANDS.some(x=>x.module===module&&x.view===i[1]&&x.task===(i[4]||'')))FINORA_COMMANDS.push({module,moduleTitle:m.title,groupTitle:g.title,title:i[0],view:i[1],icon:i[2],guard:i[3]||'',task:i[4]||''})})));
25
}
26
-function injectRail(){const rail=document.getElementById('module-rail');if(!rail)return;const before=rail.querySelector('[data-module="reports"]');[['office','view-office','✉','اتوماسیون','inbox'],['requests','view-requests','✓','درخواستها','new']].forEach(([m,v,ic,label,task])=>{if(rail.querySelector('[data-module="'+m+'"]'))return;const b=document.createElement('button');b.className='module-tab';b.dataset.module=m;b.dataset.view=v;b.title=label;b.innerHTML='<span>'+ic+'</span><b>'+label+'</b>';b.onclick=()=>openModule(m,v,task);rail.insertBefore(b,before||null)})}
27
-function applyLicensedUI(){injectRail();document.querySelectorAll('.module-tab').forEach(b=>{b.style.display=canModule(b.dataset.module||'core','')?'':'none'})}
26
+function applyLicensedUI(){document.querySelectorAll('.module-tab').forEach(b=>{b.style.display=canModule(b.dataset.module||'core','')?'':'none'})}
27
window.applyLicensedModuleUI=applyLicensedUI;
28
registerShellModules();
29
if(typeof canShowShellCommand==='function'){const baseCan=canShowShellCommand;canShowShellCommand=function(cmd){if(!baseCan(cmd))return false;if(cmd&&cmd.module)return canModule(cmd.module,cmd.task||'');return true}}
@@ -32,7 +31,7 @@ if(typeof renderModulePanel==='function'){const basePanel=renderModulePanel;rend
31
if(typeof openModule==='function'){const baseOpen=openModule;openModule=function(moduleKey,defaultView,defaultTask=''){if(!canModule(moduleKey,defaultTask||'')){alert('این ماژول در لایسنس فعلی فعال نیست.');return showModuleLauncher(true)}return baseOpen(moduleKey,defaultView,defaultTask)}}
32
if(typeof navigateShell==='function'){const baseNav=navigateShell;navigateShell=function(moduleKey,viewId,task='',rerender=true){if(!canModule(moduleKey,task||'')){alert('دسترسی این ماژول در لایسنس فعلی فعال نیست.');return false}return baseNav(moduleKey,viewId,task,rerender)}}
33
if(typeof refreshAllSurfaces==='function'){const baseRefresh=refreshAllSurfaces;refreshAllSurfaces=function(){const r=baseRefresh();applyLicensedUI();if(document.getElementById('view-office')?.classList.contains('active')&&typeof officeRender==='function')officeRender(window.FINORA_OFFICE_TASK||'inbox');if(document.getElementById('view-requests')?.classList.contains('active')&&typeof requestsRender==='function')requestsRender(window.FINORA_REQUEST_TASK||'mine');return r}}
35
-function launcherModules(){const list=[['accounting','accounting','view-accounting-foundation','accounts'],['commerce','commerce','view-invoices',''],['treasury','treasury','view-payments',''],['contracting','projects','view-contracting',''],['inventory','inventory','view-inventory','stock'],['assets','assets','view-assets','asset-register'],['hr_payroll','enterprise','view-enterprise','employees'],['office_automation','office','view-office','inbox'],['requests_workflow','requests','view-requests','new'],['group_consolidation','enterprise','view-enterprise','group'],['analytics','reports','view-reports','']];return list.filter(x=>licensed(x[0]))}
34
+function launcherModules(){const list=[['accounting','accounting','view-accounting-foundation','accounts'],['commerce','commerce','view-invoices',''],['treasury','treasury','view-payments',''],['contracting','projects','view-contracting',''],['inventory','inventory','view-inventory','stock'],['assets','assets','view-assets','asset-register'],['hr_payroll','enterprise','view-enterprise','employees'],['office_automation','office','view-office','inbox'],['requests_workflow','requests','view-requests','new'],['group_consolidation','enterprise','view-enterprise','group'],['analytics','reports','view-reports','']];return list.filter(x=>licensed(x[0])&&canShowShellCommand({module:x[1],view:x[2],task:x[3]}))}
35
function ensureLauncher(){let el=document.getElementById('finora-module-launcher');if(el)return el;el=document.createElement('div');el.id='finora-module-launcher';el.className='modal-backdrop';el.innerHTML='<div class="modal-card" style="max-width:860px"><div style="display:flex;justify-content:space-between;gap:12px;align-items:center"><div><h3 style="font-size:20px">ورود به فضای کاری</h3><p style="color:var(--text-muted);font-size:12px;margin-top:5px">فقط ماژولهای فعال در لایسنس شما نمایش داده میشوند.</p></div><button class="btn btn-secondary btn-inline" onclick="closeModuleLauncher()">ادامه در داشبورد</button></div><div id="finora-launcher-grid" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:12px;margin-top:18px"></div></div>';document.body.appendChild(el);return el}
36
function showModuleLauncher(force=false){if(!currentUser)return;const choices=launcherModules();if(!force&&choices.length<=1)return;const el=ensureLauncher(),grid=document.getElementById('finora-launcher-grid');grid.innerHTML=choices.map(x=>{const c=MODULE_CATALOG[x[0]];return '<button class="card" style="text-align:right;cursor:pointer;border:1px solid var(--border);padding:16px" onclick="enterLicensedWorkspace(\''+x[1]+'\',\''+x[2]+'\',\''+x[3]+'\')"><div style="font-size:24px">'+c.icon+'</div><strong style="display:block;margin-top:8px">'+c.title+'</strong><small style="color:var(--text-muted)">ورود به ماژول</small></button>'}).join('');el.classList.add('active')}
37
window.showModuleLauncher=showModuleLauncher;window.closeModuleLauncher=()=>document.getElementById('finora-module-launcher')?.classList.remove('active');window.enterLicensedWorkspace=(m,v,t)=>{closeModuleLauncher();navigateShell(m,v,t||'')};
@@ -57,4 +56,4 @@ if(typeof applyLicenseDurationChange==='function')applyLicenseDurationChange=asy
56
};
57
if(typeof enterApp==='function'){const baseEnter=enterApp;enterApp=async function(authUser){await baseEnter(authUser);if(!currentUser)return;applyLicensedUI()}}
58
applyLicensedUI();
60
-})();
\ No newline at end of file
59
+})();
js/ui.js
+16
-3
@@ -95,7 +95,7 @@ const FINORA_MODULES={
95
{title:'دفاتر و کنترل',items:[['تراز آزمایشی','view-accounting-reports','▥','','trial'],['دفتر کل / معین / تفصیلی','view-accounting-reports','▤','','ledger']]},
96
{title:'صورتهای مالی و تحلیل',items:[['صورتهای مالی','view-accounting-reports','◫','','financials'],['جریان وجوه نقد','view-accounting-reports','↕','','cashflow'],['سن مطالبات و بدهیها','view-accounting-reports','◷','','aging']]}
97
]},
98
- commerce:{title:'بازرگانی',context:'اشخاص، کالا و اسناد تجاری',groups:[{title:'اشخاص و کالا',items:[['اشخاص','view-contacts','◎'],['کالا و خدمات','view-products','◇']]},{title:'اسناد تجاری',items:[['فاکتورها','view-invoices','▤']]}]},
98
+ commerce:{title:'بازرگانی',context:'اشخاص، کالا و اسناد تجاری',groups:[{title:'اشخاص و کالا',items:[['اشخاص','view-contacts','◎'],['کالا و خدمات','view-products','◇']]},{title:'اسناد تجاری',items:[['فاکتور فروش','view-invoices','▤'],['فاکتور خرید','view-purchases','▤']]}]},
99
treasury:{title:'خزانهداری',context:'دریافت، پرداخت، چک و کنترل نقدینگی',groups:[{title:'عملیات',items:[['دریافت و پرداخت','view-payments','↔'],['چکها و صیاد','view-cheques','◈']]},{title:'کنترل',items:[['سن مطالبات و بدهیها','view-accounting-reports','◷','','aging'],['جریان وجوه نقد','view-accounting-reports','↕','','cashflow']]}]},
100
projects:{title:'پیمانها',context:'پیمان، پروژه/کارگاه، کسورات، تضمین و صورتوضعیت',groups:[{title:'اطلاعات پایه',items:[['پروژهها و کارگاهها','view-accounting-foundation','▧','','projects']]},{title:'عملیات پیمان',items:[['پیمانها و قراردادهای اجرایی','view-contracting','▦']]},{title:'گزارش',items:[['گزارش پیمان و پروژه','view-accounting-reports','▥','','projects']]}]},
101
inventory:{title:'انبار',context:'انبار، گردش، شمارش و بهای موجودی',groups:[{title:'اطلاعات پایه',items:[['تعریف انبار','view-inventory','▦','','warehouse']]},{title:'عملیات',items:[['گردش انبار','view-inventory','⇄','','movement'],['انبارگردانی','view-inventory','✓','','count']]},{title:'گزارش و کنترل',items:[['موجودی و بهای میانگین','view-inventory','▥','','stock']]}]},
@@ -113,6 +113,18 @@ const FINORA_VIEW_HOME={
113
const FINORA_COMMANDS=Object.entries(FINORA_MODULES).flatMap(([module,m])=>m.groups.flatMap(g=>g.items.map(i=>({module,moduleTitle:m.title,groupTitle:g.title,title:i[0],view:i[1],icon:i[2],guard:i[3]||'',task:i[4]||''}))));
114
let FINORA_ACTIVE_TASK='';
115
function canShowShellCommand(cmd){
116
+ if(cmd.view){
117
+ if(!document.getElementById(cmd.view)&&!(cmd.view==='view-enterprise'&&typeof window.ensureEnterpriseView==='function'))return false;
118
+ const implementations={
119
+ 'view-dashboard':window.renderDashboard,'view-invoices':window.renderInvoices,'view-purchases':window.purSave,
120
+ 'view-contacts':window.renderContacts,'view-products':window.renderProducts,'view-payments':window.renderPayments,
121
+ 'view-journal':window.renderJournal,'view-accounting-foundation':window.renderAccountingFoundation,'view-accounting-reports':window.P6Reports?.render,
122
+ 'view-contracting':window.renderPhase4,'view-enterprise':window.enterpriseRender,'view-reports':window.renderFinancialReports,
123
+ 'view-inventory':window.p5Render,'view-assets':window.p5Render,'view-currency':window.p5Render,'view-data-center':window.p5Render,'view-integrations':window.p5Render,
124
+ 'view-office':window.officeRender,'view-requests':window.requestsRender
125
+ };
126
+ if(Object.prototype.hasOwnProperty.call(implementations,cmd.view)&&typeof implementations[cmd.view]!=='function')return false;
127
+ }
128
// Admin-only entries are shown based on the verified role of the signed-in user
129
// (server-side RLS/RPC still enforces the real permission).
130
if(cmd.guard==='admin')return !!(typeof currentUser!=='undefined'&¤tUser&¤tUser.role==='admin');
@@ -123,7 +135,7 @@ function renderModulePanel(moduleKey,activeView,activeTask=''){
135
const title=document.getElementById('module-panel-title'),box=document.getElementById('module-panel-links');
136
if(title)title.textContent=m.title;
137
if(!box)return;
126
- box.innerHTML=m.groups.map(g=>'<div class="module-group"><div class="module-group-title">'+g.title+'</div>'+g.items.filter(i=>canShowShellCommand({guard:i[3]||''})).map(i=>{const task=i[4]||'',active=i[1]===activeView&&task===activeTask;return '<button class="module-link '+(active?'active':'')+'" data-view="'+i[1]+'" data-task="'+task+'" onclick="navigateShell(\''+moduleKey+'\',\''+i[1]+'\',\''+task+'\')"><span class="mi">'+i[2]+'</span><span>'+i[0]+'</span></button>'}).join('')+'</div>').join('');
138
+ box.innerHTML=m.groups.map(g=>{const items=g.items.filter(i=>canShowShellCommand({module:moduleKey,view:i[1],task:i[4]||'',guard:i[3]||''}));return items.length?'<div class="module-group"><div class="module-group-title">'+g.title+'</div>'+items.map(i=>{const task=i[4]||'',active=i[1]===activeView&&task===activeTask;return '<button class="module-link '+(active?'active':'')+'" data-view="'+i[1]+'" data-task="'+task+'" onclick="navigateShell(\''+moduleKey+'\',\''+i[1]+'\',\''+task+'\')"><span class="mi">'+i[2]+'</span><span>'+i[0]+'</span></button>'}).join('')+'</div>':''}).join('');
139
}
140
function updateShellContext(moduleKey,viewId,task=''){
141
const m=FINORA_MODULES[moduleKey]||FINORA_MODULES.dashboard;
@@ -160,6 +172,7 @@ function openModule(moduleKey,defaultView,defaultTask=''){
172
}
173
function navigateShell(moduleKey,viewId,task='',rerender=true){
174
if(viewId==='view-journal'&&typeof ensureJournalView==='function')ensureJournalView();
175
+ if(viewId==='view-enterprise'&&typeof ensureEnterpriseView==='function')ensureEnterpriseView();
176
switchView(viewId);
177
if(viewId==='view-payments'&&typeof renderPayments==='function')renderPayments();
178
if(viewId==='view-journal'&&typeof renderJournal==='function')renderJournal();
@@ -215,7 +228,7 @@ function syncShellForView(viewId){
228
}
229
document.addEventListener('click',e=>{if(!e.target.closest('.global-search'))closeCommandSearch();if(!e.target.closest('.quick-create'))closeQuickCreateMenu();});
230
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)}
231
+document.addEventListener('DOMContentLoaded',()=>{
232
try{if(localStorage.getItem('finora.shell.panelCollapsed')==='1')document.body.classList.add('shell-panel-collapsed');}catch(_){}
233
syncModulePanelHandle();
234
renderModulePanel('dashboard','view-dashboard','overview');updateShellContext('dashboard','view-dashboard','overview');
scripts/commercial-rnd-check.mjs
+3
-3
@@ -5,8 +5,8 @@ const commerce=fs.readFileSync('js/commercial-rnd.js','utf8');
5
const html=fs.readFileSync('index.html','utf8');
6
const purchase=fs.readFileSync('js/purchases.js','utf8');
7
function ok(v,m){if(!v)throw new Error(m);}
8
-ok(ui.includes("['فاکتورها','view-invoices'"),'Commerce must expose one invoice workspace.');
9
-ok(!ui.includes("['فاکتور خرید','view-purchases'"),'Purchase must not be a separate Commerce menu item.');
8
+ok(ui.includes("['فاکتور فروش','view-invoices'"),'Commerce must expose the implemented sales workspace.');
9
+ok(ui.includes("['فاکتور خرید','view-purchases'"),'Commerce must expose the implemented purchase workspace.');
10
ok(contacts.includes("FINORA_QUICK_CONTACT_ROLE"),'Quick contact must preserve customer/supplier context.');
11
ok(commerce.includes("openQuickContactModal('supplier')"),'Purchase must support quick supplier creation.');
12
ok(commerce.includes('downloadInvoiceItemsExcelTemplate')&&commerce.includes('purDownloadExcelTemplate'),'Both invoice imports need downloadable templates.');
@@ -18,4 +18,4 @@ ok(!html.includes('🧾 فاکتور فروش</button>')&&!html.includes('🛒
18
ok(!fs.readFileSync('js/ux-hardening-r2.js','utf8').includes('finora-commerce-toolbar'),'Invoice workspace must not duplicate sale/purchase/pre-invoice workflow buttons above the form.');
19
ok(['sale','purchase','pre_invoice','contract_statement'].every(v=>commerce.includes('<option value="'+v+'"')),'Unified document selector must contain sale, purchase, sales pre-invoice and sales progress statement.');
20
ok(purchase.includes("jePostSourceRecord('purchase',record)"),'Purchase posting must remain automatic.');
21
-console.log('Commercial R&D invariants passed.');
\ No newline at end of file
21
+console.log('Commercial R&D invariants passed.');
scripts/dom-smoke.spec.js
+147
-1
@@ -1,6 +1,152 @@
1
const {test,expect}=require('@playwright/test');
2
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([]);});
3
+
4
+const PHASE_A_RAIL=[
5
+ ['dashboard','داشبورد'],['accounting','حسابداری'],['commerce','بازرگانی'],
6
+ ['treasury','خزانهداری'],['inventory','انبار'],['projects','پیمانها'],
7
+ ['reports','گزارشها'],['settings','تنظیمات']
8
+];
9
+async function phaseABrowser(page){
10
+ // This fixture never authenticates against, reads, or writes a real tenant.
11
+ await page.route(/https:\/\/[^/]*supabase\.co\//,route=>route.abort());
12
+ await page.goto('http://127.0.0.1:4173/index.html',{waitUntil:'domcontentloaded'});
13
+ await page.waitForFunction(()=>window.FinoraStartupStatus?.extensionsReady===true&&
14
+ window.FinoraStartupStatus?.failedExtensionCount===0&&
15
+ window.FinoraStartupStatus?.authChecked===true&&
16
+ typeof window.applyLicensedModuleUI==='function'&&typeof window.purSave==='function',null,{timeout:20000});
17
+ await page.evaluate(()=>{
18
+ const uid='PHASE_A_LOCAL_ONLY';
19
+ currentUser={id:uid,fullName:'آزمون ناوبری',role:'admin',isOrganizationOwner:true,
20
+ organizationId:'QA_ORG',organizationName:'سازمان آزمون',maxCompanies:2,maxUsers:2,
21
+ organizations:[{organization:{id:'QA_ORG',name:'سازمان آزمون'}},{organization:{id:'QA_ORG_2',name:'سازمان دوم'}}],
22
+ modules:['full_suite'],commercialModules:['full_suite'],modulePermissions:[],
23
+ subscription:{type:'lifetime',status:'active',endDate:'2099-01-01'}};
24
+ COLLS.forEach(key=>datastore[key]=[]);
25
+ datastore.companies=[{id:'QA_COMPANY',ownerUserId:uid,name:'شرکت آزمون'}];
26
+ datastore.settings=[{ownerUserId:uid,default_company_id:'QA_COMPANY',ui_theme:'light',currency_mode:'rial'}];
27
+ // Renderers may seed local master defaults. Persistence stays disconnected.
28
+ window.saveDatastore=()=>{};
29
+ document.querySelector('#auth-screen').style.display='none';
30
+ document.body.classList.remove('shell-panel-collapsed');
31
+ document.body.classList.add('is-admin');
32
+ refreshAllSurfaces();applyLicensedModuleUI();
33
+ document.querySelectorAll('.modal-backdrop.active').forEach(el=>el.classList.remove('active'));
34
+ });
35
+}
36
+async function expectPhaseARail(page){
37
+ const buttons=page.locator('#module-rail > button');
38
+ await expect(buttons).toHaveCount(PHASE_A_RAIL.length);
39
+ expect(await buttons.evaluateAll(nodes=>nodes.map(el=>[el.dataset.module,el.querySelector('b')?.textContent]))).toEqual(PHASE_A_RAIL);
40
+ await expect(page.locator('#module-rail [data-module="assets"],#module-rail [data-module="enterprise"],#module-rail [data-module="office"],#module-rail [data-module="requests"]')).toHaveCount(0);
41
+}
42
+
43
+test('Phase A rail stays exact through organization refresh and real commerce/accounting/report navigation',async({page})=>{
44
+ const errors=[];page.on('pageerror',error=>errors.push(error.message));
45
+ await phaseABrowser(page);
46
+ await expectPhaseARail(page);
47
+ for(let attempt=0;attempt<3;attempt++){
48
+ await page.evaluate(()=>{refreshAllSurfaces();applyLicensedModuleUI()});
49
+ await expectPhaseARail(page);
50
+ }
51
+ for(const id of ['finora-org-switch-btn','finora-org-access-btn']){
52
+ await expect(page.locator('#'+id)).toBeVisible();
53
+ await expect(page.locator('#module-rail #'+id)).toHaveCount(0);
54
+ await expect(page.locator('#'+id)).toHaveCount(1);
55
+ }
56
+ const rail=page.locator('#module-rail'),panel=page.locator('#module-panel-links');
57
+ await rail.locator('[data-module="commerce"]').click();
58
+ const sale=panel.locator('[data-view="view-invoices"]');
59
+ const purchase=panel.locator('[data-view="view-purchases"]');
60
+ await expect(sale).toHaveText(/فاکتور فروش/);await expect(sale).toHaveCount(1);
61
+ await expect(purchase).toHaveText(/فاکتور خرید/);await expect(purchase).toHaveCount(1);
62
+ await purchase.click();
63
+ await expect(page.locator('#view-purchases')).toHaveClass(/active/);
64
+ await expect(page.locator('#pur-save-btn')).toBeVisible();
65
+ await expect(page.locator('#view-invoices')).not.toHaveClass(/active/);
66
+ await expect(purchase).toHaveClass(/active/);
67
+ await expect(rail.locator('[data-module="commerce"]')).toHaveClass(/active/);
68
+ await sale.click();
69
+ await expect(page.locator('#view-invoices')).toHaveClass(/active/);
70
+ await expect(page.locator('#view-purchases')).not.toHaveClass(/active/);
71
+ await page.locator('#global-command-search').fill('فاکتور خرید');
72
+ await expect(page.locator('#command-search-results .command-result')).toHaveCount(1);
73
+ await page.locator('#command-search-results .command-result').click();
74
+ await expect(page.locator('#view-purchases')).toHaveClass(/active/);
75
+ await expect(page.locator('#module-panel-title')).toHaveText('بازرگانی');
76
+ await rail.locator('[data-module="accounting"]').click();
77
+ await panel.locator('[data-view="view-journal"][data-task="new"]').click();
78
+ await expect(page.locator('#view-journal [data-finora-task="new"]')).toBeVisible();
79
+ await expect(page.locator('#view-journal [data-finora-task="register"]')).toBeHidden();
80
+ await panel.locator('[data-view="view-journal"][data-task="register"]').click();
81
+ await expect(page.locator('#view-journal [data-finora-task="register"]')).toBeVisible();
82
+ await expect(page.locator('#view-journal [data-finora-task="new"]')).toBeHidden();
83
+ await panel.locator('[data-view="view-accounting-reports"][data-task="trial"]').click();
84
+ await expect(page.locator('#view-accounting-reports')).toHaveClass(/active/);
85
+ await expect(page.locator('#p6-reporting-root [data-finora-task="trial"]')).toBeVisible();
86
+ await expect(page.locator('#p6-reporting-root [data-finora-task="ledger"]')).toBeHidden();
87
+ await rail.locator('[data-module="reports"]').click();
88
+ await panel.locator('[data-view="view-accounting-reports"][data-task="trial"]').click();
89
+ await expect(page.locator('#view-accounting-reports')).toHaveClass(/active/);
90
+ await expect(page.locator('#p6-reporting-root [data-finora-task="trial"]')).toBeVisible();
91
+ await expect(rail.locator('[data-module="reports"]')).toHaveClass(/active/);
92
+ await expect(page.locator('#module-panel-title')).toHaveText('گزارشها');
93
+ await rail.locator('[data-module="settings"]').click();
94
+ await expect(panel.locator('[data-view="view-admin"]')).toHaveCount(1);
95
+ await page.evaluate(()=>{currentUser.role='accountant';currentUser.isOrganizationOwner=false;refreshAllSurfaces();applyLicensedModuleUI()});
96
+ await rail.locator('[data-module="settings"]').click();
97
+ await expect(panel.locator('[data-view="view-admin"]')).toHaveCount(0);
98
+ await expect(page.locator('#finora-org-switch-btn')).toBeVisible();
99
+ await expectPhaseARail(page);
100
+ expect(await page.evaluate(()=>['invoices','purchases','journalVouchers','journalLines'].map(key=>datastore[key].length))).toEqual([0,0,0,0]);
101
+ expect(errors).toEqual([]);
102
+});
103
+
104
+test('Phase A visible licensed launcher preserves extra workspaces without adding rail items',async({page})=>{
105
+ const errors=[];page.on('pageerror',error=>errors.push(error.message));
106
+ await phaseABrowser(page);
107
+ const toggle=page.locator('#finora-module-launcher-toggle');
108
+ await expect(toggle).toBeVisible();
109
+ await expect(page.locator('#module-rail #finora-module-launcher-toggle')).toHaveCount(0);
110
+ const launcher=page.locator('#finora-module-launcher'),grid=page.locator('#finora-launcher-grid');
111
+ for(const [label,view] of [
112
+ ['دارایی ثابت','view-assets'],['منابع انسانی و حقوق','view-enterprise'],
113
+ ['اتوماسیون اداری','view-office'],['درخواستها و فرایندها','view-requests']
114
+ ]){
115
+ await toggle.click();await expect(launcher).toHaveClass(/active/);
116
+ await grid.getByRole('button',{name:new RegExp(label)}).click();
117
+ await expect(launcher).not.toHaveClass(/active/);
118
+ await expect(page.locator('#'+view)).toHaveClass(/active/);
119
+ await expectPhaseARail(page);
120
+ }
121
+ await page.evaluate(()=>{switchView('view-dashboard');currentUser.modules=['accounting'];currentUser.commercialModules=['accounting'];applyLicensedModuleUI()});
122
+ await toggle.click();
123
+ await expect(grid.locator('button')).toHaveCount(1);
124
+ await expect(grid).toContainText('حسابداری');
125
+ for(const label of ['دارایی ثابت','منابع انسانی و حقوق','اتوماسیون اداری','درخواستها و فرایندها','CRM','ناوگان','MRP'])await expect(grid).not.toContainText(label);
126
+ expect(await page.evaluate(()=>({office:canAccessFinoraModule('office'),workflow:canAccessFinoraModule('requests')}))).toEqual({office:false,workflow:false});
127
+ await grid.getByRole('button',{name:/حسابداری/}).click();
128
+ await expect(page.locator('#view-accounting-foundation')).toHaveClass(/active/);
129
+ expect(errors).toEqual([]);
130
+});
131
+
132
+test('Phase A omits an unavailable purchase command and restores it when its implementation returns',async({page})=>{
133
+ await phaseABrowser(page);
134
+ await page.evaluate(()=>{window.__phaseAPurSave=window.purSave;window.purSave=undefined});
135
+ try{
136
+ await page.locator('#module-rail [data-module="commerce"]').click();
137
+ await expect(page.locator('#module-panel-links [data-view="view-purchases"]')).toHaveCount(0);
138
+ await expect(page.locator('#module-panel-links [data-view="view-invoices"]')).toHaveCount(1);
139
+ await page.locator('#global-command-search').fill('فاکتور خرید');
140
+ await expect(page.locator('#command-search-results')).not.toContainText('فاکتور خرید');
141
+ // Availability filters must not destroy the registered command catalog.
142
+ expect(await page.evaluate(()=>FINORA_COMMANDS.some(command=>command.module==='commerce'&&command.view==='view-purchases'))).toBe(true);
143
+ }finally{
144
+ await page.evaluate(()=>{window.purSave=window.__phaseAPurSave;delete window.__phaseAPurSave});
145
+ }
146
+ await page.locator('#module-rail [data-module="commerce"]').click();
147
+ await expect(page.locator('#module-panel-links [data-view="view-purchases"]')).toHaveCount(1);
148
+});
149
+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('#module-rail [data-module="assets"]')).toHaveCount(0);await expect(page.locator('#module-rail [data-module="enterprise"]')).toHaveCount(0);await page.waitForFunction(()=>typeof enterpriseRender==='function'&&window.FinoraStartupStatus?.extensionsReady===true&&window.FinoraStartupStatus?.failedExtensionCount===0&&window.FinoraStartupStatus?.authChecked===true);await expect(page.locator('#module-rail [data-module="enterprise"]')).toHaveCount(0);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([]);});
150
151
152
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([]);});
scripts/login-connectivity-check.mjs
+1
-1
@@ -9,7 +9,7 @@ assert(html.includes('id="auth-connectivity-result" aria-live="polite"'),'Diagno
9
assert(html.includes('js/login-connectivity.js?v=20261012-data-probe-v3'),'Missing versioned script');
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');
12
+assert(html.includes('js/bootstrap.js?v=20261023-phase-a-navigation-v1'),'Navigation extension manifest must use the Phase A cache version');
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');
scripts/pages-artifact.spec.js
+6
-1
@@ -229,7 +229,12 @@ test('Published Pages CSP event bindings open Commerce and the top-bar sales inv
229
await commerce.click();
230
await expect(page.locator('#view-invoices')).toHaveClass(/active/);
231
await expect(page.locator('#module-panel-title')).toHaveText('بازرگانی');
232
- await expect(page.locator('#module-panel-links')).toContainText('فاکتورها');
232
+ await expect(page.locator('#module-panel-links')).toContainText('فاکتور فروش');
233
+ await expect(page.locator('#module-panel-links')).toContainText('فاکتور خرید');
234
+ await page.locator('#module-panel-links [data-view="view-purchases"]').click();
235
+ await expect(page.locator('#view-purchases')).toHaveClass(/active/);
236
+ await page.locator('#module-panel-links [data-view="view-invoices"]').click();
237
+ await expect(page.locator('#view-invoices')).toHaveClass(/active/);
238
await expect(page.locator('#module-panel-links')).toContainText('کالا و خدمات');
239
// On the hardened Pages build, onclick was replaced by generated CSP-safe handlers.
240
// Testing raw source index.html alone cannot validate this event-wiring path.
scripts/phase0-modal-dashboard.spec.js
+5
-2
@@ -61,7 +61,7 @@ test('dashboard cash/assets cards drill to accounts, rows to ledger, recent vouc
61
});
62
63
64
-test('F0-02 commerce tab navigates away from accounting and exposes invoice, product and contact links',async({page})=>{
64
+test('F0-02 commerce tab navigates away from accounting and exposes sales, purchases, product and contact links',async({page})=>{
65
// Synthetic local UI test. No real Supabase session or financial writes.
66
await boot(page);
67
await page.waitForFunction(()=>typeof window.applyLicensedModuleUI==='function'&&typeof window.openModule==='function');
@@ -74,11 +74,14 @@ test('F0-02 commerce tab navigates away from accounting and exposes invoice, pro
74
await rail.locator('[data-module="commerce"]').click();
75
await expect(page.locator('#view-invoices')).toHaveClass(/active/);
76
await expect(page.locator('#module-panel-title')).toHaveText('بازرگانی');
77
- await expect(page.locator('#module-panel-links')).toContainText('فاکتورها');
77
+ await expect(page.locator('#module-panel-links')).toContainText('فاکتور فروش');
78
+ await expect(page.locator('#module-panel-links')).toContainText('فاکتور خرید');
79
await expect(page.locator('#module-panel-links')).toContainText('کالا و خدمات');
80
await expect(page.locator('#module-panel-links')).toContainText('اشخاص');
81
await expect(page.locator('#module-panel-links [data-view="view-journal"]')).toHaveCount(0);
82
await expect(rail.locator('[data-module="commerce"]')).toHaveClass(/active/);
83
+ await page.locator('#module-panel-links [data-view="view-purchases"]').click();
84
+ await expect(page.locator('#view-purchases')).toHaveClass(/active/);
85
await page.locator('#module-panel-links [data-view="view-products"]').click();
86
await expect(page.locator('#view-products')).toHaveClass(/active/);
87
await page.locator('#module-panel-links [data-view="view-invoices"]').click();
scripts/platform-office.spec.js
+9
-2
@@ -3,9 +3,16 @@ const {test,expect}=require('@playwright/test');
3
test('modular launcher and office surfaces render from licensed modules',async({page})=>{
4
const errs=[];page.on('pageerror',e=>errs.push(String(e)));
5
await page.goto('http://127.0.0.1:4173/index.html',{waitUntil:'domcontentloaded'});
6
- await page.waitForFunction(()=>window.FINORA_MODULE_CATALOG&&typeof window.officeRender==='function'&&typeof window.requestsRender==='function');
6
+ await page.waitForFunction(()=>window.FINORA_MODULE_CATALOG&&typeof window.officeRender==='function'&&typeof window.requestsRender==='function'&&window.FinoraStartupStatus?.extensionsReady===true&&window.FinoraStartupStatus?.failedExtensionCount===0&&window.FinoraStartupStatus?.authChecked===true);
7
await page.evaluate(()=>{currentUser={id:'platform-smoke',email:'platform@example.test',role:'admin',modules:['office_automation','requests_workflow'],subscription:{type:'lifetime',status:'active',endDate:'2099-01-01'}};['officeRegistries','correspondence','correspondenceAttachments','correspondenceReferrals','correspondenceAudit','requestTypes','requests','requestActions'].forEach(k=>datastore[k]=[]);applyLicensedModuleUI()});
8
- await expect(page.locator('[data-module="office"]')).toBeVisible();await expect(page.locator('[data-module="requests"]')).toBeVisible();await expect(page.locator('[data-module="accounting"]')).toBeHidden();await expect(page.locator('[data-module="settings"]')).toBeVisible();
8
+ await page.evaluate(()=>{document.querySelector('#auth-screen').style.display='none'});
9
+ await expect(page.locator('#module-rail [data-module="office"]')).toHaveCount(0);await expect(page.locator('#module-rail [data-module="requests"]')).toHaveCount(0);await expect(page.locator('[data-module="accounting"]')).toBeHidden();await expect(page.locator('[data-module="settings"]')).toBeVisible();
10
+ await page.locator('#finora-module-launcher-toggle').click();
11
+ await expect(page.locator('#finora-launcher-grid')).toContainText('اتوماسیون اداری');
12
+ await expect(page.locator('#finora-launcher-grid')).toContainText('درخواستها و فرایندها');
13
+ await expect(page.locator('#finora-launcher-grid')).not.toContainText('حسابداری');
14
+ await page.locator('#finora-launcher-grid').getByRole('button',{name:/اتوماسیون اداری/}).click();
15
+ await expect(page.locator('#view-office')).toHaveClass(/active/);
16
expect(await page.evaluate(()=>hasLicensedModule('office_automation'))).toBe(true);expect(await page.evaluate(()=>hasLicensedModule('accounting'))).toBe(false);
17
await page.evaluate(()=>{switchView('view-office');officeRender('registries')});await expect(page.locator('#view-office')).toContainText('دفاتر دبیرخانه و شمارهگذاری');await expect(page.locator('#view-office')).toContainText('اتمیک');
18
await page.evaluate(()=>{switchView('view-office');officeRender('new')});await expect(page.locator('#office-files')).toHaveAttribute('accept',/application\/pdf/);await expect(page.locator('#view-office')).toContainText('OCR-ready');
scripts/quality-check.mjs
+6
-2
@@ -18,7 +18,10 @@ if(!index.includes("frame-ancestors 'none'")||!index.includes('upgrade-insecure-
18
if(!index.includes('name="referrer" content="strict-origin-when-cross-origin"'))throw new Error('Referrer policy metadata missing');
19
for(const needle of ["replace(/&/g,'&')","replace(/</g,'<')","replace(/>/g,'>')","replace(/\"/g,'"')","replace(/'/g,''')"])if(!fs.readFileSync(path.join(root,'js','core.js'),'utf8').includes(needle))throw new Error('HTML escaping invariant missing '+needle);
20
if(!index.includes('فینورا — نسخه ۱.۰')||!index.includes('نسخه ۱.۰'))throw new Error('Visible application version is inconsistent');
21
-for(const shellId of ['module-rail','module-panel','module-panel-handle','module-panel-links','global-command-search','command-search-results','quick-create-toggle','quick-create-menu','topbar-company','topbar-fiscal-year','workspace-title','workspace-context-text'])if(!ids.includes(shellId))throw new Error('Phase 1 shell missing #'+shellId);
21
+for(const shellId of ['module-rail','module-panel','module-panel-handle','module-panel-links','finora-module-launcher-toggle','global-command-search','command-search-results','quick-create-toggle','quick-create-menu','topbar-company','topbar-fiscal-year','workspace-title','workspace-context-text'])if(!ids.includes(shellId))throw new Error('Phase 1 shell missing #'+shellId);
22
+const railMarkup=index.match(/<div\b[^>]*id="module-rail"[^>]*>([\s\S]*?)<\/div>/)?.[1]||'';
23
+const railModules=[...railMarkup.matchAll(/\bdata-module="([^"]+)"/g)].map(match=>match[1]);
24
+if(JSON.stringify(railModules)!==JSON.stringify(['dashboard','accounting','commerce','treasury','inventory','projects','reports','settings']))throw new Error('Phase A default rail must contain exactly eight ordered modules');
25
for(const cls of ['module-rail','module-panel','topbar','global-search'])if(!index.includes('class="'+cls)&&!index.includes('class="sidebar '+cls)&&!index.includes('class="'+cls+' '))throw new Error('Phase 1 shell class missing: '+cls);
26
27
@@ -92,7 +95,8 @@ const p5=all['phase5-enterprise.js']||'';for(const x of ['getMyWarehouses','p5Po
95
for(const coll of ['warehouses','stockMovements','inventoryCounts','fixedAssets','assetDepreciations','currencies','exchangeRates','costCenters','importBatches','integrationConnections','integrationOutbox','phase5Audit'])if(!all['core.js'].includes("'"+coll+"'")||!all['sync.js'].includes(coll))throw new Error('Phase5 persistence missing '+coll);
96
for(const v of ['view-inventory','view-assets','view-currency','view-data-center','view-integrations'])if(!index.includes('id="'+v+'"'))throw new Error('Phase5 workspace missing '+v);
97
for(const [view,module] of [['view-inventory','inventory'],['view-assets','assets'],['view-currency','accounting'],['view-data-center','settings'],['view-integrations','settings']])if(!all['ui.js'].includes("'"+view+"':'"+module+"'"))throw new Error('Phase5 IA v2 mapping missing '+view+' -> '+module);
95
-if(!index.includes('phase5-domain.js')||!index.includes('phase5-enterprise.js')||!index.includes('data-module="inventory"')||!index.includes('data-module="assets"'))throw new Error('Phase5 IA v2 shell/scripts missing');
98
+if(!index.includes('phase5-domain.js')||!index.includes('phase5-enterprise.js')||!index.includes('data-module="inventory"'))throw new Error('Phase5 workspace scripts/inventory shell missing');
99
+for(const key of ['assets','enterprise','office','requests'])if(railModules.includes(key))throw new Error('Phase A launcher-only module remains in default rail: '+key);
100
for(const legacy of ['data-module="home"','data-module="catalog"','data-module="erp"'])if(index.includes(legacy))throw new Error('Deprecated rail module remains '+legacy);
101
for(const required of ['data-module="dashboard"','<b>داشبورد</b>','ساختار مالی','ثبت و عملیات','دفاتر و کنترل','صورتهای مالی و تحلیل','کدینگ حسابها','تفصیلیهای شناور'])if(!index.includes(required)&&!all['ui.js'].includes(required))throw new Error('Enterprise navigation contract missing '+required);
102
scripts/shell-scroll-ownership.spec.js
+1
-1
@@ -4,7 +4,7 @@ test('desktop shell keeps three independent right-edge vertical scroll owners',a
4
await page.setViewportSize({width:1536,height:420});
5
await page.goto('http://127.0.0.1:4173/index.html',{waitUntil:'domcontentloaded'});
6
const uiSrc=await page.locator('script[src^="js/ui.js"]').getAttribute('src');
7
- expect(uiSrc).toBe('js/ui.js?v=20261002-shell-scroll-ownership-v2');
7
+ expect(uiSrc).toBe('js/ui.js?v=20261023-phase-a-navigation-v1');
8
const result=await page.evaluate(()=>{
9
const rail=document.getElementById('module-rail');
10
const panel=document.getElementById('module-panel-links');