سامانه صدور فاکتور و حسابداری
Mirrored from https://github.com/davoodmehraban89/Factor-easy.git
Synced Dec 3, 18:15 UTC
fix/office-c7-source-ref-binding-v2
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 | async function loadOrganizationContext(user){ |
| 5 | const {data:members,error:memberError}=await sb.from('organization_members').select('id,organization_id,unit_id,position_title,status,is_owner').eq('user_id',user.id).eq('status','active'); |
| 6 | if(memberError)throw memberError; |
| 7 | const orgIds=(members||[]).map(x=>x.organization_id); |
| 8 | if(!orgIds.length)throw new Error('عضویت سازمانی برای این کاربر تعریف نشده است.'); |
| 9 | 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([ |
| 10 | sb.from('organizations').select('id,name,status').in('id',orgIds), |
| 11 | sb.from('member_module_permissions').select('id,organization_id,member_id,module_key,capabilities,scope_type,scope_id,confidentiality_level').in('organization_id',orgIds), |
| 12 | sb.from('licenses').select('*').in('organization_id',orgIds), |
| 13 | sb.from('organization_members').select('id,organization_id,status').in('organization_id',orgIds).eq('status','active'), |
| 14 | sb.from('organization_roles').select('id,organization_id,role_key,title,active,is_system').in('organization_id',orgIds).eq('active',true), |
| 15 | sb.from('organization_role_permissions').select('id,organization_id,role_id,module_key,capabilities,scope_type,scope_id,confidentiality_level').in('organization_id',orgIds), |
| 16 | sb.from('organization_member_roles').select('id,organization_id,member_id,role_id,active').in('organization_id',orgIds).eq('active',true) |
| 17 | ]); |
| 18 | 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; |
| 19 | const contexts=(members||[]).map(m=>{ |
| 20 | const assignments=(memberRoles||[]).filter(x=>x.member_id===m.id&&x.organization_id===m.organization_id); |
| 21 | const assignedRoleIds=new Set(assignments.map(x=>x.role_id)); |
| 22 | const rolePermissions=(rolePerms||[]).filter(p=>p.organization_id===m.organization_id&&assignedRoleIds.has(p.role_id)).map(p=>Object.assign({source:'role'},p)); |
| 23 | const directPermissions=(perms||[]).filter(p=>p.member_id===m.id).map(p=>Object.assign({source:'direct'},p)); |
| 24 | 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))}; |
| 25 | }).filter(x=>x.organization&&x.license); |
| 26 | const saved=localStorage.getItem('finora_active_org_'+user.id); |
| 27 | const selected=contexts.find(x=>x.organization.id===saved)||contexts.find(x=>x.membership.is_owner)||contexts[0]; |
| 28 | const lic=selected.license,sub={type:lic.plan,startDate:lic.starts_at,endDate:lic.ends_at,status:lic.status}; |
| 29 | user.organizations=contexts; |
| 30 | user.organizationId=selected.organization.id; |
| 31 | user.organizationName=selected.organization.name; |
| 32 | user.membershipId=selected.membership.id; |
| 33 | user.organizationUnitId=selected.membership.unit_id||''; |
| 34 | user.isOrganizationOwner=!!selected.membership.is_owner; |
| 35 | user.modulePermissions=selected.permissions||[]; |
| 36 | user.directModulePermissions=selected.directPermissions||[]; |
| 37 | user.roleModulePermissions=selected.rolePermissions||[]; |
| 38 | user.organizationRoles=selected.roles||[]; |
| 39 | const commercial=Array.isArray(lic.modules)&&lic.modules.length?lic.modules.slice():['full_suite']; |
| 40 | user.commercialModules=commercial; |
| 41 | if(user.isOrganizationOwner)user.modules=commercial.slice(); |
| 42 | 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)))];} |
| 43 | user.maxCompanies=Math.max(1,Number(lic.max_companies||1)); |
| 44 | user.maxUsers=Math.max(1,Number(lic.max_users||1)); |
| 45 | user.activeSeatCount=(activeMembers||[]).filter(x=>x.organization_id===selected.organization.id).length; |
| 46 | user.remainingSeats=Math.max(0,user.maxUsers-user.activeSeatCount); |
| 47 | user.subscription=sub;user.subscriptionType=sub.type;user.subscriptionStart=sub.startDate;user.subscriptionEnd=sub.endDate;user.licenseStatus=sub.status; |
| 48 | return user; |
| 49 | } |
| 50 | fetchCurrentUser=async function(authUser){return loadOrganizationContext(await baseFetchCurrentUser(authUser))}; |
| 51 | window.hasFinoraCapability=function(moduleKey,capability='read'){ |
| 52 | if(!currentUser)return false; |
| 53 | if(moduleKey==='core'&&capability==='read')return true; |
| 54 | const mods=Array.isArray(currentUser.commercialModules)&¤tUser.commercialModules.length?currentUser.commercialModules:['full_suite']; |
| 55 | if(moduleKey!=='core'&&!(mods.includes('full_suite')||mods.includes(moduleKey)))return false; |
| 56 | if(currentUser.isOrganizationOwner)return true; |
| 57 | return (currentUser.modulePermissions||[]).some(p=>(p.module_key===moduleKey||p.module_key==='full_suite')&&Array.isArray(p.capabilities)&&p.capabilities.includes(capability)); |
| 58 | }; |
| 59 | const legacyPullAll=pullAll; |
| 60 | pullAll=async function(){ |
| 61 | if(!currentUser?.organizationId)return legacyPullAll(); |
| 62 | const uid=currentUser.id,fresh={};COLLS.forEach(k=>fresh[k]=[]); |
| 63 | const snap=new Map(),page=1000;let from=0; |
| 64 | for(;;){ |
| 65 | const {data,error}=await sb.from('records').select('collection,id,data,owner_id,organization_id').eq('organization_id',currentUser.organizationId).order('collection').order('id').range(from,from+page-1); |
| 66 | if(error)throw error; |
| 67 | (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)}); |
| 68 | if(!data||data.length<page)break;from+=page; |
| 69 | } |
| 70 | datastore=fresh;syncSnap.clear();snap.forEach((v,k)=>syncSnap.set(k,v)); |
| 71 | }; |
| 72 | runSync=async function(){ |
| 73 | if(!currentUser)return;if(syncRunning){syncAgain=true;return;}syncRunning=true; |
| 74 | 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} |
| 75 | }; |
| 76 | window.switchFinoraOrganization=async function(orgId){ |
| 77 | if(!currentUser?.organizations?.some(x=>x.organization.id===orgId))return false; |
| 78 | localStorage.setItem('finora_active_org_'+currentUser.id,orgId); |
| 79 | const {data}=await sb.auth.getUser();if(!data?.user)return false; |
| 80 | currentUser=await fetchCurrentUser(data.user);await pullAll();refreshAllSurfaces();if(typeof showModuleLauncher==='function')showModuleLauncher(true);return true; |
| 81 | }; |
| 82 | window.finoraOrganizationSwitcherHtml=function(){ |
| 83 | const xs=currentUser?.organizations||[];if(xs.length<2)return ''; |
| 84 | 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>'; |
| 85 | }; |
| 86 | window.finoraCanConfigureModule=function(moduleKey){return !!currentUser&&(currentUser.isOrganizationOwner||hasFinoraCapability(moduleKey,'configure'))}; |
| 87 | window.finoraCanManageOrganization=function(){return !!currentUser&&(currentUser.isOrganizationOwner||hasFinoraCapability('core','configure'))}; |
| 88 | async function orgManagerData(){ |
| 89 | 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; |
| 90 | const ids=(members||[]).map(x=>x.user_id),profiles=ids.length?(await sb.from('profiles').select('id,full_name,email').in('id',ids)).data||[]:[]; |
| 91 | return (members||[]).map(m=>Object.assign({},m,{profile:profiles.find(p=>p.id===m.user_id)})); |
| 92 | } |
| 93 | async function roleManagerData(){ |
| 94 | const [{data:roles,error:re},{data:perms,error:pe},{data:assignments,error:ae}]=await Promise.all([ |
| 95 | 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'), |
| 96 | sb.from('organization_role_permissions').select('id,role_id,module_key,capabilities,scope_type,scope_id,confidentiality_level').eq('organization_id',currentUser.organizationId), |
| 97 | sb.from('organization_member_roles').select('id,member_id,role_id,active').eq('organization_id',currentUser.organizationId).eq('active',true) |
| 98 | ]); |
| 99 | if(re)throw re;if(pe)throw pe;if(ae)throw ae; |
| 100 | return {roles:roles||[],permissions:perms||[],assignments:assignments||[]}; |
| 101 | } |
| 102 | function roleConfigurableModules(){ |
| 103 | const catalog=window.FINORA_MODULE_CATALOG||{},commercial=currentUser?.commercialModules||['full_suite']; |
| 104 | const allowed=k=>k==='core'||commercial.includes('full_suite')||commercial.includes(k); |
| 105 | return [['core','هسته و مدیریت سازمان'],...Object.entries(catalog).filter(([k,v])=>k!=='core'&&v.implemented&&allowed(k)).map(([k,v])=>[k,v.title])]; |
| 106 | } |
| 107 | function configurableModules(){ |
| 108 | if(currentUser?.isOrganizationOwner)return Object.entries(window.FINORA_MODULE_CATALOG||{}).filter(([k,v])=>k!=='core'&&v.implemented).map(([k,v])=>[k,v.title]); |
| 109 | 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]); |
| 110 | } |
| 111 | window.showOrganizationAccessManager=async function(){ |
| 112 | const canManage=finoraCanManageOrganization(); |
| 113 | if(!canManage&&!configurableModules().length)return alert('دسترسی مدیریت اعضا یا مجوزهای ماژول را ندارید.'); |
| 114 | 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)} |
| 115 | const members=await orgManagerData(),mods=configurableModules(),roleData=canManage?await roleManagerData():{roles:[],permissions:[],assignments:[]}; |
| 116 | const roleModules=canManage?roleConfigurableModules():[]; |
| 117 | const activeCount=members.filter(m=>m.status==='active').length,maxUsers=Math.max(1,Number(currentUser.maxUsers||1)),remaining=Math.max(0,maxUsers-activeCount); |
| 118 | const memberRows=members.map(m=>'<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>'+(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>':'—'))+'</td></tr>').join(''); |
| 119 | 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="document.getElementById(\'finora-org-access-modal\').classList.remove(\'active\')">بستن</button></div>'+ |
| 120 | (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">دعوت کاربر فاقد حساب در ELI-3 اضافه میشود.</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>':'')+ |
| 121 | (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>':'')+ |
| 122 | '<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>'; |
| 123 | el.classList.add('active'); |
| 124 | }; |
| 125 | window.organizationAddMemberFromUi=async function(){ |
| 126 | if(!finoraCanManageOrganization())return; |
| 127 | const email=String(document.getElementById('org-member-email')?.value||'').trim(),position=String(document.getElementById('org-member-position')?.value||'').trim();if(!email)return alert('ایمیل عضو را وارد کنید.'); |
| 128 | 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(); |
| 129 | }; |
| 130 | window.organizationSetMemberStatusFromUi=async function(memberId,status){ |
| 131 | if(!finoraCanManageOrganization())return; |
| 132 | const {error}=await sb.rpc('organization_set_member_status',{p_organization_id:currentUser.organizationId,p_member_id:memberId,p_status:status}); |
| 133 | if(error)return alert('تغییر وضعیت عضو انجام نشد: '+error.message); |
| 134 | const {data}=await sb.auth.getUser();if(data?.user)currentUser=await fetchCurrentUser(data.user); |
| 135 | await showOrganizationAccessManager(); |
| 136 | }; |
| 137 | window.organizationCreateRoleFromUi=async function(){ |
| 138 | if(!finoraCanManageOrganization())return; |
| 139 | const key=String(document.getElementById('org-role-key')?.value||'').trim().toLowerCase(),title=String(document.getElementById('org-role-title')?.value||'').trim(); |
| 140 | if(!/^[a-z][a-z0-9_]{1,63}$/.test(key)||!title)return alert('کلید انگلیسی معتبر و عنوان نقش الزامی است.'); |
| 141 | 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}); |
| 142 | if(error)return alert('ثبت نقش انجام نشد: '+error.message);await showOrganizationAccessManager(); |
| 143 | }; |
| 144 | window.organizationAssignRoleFromUi=async function(){ |
| 145 | if(!finoraCanManageOrganization())return; |
| 146 | const member=document.getElementById('org-role-member')?.value,role=document.getElementById('org-role-assign')?.value;if(!member||!role)return alert('عضو و نقش را انتخاب کنید.'); |
| 147 | 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}); |
| 148 | if(error)return alert('تخصیص نقش انجام نشد: '+error.message);alert('نقش تخصیص یافت.');await showOrganizationAccessManager(); |
| 149 | }; |
| 150 | window.organizationSaveRolePermissionFromUi=async function(){ |
| 151 | if(!finoraCanManageOrganization())return; |
| 152 | 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); |
| 153 | if(!role||!module||!caps.length)return alert('نقش، ماژول و حداقل یک قابلیت الزامی است.'); |
| 154 | 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}); |
| 155 | if(error)return alert('ثبت مجوز نقش انجام نشد: '+error.message);alert('مجوز نقش ثبت شد.');await showOrganizationAccessManager(); |
| 156 | }; |
| 157 | window.organizationSavePermissionFromUi=async function(){ |
| 158 | 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); |
| 159 | if(!member||!module||!caps.length)return alert('عضو، ماژول و حداقل یک قابلیت الزامی است.');if(!['own','organization'].includes(scope)&&!scopeId)return alert('شناسه دامنه را وارد کنید.'); |
| 160 | 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(); |
| 161 | }; |
| 162 | function ensureOrgAccessButton(){ |
| 163 | const rail=document.getElementById('module-rail');if(!rail||document.getElementById('finora-org-access-btn'))return; |
| 164 | const b=document.createElement('button');b.id='finora-org-access-btn';b.className='module-tab';b.title='سازمان و دسترسیها';b.innerHTML='<span>♙</span><b>دسترسیها</b>';b.onclick=showOrganizationAccessManager;rail.appendChild(b); |
| 165 | b.style.display=(finoraCanManageOrganization()||configurableModules().length)?'':'none'; |
| 166 | } |
| 167 | const baseEnterAppOrg=enterApp; |
| 168 | enterApp=async function(authUser){const r=await baseEnterAppOrg(authUser);ensureOrgAccessButton();return r}; |
| 169 | })(); |