سامانه صدور فاکتور و حسابداری
Mirrored from https://github.com/davoodmehraban89/Factor-easy.git
Synced Dec 4, 15:30 UTC
fix/finora-v2-b03-r2-qa-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
| 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 query=sb.from('organization_members').select('id,organization_id,status').eq('user_id',uid).eq('status','active'); |
| 88 | const {data,error}=options?.signal?await finoraOrganizationRead(query,options.signal):await query; |
| 89 | if(!finoraSyncContextMatches(context))return false; |
| 90 | if(error){if(sensitive)return false;throw error} |
| 91 | const active=data||[]; |
| 92 | if(active.some(m=>m.organization_id===orgId))return true; |
| 93 | clearFinoraTenantMemory(uid);currentUser=null;showFinoraMembershipLock(active.length>0); |
| 94 | if(!active.length){try{await sb.auth.signOut()}catch(e){console.error('revoked-session signout failed',e)}} |
| 95 | return false; |
| 96 | }finally{finoraMembershipRevalidationBusy=false} |
| 97 | }; |
| 98 | window.requireFreshFinoraMembership=async function(){return window.revalidateFinoraMembership({sensitive:true})}; |
| 99 | setInterval(()=>{if(currentUser)window.revalidateFinoraMembership({sensitive:false}).catch(e=>console.error('membership revalidation failed',e))},30000); |
| 100 | document.addEventListener('visibilitychange',()=>{if(document.visibilityState==='visible'&¤tUser)window.revalidateFinoraMembership({sensitive:false}).catch(e=>console.error('membership revalidation failed',e))}); |
| 101 | window.hasFinoraCapability=function(moduleKey,capability='read'){ |
| 102 | if(!currentUser)return false; |
| 103 | if(moduleKey==='core'&&capability==='read')return true; |
| 104 | const mods=Array.isArray(currentUser.commercialModules)&¤tUser.commercialModules.length?currentUser.commercialModules:['full_suite']; |
| 105 | if(moduleKey!=='core'&&!(mods.includes('full_suite')||mods.includes(moduleKey)))return false; |
| 106 | if(currentUser.isOrganizationOwner)return true; |
| 107 | return (currentUser.modulePermissions||[]).some(p=>(p.module_key===moduleKey||p.module_key==='full_suite')&&Array.isArray(p.capabilities)&&p.capabilities.includes(capability)); |
| 108 | }; |
| 109 | const legacyPullAll=pullAll; |
| 110 | async function finoraReadOrganizationSnapshot(orgId,uid,signal,strict=false){ |
| 111 | const fresh={};COLLS.forEach(k=>fresh[k]=[]); |
| 112 | const snap=new Map(),snapVersions=new Map(),page=1000;let from=0; |
| 113 | for(;;){ |
| 114 | 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); |
| 115 | const {data,error}=await finoraOrganizationRead(request,signal); |
| 116 | if(error)throw error; |
| 117 | if(strict&&(!Array.isArray(data)||data.some(r=>!r||r.organization_id!==orgId||typeof r.id!=='string'||!r.data||typeof r.data!=='object'||Array.isArray(r.data))))throw finoraSyncIssue('FINORA_REVIEW_INVALID_SNAPSHOT'); |
| 118 | (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;if(strict&&snap.has(key))throw finoraSyncIssue('FINORA_REVIEW_DUPLICATE_ROW');snap.set(key,JSON.stringify(stripOwner(obj)));snapVersions.set(key,obj._serverVersion);obj.ownerUserId=uid;fresh[r.collection].push(obj)}); |
| 119 | if(!data||data.length<page)break;from+=page; |
| 120 | } |
| 121 | if(signal?.aborted)throw new Error('FINORA_LOGIN_READ_TIMEOUT'); |
| 122 | return {fresh,snap,snapVersions}; |
| 123 | } |
| 124 | function finoraPublishOrganizationSnapshot(snapshot,context){ |
| 125 | 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)); |
| 126 | finoraReadPublished(context); |
| 127 | } |
| 128 | pullAll=async function(options={}){ |
| 129 | const signal=options?.signal; |
| 130 | if(!currentUser?.organizationId)return legacyPullAll(options); |
| 131 | const capture=finoraCaptureRead(),uid=capture.context.uid,orgId=capture.context.org; |
| 132 | const snapshot=await finoraReadOrganizationSnapshot(orgId,uid,signal); |
| 133 | if(signal?.aborted)throw new Error('FINORA_LOGIN_READ_TIMEOUT'); |
| 134 | if(currentUser?.id!==uid||currentUser.organizationId!==orgId)throw new Error('FINORA_ORGANIZATION_CONTEXT_CHANGED'); |
| 135 | finoraAssertRead(capture); |
| 136 | finoraPublishOrganizationSnapshot(snapshot,capture.context); |
| 137 | }; |
| 138 | // Deliberate discard is not a retry or a financial transaction receipt. |
| 139 | // Read and validate first; no local replacement without explicit consent. |
| 140 | let finoraConflictReviewBusy=false; |
| 141 | window.finoraReviewSyncConflict=async function(){ |
| 142 | if(finoraConflictReviewBusy||syncRunning||!finoraSyncIsPaused()||!currentUser?.organizationId)return false; |
| 143 | const context=finoraSyncContext(),fingerprint=finoraSyncStateFingerprint(),serial=finoraSnapshotSerial,readSerial=finoraReadSerial; |
| 144 | const controller=new AbortController(),timer=setTimeout(()=>controller.abort(),20000); |
| 145 | const button=document.getElementById('sync-conflict-review'); |
| 146 | const unchanged=()=>!controller.signal.aborted&&finoraSyncContextMatches(context)&&finoraSyncIsPaused()&&!syncRunning&&serial===finoraSnapshotSerial&&readSerial===finoraReadSerial&&fingerprint===finoraSyncStateFingerprint(); |
| 147 | const check=()=>{if(!unchanged())throw finoraSyncIssue('FINORA_REVIEW_CONTEXT_CHANGED');}; |
| 148 | async function verify(){ |
| 149 | check(); |
| 150 | const {data,error}=await finoraAbortableRead(sb.auth.getUser(),controller.signal); |
| 151 | check(); |
| 152 | if(error||data?.user?.id!==context.uid)throw finoraSyncIssue('FINORA_REVIEW_IDENTITY_CHANGED'); |
| 153 | const active=await window.revalidateFinoraMembership({sensitive:true,signal:controller.signal}); |
| 154 | check(); |
| 155 | if(!active)throw finoraSyncIssue('FINORA_REVIEW_ACCESS_UNVERIFIED'); |
| 156 | } |
| 157 | finoraConflictReviewBusy=true; |
| 158 | if(button)button.disabled=true; |
| 159 | try{ |
| 160 | await verify(); |
| 161 | const snapshot=await finoraReadOrganizationSnapshot(context.org,context.uid,controller.signal,true); |
| 162 | check(); |
| 163 | const {up,del}=computeDiff(); |
| 164 | if(!confirm('بازخوانی سرور آماده است. با تأیید، تمام تغییرات محلی ذخیرهنشده ('+up.length+' ثبت یا ویرایش و '+del.length+' حذف) کنار گذاشته میشوند؛ ورودیهای ذخیرهنشده فرمها نیز ممکن است از بین بروند. عملیات قبلی ممکن است در سرور ثبت شده باشد؛ پیش از ثبت دوباره، سوابق را بررسی کنید. از تغییرات محلی صرفنظر و نسخه سرور را بارگذاری میکنید؟'))return false; |
| 165 | await verify(); |
| 166 | check(); |
| 167 | clearTimeout(syncTimer);syncTimer=null;syncAgain=false; |
| 168 | finoraInvalidateSyncContext(); |
| 169 | finoraPublishOrganizationSnapshot(snapshot,finoraSyncContext()); |
| 170 | setSyncBadge('serverLoaded'); |
| 171 | try{refreshAllSurfaces();}catch(error){console.error('conflict review surface refresh failed',error);alert('نسخه سرور بارگذاری شد؛ بازخوانی نما کامل نشد.');} |
| 172 | return true; |
| 173 | }catch(error){ |
| 174 | if(finoraSyncContextMatches(context)){console.error('conflict review failed',error);alert('بازخوانی انجام نشد؛ تغییرات محلی محفوظ است.');setSyncBadge('conflict');} |
| 175 | return false; |
| 176 | }finally{ |
| 177 | clearTimeout(timer);finoraConflictReviewBusy=false; |
| 178 | if(button)button.disabled=false; |
| 179 | finoraShowConflictReview(finoraSyncIsPaused()&&!!currentUser?.organizationId); |
| 180 | } |
| 181 | }; |
| 182 | let finoraOrganizationSwitchBusy=false; |
| 183 | // Keep the version-aware, atomic runSync implementation from js/sync.js. |
| 184 | // The former organization override called legacy finora_sync_records without expected_version, |
| 185 | // bypassing optimistic concurrency and allowing stale writes. |
| 186 | window.switchFinoraOrganization=async function(orgId,selector){ |
| 187 | const resetSelection=()=>{if(selector)selector.value=currentUser?.organizationId||'';}; |
| 188 | if(!currentUser?.organizations?.some(x=>x.organization.id===orgId)||finoraOrganizationSwitchBusy){resetSelection();return false;} |
| 189 | if(currentUser.organizationId===orgId){resetSelection();return true;} |
| 190 | const context=finoraSyncContext(); |
| 191 | const isClean=()=>finoraSyncContextMatches(context)&&finoraHydratedTenant===finoraTenantKey(context)&&!syncRunning&&!syncPending&&!finoraSyncIsPaused()&&!finoraSyncHasChanges(); |
| 192 | const blocked=()=>{alert('تغییر سازمان انجام نشد؛ ابتدا وضعیت ذخیرهٔ تغییرات سازمان فعلی را مشخص کنید.');return false;}; |
| 193 | if(!isClean()){resetSelection();return blocked();} |
| 194 | const fingerprint=finoraSyncStateFingerprint(); |
| 195 | finoraOrganizationSwitchBusy=true; |
| 196 | if(selector)selector.disabled=true; |
| 197 | try{ |
| 198 | const {data,error}=await sb.auth.getUser(); |
| 199 | if(!isClean()||fingerprint!==finoraSyncStateFingerprint())return blocked(); |
| 200 | if(error||data?.user?.id!==context.uid)return false; |
| 201 | // Stage both identity and snapshot without publishing a new tenant or |
| 202 | // overwriting the previous tenant's local state while any read is pending. |
| 203 | const target=await fetchCurrentUser(data.user,{organizationId:orgId}); |
| 204 | if(!isClean()||fingerprint!==finoraSyncStateFingerprint())return blocked(); |
| 205 | if(target?.id!==context.uid||target.organizationId!==orgId)return false; |
| 206 | const snapshot=await finoraReadOrganizationSnapshot(orgId,context.uid); |
| 207 | if(!isClean()||fingerprint!==finoraSyncStateFingerprint())return blocked(); |
| 208 | localStorage.setItem('finora_active_org_'+context.uid,orgId); |
| 209 | clearTimeout(syncTimer);syncTimer=null;syncAgain=false; |
| 210 | finoraInvalidateSyncContext(); |
| 211 | currentUser=target; |
| 212 | finoraPublishOrganizationSnapshot(snapshot,finoraSyncContext()); |
| 213 | // The transition itself has committed locally. A rendering failure must |
| 214 | // not claim the old tenant is still active or undo the verified snapshot. |
| 215 | try{ |
| 216 | if(typeof jeRpcRefreshEffectiveStatuses==='function')await jeRpcRefreshEffectiveStatuses(); |
| 217 | refreshAllSurfaces();if(typeof showModuleLauncher==='function')showModuleLauncher(true); |
| 218 | }catch(e){console.error('organization surface refresh failed',e);alert('سازمان تغییر کرد، اما بازخوانی نما کامل نشد.');} |
| 219 | return true; |
| 220 | }catch(e){ |
| 221 | console.error('organization switch failed',e);alert('تغییر سازمان انجام نشد؛ اطلاعات سازمان فعلی محفوظ است.');return false; |
| 222 | }finally{ |
| 223 | finoraOrganizationSwitchBusy=false; |
| 224 | if(selector)selector.disabled=false; |
| 225 | resetSelection(); |
| 226 | } |
| 227 | }; |
| 228 | window.finoraOrganizationSwitcherHtml=function(){ |
| 229 | const xs=currentUser?.organizations||[];if(xs.length<2)return ''; |
| 230 | 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>'; |
| 231 | }; |
| 232 | window.finoraCanConfigureModule=function(moduleKey){return !!currentUser&&(currentUser.isOrganizationOwner||hasFinoraCapability(moduleKey,'configure'))}; |
| 233 | window.finoraCanManageOrganization=function(){return !!currentUser&&(currentUser.isOrganizationOwner||hasFinoraCapability('core','configure'))}; |
| 234 | async function orgManagerData(){ |
| 235 | 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; |
| 236 | const ids=(members||[]).map(x=>x.user_id),profiles=ids.length?(await sb.from('profiles').select('id,full_name,email').in('id',ids)).data||[]:[]; |
| 237 | return (members||[]).map(m=>Object.assign({},m,{profile:profiles.find(p=>p.id===m.user_id)})); |
| 238 | } |
| 239 | async function roleManagerData(){ |
| 240 | const [{data:roles,error:re},{data:perms,error:pe},{data:assignments,error:ae}]=await Promise.all([ |
| 241 | 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'), |
| 242 | sb.from('organization_role_permissions').select('id,role_id,module_key,capabilities,scope_type,scope_id,confidentiality_level').eq('organization_id',currentUser.organizationId), |
| 243 | sb.from('organization_member_roles').select('id,member_id,role_id,active').eq('organization_id',currentUser.organizationId).eq('active',true) |
| 244 | ]); |
| 245 | if(re)throw re;if(pe)throw pe;if(ae)throw ae; |
| 246 | return {roles:roles||[],permissions:perms||[],assignments:assignments||[]}; |
| 247 | } |
| 248 | function roleConfigurableModules(){ |
| 249 | const catalog=window.FINORA_MODULE_CATALOG||{},commercial=currentUser?.commercialModules||['full_suite']; |
| 250 | const allowed=k=>k==='core'||commercial.includes('full_suite')||commercial.includes(k); |
| 251 | return [['core','هسته و مدیریت سازمان'],...Object.entries(catalog).filter(([k,v])=>k!=='core'&&v.implemented&&allowed(k)).map(([k,v])=>[k,v.title])]; |
| 252 | } |
| 253 | function configurableModules(){ |
| 254 | if(currentUser?.isOrganizationOwner)return Object.entries(window.FINORA_MODULE_CATALOG||{}).filter(([k,v])=>k!=='core'&&v.implemented).map(([k,v])=>[k,v.title]); |
| 255 | 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]); |
| 256 | } |
| 257 | window.finoraCanOpenOrganizationAccess=function(){return !!currentUser?.organizationId&&(finoraCanManageOrganization()||configurableModules().length>0)}; |
| 258 | let organizationPanelEpoch=0; |
| 259 | window.closeOrganizationAccessManager=function(){organizationPanelEpoch++;document.getElementById('finora-org-access-modal')?.classList.remove('active')}; |
| 260 | window.finoraOrganizationPanelCurrent=function(context){return !!context&&organizationPanelEpoch===context.epoch&¤tUser?.id===context.userId&¤tUser?.organizationId===context.orgId&&finoraCanManageOrganization()===context.canManage&&!!window.finoraCanOpenOrganizationAccess()&&document.getElementById('finora-org-access-modal')?.classList.contains('active')}; |
| 261 | window.finoraOrganizationPanelRead=async function(read){ |
| 262 | const controller=new AbortController(),timer=setTimeout(()=>controller.abort(),20000); |
| 263 | try{return await finoraAbortableRead(read,controller.signal)}finally{clearTimeout(timer)} |
| 264 | }; |
| 265 | window.showOrganizationAccessManager=async function(){ |
| 266 | const canManage=finoraCanManageOrganization(); |
| 267 | if(!window.finoraCanOpenOrganizationAccess()){alert('دسترسی مدیریت اعضا یا مجوزهای ماژول را ندارید.');return false;} |
| 268 | 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)} |
| 269 | const context={epoch:++organizationPanelEpoch,userId:currentUser.id,orgId:currentUser.organizationId,canManage}; |
| 270 | 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>'; |
| 271 | el.classList.add('active'); |
| 272 | try{ |
| 273 | const members=await window.finoraOrganizationPanelRead(orgManagerData()); |
| 274 | if(!window.finoraOrganizationPanelCurrent(context))return false; |
| 275 | const mods=configurableModules(),roleData=canManage?await window.finoraOrganizationPanelRead(roleManagerData()):{roles:[],permissions:[],assignments:[]}; |
| 276 | if(!window.finoraOrganizationPanelCurrent(context))return false; |
| 277 | const roleModules=canManage?roleConfigurableModules():[]; |
| 278 | const activeCount=members.filter(m=>m.status==='active').length,maxUsers=Math.max(1,Number(currentUser.maxUsers||1)),remaining=Math.max(0,maxUsers-activeCount); |
| 279 | const memberRows=members.map(m=>{ |
| 280 | 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>':'—'); |
| 281 | 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>':''; |
| 282 | 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>'; |
| 283 | }).join(''); |
| 284 | 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>'+ |
| 285 | (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>':'')+ |
| 286 | (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>':'')+ |
| 287 | '<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>'; |
| 288 | return context; |
| 289 | }catch(error){ |
| 290 | 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>'; |
| 291 | return false; |
| 292 | } |
| 293 | }; |
| 294 | window.organizationAddMemberFromUi=async function(){ |
| 295 | if(!finoraCanManageOrganization())return; |
| 296 | const email=String(document.getElementById('org-member-email')?.value||'').trim(),position=String(document.getElementById('org-member-position')?.value||'').trim();if(!email)return alert('ایمیل عضو را وارد کنید.'); |
| 297 | 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(); |
| 298 | }; |
| 299 | window.organizationSetMemberStatusFromUi=async function(memberId,status){ |
| 300 | if(!finoraCanManageOrganization())return; |
| 301 | const {error}=await sb.rpc('organization_set_member_status',{p_organization_id:currentUser.organizationId,p_member_id:memberId,p_status:status}); |
| 302 | if(error)return alert('تغییر وضعیت عضو انجام نشد: '+error.message); |
| 303 | const {data}=await sb.auth.getUser();if(data?.user)currentUser=await fetchCurrentUser(data.user); |
| 304 | await showOrganizationAccessManager(); |
| 305 | }; |
| 306 | window.organizationCreateRoleFromUi=async function(){ |
| 307 | if(!finoraCanManageOrganization())return; |
| 308 | const key=String(document.getElementById('org-role-key')?.value||'').trim().toLowerCase(),title=String(document.getElementById('org-role-title')?.value||'').trim(); |
| 309 | if(!/^[a-z][a-z0-9_]{1,63}$/.test(key)||!title)return alert('کلید انگلیسی معتبر و عنوان نقش الزامی است.'); |
| 310 | 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}); |
| 311 | if(error)return alert('ثبت نقش انجام نشد: '+error.message);await showOrganizationAccessManager(); |
| 312 | }; |
| 313 | window.organizationAssignRoleFromUi=async function(){ |
| 314 | if(!finoraCanManageOrganization())return; |
| 315 | const member=document.getElementById('org-role-member')?.value,role=document.getElementById('org-role-assign')?.value;if(!member||!role)return alert('عضو و نقش را انتخاب کنید.'); |
| 316 | 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}); |
| 317 | if(error)return alert('تخصیص نقش انجام نشد: '+error.message);alert('نقش تخصیص یافت.');await showOrganizationAccessManager(); |
| 318 | }; |
| 319 | window.organizationSaveRolePermissionFromUi=async function(){ |
| 320 | if(!finoraCanManageOrganization())return; |
| 321 | 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); |
| 322 | if(!role||!module||!caps.length)return alert('نقش، ماژول و حداقل یک قابلیت الزامی است.'); |
| 323 | 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}); |
| 324 | if(error)return alert('ثبت مجوز نقش انجام نشد: '+error.message);alert('مجوز نقش ثبت شد.');await showOrganizationAccessManager(); |
| 325 | }; |
| 326 | window.organizationSavePermissionFromUi=async function(){ |
| 327 | 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); |
| 328 | if(!member||!module||!caps.length)return alert('عضو، ماژول و حداقل یک قابلیت الزامی است.');if(!['own','organization'].includes(scope)&&!scopeId)return alert('شناسه دامنه را وارد کنید.'); |
| 329 | 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(); |
| 330 | }; |
| 331 | function ensureOrgAccessButton(){ |
| 332 | const card=document.getElementById('finora-org-access-settings-card'); |
| 333 | const b=document.getElementById('finora-org-access-btn');if(!card||!b)return; |
| 334 | // Resolve the current wrapper at click time (invitations and capacity extend it). |
| 335 | b.onclick=()=>{if(window.finoraCanOpenOrganizationAccess())return window.showOrganizationAccessManager();}; |
| 336 | const allowed=window.finoraCanOpenOrganizationAccess(); |
| 337 | card.hidden=!allowed;b.disabled=!allowed; |
| 338 | } |
| 339 | window.refreshFinoraOrganizationAccessButton=ensureOrgAccessButton; |
| 340 | const baseEnterAppOrg=enterApp; |
| 341 | enterApp=async function(authUser){const r=await baseEnterAppOrg(authUser);ensureOrgAccessButton();return r}; |
| 342 | // Signal only after the full organization module and its account wrapper exist. |
| 343 | window.finoraMarkOrganizationContextReady?.(); |
| 344 | })(); |