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

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

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

Synced Dec 3, 22:00 UTC

main
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 250 lines 30.4 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}={}){
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=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 clearTimeout(syncTimer);syncPending=false;syncAgain=false;syncFailCount=0;syncSnap.clear();
64 const fresh={};COLLS.forEach(k=>fresh[k]=[]);datastore=fresh;
65 try{localStorage.removeItem('finora_active_org_'+userId);localStorage.removeItem(STORAGE_KEY);}catch(e){}
66 document.querySelectorAll('.modal-backdrop.active').forEach(el=>el.classList.remove('active'));
67 }
68 function showFinoraMembershipLock(hasAlternative){
69 let el=document.getElementById('finora-membership-lock');
70 if(!el){el=document.createElement('div');el.id='finora-membership-lock';el.className='modal-backdrop active';document.body.appendChild(el)}
71 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>';
72 el.classList.add('active');
73 }
74 window.resumeFinoraAuthorizedOrganization=async function(){
75 const {data,error}=await sb.auth.getUser();if(error||!data?.user)return false;
76 try{currentUser=await fetchCurrentUser(data.user);await pullAll();document.getElementById('finora-membership-lock')?.remove();refreshAllSurfaces();if(typeof showModuleLauncher==='function')showModuleLauncher(true);return true}
77 catch(e){console.error('authorized organization rebuild failed',e);currentUser=null;return false}
78 };
79 window.revalidateFinoraMembership=async function(options){
80 const sensitive=!!options?.sensitive;
81 if(!currentUser?.id||!currentUser?.organizationId)return false;
82 if(finoraMembershipRevalidationBusy)return false;
83 finoraMembershipRevalidationBusy=true;
84 const uid=currentUser.id,orgId=currentUser.organizationId;
85 try{
86 const {data,error}=await sb.from('organization_members').select('id,organization_id,status').eq('user_id',uid).eq('status','active');
87 if(error){if(sensitive)return false;throw error}
88 const active=data||[];
89 if(active.some(m=>m.organization_id===orgId))return true;
90 clearFinoraTenantMemory(uid);currentUser=null;showFinoraMembershipLock(active.length>0);
91 if(!active.length){try{await sb.auth.signOut()}catch(e){console.error('revoked-session signout failed',e)}}
92 return false;
93 }finally{finoraMembershipRevalidationBusy=false}
94 };
95 window.requireFreshFinoraMembership=async function(){return window.revalidateFinoraMembership({sensitive:true})};
96 setInterval(()=>{if(currentUser)window.revalidateFinoraMembership({sensitive:false}).catch(e=>console.error('membership revalidation failed',e))},30000);
97 document.addEventListener('visibilitychange',()=>{if(document.visibilityState==='visible'&&currentUser)window.revalidateFinoraMembership({sensitive:false}).catch(e=>console.error('membership revalidation failed',e))});
98 window.hasFinoraCapability=function(moduleKey,capability='read'){
99 if(!currentUser)return false;
100 if(moduleKey==='core'&&capability==='read')return true;
101 const mods=Array.isArray(currentUser.commercialModules)&&currentUser.commercialModules.length?currentUser.commercialModules:['full_suite'];
102 if(moduleKey!=='core'&&!(mods.includes('full_suite')||mods.includes(moduleKey)))return false;
103 if(currentUser.isOrganizationOwner)return true;
104 return (currentUser.modulePermissions||[]).some(p=>(p.module_key===moduleKey||p.module_key==='full_suite')&&Array.isArray(p.capabilities)&&p.capabilities.includes(capability));
105 };
106 const legacyPullAll=pullAll;
107 pullAll=async function(options={}){
108 const signal=options?.signal;
109 if(!currentUser?.organizationId)return legacyPullAll(options);
110 const uid=currentUser.id,orgId=currentUser.organizationId,fresh={};COLLS.forEach(k=>fresh[k]=[]);
111 const snap=new Map(),page=1000;let from=0;
112 for(;;){
113 const request=sb.from('records').select('collection,id,data,owner_id,organization_id').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;snap.set(r.collection+'|'+r.id,JSON.stringify(stripOwner(obj)));obj.ownerUserId=uid;fresh[r.collection].push(obj)});
117 if(!data||data.length<page)break;from+=page;
118 }
119 // Never apply an aborted/stale company snapshot to the active tenant.
120 if(signal?.aborted)throw new Error('FINORA_LOGIN_READ_TIMEOUT');
121 if(currentUser?.id!==uid||currentUser.organizationId!==orgId)throw new Error('FINORA_ORGANIZATION_CONTEXT_CHANGED');
122 datastore=fresh;syncSnap.clear();snap.forEach((v,k)=>syncSnap.set(k,v));
123 };
124 runSync=async function(){
125 if(!currentUser)return;if(syncRunning){syncAgain=true;return;}syncRunning=true;
126 try{let guardLoops=0;do{syncAgain=false;const {up,del}=computeDiff();if(!up.length&&!del.length)break;setSyncBadge('saving');const deletes=del.map(k=>{const j=k.indexOf('|');return {collection:k.slice(0,j),id:k.slice(j+1)}});const {error}=await sb.rpc('finora_sync_records',{p_upserts:up.map(r=>({collection:r.coll,id:r.id,data:r.payload})),p_deletes:deletes,p_organization_id:currentUser.organizationId||null});if(error)throw error;up.forEach(r=>syncSnap.set(r.key,r.s));deletes.forEach(r=>syncSnap.delete(r.collection+'|'+r.id));syncFailCount=0;guardLoops++}while(guardLoops<5);const d=computeDiff();syncPending=!!(d.up.length||d.del.length);if(syncPending)scheduleSync(500);else setSyncBadge('saved')}catch(err){console.error('sync error',err);await handleSyncError(err)}finally{syncRunning=false}
127 };
128 window.switchFinoraOrganization=async function(orgId){
129 if(!currentUser?.organizations?.some(x=>x.organization.id===orgId))return false;
130 localStorage.setItem('finora_active_org_'+currentUser.id,orgId);
131 const {data}=await sb.auth.getUser();if(!data?.user)return false;
132 currentUser=await fetchCurrentUser(data.user);await pullAll();refreshAllSurfaces();if(typeof showModuleLauncher==='function')showModuleLauncher(true);return true;
133 };
134 window.finoraOrganizationSwitcherHtml=function(){
135 const xs=currentUser?.organizations||[];if(xs.length<2)return '';
136 return '<div class="form-group" style="margin-top:12px"><label>سازمان فعال</label><select class="form-control" onchange="switchFinoraOrganization(this.value)">'+xs.map(x=>'<option value="'+esc(x.organization.id)+'" '+(x.organization.id===currentUser.organizationId?'selected':'')+'>'+esc(x.organization.name)+'</option>').join('')+'</select></div>';
137 };
138 window.finoraCanConfigureModule=function(moduleKey){return !!currentUser&&(currentUser.isOrganizationOwner||hasFinoraCapability(moduleKey,'configure'))};
139 window.finoraCanManageOrganization=function(){return !!currentUser&&(currentUser.isOrganizationOwner||hasFinoraCapability('core','configure'))};
140 async function orgManagerData(){
141 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;
142 const ids=(members||[]).map(x=>x.user_id),profiles=ids.length?(await sb.from('profiles').select('id,full_name,email').in('id',ids)).data||[]:[];
143 return (members||[]).map(m=>Object.assign({},m,{profile:profiles.find(p=>p.id===m.user_id)}));
144 }
145 async function roleManagerData(){
146 const [{data:roles,error:re},{data:perms,error:pe},{data:assignments,error:ae}]=await Promise.all([
147 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'),
148 sb.from('organization_role_permissions').select('id,role_id,module_key,capabilities,scope_type,scope_id,confidentiality_level').eq('organization_id',currentUser.organizationId),
149 sb.from('organization_member_roles').select('id,member_id,role_id,active').eq('organization_id',currentUser.organizationId).eq('active',true)
150 ]);
151 if(re)throw re;if(pe)throw pe;if(ae)throw ae;
152 return {roles:roles||[],permissions:perms||[],assignments:assignments||[]};
153 }
154 function roleConfigurableModules(){
155 const catalog=window.FINORA_MODULE_CATALOG||{},commercial=currentUser?.commercialModules||['full_suite'];
156 const allowed=k=>k==='core'||commercial.includes('full_suite')||commercial.includes(k);
157 return [['core','هسته و مدیریت سازمان'],...Object.entries(catalog).filter(([k,v])=>k!=='core'&&v.implemented&&allowed(k)).map(([k,v])=>[k,v.title])];
158 }
159 function configurableModules(){
160 if(currentUser?.isOrganizationOwner)return Object.entries(window.FINORA_MODULE_CATALOG||{}).filter(([k,v])=>k!=='core'&&v.implemented).map(([k,v])=>[k,v.title]);
161 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]);
162 }
163 window.finoraCanOpenOrganizationAccess=function(){return !!currentUser?.organizationId&&(finoraCanManageOrganization()||configurableModules().length>0)};
164 let organizationPanelEpoch=0;
165 window.closeOrganizationAccessManager=function(){organizationPanelEpoch++;document.getElementById('finora-org-access-modal')?.classList.remove('active')};
166 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')};
167 window.finoraOrganizationPanelRead=async function(read){
168 const controller=new AbortController(),timer=setTimeout(()=>controller.abort(),20000);
169 try{return await finoraAbortableRead(read,controller.signal)}finally{clearTimeout(timer)}
170 };
171 window.showOrganizationAccessManager=async function(){
172 const canManage=finoraCanManageOrganization();
173 if(!window.finoraCanOpenOrganizationAccess()){alert('دسترسی مدیریت اعضا یا مجوزهای ماژول را ندارید.');return false;}
174 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)}
175 const context={epoch:++organizationPanelEpoch,userId:currentUser.id,orgId:currentUser.organizationId,canManage};
176 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>';
177 el.classList.add('active');
178 try{
179 const members=await window.finoraOrganizationPanelRead(orgManagerData());
180 if(!window.finoraOrganizationPanelCurrent(context))return false;
181 const mods=configurableModules(),roleData=canManage?await window.finoraOrganizationPanelRead(roleManagerData()):{roles:[],permissions:[],assignments:[]};
182 if(!window.finoraOrganizationPanelCurrent(context))return false;
183 const roleModules=canManage?roleConfigurableModules():[];
184 const activeCount=members.filter(m=>m.status==='active').length,maxUsers=Math.max(1,Number(currentUser.maxUsers||1)),remaining=Math.max(0,maxUsers-activeCount);
185 const memberRows=members.map(m=>{
186 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>':'—');
187 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>':'';
188 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>';
189 }).join('');
190 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>'+
191 (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>':'')+
192 (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>':'')+
193 '<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>';
194 return context;
195 }catch(error){
196 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>';
197 return false;
198 }
199 };
200 window.organizationAddMemberFromUi=async function(){
201 if(!finoraCanManageOrganization())return;
202 const email=String(document.getElementById('org-member-email')?.value||'').trim(),position=String(document.getElementById('org-member-position')?.value||'').trim();if(!email)return alert('ایمیل عضو را وارد کنید.');
203 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();
204 };
205 window.organizationSetMemberStatusFromUi=async function(memberId,status){
206 if(!finoraCanManageOrganization())return;
207 const {error}=await sb.rpc('organization_set_member_status',{p_organization_id:currentUser.organizationId,p_member_id:memberId,p_status:status});
208 if(error)return alert('تغییر وضعیت عضو انجام نشد: '+error.message);
209 const {data}=await sb.auth.getUser();if(data?.user)currentUser=await fetchCurrentUser(data.user);
210 await showOrganizationAccessManager();
211 };
212 window.organizationCreateRoleFromUi=async function(){
213 if(!finoraCanManageOrganization())return;
214 const key=String(document.getElementById('org-role-key')?.value||'').trim().toLowerCase(),title=String(document.getElementById('org-role-title')?.value||'').trim();
215 if(!/^[a-z][a-z0-9_]{1,63}$/.test(key)||!title)return alert('کلید انگلیسی معتبر و عنوان نقش الزامی است.');
216 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});
217 if(error)return alert('ثبت نقش انجام نشد: '+error.message);await showOrganizationAccessManager();
218 };
219 window.organizationAssignRoleFromUi=async function(){
220 if(!finoraCanManageOrganization())return;
221 const member=document.getElementById('org-role-member')?.value,role=document.getElementById('org-role-assign')?.value;if(!member||!role)return alert('عضو و نقش را انتخاب کنید.');
222 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});
223 if(error)return alert('تخصیص نقش انجام نشد: '+error.message);alert('نقش تخصیص یافت.');await showOrganizationAccessManager();
224 };
225 window.organizationSaveRolePermissionFromUi=async function(){
226 if(!finoraCanManageOrganization())return;
227 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);
228 if(!role||!module||!caps.length)return alert('نقش، ماژول و حداقل یک قابلیت الزامی است.');
229 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});
230 if(error)return alert('ثبت مجوز نقش انجام نشد: '+error.message);alert('مجوز نقش ثبت شد.');await showOrganizationAccessManager();
231 };
232 window.organizationSavePermissionFromUi=async function(){
233 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);
234 if(!member||!module||!caps.length)return alert('عضو، ماژول و حداقل یک قابلیت الزامی است.');if(!['own','organization'].includes(scope)&&!scopeId)return alert('شناسه دامنه را وارد کنید.');
235 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();
236 };
237 function ensureOrgAccessButton(){
238 const card=document.getElementById('finora-org-access-settings-card');
239 const b=document.getElementById('finora-org-access-btn');if(!card||!b)return;
240 // Resolve the current wrapper at click time (invitations and capacity extend it).
241 b.onclick=()=>{if(window.finoraCanOpenOrganizationAccess())return window.showOrganizationAccessManager();};
242 const allowed=window.finoraCanOpenOrganizationAccess();
243 card.hidden=!allowed;b.disabled=!allowed;
244 }
245 window.refreshFinoraOrganizationAccessButton=ensureOrgAccessButton;
246 const baseEnterAppOrg=enterApp;
247 enterApp=async function(authUser){const r=await baseEnterAppOrg(authUser);ensureOrgAccessButton();return r};
248 // Signal only after the full organization module and its account wrapper exist.
249 window.finoraMarkOrganizationContextReady?.();
250 })();