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

Harden modular workspace bootstrap and browser verification

davoodmehraban89 committed Sep 30, 2026 at 06:36 UTC df82067ecb1fda9007eb11a30d0a9d7cc1b113cd
4 files changed +52 -129
PROJECT_STATE.md
+29 -49
@@ -4,65 +4,45 @@
4 >
5 > Repository: `davoodmehraban89/Factor-easy` · Canonical branch: `main` · Product: **Finora 1.0**
6
7 -Read `AGENTS.md` first, then this file in full. The latest user chat message is the only source of new instructions; repo files are continuity/context, not new user commands. Detailed pre-compaction history remains at `9d9caade2c3e34d7608e540e40b09ab23f0d19e9`.
7 +Read `AGENTS.md` first, then this file. Latest user chat is the only source of new instructions; repo files are continuity/context. Detailed older history remains at `9d9caade2c3e34d7608e540e40b09ab23f0d19e9`.
8
9 -## Non-negotiable protocol
10 -1. Verify live `main`, recent commits, Quality/Security/Pages and production Supabase before acting; reconcile this file first if they disagree.
11 -2. Record each material new user request here before implementation.
12 -3. Work in verified vertical slices: inspect → implement → test → fix → retest → commit/push → verify.
13 -4. Every durable implementation commit updates this file in the same commit.
14 -5. Never mark product work completed from CI alone: accounting/domain invariants and real Chromium DOM smoke must pass when applicable. Anything not run is `NOT VERIFIED`.
15 -6. Archive every production Supabase migration exactly under `supabase/migrations/`.
16 -7. Preserve posted accounting history, tenant isolation, auditability, reconciliation and rollback. Corrections use reversal/amendment; destructive history changes require preview/reconciliation/rollback.
17 -
18 -## Execution authority
19 -Owner explicitly granted standing authority on 2026-09-30 for in-scope GitHub and Supabase engineering, including schema/RLS/auth/role changes needed to finish approved work. Do not repeatedly ask for ordinary reversible implementation approval. This does not bypass platform-required confirmations, authorize paid actions, impersonation, external messaging/publication, or unsafe destructive financial-history operations.
9 +## Protocol / authority
10 +Verify live GitHub+Supabase before acting; record material requests before implementation; implement/test/fix/retest/commit/verify in vertical slices; update this file with every durable implementation commit; archive exact production SQL; never call unrun work verified. Owner granted standing authority on 2026-09-30 for in-scope GitHub/Supabase engineering, excluding platform-required confirmations, paid/public/external actions and unsafe destructive financial-history changes.
11
12 ## Current change ledger
13 | Date | Request / decision | Status | Evidence / next action |
14 |---|---|---|---|
24 -| 2026-09-30 | Expand Finora into a modular organization-wide ERP: professional office automation, scanned correspondence/attachments, secretariat numbering, configurable requests/forms, module managers and granular read/write/approve/secretariat permissions, modular entry experience, module-by-module commercial licensing/full suite, and future transport/operations modules. Research mature Iranian patterns including Barid/ParGar, Chargoon/Didgah and Faragostar. | **SLICE A IMPLEMENTED / CI VERIFICATION IN PROGRESS** | Request `0b622439`; implementation `d3934690`. Architecture `docs/FINORA_MODULAR_ERP_OFFICE_AUTOMATION_V1.md`. Production migrations `20260930025546`, `20260930025647`, plus hardening `20260930030314 preserve_readonly_access_after_license_expiry`. The hardening preserves the established expired-license behavior: entitled historical data remains readable while `has_active_license()` continues to gate writes. Production introspection: all 4 existing licenses grandfathered to `full_suite`; 4/4 records policies include module guards; private office bucket and unique correspondence number index exist. Negative DB checks: non-admin module-license RPC denied; unlicensed office write denied. Transactional positive check advanced registry counter 7→8 then rolled back. Quality run `36662546643` has already passed syntax, all accounting/Phase 2–6/Golden gates and the new platform-office invariant gate; Chromium Real-DOM is still running at this state snapshot. Full multi-login organization sharing/module-manager RBAC remains Slice B and is not claimed. |
25 -| 2026-09-30 | `@GitHub @Supabase`: perform required remaining work without routine permission prompts. | COMPLETED for prior hardening checkpoint | Prior Quality `36661446705`, Security `36661446688`, Pages `36661445458` PASS. |
26 -| 2026-09-30 | Iran-first high-assurance enterprise ERP with accounting/tax/VAT/commerce/labor/social-security controls and enterprise modules. | IN PROGRESS — broader roadmap | Baseline `docs/IRAN_COMPLIANCE_MATRIX_V1.md`; do not claim statutory consolidation/full tax submission/full HR/CRM until complete lifecycle/accounting/permissions/tests exist. |
15 +| 2026-09-30 | Modular organization-wide ERP: office automation/scanned correspondence/secretariat, configurable requests, module managers/permissions, module-select entry, module-by-module/full-suite licensing, future transport/operations; research Barid/ParGar, Chargoon/Didgah, Faragostar. | **SLICE A IMPLEMENTED / FINAL CI PENDING** | Request `0b622439`; initial implementation `d3934690`; read-only expiry hardening `906d78d7`. Production migrations `20260930025546`, `20260930025647`, `20260930030314` applied+archived. Quality `36662546643` proved all static/accounting/Phase2–6/Golden/new platform invariants PASS, then exposed 3 browser-harness/integration issues: auto workspace modal intercepted the legacy DOM smoke; delayed extension bootstrap could rerun auth after a manual smoke login; new request-builder test counted the required checkbox as a text input. This checkpoint removes automatic modal interception while retaining explicit workspace launcher/switching, prevents delayed bootstrap from reinitializing auth when a user is already active, and corrects the test selector to `input.form-control`. Product module gating remains unchanged. Fresh Quality/Security/Pages required. Multi-login tenant/RBAC remains Slice B and is not claimed. |
16 +| 2026-09-30 | Iran-first high-assurance ERP expansion. | IN PROGRESS — broader roadmap | `docs/IRAN_COMPLIANCE_MATRIX_V1.md`; do not claim statutory consolidation/full tax submission/full HR/CRM until complete lifecycle/accounting/permissions/tests exist. |
17
18 ## Current production state — 2026-09-30
29 -- Code implementation head before this hardening archive commit: `d3934690eab066ee61fb65de5226777277818752`.
30 -- Supabase `hcsixhqbyuhpshfwqpjx`: `ACTIVE_HEALTHY`, PostgreSQL `17.6.1.166`.
31 -- Applied migrations: 24 through `20260930030314 preserve_readonly_access_after_license_expiry`; all current platform migrations are archived in Git after this commit.
32 -- `licenses.modules` supports explicit modules or `full_suite`; `admin_set_license_modules` validates keys and rechecks admin server-side.
33 -- Record SELECT is owner + purchased-module scoped even after license expiry; INSERT/UPDATE/DELETE and atomic sync additionally require active license.
34 -- Office collections: `officeRegistries`, `correspondence`, `correspondenceAttachments`, `correspondenceReferrals`, `correspondenceAudit`; request collections: `requestTypes`, `requests`, `requestActions`.
35 -- Private `office-attachments`: max 20 MB/object, PDF/JPEG/PNG/TIFF, owner + office-module RLS.
36 -- Secretariat registration RPC uses row lock + unique owner/registry/register-number index.
37 -- Performance advisor after migrations: clean.
38 -- Security advisor after migrations: 7 public authenticated-callable SECURITY DEFINER warnings (the prior six plus `admin_set_license_modules`) + leaked-password protection disabled. The new admin RPC was negative-tested as a non-admin and correctly returned 42501. Do not remove authenticated RPC access merely to silence lint; the client requires the RPC and it has an internal admin authorization check.
39 -
40 -## Master roadmap status
41 -Phases 1–6 remain accepted/completed: UX shell; accounting foundation; double-entry accounting; projects/contracts; inventory/costing/assets/multi-currency/import/integrations; reports/reconciliation/release. Current work is post-release hardening + Iran-first enterprise/platform expansion, not a reset.
42 -
43 -## Platform / accounting invariants
44 -- Posted journal lines are accounting truth; posted/reversed history is immutable; correction uses reversal/amendment.
45 -- Posted vouchers balance and obey fiscal locks; source event/version uniqueness prevents duplicate posting.
46 -- Tenant isolation is mandatory at the data boundary; authorization never relies on user-editable metadata.
47 -- Commercial module entitlement and member authorization are independent. Effective access is their intersection plus tenant/record scope. UI hiding is never a security boundary.
48 -- Expired/cancelled license keeps entitled historical records readable but cannot write; module removal hides/denies that module's records.
49 -- Office registration numbers are allocated server-side atomically; binary scans live in private Storage, not JSON records.
50 -- Do not expose/sell roadmap-only modules as operational.
19 +- Pre-fix repo head: `906d78d751c7673196044ff55ba5a2224d6ce7ed`; this checkpoint contains only browser/bootstrap/test integration fixes, no new DB mutation.
20 +- Supabase `hcsixhqbyuhpshfwqpjx`: `ACTIVE_HEALTHY`, PostgreSQL `17.6.1.166`, 24 migrations through `20260930030314`.
21 +- Existing 4 licenses grandfathered to `full_suite`; `admin_set_license_modules` validates explicit module keys.
22 +- 4/4 records policies include module entitlement; writes and atomic sync additionally require active license. Expired/cancelled users retain read-only access to entitled historical data.
23 +- Private `office-attachments`: max 20 MB, PDF/JPEG/PNG/TIFF, owner+office-module RLS. Secretariat numbering uses server row lock + unique index.
24 +- DB negative tests PASS: non-admin module RPC denied; unlicensed office write denied. Positive transactional registration test advanced registry counter 7→8 then rolled back.
25 +- Performance advisor after migrations: clean. Security advisor: 7 reviewed public SECURITY DEFINER RPC warnings (prior six + `admin_set_license_modules`) plus leaked-password protection disabled; new admin RPC negative-tested 42501 for non-admin.
26 +
27 +## Implemented Slice A
28 +- Architecture/research: `docs/FINORA_MODULAR_ERP_OFFICE_AUTOMATION_V1.md`.
29 +- Server-enforced commercial module entitlements; full suite or explicit module subset independent of duration/company capacity.
30 +- Module-filtered rail, command routing, explicit workspace launcher and admin license module picker. Roadmap-only CRM/transport/manufacturing/maintenance disabled for sale.
31 +- Office: secretariat registries, incoming/outgoing/internal metadata, drafts, server-atomic registration number, private scan attachments, archive metadata search, OCR-ready fields.
32 +- Requests: admin-defined request type/field schema + request submission foundation.
33 +
34 +## Invariants
35 +Posted accounting history is immutable and balanced; tenant isolation is data-boundary enforced; commercial module entitlement and member authorization are independent; UI hiding is never security; expired licenses are read-only; office numbers are server-atomic; binary scans stay in private Storage; roadmap-only modules are not presented as operational.
36
37 ## Required evidence
53 -`docs/PHASE_1_REDESIGN_VERIFICATION.md` · `docs/PHASE_2_REDESIGN_VERIFICATION.md` · `docs/PHASE_3_REDESIGN_VERIFICATION.md` · `docs/PHASE_4_REDESIGN_VERIFICATION.md` · `docs/PHASE_5_VERIFICATION.md` · `docs/PHASE_6_VERIFICATION.md` · `docs/IRAN_COMPLIANCE_MATRIX_V1.md` · `docs/FINORA_ERP_EXPANSION_ROADMAP_V4.md` · `docs/FINORA_UX_ACCOUNTING_BENCHMARK_V3.md` · `docs/FINORA_MODULAR_ERP_OFFICE_AUTOMATION_V1.md` · `docs/PRODUCTION_RUNBOOK.md` · exact SQL under `supabase/migrations/`.
38 +`docs/PHASE_1_REDESIGN_VERIFICATION.md` · `docs/PHASE_2_REDESIGN_VERIFICATION.md` · `docs/PHASE_3_REDESIGN_VERIFICATION.md` · `docs/PHASE_4_REDESIGN_VERIFICATION.md` · `docs/PHASE_5_VERIFICATION.md` · `docs/PHASE_6_VERIFICATION.md` · `docs/IRAN_COMPLIANCE_MATRIX_V1.md` · `docs/FINORA_ERP_EXPANSION_ROADMAP_V4.md` · `docs/FINORA_UX_ACCOUNTING_BENCHMARK_V3.md` · `docs/FINORA_MODULAR_ERP_OFFICE_AUTOMATION_V1.md` · `docs/PRODUCTION_RUNBOOK.md` · `supabase/migrations/`.
39
40 ## NOT VERIFIED / external boundary
56 -- Multi-login organization membership/module-manager RBAC/shared inbox/referral: NOT YET IMPLEMENTED; Slice B must migrate this securely.
57 -- OCR engine accuracy on real Persian scans: NOT VERIFIED; only OCR-ready metadata exists.
58 -- Authenticated production-user browser E2E: NOT VERIFIED; no production user credential/session supplied here.
59 -- Physical-printer behavior: NOT VERIFIED.
60 -- Live third-party webhook/ECE/email gateway delivery: NOT VERIFIED.
61 -- Supabase leaked-password-protection enablement: connector exposes no Auth password-policy mutation.
62 -- PostgreSQL 17.11 upgrade/reindex: NOT PERFORMED; connector exposes no database-upgrade action.
41 +Multi-login organization membership/module-manager RBAC/shared inbox/referral; real Persian OCR accuracy; authenticated production-user browser E2E; physical printer; third-party webhook/ECE/email gateways; Supabase leaked-password setting; PostgreSQL 17.11 platform upgrade.
42
43 ## Exact next executable work
65 -1. Verify the fresh hardening/archive head with Quality/Security/Pages; if Real-DOM finds a defect, fix/retest before progressing.
66 -2. Slice B: organization tenant + memberships + module roles/capabilities + row scopes + confidentiality clearance + immutable permission/referral audit. Only after positive/negative RLS tests may shared secretariat inboxes and module-manager roles be claimed.
67 -3. Slice C: letter templates/editor/signature/approval/referral/read receipts/SLA/reply graph/archive classification/OCR service and Persian quality benchmark/full-text search/integration adapters.
68 -4. Slice D/E: versioned workflow engine, then transport/procurement/service/CRM/manufacturing/maintenance as complete tested vertical modules.
44 +1. Run fresh Quality/Security/Pages on this browser-integration fix; no progress to Slice B until green.
45 +2. Recheck Supabase migrations/RLS/storage/advisors.
46 +3. Slice B: organization tenant + memberships + module roles/capabilities + row scopes + confidentiality + immutable permission/referral audit, with positive/negative RLS tests.
47 +4. Slice C: mature office lifecycle (templates/editor/signature/approval/referral/read receipts/SLA/reply graph/archive/OCR/full-text/integration adapters).
48 +5. Slice D/E: versioned workflow engine then transport/procurement/service/CRM/manufacturing/maintenance as complete tested vertical modules.
js/bootstrap.js
+1 -1
@@ -1,2 +1,2 @@
1 function finoraLoadScript(src){return new Promise((resolve,reject)=>{const s=document.createElement('script');s.src=src;s.onload=resolve;s.onerror=()=>reject(new Error('Failed to load '+src));document.head.appendChild(s)})}
2 -window.addEventListener('DOMContentLoaded',async()=>{try{await finoraLoadScript('js/platform-modules.js?v=20260930-platform-v1');await finoraLoadScript('js/office-automation.js?v=20260930-office-v1')}catch(e){console.error('Finora platform extension load failed',e)}initAuthSystem();});
2 +window.addEventListener('DOMContentLoaded',async()=>{try{await finoraLoadScript('js/platform-modules.js?v=20260930-platform-v2');await finoraLoadScript('js/office-automation.js?v=20260930-office-v1')}catch(e){console.error('Finora platform extension load failed',e)}if(!currentUser)initAuthSystem();});
js/platform-modules.js
+15 -55
@@ -7,80 +7,40 @@ window.FINORA_MODULE_CATALOG=MODULE_CATALOG;
7 const newColls=['officeRegistries','correspondence','correspondenceAttachments','correspondenceReferrals','correspondenceAudit','requestTypes','requests','requestActions'];
8 if(typeof COLLS!=='undefined')newColls.forEach(k=>{if(!COLLS.includes(k))COLLS.push(k)});
9 if(typeof datastore!=='undefined')newColls.forEach(k=>{if(!Array.isArray(datastore[k]))datastore[k]=[]});
10 -
11 -if(typeof buildUserFromRows==='function'){
12 - const baseBuild=buildUserFromRows;
13 - buildUserFromRows=function(profile,lic){const u=baseBuild(profile,lic);u.modules=Array.isArray(lic?.modules)&&lic.modules.length?lic.modules.slice():['full_suite'];return u};
14 -}
10 +if(typeof buildUserFromRows==='function'){const baseBuild=buildUserFromRows;buildUserFromRows=function(profile,lic){const u=baseBuild(profile,lic);u.modules=Array.isArray(lic?.modules)&&lic.modules.length?lic.modules.slice():['full_suite'];return u}}
11 function licensed(key){if(key==='core')return true;if(!currentUser)return false;const mods=Array.isArray(currentUser.modules)&&currentUser.modules.length?currentUser.modules:['full_suite'];return mods.includes('full_suite')||mods.includes(key)}
12 window.hasLicensedModule=licensed;
13 function shellEntitlement(moduleKey,task=''){
18 - if(['dashboard','settings'].includes(moduleKey))return 'core';
19 - if(moduleKey==='accounting')return 'accounting';if(moduleKey==='commerce')return 'commerce';if(moduleKey==='treasury')return 'treasury';if(moduleKey==='projects')return 'contracting';if(moduleKey==='inventory')return 'inventory';if(moduleKey==='assets')return 'assets';if(moduleKey==='office')return 'office_automation';if(moduleKey==='requests')return 'requests_workflow';if(moduleKey==='reports')return licensed('analytics')?'analytics':'accounting';
20 - if(moduleKey==='enterprise'){
21 - if(['employees','contracts','leave','payroll','benefits'].includes(task))return 'hr_payroll';
22 - if(['treasury','pettyops'].includes(task))return 'treasury';
23 - if(task==='group')return 'group_consolidation';
24 - return 'accounting';
25 - }
26 - return 'core';
14 + if(['dashboard','settings'].includes(moduleKey))return 'core';if(moduleKey==='accounting')return 'accounting';if(moduleKey==='commerce')return 'commerce';if(moduleKey==='treasury')return 'treasury';if(moduleKey==='projects')return 'contracting';if(moduleKey==='inventory')return 'inventory';if(moduleKey==='assets')return 'assets';if(moduleKey==='office')return 'office_automation';if(moduleKey==='requests')return 'requests_workflow';if(moduleKey==='reports')return licensed('analytics')?'analytics':'accounting';
15 + if(moduleKey==='enterprise'){if(['employees','contracts','leave','payroll','benefits'].includes(task))return 'hr_payroll';if(['treasury','pettyops'].includes(task))return 'treasury';if(task==='group')return 'group_consolidation';return 'accounting'}return 'core'
16 }
17 function canModule(moduleKey,task=''){if(moduleKey==='enterprise'&&!task)return ['hr_payroll','treasury','group_consolidation','accounting'].some(licensed);if(moduleKey==='reports'&&!task)return licensed('analytics')||licensed('accounting');return licensed(shellEntitlement(moduleKey,task))}
18 window.canAccessFinoraModule=canModule;
30 -
19 function registerShellModules(){
20 if(typeof FINORA_MODULES==='undefined')return;
21 if(!FINORA_MODULES.office)FINORA_MODULES.office={title:'اتوماسیون اداری',context:'دبیرخانه، مکاتبات، اسکن و بایگانی',groups:[{title:'دبیرخانه',items:[['کارتابل مکاتبات','view-office','✉','','inbox'],['ثبت نامه','view-office','+','','new'],['دفاتر و شماره‌گذاری','view-office','▤','','registries']]},{title:'بایگانی و کنترل',items:[['جست‌وجو و آرشیو','view-office','⌕','','archive'],['پیوست‌ها و اسکن','view-office','▣','','attachments']]}]};
22 if(!FINORA_MODULES.requests)FINORA_MODULES.requests={title:'درخواست‌ها',context:'فرم‌ساز و گردش درخواست‌های سازمانی',groups:[{title:'کار من',items:[['درخواست جدید','view-requests','+','','new'],['درخواست‌های من','view-requests','▤','','mine']]},{title:'راه‌اندازی',items:[['انواع درخواست و فرم‌ساز','view-requests','⚙','','types']]}]};
23 if(typeof FINORA_VIEW_HOME!=='undefined'){FINORA_VIEW_HOME['view-office']='office';FINORA_VIEW_HOME['view-requests']='requests'}
36 - if(typeof FINORA_COMMANDS!=='undefined'){
37 - [['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]||''})})));
38 - }
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)})}
41 -function applyLicensedUI(){injectRail();document.querySelectorAll('.module-tab').forEach(b=>{b.style.display=canModule(b.dataset.module||'core','')?'':'none'});const q=document.getElementById('quick-create-menu');if(q)q.querySelectorAll('[data-finora-license-gated]').forEach(x=>x.remove())}
27 +function applyLicensedUI(){injectRail();document.querySelectorAll('.module-tab').forEach(b=>{b.style.display=canModule(b.dataset.module||'core','')?'':'none'})}
28 window.applyLicensedModuleUI=applyLicensedUI;
43 -
29 registerShellModules();
45 -if(typeof canShowShellCommand==='function'){
46 - const baseCan=canShowShellCommand;
47 - canShowShellCommand=function(cmd){if(!baseCan(cmd))return false;if(cmd&&cmd.module)return canModule(cmd.module,cmd.task||'');return true};
48 -}
49 -if(typeof renderModulePanel==='function'){
50 - const basePanel=renderModulePanel;
51 - renderModulePanel=function(moduleKey,activeView,activeTask=''){if(!canModule(moduleKey,activeTask||'')){showModuleLauncher(true);return}basePanel(moduleKey,activeView,activeTask);const box=document.getElementById('module-panel-links');if(box)box.querySelectorAll('.module-link').forEach(btn=>{const task=btn.dataset.task||'',view=btn.dataset.view||'';const cmd=typeof FINORA_COMMANDS!=='undefined'?FINORA_COMMANDS.find(x=>x.module===moduleKey&&x.view===view&&x.task===task):null;if(cmd&&!canModule(moduleKey,task))btn.remove()})};
52 -}
53 -if(typeof openModule==='function'){
54 - const baseOpen=openModule;
55 - openModule=function(moduleKey,defaultView,defaultTask=''){if(!canModule(moduleKey,defaultTask||'')){alert('این ماژول در لایسنس فعلی فعال نیست.');return showModuleLauncher(true)}return baseOpen(moduleKey,defaultView,defaultTask)};
56 -}
57 -if(typeof navigateShell==='function'){
58 - const baseNav=navigateShell;
59 - navigateShell=function(moduleKey,viewId,task='',rerender=true){if(!canModule(moduleKey,task||'')){alert('دسترسی این ماژول در لایسنس فعلی فعال نیست.');return false}return baseNav(moduleKey,viewId,task,rerender)};
60 -}
61 -if(typeof refreshAllSurfaces==='function'){
62 - const baseRefresh=refreshAllSurfaces;
63 - 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};
64 -}
65 -
30 +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}}
31 +if(typeof renderModulePanel==='function'){const basePanel=renderModulePanel;renderModulePanel=function(moduleKey,activeView,activeTask=''){if(!canModule(moduleKey,activeTask||'')){showModuleLauncher(true);return}basePanel(moduleKey,activeView,activeTask);const box=document.getElementById('module-panel-links');if(box)box.querySelectorAll('.module-link').forEach(btn=>{const task=btn.dataset.task||'',view=btn.dataset.view||'',cmd=typeof FINORA_COMMANDS!=='undefined'?FINORA_COMMANDS.find(x=>x.module===moduleKey&&x.view===view&&x.task===task):null;if(cmd&&!canModule(moduleKey,task))btn.remove()})}}
32 +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)}}
33 +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)}}
34 +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]))}
36 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}
37 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')}
69 -window.showModuleLauncher=showModuleLauncher;
70 -window.closeModuleLauncher=()=>document.getElementById('finora-module-launcher')?.classList.remove('active');
71 -window.enterLicensedWorkspace=(m,v,t)=>{closeModuleLauncher();navigateShell(m,v,t||'')};
72 -
73 -function ensureLicensePicker(){const modal=document.querySelector('#modal-admin-license-edit .modal-card');if(!modal||document.getElementById('modal-license-modules'))return;const actions=modal.querySelector('div[style*="margin-top:16px"]');const box=document.createElement('div');box.id='modal-license-modules';box.className='form-group';box.innerHTML='<label>ماژول‌های فعال لایسنس</label><div id="license-module-grid" style="display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:7px;margin-top:8px"></div><small style="color:var(--text-muted)">«کامل» همه ماژول‌های فعلی و آینده را باز می‌کند. ماژول‌های آتی تا زمان عملیاتی‌شدن قابل فروش نیستند.</small>';modal.insertBefore(box,actions||null)}
74 -function renderLicensePicker(uid){ensureLicensePicker();const u=typeof adminUsersCache!=='undefined'?adminUsersCache.find(x=>x.id===uid):null,mods=Array.isArray(u?.lic?.modules)&&u.lic.modules.length?u.lic.modules:['full_suite'],grid=document.getElementById('license-module-grid');if(!grid)return;grid.innerHTML='<label style="grid-column:1/-1"><input type="checkbox" value="full_suite" '+(mods.includes('full_suite')?'checked':'')+' onchange="toggleFullSuiteModules(this)"> <strong>لایسنس کامل ERP</strong></label>'+Object.entries(MODULE_CATALOG).filter(([k,v])=>k!=='core').map(([k,v])=>'<label style="opacity:'+(v.implemented?1:.5)+'"><input class="license-module-check" type="checkbox" value="'+k+'" '+(mods.includes('full_suite')||mods.includes(k)?'checked':'')+' '+(v.implemented?'':'disabled')+'> '+v.title+(v.implemented?'':' — آتی')+'</label>').join('');toggleFullSuiteModules(grid.querySelector('input[value="full_suite"]'),true)}
38 +window.showModuleLauncher=showModuleLauncher;window.closeModuleLauncher=()=>document.getElementById('finora-module-launcher')?.classList.remove('active');window.enterLicensedWorkspace=(m,v,t)=>{closeModuleLauncher();navigateShell(m,v,t||'')};
39 +function ensureLicensePicker(){const modal=document.querySelector('#modal-admin-license-edit .modal-card');if(!modal||document.getElementById('modal-license-modules'))return;const actions=modal.querySelector('div[style*="margin-top:16px"]'),box=document.createElement('div');box.id='modal-license-modules';box.className='form-group';box.innerHTML='<label>ماژول‌های فعال لایسنس</label><div id="license-module-grid" style="display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:7px;margin-top:8px"></div><small style="color:var(--text-muted)">«کامل» همه ماژول‌های فعلی و آینده را باز می‌کند. ماژول‌های آتی تا زمان عملیاتی‌شدن قابل فروش نیستند.</small>';modal.insertBefore(box,actions||null)}
40 +function renderLicensePicker(uid){ensureLicensePicker();const u=typeof adminUsersCache!=='undefined'?adminUsersCache.find(x=>x.id===uid):null,mods=Array.isArray(u?.lic?.modules)&&u.lic.modules.length?u.lic.modules:['full_suite'],grid=document.getElementById('license-module-grid');if(!grid)return;grid.innerHTML='<label style="grid-column:1/-1"><input type="checkbox" value="full_suite" '+(mods.includes('full_suite')?'checked':'')+' onchange="toggleFullSuiteModules(this)"> <strong>لایسنس کامل ERP</strong></label>'+Object.entries(MODULE_CATALOG).filter(([k])=>k!=='core').map(([k,v])=>'<label style="opacity:'+(v.implemented?1:.5)+'"><input class="license-module-check" type="checkbox" value="'+k+'" '+(mods.includes('full_suite')||mods.includes(k)?'checked':'')+' '+(v.implemented?'':'disabled')+'> '+v.title+(v.implemented?'':' — آتی')+'</label>').join('');toggleFullSuiteModules(grid.querySelector('input[value="full_suite"]'),true)}
41 window.toggleFullSuiteModules=function(el,keep){document.querySelectorAll('.license-module-check').forEach(x=>{if(el?.checked){x.checked=true;x.disabled=true}else{x.disabled=!MODULE_CATALOG[x.value]?.implemented;if(!keep&&MODULE_CATALOG[x.value]?.implemented)x.checked=false}})};
42 if(typeof openLicenseEditModal==='function'){const baseOpenLicense=openLicenseEditModal;openLicenseEditModal=function(uid){baseOpenLicense(uid);renderLicensePicker(uid)}}
77 -if(typeof applyLicenseDurationChange==='function'){
78 - applyLicenseDurationChange=async function(){const uid=document.getElementById('modal-license-target-username').value,plan=document.getElementById('modal-license-duration-select').value,u=adminUsersCache.find(x=>x.id===uid),ready=!!(u?.lic&&Object.prototype.hasOwnProperty.call(u.lic,'max_companies')),cap=Math.max(1,Math.min(1000,Number(document.getElementById('modal-license-company-limit')?.value||1))),full=document.querySelector('#license-module-grid input[value="full_suite"]')?.checked,mods=full?['full_suite']:[...document.querySelectorAll('.license-module-check:checked:not(:disabled)')].map(x=>x.value);if(!mods.length)return alert('حداقل یک ماژول عملیاتی را انتخاب کنید.');closeLicenseEditModal();let ok=await adminRpc('admin_set_license',{target:uid,new_plan:plan,new_status:'active'},'');if(!ok)return false;if(ready){ok=await adminRpc('admin_set_company_limit',{target:uid,new_max_companies:cap},'');if(!ok)return false}ok=await adminRpc('admin_set_license_modules',{target:uid,new_modules:mods},'لایسنس، ظرفیت و ماژول‌های کاربر اعمال شد.');if(ok&&currentUser?.id===uid){currentUser=await fetchCurrentUser({id:uid});await pullAll();refreshAllSurfaces()}return ok};
79 -}
80 -if(typeof enterApp==='function'){
81 - const baseEnter=enterApp;
82 - enterApp=async function(authUser){await baseEnter(authUser);if(!currentUser)return;applyLicensedUI();setTimeout(()=>{if(!document.getElementById('modal-user-onboarding')?.classList.contains('active'))showModuleLauncher(false)},50)};
83 -}
84 -window.addEventListener('finora:onboarding-complete',()=>showModuleLauncher(false));
43 +if(typeof applyLicenseDurationChange==='function')applyLicenseDurationChange=async function(){const uid=document.getElementById('modal-license-target-username').value,plan=document.getElementById('modal-license-duration-select').value,u=adminUsersCache.find(x=>x.id===uid),ready=!!(u?.lic&&Object.prototype.hasOwnProperty.call(u.lic,'max_companies')),cap=Math.max(1,Math.min(1000,Number(document.getElementById('modal-license-company-limit')?.value||1))),full=document.querySelector('#license-module-grid input[value="full_suite"]')?.checked,mods=full?['full_suite']:[...document.querySelectorAll('.license-module-check:checked:not(:disabled)')].map(x=>x.value);if(!mods.length)return alert('حداقل یک ماژول عملیاتی را انتخاب کنید.');closeLicenseEditModal();let ok=await adminRpc('admin_set_license',{target:uid,new_plan:plan,new_status:'active'},'');if(!ok)return false;if(ready){ok=await adminRpc('admin_set_company_limit',{target:uid,new_max_companies:cap},'');if(!ok)return false}ok=await adminRpc('admin_set_license_modules',{target:uid,new_modules:mods},'لایسنس، ظرفیت و ماژول‌های کاربر اعمال شد.');if(ok&&currentUser?.id===uid){currentUser=await fetchCurrentUser({id:uid});await pullAll();refreshAllSurfaces()}return ok};
44 +if(typeof enterApp==='function'){const baseEnter=enterApp;enterApp=async function(authUser){await baseEnter(authUser);if(!currentUser)return;applyLicensedUI()}}
45 applyLicensedUI();
46 })();
\ No newline at end of file
scripts/platform-office.spec.js
+7 -24
@@ -4,29 +4,12 @@ test('modular launcher, office and request builder render from licensed modules'
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');
7 - await page.evaluate(()=>{
8 - currentUser={id:'platform-smoke',email:'platform@example.test',role:'admin',modules:['office_automation','requests_workflow'],subscription:{type:'lifetime',status:'active',endDate:'2099-01-01'}};
9 - ['officeRegistries','correspondence','correspondenceAttachments','correspondenceReferrals','correspondenceAudit','requestTypes','requests','requestActions'].forEach(k=>datastore[k]=[]);
10 - applyLicensedModuleUI();
11 - });
12 - await expect(page.locator('[data-module="office"]')).toBeVisible();
13 - await expect(page.locator('[data-module="requests"]')).toBeVisible();
14 - await expect(page.locator('[data-module="accounting"]')).toBeHidden();
15 - await expect(page.locator('[data-module="settings"]')).toBeVisible();
16 - expect(await page.evaluate(()=>hasLicensedModule('office_automation'))).toBe(true);
17 - expect(await page.evaluate(()=>hasLicensedModule('accounting'))).toBe(false);
18 - await page.evaluate(()=>{switchView('view-office');officeRender('registries')});
19 - await expect(page.locator('#view-office')).toContainText('دفاتر دبیرخانه و شماره‌گذاری');
20 - await expect(page.locator('#view-office')).toContainText('اتمیک');
21 - await page.evaluate(()=>{switchView('view-office');officeRender('new')});
22 - await expect(page.locator('#office-files')).toHaveAttribute('accept',/application\/pdf/);
23 - await expect(page.locator('#view-office')).toContainText('OCR-ready');
24 - await page.evaluate(()=>{switchView('view-requests');requestsRender('types');addRequestField()});
25 - await expect(page.locator('#request-field-builder input')).toHaveCount(1);
26 - await expect(page.locator('#view-requests')).toContainText('فرم‌ساز');
27 - await page.evaluate(()=>{adminUsersCache=[{id:'platform-smoke',email:'platform@example.test',role:'admin',lic:{plan:'lifetime',status:'active',starts_at:'2026-01-01',ends_at:'2099-01-01',max_companies:1,modules:['office_automation','requests_workflow']}}];openLicenseEditModal('platform-smoke')});
28 - await expect(page.locator('#modal-license-modules')).toContainText('لایسنس کامل ERP');
29 - await expect(page.locator('#license-module-grid input[value="transport"]')).toBeDisabled();
30 - await expect(page.locator('#license-module-grid input[value="office_automation"]')).toBeChecked();
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();
9 + expect(await page.evaluate(()=>hasLicensedModule('office_automation'))).toBe(true);expect(await page.evaluate(()=>hasLicensedModule('accounting'))).toBe(false);
10 + await page.evaluate(()=>{switchView('view-office');officeRender('registries')});await expect(page.locator('#view-office')).toContainText('دفاتر دبیرخانه و شماره‌گذاری');await expect(page.locator('#view-office')).toContainText('اتمیک');
11 + 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');
12 + await page.evaluate(()=>{switchView('view-requests');requestsRender('types');addRequestField()});await expect(page.locator('#request-field-builder input.form-control')).toHaveCount(1);await expect(page.locator('#view-requests')).toContainText('فرم‌ساز');
13 + await page.evaluate(()=>{adminUsersCache=[{id:'platform-smoke',email:'platform@example.test',role:'admin',lic:{plan:'lifetime',status:'active',starts_at:'2026-01-01',ends_at:'2099-01-01',max_companies:1,modules:['office_automation','requests_workflow']}}];openLicenseEditModal('platform-smoke')});await expect(page.locator('#modal-license-modules')).toContainText('لایسنس کامل ERP');await expect(page.locator('#license-module-grid input[value="transport"]')).toBeDisabled();await expect(page.locator('#license-module-grid input[value="office_automation"]')).toBeChecked();
14 expect(errs.filter(x=>!x.includes('ResizeObserver'))).toEqual([]);
15 });