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

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

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

Synced Dec 4, 04:15 UTC

docs/finora-v2-m01-coverage-20261124
audit-remediation-wave3-4-20261002 audit-remediation-wave3-verify-20261002 audit-remediation-wave4-20261002 audit-remediation-wave4b-20261002 audit-remediation-wave5a-identity-20261002 audit-remediation-wave5b-offboarding-20261002 audit-remediation-wave5c-authorization-20261002 audit-security-intent-review-20261002 audit/finora-financial-core-20261115 audit/finora-master-prompt-phase0-20261016 audit/finora-stage3-legacy-source-readonly-20261023 audit/full-controls-20261030 audit/owner-live-state-reconcile-20261012 audit/owner-review-20261007 audit/phase1-live-permissions-readonly-20261013 audit/reconcile-live-state-20261006 audit/reconcile-state-20261002 audit/wp0-hardening-baseline-20261102 branding-login-favicon-20261002 c8-workflow-task1 c8-workflow-task2 c8-workflow-task3 chore/wave0-pages-gate-closeout claude-code-plugins-setup design/finora-c01-authoritative-source-draft-20261124 docs-wave4b-verified-20261002 docs/active-company-invoice-release-evidence-20261014 docs/agent-operating-model-20261114 docs/chart-taxpayer-release-evidence-20261004 docs/cloud-only-agent-orchestration-20261115 docs/confirm-finora-product-charter-20261115 docs/continuation-20261030 docs/d4a-verified docs/external-work-review-20261121 docs/finora-audit-continuity-20261014 docs/finora-backup-merge-evidence-20261014 docs/finora-ci-reconciliation-20261122 docs/finora-codex-master-prompt docs/finora-eight-phase-plan-20261011 docs/finora-f002-live-buyer-filter-verified-20261015 docs/finora-license-race-release-evidence-20261014 docs/finora-license-rollout-acceptance-20261015 docs/finora-phase0-repeat-and-pages-nav-verified-20261015 docs/finora-phase0-repeat-evidence-20261015 docs/finora-selectors-release-and-fixture-qa-20261015 docs/finora-stagea-pr240-ci-triage-20261123 docs/finora-test-license-live-pass-20261015 docs/finora-v2-m01-coverage-20261124 docs/handoff-charter-v2-20261124 docs/invoice-product-search-release-20261011 docs/invoice-workspace-release-20261007 docs/phase-status-20261031 docs/phase0-acceptance-release-evidence-20261012 docs/phase0-admin-provision-release-evidence-20261012 docs/phase0-core-bundle-owner-login-open-20261013 docs/phase0-duplicate-js-release-20261016 docs/phase0-f001-auth-rest-shared-timeout-20261013 docs/phase0-f001-owner-login-observed-20261013 docs/phase0-f001-second-device-fail-40s-20261013 docs/phase0-f003-release-verification-20261011 docs/phase0-f004-print-release-evidence-20261012 docs/phase0-f004-watermark-release-evidence-20261012 docs/phase0-f005-large-selector-release-20261012 docs/phase0-f005-release-evidence-20261012 docs/phase0-f006-dark-release-evidence-20261012 docs/phase0-f008-final-pr-closure-evidence-20261012 docs/phase0-f008-reconcile-stale-prs-20261012 docs/phase0-f107-production-evidence-20261012 docs/phase0-kavenegar-otp-preflight-release-20261012 docs/phase0-login-release-evidence-20261012 docs/phase0-login-rest-bootstrap-stage-release-20261012 docs/phase0-owner-app-assets-bundle-release-20261013 docs/phase0-owner-login-csp-release-20261012 docs/phase0-reconcile-postmerge-evidence-20261012 docs/phase0-site-probe-release-evidence-20261012 docs/phase0-startup-release-evidence-20261012 docs/phase3-treasury-release-evidence-20261014 docs/pilot-posted-correction-release-evidence-20261014 docs/pilot-purchase-correction-release-evidence-20261014 docs/print-persian-release-verification-20261011 docs/qa-ci-triage-218-20261122 docs/real-account-qa-20261030 docs/release-state-20261007 docs/seamless-amendment-release-20261014 docs/seamless-document-correction-release-20261014 docs/settings-login-release-20261025 docs/stripe-qa-deployment-evidence-20261011 docs/ux-f2-release-evidence-20261011 docs/ux-f2-release-verification-20261011 docs/wave0-closeout docs/wave2-closeout exec-phase1-architecture exec-phase1-implementation exec-phase1-qa exec-phase1-security-release exec-phase1-ux feat/accounting-document-draft-approval-20261011 feat/accounting-document-release-candidate-20261011 feat/active-company-strict-isolation-20261014 feat/admin-provisioning-reconciled-20261011 feat/admin-secure-user-provisioning-20261011 feat/admin-user-provisioning-merged-20261011 feat/d4a-request-work-queue feat/document-lifecycle-atf-20261118 feat/document-lifecycle-temp-permanent-atef feat/draft-first-attachment-lifecycle-216 feat/finora-offline-encrypted-backup-20261014 feat/finora-phase-a-navigation-20261023 feat/finora-stripe-sandbox-edge-gate feat/immutable-attachment-temporary-vouchers feat/iran-accounting-design-audit feat/journal-document-lifecycle-20261118 feat/journal-rpc-repository-adapter-20261117 feat/office-c7-fulltext-ocr-provenance feat/password-recovery-admin-reset-20261025 feat/pilot-expense-income-inplace-amendment-20261014 feat/pilot-journal-invoice-correction-20261014 feat/pilot-purchase-correction-20261014 feat/pilot-treasury-unallocated-correction-20261014 feat/retain-document-editor-after-save-20261014 feat/seamless-financial-document-correction-20261014 feat/slice-b-tenant-rbac feat/stripe-sandbox-invoice-probe feature/accounting-core-p0 feature/accounting-product-guidance feature/admin-identity-phone-auth feature/commercial-rnd feature/finora-phase1a-supabase-cli-20261016 feature/finora-stage2-manual-canary-20261017 feature/finora-stage3-commercial-payload-20261023 feature/finora-stage3-enforce-invoice-rpc-20261023 feature/finora-stage3-enforce-purchase-red-20261023 feature/invoice-workspace-cleanup feature/phase0-kavenegar-otp-preflight-20261012 feature/ux-commerce-settings-r2 fix-shell-scroll-live-cache-20261002 fix-shell-scrollbar-explicit-ownership-20261002 fix-shell-scrollbar-ownership-20261002 fix-shell-scrollbar-right-edge-20261002 fix/about-bug-report-20261114 fix/active-company-invoice-scope-20261014 fix/active-company-isolation-reconcile-20261014 fix/admin-central-password-reset-20261028 fix/auth-network-diagnostics fix/chart-taxpayer-reference-20261003 fix/combobox-enter-reliability fix/combobox-live-search fix/combobox-production-cache fix/combobox-release-asset-v2 fix/company-edit-action-20261028 fix/company-edit-pilot-delete-20261014 fix/company-form-action-state-20261014 fix/company-form-action-state-rebased-20261014 fix/contact-operational-balance-20261111 fix/dark-theme-contrast fix/financial-lifecycle-recovery-20261124 fix/finora-accounting-test-organization-readiness-20261015 fix/finora-b01-safe-org-switch-20261124 fix/finora-b02-sync-recovery-20261124 fix/finora-b03-conflict-review-20261124 fix/finora-org-license-bootstrap-race-20261014 fix/finora-stage3-posted-source-immutable-20261023 fix/finora-v2-b03-r2-qa-20261124 fix/finora-v2-b03-r3-readonly-20261124 fix/g01-asof-financial-position-20261128 fix/invoice-product-search-rehydrate-20261011 fix/invoice-search-cache-bust fix/issue229-linked-draft-status-20261122 fix/login-assets-retry-20261014 fix/login-inert-startup-20261110 fix/login-member-access-20261101 fix/login-resilience-20261017 fix/login-short-viewport-20261028 fix/login-startup-readiness-20261024 fix/navigation-utilities-placement-20261105 fix/office-c7-source-ref-binding fix/office-c7-source-ref-binding-v2 fix/owner-login-network-20261026 fix/password-recovery-invalid-cancel-20261026 fix/payment-amount-format-20261111 fix/phase0-admin-provision-seat-bootstrap-20261012 fix/phase0-auth-bundled-assets-for-unstable-isp-20261013 fix/phase0-auth-handler-binding-stalled-session-20261012 fix/phase0-login-context-stage-visibility-20261012 fix/phase0-login-single-local-bundle-20261013 fix/phase0-login-site-probe-clarity-20261012 fix/phase0-login-ui-ready-20261012 fix/phase0-modal-dashboard-drill-20261011 fix/phase0-pages-blocking-core-bundles-20261013 fix/phase0-print-no-draft-watermark-20261012 fix/phase0-startup-parallel-asset-load-20261012 fix/phase3-behavioral-verification fix/preserve-pending-edits-20261121 fix/print-persian-digit-consistency-20261011 fix/recovery-login-startup-20261027 fix/report-opening-balance-release-20261130 fix/settings-checkbox-persistence-20261024 fix/taxpayer-arithmetic-20261004 fix/ux-keyboard-search-f2-20261011 fix/wave2-request-input-integrity hardening/c01-source-draft-20261129 hardening/global-draft-conversion-20261113 hardening/wp1-ledger-integrity-20261102 integration/finora-execution-20261124 integration/issue229-ui-qa-20261122 integration/wp1-ledger-core-20261115 integration/wp2-manual-journal-rpc-20261116 main ops-heartbeat-v2-20261002 ops-progress-heartbeat-rule-20261002 ops/wave4-production-20261003 plan/financial-core-phase1-approval-20261016 qa/attachment-allocator-two-session-20261122 qa/draft-first-save-red-evidence-20261122 qa/finora-autopost-retry-identity-red-20261122 qa/finora-identity-rpc-security-tripwire-20261122 qa/finora-issue223-manual-kardex-browser-red-20261123 qa/finora-issue223-stock-real-jwt-20261123 qa/finora-issue238-inventory-count-browser-red-20261123 qa/finora-issue238-save-browser-red-20261122 qa/finora-login-cors-header-preflight-20261025 qa/finora-phase0-saved-session-repeat-20261015 qa/finora-phase5-posted-insert-jwt-red-20261123 qa/finora-stage3-ui-jwt-autopost-20261023 qa/finora-v2-g01-report-reconciliation-20261125 qa/free-supabase-local-wp2-20261116 qa/issue229-approval-boundary-jwt-20261122 qa/issue229-sale-save-linked-draft-red-20261122 qa/phase0-acceptance-start-20261012 qa/phase0-f005-account-project-contract-stress-20261012 qa/phase0-f005-selector-stress-20261012 qa/phase0-f006-dark-contrast-20261012 qa/post-wave4-verification-20261003 qa/posted-source-immutable-jwt-20261122 qa/pr219-wp1-disposable-dburl-proof-20261123 qa/purchase-source-jwt-20261122 qa/real-settings-acceptance-20261025 qa/recovery-mail-acceptance-20261026 qa/source-autopost-jwt-atomicity-20261122 qa/wave0-negative-gate-proof qa/wp2-auth-tenant-e2e-20261117 qa/wp2-authorized-journal-write-20261122 qa/wp2-financial-paths-reconciliation-20261122 qa/wp3-financial-tenant-isolation-20261117 remediation/wave0-liveqa-wave1 remediation/wave2-request-integrity staging/finora-stage22-free-20261022 state-scroll-verified-20261002 state-wave4b-production-20261002 state-wave5a-production-20261002 test/finora-accounting-boot-readiness-20261015 test/finora-f0-02-production-selectors-20261015 test/finora-pages-commerce-event-wiring-20261015 test/finora-pages-invoice-selectors-readonly-20261015 test/finora-stage3-jwt-source-post-20261023 test/phase0-invoice-fixture-bootstrap-20261016 test/phase0-invoice-persistence-20261011 test/phase0-pages-delayed-dispatcher-20261016 ux-scroll-ownership-20261002 work/finora-stage3-enforce-purchase-green-20261023 work/finora-stage3-enforce-sale-green-20261023 work/finora-stage3-payload-green-20261023
js 298 lines 33 KB
Raw
1 /* Finora Slice B organization context + member capabilities. Server RLS remains authoritative. */
2 (function(){
3 const baseFetchCurrentUser=fetchCurrentUser;
4 // Forward read-only timeout through the actual membership/license lookups.
5 async function finoraOrganizationRead(query,signal,stage='ORG_ACCESS'){
6 if(signal&&typeof query.abortSignal==='function')query=query.abortSignal(signal);
7 const request=finoraAbortableRead(query,signal);
8 const result=await finoraTrackLoginRead(stage,request);
9 if(signal?.aborted)throw new Error('FINORA_LOGIN_READ_TIMEOUT');
10 return result;
11 }
12 async function loadOrganizationContext(user,{signal,organizationId}={}){
13 const {data:members,error:memberError}=await finoraOrganizationRead(sb.from('organization_members').select('id,organization_id,unit_id,position_title,status,is_owner').eq('user_id',user.id).eq('status','active'),signal,'ORG_MEMBERSHIP');
14 if(memberError)throw memberError;
15 const orgIds=(members||[]).map(x=>x.organization_id);
16 if(!orgIds.length)throw new Error('FINORA_ORGANIZATION_CONTEXT_UNAVAILABLE');
17 const [{data:orgs,error:orgError},{data:perms,error:permError},{data:licenses,error:licenseError},{data:activeMembers,error:seatError},{data:roles,error:roleError},{data:rolePerms,error:rolePermError},{data:memberRoles,error:memberRoleError}]=await Promise.all([
18 sb.from('organizations').select('id,name,status').in('id',orgIds),
19 sb.from('member_module_permissions').select('id,organization_id,member_id,module_key,capabilities,scope_type,scope_id,confidentiality_level').in('organization_id',orgIds),
20 sb.from('licenses').select('*').in('organization_id',orgIds),
21 sb.from('organization_members').select('id,organization_id,status').in('organization_id',orgIds).eq('status','active'),
22 sb.from('organization_roles').select('id,organization_id,role_key,title,active,is_system').in('organization_id',orgIds).eq('active',true),
23 sb.from('organization_role_permissions').select('id,organization_id,role_id,module_key,capabilities,scope_type,scope_id,confidentiality_level').in('organization_id',orgIds),
24 sb.from('organization_member_roles').select('id,organization_id,member_id,role_id,active').in('organization_id',orgIds).eq('active',true)
25 ].map(query=>finoraOrganizationRead(query,signal)));
26 if(signal?.aborted)throw new Error('FINORA_LOGIN_READ_TIMEOUT');
27 if(orgError)throw orgError;if(permError)throw permError;if(licenseError)throw licenseError;if(seatError)throw seatError;if(roleError)throw roleError;if(rolePermError)throw rolePermError;if(memberRoleError)throw memberRoleError;
28 const contexts=(members||[]).map(m=>{
29 const assignments=(memberRoles||[]).filter(x=>x.member_id===m.id&&x.organization_id===m.organization_id);
30 const assignedRoleIds=new Set(assignments.map(x=>x.role_id));
31 const rolePermissions=(rolePerms||[]).filter(p=>p.organization_id===m.organization_id&&assignedRoleIds.has(p.role_id)).map(p=>Object.assign({source:'role'},p));
32 const directPermissions=(perms||[]).filter(p=>p.member_id===m.id).map(p=>Object.assign({source:'direct'},p));
33 return {membership:m,organization:(orgs||[]).find(o=>o.id===m.organization_id),license:(licenses||[]).find(l=>l.organization_id===m.organization_id),permissions:directPermissions.concat(rolePermissions),directPermissions,rolePermissions,roles:(roles||[]).filter(r=>assignedRoleIds.has(r.id))};
34 }).filter(x=>x.organization&&x.license);
35 const saved=localStorage.getItem('finora_active_org_'+user.id);
36 const selected=organizationId?contexts.find(x=>x.organization.id===organizationId):contexts.find(x=>x.organization.id===saved)||contexts.find(x=>x.membership.is_owner)||contexts[0];
37 if(!selected)throw new Error('FINORA_ORGANIZATION_CONTEXT_UNAVAILABLE');
38 const lic=selected.license,sub={type:lic.plan,startDate:lic.starts_at,endDate:lic.ends_at,status:lic.status};
39 user.organizations=contexts;
40 user.organizationId=selected.organization.id;
41 user.organizationName=selected.organization.name;
42 user.membershipId=selected.membership.id;
43 user.organizationUnitId=selected.membership.unit_id||'';
44 user.isOrganizationOwner=!!selected.membership.is_owner;
45 user.modulePermissions=selected.permissions||[];
46 user.directModulePermissions=selected.directPermissions||[];
47 user.roleModulePermissions=selected.rolePermissions||[];
48 user.organizationRoles=selected.roles||[];
49 const commercial=Array.isArray(lic.modules)&&lic.modules.length?lic.modules.slice():['full_suite'];
50 user.commercialModules=commercial;
51 if(user.isOrganizationOwner)user.modules=commercial.slice();
52 else{const readable=(user.modulePermissions||[]).filter(p=>Array.isArray(p.capabilities)&&p.capabilities.includes('read')).map(p=>p.module_key);user.modules=readable.includes('full_suite')?['full_suite']:[...new Set(readable.filter(k=>commercial.includes('full_suite')||commercial.includes(k)))];}
53 user.maxCompanies=Math.max(1,Number(lic.max_companies||1));
54 user.maxUsers=Math.max(1,Number(lic.max_users||1));
55 user.activeSeatCount=(activeMembers||[]).filter(x=>x.organization_id===selected.organization.id).length;
56 user.remainingSeats=Math.max(0,user.maxUsers-user.activeSeatCount);
57 user.subscription=sub;user.subscriptionType=sub.type;user.subscriptionStart=sub.startDate;user.subscriptionEnd=sub.endDate;user.licenseStatus=sub.status;
58 return user;
59 }
60 fetchCurrentUser=async function(authUser,options={}){return loadOrganizationContext(await baseFetchCurrentUser(authUser,options),options)};
61 let finoraMembershipRevalidationBusy=false;
62 function clearFinoraTenantMemory(userId){
63 finoraInvalidateSyncContext();syncVersionSnap.clear();
64 clearTimeout(syncTimer);syncPending=false;syncAgain=false;syncFailCount=0;syncSnap.clear();
65 const fresh={};COLLS.forEach(k=>fresh[k]=[]);datastore=fresh;
66 try{localStorage.removeItem('finora_active_org_'+userId);localStorage.removeItem(STORAGE_KEY);}catch(e){}
67 document.querySelectorAll('.modal-backdrop.active').forEach(el=>el.classList.remove('active'));
68 }
69 function showFinoraMembershipLock(hasAlternative){
70 let el=document.getElementById('finora-membership-lock');
71 if(!el){el=document.createElement('div');el.id='finora-membership-lock';el.className='modal-backdrop active';document.body.appendChild(el)}
72 el.innerHTML='<div class="modal-card" style="max-width:520px"><h3>دسترسی سازمانی متوقف شده است</h3><p class="af-hint">عضویت شما در سازمان فعال تعلیق یا حذف شده است. داده‌های این سازمان از حافظه این نشست پاک شد و همگام‌سازی، خروجی و عملیات حساس تا احراز مجدد متوقف هستند.</p>'+(hasAlternative?'<button class="btn btn-primary" onclick="resumeFinoraAuthorizedOrganization()">ورود به سازمان مجاز دیگر</button>':'<p class="af-hint">عضویت فعال دیگری برای این حساب در دسترس نیست؛ نشست بسته می‌شود.</p>')+'</div>';
73 el.classList.add('active');
74 }
75 window.resumeFinoraAuthorizedOrganization=async function(){
76 const {data,error}=await sb.auth.getUser();if(error||!data?.user)return false;
77 try{currentUser=await fetchCurrentUser(data.user);await pullAll();document.getElementById('finora-membership-lock')?.remove();refreshAllSurfaces();if(typeof showModuleLauncher==='function')showModuleLauncher(true);return true}
78 catch(e){console.error('authorized organization rebuild failed',e);currentUser=null;return false}
79 };
80 window.revalidateFinoraMembership=async function(options){
81 const sensitive=!!options?.sensitive;
82 if(!currentUser?.id||!currentUser?.organizationId)return false;
83 if(finoraMembershipRevalidationBusy)return false;
84 finoraMembershipRevalidationBusy=true;
85 const context=finoraSyncContext(),uid=context.uid,orgId=context.org;
86 try{
87 const {data,error}=await sb.from('organization_members').select('id,organization_id,status').eq('user_id',uid).eq('status','active');
88 if(!finoraSyncContextMatches(context))return false;
89 if(error){if(sensitive)return false;throw error}
90 const active=data||[];
91 if(active.some(m=>m.organization_id===orgId))return true;
92 clearFinoraTenantMemory(uid);currentUser=null;showFinoraMembershipLock(active.length>0);
93 if(!active.length){try{await sb.auth.signOut()}catch(e){console.error('revoked-session signout failed',e)}}
94 return false;
95 }finally{finoraMembershipRevalidationBusy=false}
96 };
97 window.requireFreshFinoraMembership=async function(){return window.revalidateFinoraMembership({sensitive:true})};
98 setInterval(()=>{if(currentUser)window.revalidateFinoraMembership({sensitive:false}).catch(e=>console.error('membership revalidation failed',e))},30000);
99 document.addEventListener('visibilitychange',()=>{if(document.visibilityState==='visible'&&currentUser)window.revalidateFinoraMembership({sensitive:false}).catch(e=>console.error('membership revalidation failed',e))});
100 window.hasFinoraCapability=function(moduleKey,capability='read'){
101 if(!currentUser)return false;
102 if(moduleKey==='core'&&capability==='read')return true;
103 const mods=Array.isArray(currentUser.commercialModules)&&currentUser.commercialModules.length?currentUser.commercialModules:['full_suite'];
104 if(moduleKey!=='core'&&!(mods.includes('full_suite')||mods.includes(moduleKey)))return false;
105 if(currentUser.isOrganizationOwner)return true;
106 return (currentUser.modulePermissions||[]).some(p=>(p.module_key===moduleKey||p.module_key==='full_suite')&&Array.isArray(p.capabilities)&&p.capabilities.includes(capability));
107 };
108 const legacyPullAll=pullAll;
109 async function finoraReadOrganizationSnapshot(orgId,uid,signal){
110 const fresh={};COLLS.forEach(k=>fresh[k]=[]);
111 const snap=new Map(),snapVersions=new Map(),page=1000;let from=0;
112 for(;;){
113 const request=sb.from('records').select('collection,id,data,owner_id,organization_id,version').eq('organization_id',orgId).order('collection').order('id').range(from,from+page-1);
114 const {data,error}=await finoraOrganizationRead(request,signal);
115 if(error)throw error;
116 (data||[]).forEach(r=>{if(!fresh[r.collection])return;const obj=(r.data&&typeof r.data==='object'&&!Array.isArray(r.data))?r.data:{};obj.id=r.id;obj._serverVersion=Number(r.version);if(!Number.isSafeInteger(obj._serverVersion)||obj._serverVersion<1)throw new Error('FINORA_SERVER_VERSION_MISSING: '+r.collection+'|'+r.id);const key=r.collection+'|'+r.id;snap.set(key,JSON.stringify(stripOwner(obj)));snapVersions.set(key,obj._serverVersion);obj.ownerUserId=uid;fresh[r.collection].push(obj)});
117 if(!data||data.length<page)break;from+=page;
118 }
119 if(signal?.aborted)throw new Error('FINORA_LOGIN_READ_TIMEOUT');
120 return {fresh,snap,snapVersions};
121 }
122 function finoraPublishOrganizationSnapshot(snapshot,context){
123 datastore=snapshot.fresh;syncSnap.clear();snapshot.snap.forEach((v,k)=>syncSnap.set(k,v));syncVersionSnap.clear();snapshot.snapVersions.forEach((v,k)=>syncVersionSnap.set(k,v));
124 finoraReadPublished(context);
125 }
126 pullAll=async function(options={}){
127 const signal=options?.signal;
128 if(!currentUser?.organizationId)return legacyPullAll(options);
129 const capture=finoraCaptureRead(),uid=capture.context.uid,orgId=capture.context.org;
130 const snapshot=await finoraReadOrganizationSnapshot(orgId,uid,signal);
131 if(signal?.aborted)throw new Error('FINORA_LOGIN_READ_TIMEOUT');
132 if(currentUser?.id!==uid||currentUser.organizationId!==orgId)throw new Error('FINORA_ORGANIZATION_CONTEXT_CHANGED');
133 finoraAssertRead(capture);
134 finoraPublishOrganizationSnapshot(snapshot,capture.context);
135 };
136 let finoraOrganizationSwitchBusy=false;
137 // Keep the version-aware, atomic runSync implementation from js/sync.js.
138 // The former organization override called legacy finora_sync_records without expected_version,
139 // bypassing optimistic concurrency and allowing stale writes.
140 window.switchFinoraOrganization=async function(orgId,selector){
141 const resetSelection=()=>{if(selector)selector.value=currentUser?.organizationId||'';};
142 if(!currentUser?.organizations?.some(x=>x.organization.id===orgId)||finoraOrganizationSwitchBusy){resetSelection();return false;}
143 if(currentUser.organizationId===orgId){resetSelection();return true;}
144 const context=finoraSyncContext();
145 const isClean=()=>finoraSyncContextMatches(context)&&finoraHydratedTenant===finoraTenantKey(context)&&!syncRunning&&!syncPending&&!finoraSyncIsPaused()&&!finoraSyncHasChanges();
146 const blocked=()=>{alert('تغییر سازمان انجام نشد؛ ابتدا وضعیت ذخیرهٔ تغییرات سازمان فعلی را مشخص کنید.');return false;};
147 if(!isClean()){resetSelection();return blocked();}
148 const fingerprint=finoraSyncStateFingerprint();
149 finoraOrganizationSwitchBusy=true;
150 if(selector)selector.disabled=true;
151 try{
152 const {data,error}=await sb.auth.getUser();
153 if(!isClean()||fingerprint!==finoraSyncStateFingerprint())return blocked();
154 if(error||data?.user?.id!==context.uid)return false;
155 // Stage both identity and snapshot without publishing a new tenant or
156 // overwriting the previous tenant's local state while any read is pending.
157 const target=await fetchCurrentUser(data.user,{organizationId:orgId});
158 if(!isClean()||fingerprint!==finoraSyncStateFingerprint())return blocked();
159 if(target?.id!==context.uid||target.organizationId!==orgId)return false;
160 const snapshot=await finoraReadOrganizationSnapshot(orgId,context.uid);
161 if(!isClean()||fingerprint!==finoraSyncStateFingerprint())return blocked();
162 localStorage.setItem('finora_active_org_'+context.uid,orgId);
163 clearTimeout(syncTimer);syncTimer=null;syncAgain=false;
164 finoraInvalidateSyncContext();
165 currentUser=target;
166 finoraPublishOrganizationSnapshot(snapshot,finoraSyncContext());
167 // The transition itself has committed locally. A rendering failure must
168 // not claim the old tenant is still active or undo the verified snapshot.
169 try{
170 if(typeof jeRpcRefreshEffectiveStatuses==='function')await jeRpcRefreshEffectiveStatuses();
171 refreshAllSurfaces();if(typeof showModuleLauncher==='function')showModuleLauncher(true);
172 }catch(e){console.error('organization surface refresh failed',e);alert('سازمان تغییر کرد، اما بازخوانی نما کامل نشد.');}
173 return true;
174 }catch(e){
175 console.error('organization switch failed',e);alert('تغییر سازمان انجام نشد؛ اطلاعات سازمان فعلی محفوظ است.');return false;
176 }finally{
177 finoraOrganizationSwitchBusy=false;
178 if(selector)selector.disabled=false;
179 resetSelection();
180 }
181 };
182 window.finoraOrganizationSwitcherHtml=function(){
183 const xs=currentUser?.organizations||[];if(xs.length<2)return '';
184 return '<div class="form-group" style="margin-top:12px"><label>سازمان فعال</label><select class="form-control" onchange="switchFinoraOrganization(this.value,this)">'+xs.map(x=>'<option value="'+esc(x.organization.id)+'" '+(x.organization.id===currentUser.organizationId?'selected':'')+'>'+esc(x.organization.name)+'</option>').join('')+'</select></div>';
185 };
186 window.finoraCanConfigureModule=function(moduleKey){return !!currentUser&&(currentUser.isOrganizationOwner||hasFinoraCapability(moduleKey,'configure'))};
187 window.finoraCanManageOrganization=function(){return !!currentUser&&(currentUser.isOrganizationOwner||hasFinoraCapability('core','configure'))};
188 async function orgManagerData(){
189 const {data:members,error}=await sb.from('organization_members').select('id,user_id,unit_id,position_title,is_owner,status').eq('organization_id',currentUser.organizationId);if(error)throw error;
190 const ids=(members||[]).map(x=>x.user_id),profiles=ids.length?(await sb.from('profiles').select('id,full_name,email').in('id',ids)).data||[]:[];
191 return (members||[]).map(m=>Object.assign({},m,{profile:profiles.find(p=>p.id===m.user_id)}));
192 }
193 async function roleManagerData(){
194 const [{data:roles,error:re},{data:perms,error:pe},{data:assignments,error:ae}]=await Promise.all([
195 sb.from('organization_roles').select('id,role_key,title,description,is_system,active').eq('organization_id',currentUser.organizationId).order('is_system',{ascending:false}).order('title'),
196 sb.from('organization_role_permissions').select('id,role_id,module_key,capabilities,scope_type,scope_id,confidentiality_level').eq('organization_id',currentUser.organizationId),
197 sb.from('organization_member_roles').select('id,member_id,role_id,active').eq('organization_id',currentUser.organizationId).eq('active',true)
198 ]);
199 if(re)throw re;if(pe)throw pe;if(ae)throw ae;
200 return {roles:roles||[],permissions:perms||[],assignments:assignments||[]};
201 }
202 function roleConfigurableModules(){
203 const catalog=window.FINORA_MODULE_CATALOG||{},commercial=currentUser?.commercialModules||['full_suite'];
204 const allowed=k=>k==='core'||commercial.includes('full_suite')||commercial.includes(k);
205 return [['core','هسته و مدیریت سازمان'],...Object.entries(catalog).filter(([k,v])=>k!=='core'&&v.implemented&&allowed(k)).map(([k,v])=>[k,v.title])];
206 }
207 function configurableModules(){
208 if(currentUser?.isOrganizationOwner)return Object.entries(window.FINORA_MODULE_CATALOG||{}).filter(([k,v])=>k!=='core'&&v.implemented).map(([k,v])=>[k,v.title]);
209 return (currentUser?.modulePermissions||[]).filter(p=>p.capabilities?.includes('configure')).map(p=>[p.module_key,(window.FINORA_MODULE_CATALOG||{})[p.module_key]?.title||p.module_key]);
210 }
211 window.finoraCanOpenOrganizationAccess=function(){return !!currentUser?.organizationId&&(finoraCanManageOrganization()||configurableModules().length>0)};
212 let organizationPanelEpoch=0;
213 window.closeOrganizationAccessManager=function(){organizationPanelEpoch++;document.getElementById('finora-org-access-modal')?.classList.remove('active')};
214 window.finoraOrganizationPanelCurrent=function(context){return !!context&&organizationPanelEpoch===context.epoch&&currentUser?.id===context.userId&&currentUser?.organizationId===context.orgId&&finoraCanManageOrganization()===context.canManage&&!!window.finoraCanOpenOrganizationAccess()&&document.getElementById('finora-org-access-modal')?.classList.contains('active')};
215 window.finoraOrganizationPanelRead=async function(read){
216 const controller=new AbortController(),timer=setTimeout(()=>controller.abort(),20000);
217 try{return await finoraAbortableRead(read,controller.signal)}finally{clearTimeout(timer)}
218 };
219 window.showOrganizationAccessManager=async function(){
220 const canManage=finoraCanManageOrganization();
221 if(!window.finoraCanOpenOrganizationAccess()){alert('دسترسی مدیریت اعضا یا مجوزهای ماژول را ندارید.');return false;}
222 let el=document.getElementById('finora-org-access-modal');if(!el){el=document.createElement('div');el.id='finora-org-access-modal';el.className='modal-backdrop';document.body.appendChild(el)}
223 const context={epoch:++organizationPanelEpoch,userId:currentUser.id,orgId:currentUser.organizationId,canManage};
224 el.innerHTML='<div class="modal-card" style="max-width:900px"><h3>مدیریت دسترسی سازمان</h3><p role="status">در حال دریافت اطلاعات سازمان…</p><button class="btn btn-secondary" onclick="closeOrganizationAccessManager()">بستن</button></div>';
225 el.classList.add('active');
226 try{
227 const members=await window.finoraOrganizationPanelRead(orgManagerData());
228 if(!window.finoraOrganizationPanelCurrent(context))return false;
229 const mods=configurableModules(),roleData=canManage?await window.finoraOrganizationPanelRead(roleManagerData()):{roles:[],permissions:[],assignments:[]};
230 if(!window.finoraOrganizationPanelCurrent(context))return false;
231 const roleModules=canManage?roleConfigurableModules():[];
232 const activeCount=members.filter(m=>m.status==='active').length,maxUsers=Math.max(1,Number(currentUser.maxUsers||1)),remaining=Math.max(0,maxUsers-activeCount);
233 const memberRows=members.map(m=>{
234 const status=m.is_owner?'مالک':(canManage?'<button class="btn btn-secondary btn-inline" onclick="organizationSetMemberStatusFromUi(\''+esc(m.id)+'\',\''+(m.status==='active'?'suspended':'active')+'\')">'+(m.status==='active'?'تعلیق':'فعال‌سازی')+'</button>':'—');
235 const recovery=canManage&&m.status==='active'?'<button class="btn btn-secondary btn-inline" data-recovery-user="'+esc(m.user_id)+'" onclick="finoraSendUserRecovery(\''+esc(m.user_id)+'\',\''+esc(currentUser.organizationId)+'\')">ارسال پیوند بازیابی</button>':'';
236 return '<tr><td>'+esc(m.profile?.full_name||m.profile?.email||m.user_id)+'</td><td>'+esc(m.position_title||'—')+'</td><td>'+esc(m.status)+'</td><td>'+status+' '+recovery+'</td></tr>';
237 }).join('');
238 el.innerHTML='<div class="modal-card" style="max-width:900px"><div style="display:flex;justify-content:space-between;gap:10px"><div><h3>مدیریت دسترسی سازمان</h3><p class="af-hint">'+esc(currentUser.organizationName||'')+' · مجوز تجاری و مجوز عضو مستقل از هم هستند.</p><p id="org-seat-summary" class="af-hint"><strong>'+toPersianDigits(activeCount)+'</strong> کاربر فعال از <strong>'+toPersianDigits(maxUsers)+'</strong> · ظرفیت باقی‌مانده '+toPersianDigits(remaining)+'</p></div><button class="btn btn-secondary btn-inline" onclick="closeOrganizationAccessManager()">بستن</button></div>'+
239 (canManage?'<div class="card" style="margin-top:14px"><h4>افزودن عضو موجود فینورا</h4><div class="form-row"><div class="form-group"><label>ایمیل</label><input id="org-member-email" class="form-control" type="email"></div><div class="form-group"><label>سمت</label><input id="org-member-position" class="form-control"></div></div><button class="btn btn-primary" onclick="organizationAddMemberFromUi()">افزودن عضو</button><p class="af-hint">برای کاربر جدید از بخش «دعوت کاربر جدید» در همین پنجره استفاده کنید.</p><div class="table-responsive" style="margin-top:12px"><table><thead><tr><th>عضو</th><th>سمت</th><th>وضعیت</th><th>عملیات</th></tr></thead><tbody>'+memberRows+'</tbody></table></div></div>':'')+
240 (canManage?'<div class="card"><h4>نقش‌های سازمانی</h4><p class="af-hint">نقش‌ها مجوزهای قابل استفاده مجدد هستند؛ مجوز مستقیم هر کاربر همچنان به‌عنوان Override مستقل باقی می‌ماند.</p><div class="form-row"><div class="form-group"><label>کلید نقش سفارشی</label><input id="org-role-key" class="form-control" placeholder="regional_accountant"></div><div class="form-group"><label>عنوان نقش</label><input id="org-role-title" class="form-control" placeholder="حسابدار ناحیه"></div></div><button class="btn btn-primary btn-inline" onclick="organizationCreateRoleFromUi()">ایجاد/به‌روزرسانی نقش</button><hr style="margin:14px 0"><div class="form-row"><div class="form-group"><label>عضو</label><select id="org-role-member" class="form-control">'+members.filter(m=>!m.is_owner&&m.status==='active').map(m=>'<option value="'+esc(m.id)+'">'+esc(m.profile?.full_name||m.profile?.email||m.position_title||m.user_id)+'</option>').join('')+'</select></div><div class="form-group"><label>نقش</label><select id="org-role-assign" class="form-control">'+roleData.roles.filter(r=>r.active).map(r=>'<option value="'+esc(r.id)+'">'+esc(r.title)+(r.is_system?' · پیش‌فرض':'')+'</option>').join('')+'</select></div></div><button class="btn btn-success btn-inline" onclick="organizationAssignRoleFromUi()">تخصیص نقش</button><hr style="margin:14px 0"><div class="form-row"><div class="form-group"><label>نقش</label><select id="org-role-perm-role" class="form-control">'+roleData.roles.filter(r=>r.active).map(r=>'<option value="'+esc(r.id)+'">'+esc(r.title)+'</option>').join('')+'</select></div><div class="form-group"><label>ماژول</label><select id="org-role-perm-module" class="form-control">'+roleModules.map(x=>'<option value="'+esc(x[0])+'">'+esc(x[1])+'</option>').join('')+'</select></div><div class="form-group"><label>سطح محرمانگی</label><select id="org-role-perm-clearance" class="form-control"><option value="0">عادی</option><option value="1">محرمانه</option><option value="2">خیلی محرمانه</option><option value="3">سری</option></select></div></div><div class="form-group"><label>قابلیت‌های نقش</label><div id="org-role-perm-caps" style="display:flex;gap:10px;flex-wrap:wrap">'+[['read','مشاهده'],['create','ایجاد'],['edit','ویرایش'],['delete','حذف'],['approve','تأیید'],['register','ثبت دبیرخانه'],['refer','ارجاع'],['archive','بایگانی'],['configure','مدیریت']].map(x=>'<label><input type="checkbox" value="'+x[0]+'" '+(x[0]==='read'?'checked':'')+'> '+x[1]+'</label>').join('')+'</div></div><button class="btn btn-success btn-inline" onclick="organizationSaveRolePermissionFromUi()">ثبت مجوز نقش</button><div class="table-responsive" style="margin-top:12px"><table><thead><tr><th>نقش</th><th>نوع</th><th>مجوزها</th><th>تخصیص‌ها</th></tr></thead><tbody>'+roleData.roles.map(r=>'<tr><td>'+esc(r.title)+'</td><td>'+(r.is_system?'پیش‌فرض':'سفارشی')+'</td><td>'+roleData.permissions.filter(p=>p.role_id===r.id).map(p=>esc(p.module_key)+' ('+esc((p.capabilities||[]).join(', '))+')').join('<br>')+'</td><td>'+toPersianDigits(roleData.assignments.filter(a=>a.role_id===r.id).length)+'</td></tr>').join('')+'</tbody></table></div></div>':'')+
241 '<div class="card"><h4>مجوز مستقیم کاربر <small style="color:var(--text-muted)">Override پیشرفته</small></h4><div class="form-row"><div class="form-group"><label>عضو</label><select id="org-perm-member" class="form-control">'+members.filter(m=>!m.is_owner&&m.status==='active').map(m=>'<option value="'+esc(m.id)+'">'+esc(m.profile?.full_name||m.profile?.email||m.position_title||m.user_id)+'</option>').join('')+'</select></div><div class="form-group"><label>ماژول</label><select id="org-perm-module" class="form-control">'+mods.map(x=>'<option value="'+esc(x[0])+'">'+esc(x[1])+'</option>').join('')+'</select></div><div class="form-group"><label>دامنه</label><select id="org-perm-scope" class="form-control" onchange="document.getElementById(\'org-perm-scope-id\').disabled=[\'own\',\'organization\'].includes(this.value)"><option value="own">فقط رکوردهای خود</option><option value="unit">واحد</option><option value="branch">شعبه</option><option value="company">شرکت</option><option value="organization">کل سازمان</option></select></div><div class="form-group"><label>شناسه دامنه</label><input id="org-perm-scope-id" class="form-control" disabled></div></div><div class="form-group"><label>قابلیت‌ها</label><div id="org-perm-caps" style="display:flex;gap:10px;flex-wrap:wrap">'+[['read','مشاهده'],['create','ایجاد'],['edit','ویرایش'],['delete','حذف'],['approve','تأیید'],['register','ثبت دبیرخانه'],['refer','ارجاع'],['archive','بایگانی'],['configure','مدیریت ماژول']].map(x=>'<label><input type="checkbox" value="'+x[0]+'" '+(x[0]==='read'?'checked':'')+'> '+x[1]+'</label>').join('')+'</div></div><div class="form-row"><div class="form-group"><label>سطح محرمانگی</label><select id="org-perm-clearance" class="form-control"><option value="0">عادی</option><option value="1">محرمانه</option><option value="2">خیلی محرمانه</option><option value="3">سری</option></select></div></div><button class="btn btn-success" onclick="organizationSavePermissionFromUi()">ثبت/به‌روزرسانی مجوز مستقیم</button></div></div>';
242 return context;
243 }catch(error){
244 if(window.finoraOrganizationPanelCurrent(context))el.innerHTML='<div class="modal-card" style="max-width:900px"><h3>مدیریت دسترسی سازمان</h3><p role="alert">دریافت اطلاعات سازمان انجام نشد. اتصال یا مجوز دسترسی را بررسی کنید و دوباره تلاش کنید. (ORG_PANEL_READ_FAILED)</p><button class="btn btn-primary" onclick="showOrganizationAccessManager()">تلاش دوباره</button> <button class="btn btn-secondary" onclick="closeOrganizationAccessManager()">بستن</button></div>';
245 return false;
246 }
247 };
248 window.organizationAddMemberFromUi=async function(){
249 if(!finoraCanManageOrganization())return;
250 const email=String(document.getElementById('org-member-email')?.value||'').trim(),position=String(document.getElementById('org-member-position')?.value||'').trim();if(!email)return alert('ایمیل عضو را وارد کنید.');
251 const {error}=await sb.rpc('organization_add_member',{p_organization_id:currentUser.organizationId,p_email:email,p_position_title:position,p_unit_id:null});if(error)return alert('افزودن عضو انجام نشد: '+error.message);await showOrganizationAccessManager();
252 };
253 window.organizationSetMemberStatusFromUi=async function(memberId,status){
254 if(!finoraCanManageOrganization())return;
255 const {error}=await sb.rpc('organization_set_member_status',{p_organization_id:currentUser.organizationId,p_member_id:memberId,p_status:status});
256 if(error)return alert('تغییر وضعیت عضو انجام نشد: '+error.message);
257 const {data}=await sb.auth.getUser();if(data?.user)currentUser=await fetchCurrentUser(data.user);
258 await showOrganizationAccessManager();
259 };
260 window.organizationCreateRoleFromUi=async function(){
261 if(!finoraCanManageOrganization())return;
262 const key=String(document.getElementById('org-role-key')?.value||'').trim().toLowerCase(),title=String(document.getElementById('org-role-title')?.value||'').trim();
263 if(!/^[a-z][a-z0-9_]{1,63}$/.test(key)||!title)return alert('کلید انگلیسی معتبر و عنوان نقش الزامی است.');
264 const {error}=await sb.rpc('organization_upsert_role',{p_organization_id:currentUser.organizationId,p_role_key:key,p_title:title,p_description:null,p_active:true});
265 if(error)return alert('ثبت نقش انجام نشد: '+error.message);await showOrganizationAccessManager();
266 };
267 window.organizationAssignRoleFromUi=async function(){
268 if(!finoraCanManageOrganization())return;
269 const member=document.getElementById('org-role-member')?.value,role=document.getElementById('org-role-assign')?.value;if(!member||!role)return alert('عضو و نقش را انتخاب کنید.');
270 const {error}=await sb.rpc('organization_assign_member_role',{p_organization_id:currentUser.organizationId,p_member_id:member,p_role_id:role,p_active:true});
271 if(error)return alert('تخصیص نقش انجام نشد: '+error.message);alert('نقش تخصیص یافت.');await showOrganizationAccessManager();
272 };
273 window.organizationSaveRolePermissionFromUi=async function(){
274 if(!finoraCanManageOrganization())return;
275 const role=document.getElementById('org-role-perm-role')?.value,module=document.getElementById('org-role-perm-module')?.value,caps=[...document.querySelectorAll('#org-role-perm-caps input:checked')].map(x=>x.value),clearance=Number(document.getElementById('org-role-perm-clearance')?.value||0);
276 if(!role||!module||!caps.length)return alert('نقش، ماژول و حداقل یک قابلیت الزامی است.');
277 const {error}=await sb.rpc('organization_set_role_permission',{p_organization_id:currentUser.organizationId,p_role_id:role,p_module_key:module,p_capabilities:caps,p_scope_type:'organization',p_scope_id:null,p_confidentiality_level:clearance});
278 if(error)return alert('ثبت مجوز نقش انجام نشد: '+error.message);alert('مجوز نقش ثبت شد.');await showOrganizationAccessManager();
279 };
280 window.organizationSavePermissionFromUi=async function(){
281 const member=document.getElementById('org-perm-member')?.value,module=document.getElementById('org-perm-module')?.value,scope=document.getElementById('org-perm-scope')?.value||'own',scopeId=['own','organization'].includes(scope)?null:String(document.getElementById('org-perm-scope-id')?.value||'').trim(),caps=[...document.querySelectorAll('#org-perm-caps input:checked')].map(x=>x.value),clearance=Number(document.getElementById('org-perm-clearance')?.value||0);
282 if(!member||!module||!caps.length)return alert('عضو، ماژول و حداقل یک قابلیت الزامی است.');if(!['own','organization'].includes(scope)&&!scopeId)return alert('شناسه دامنه را وارد کنید.');
283 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();
284 };
285 function ensureOrgAccessButton(){
286 const card=document.getElementById('finora-org-access-settings-card');
287 const b=document.getElementById('finora-org-access-btn');if(!card||!b)return;
288 // Resolve the current wrapper at click time (invitations and capacity extend it).
289 b.onclick=()=>{if(window.finoraCanOpenOrganizationAccess())return window.showOrganizationAccessManager();};
290 const allowed=window.finoraCanOpenOrganizationAccess();
291 card.hidden=!allowed;b.disabled=!allowed;
292 }
293 window.refreshFinoraOrganizationAccessButton=ensureOrgAccessButton;
294 const baseEnterAppOrg=enterApp;
295 enterApp=async function(authUser){const r=await baseEnterAppOrg(authUser);ensureOrgAccessButton();return r};
296 // Signal only after the full organization module and its account wrapper exist.
297 window.finoraMarkOrganizationContextReady?.();
298 })();