سامانه صدور فاکتور و حسابداری
claude-code-plugins-setup
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 UX hardening R2 — searchable selectors, keyboard UX, themes, Excel templates, stats and modal safety. |
| 2 | (function(){ |
| 3 | const $=id=>document.getElementById(id); |
| 4 | function activeCompanyId(){try{return getMySettings().default_company_id||getMyCompanies()[0]?.id||''}catch(_){return''}} |
| 5 | function ownedRows(k){const cid=activeCompanyId(),all=Array.isArray(datastore?.[k])?datastore[k]:[];return all.filter(r=>r?.ownerUserId===currentUser?.id&&(!r.companyId||r.companyId===cid))} |
| 6 | window.finoraFaDigits=v=>String(v??'').replace(/[0-9]/g,d=>'۰۱۲۳۴۵۶۷۸۹'[d]); |
| 7 | function searchMeta(value,text){ |
| 8 | const id=String(value||''),parts=[text||''];try{ |
| 9 | const p=typeof getMyProducts==='function'?getMyProducts().find(x=>x.id===id):null;if(p)parts.push(p.code,p.name,p.spec,p.barcode,p.internal_id,p.official_id,p.category,p.subcategory,p.unit); |
| 10 | const c=typeof getMyContacts==='function'?getMyContacts().find(x=>x.id===id):null;if(c)parts.push(c.name,c.mobile,c.national_id,c.economic_code,c.reg_number,c.postal_code); |
| 11 | const pr=typeof getMyGlobalProjects==='function'?getMyGlobalProjects().find(x=>x.id===id):null;if(pr)parts.push(pr.code,pr.name,pr.floatingCode); |
| 12 | const a=typeof getMyAccounts==='function'?getMyAccounts().find(x=>x.id===id):null;if(a)parts.push(a.code,a.title); |
| 13 | }catch(_){} |
| 14 | return parts.filter(Boolean).join(' ').toLowerCase(); |
| 15 | } |
| 16 | function searchNorm(v){return String(v||'').toLowerCase().replace(/[يى]/g,'ی').replace(/ك/g,'ک').replace(/[۰-۹]/g,d=>'۰۱۲۳۴۵۶۷۸۹'.indexOf(d)).replace(/[أإآ]/g,'ا').replace(/\s+/g,' ').trim()} |
| 17 | function comboOptions(select,q){ |
| 18 | const query=searchNorm(q),tokens=query.split(' ').filter(Boolean),productSelect=select.matches('.row-product-select,.pur-prod');return [...select.options].filter(o=>o.value).map(o=>({o,hay:searchNorm([o.dataset.search,productSelect?o.textContent:searchMeta(o.value,o.textContent)].filter(Boolean).join(' '))})).filter(x=>!tokens.length||tokens.every(t=>x.hay.includes(t))).sort((a,b)=>{if(!query)return 0;const as=a.hay.startsWith(query)?0:a.hay.includes(' '+query)?1:2,bs=b.hay.startsWith(query)?0:b.hay.includes(' '+query)?1:2;return as-bs}).map(x=>x.o); |
| 19 | } |
| 20 | function comboLabel(o){return String(o?.textContent||'').trim()} |
| 21 | function syncProductSelectOptions(select){ |
| 22 | if(!select||!select.matches('.row-product-select,.pur-prod')||typeof getMyProducts!=='function')return; |
| 23 | const products=getMyProducts();if(!Array.isArray(products))return; |
| 24 | const purchase=select.classList.contains('pur-prod'),existing=[...select.options].filter(o=>o.value),selectedId=select.value; |
| 25 | const rows=products.filter(p=>p&&p.id!=null).map(p=>({id:String(p.id),name:String(p.name||''),spec:String(p.spec||''),unit:String(p.unit||'عدد'),price:String((purchase?p.buy_price:p.sale_price)||0),search:[p.code,p.name,p.spec,p.barcode,p.internal_id,p.official_id,p.category,p.subcategory,p.unit].filter(Boolean).join(' ').toLowerCase()})); |
| 26 | const same=existing.length===rows.length&&rows.every((p,i)=>existing[i].value===p.id&&existing[i].textContent===p.name+(p.spec?' ('+p.spec+')':'')&&existing[i].dataset.price===p.price&&existing[i].dataset.unit===p.unit&&existing[i].dataset.search===p.search); |
| 27 | if(same)return; |
| 28 | const placeholder=select.querySelector('option[value=""]')?.cloneNode(true)||new Option('-- انتخاب کالا / خدمات --',''); |
| 29 | const original=existing.find(o=>o.value===selectedId),fragment=document.createDocumentFragment();fragment.appendChild(placeholder); |
| 30 | for(const p of rows){const option=new Option(p.name+(p.spec?' ('+p.spec+')':''),p.id);option.dataset.price=p.price;option.dataset.unit=p.unit;option.dataset.search=p.search;fragment.appendChild(option)} |
| 31 | // Preserve selected historical records when a master item was archived or removed. |
| 32 | if(selectedId&&!rows.some(p=>p.id===selectedId)&&original)fragment.appendChild(original.cloneNode(true)); |
| 33 | select.replaceChildren(fragment); |
| 34 | if(selectedId&&[...select.options].some(o=>o.value===selectedId))select.value=selectedId; |
| 35 | } |
| 36 | window.finoraRefreshSearchableSelect=function(select){ |
| 37 | if(!select||select.multiple||select.classList.contains('je-account'))return; |
| 38 | syncProductSelectOptions(select); |
| 39 | if(select.dataset.finoraSearchReady==='1')return; |
| 40 | const ids=['invoice-contact-id','pur-supplier','invoice-project-id','pur-costcenter','chq-contact-select','trx-contact-select','trx-project-select','company-parent-id','invoice-company-id','filter-invoice-company','af-project-parent','af-project-branch']; |
| 41 | const targeted=ids.includes(select.id)||select.classList.contains('row-product-select')||select.classList.contains('pur-prod');if(!targeted&&(select.options.length<8||select.dataset.finoraNoSearch==='1'))return; |
| 42 | select.dataset.finoraSearchReady='1';const wrap=document.createElement('div');wrap.className='finora-combobox';wrap.style.cssText='position:relative;width:100%';select.parentNode?.insertBefore(wrap,select);wrap.appendChild(select);select.style.display='none'; |
| 43 | const input=document.createElement('input');input.type='text';input.className='form-control finora-combobox-input';input.autocomplete='off';input.placeholder=select.classList.contains('row-product-select')||select.classList.contains('pur-prod')?'انتخاب یا جستجوی کالا (نام، کد، مشخصه...)':'انتخاب یا جستجو...';wrap.insertBefore(input,select); |
| 44 | const list=document.createElement('div');list.className='finora-combobox-list';list.setAttribute('role','listbox');list.style.cssText='display:none;position:absolute;z-index:1200;top:calc(100% + 3px);right:0;left:0;max-height:240px;overflow:auto;background:var(--card,#fff);border:1px solid var(--border,#cbd5e1);border-radius:8px;box-shadow:0 8px 24px rgba(15,23,42,.14)';wrap.appendChild(list); |
| 45 | const isProduct=select.matches('.row-product-select,.pur-prod'); |
| 46 | const listId='finora-combo-list-'+(window.__finoraComboSequence=(window.__finoraComboSequence||0)+1); |
| 47 | list.id=listId;input.setAttribute('role','combobox');input.setAttribute('aria-autocomplete','list');input.setAttribute('aria-controls',listId);input.setAttribute('aria-expanded','false'); |
| 48 | let activeIndex=-1; |
| 49 | const options=()=>[...list.querySelectorAll('.finora-combobox-option')]; |
| 50 | const activate=(index,ensureVisible=false)=>{ |
| 51 | const rows=options(); |
| 52 | activeIndex=rows.length?Math.max(0,Math.min(rows.length-1,index)):-1; |
| 53 | rows.forEach((b,i)=>{const active=i===activeIndex;b.classList.toggle('finora-combobox-active',active);b.setAttribute('aria-selected',String(active));b.style.background=active?'var(--finora-selection-bg,rgba(35,120,200,.15))':'transparent'}); |
| 54 | if(activeIndex<0){input.removeAttribute('aria-activedescendant');return} |
| 55 | input.setAttribute('aria-activedescendant',rows[activeIndex].id); |
| 56 | if(ensureVisible)rows[activeIndex].scrollIntoView({block:'nearest'}); |
| 57 | }; |
| 58 | const placeList=()=>{if(!isProduct)return;const rect=wrap.getBoundingClientRect(),spaceBelow=window.innerHeight-rect.bottom,above=spaceBelow<115&&rect.top>spaceBelow;const maxH=Math.max(75,Math.min(240,(above?rect.top:spaceBelow)-8));list.style.position='fixed';list.style.right='auto';list.style.left=Math.max(0,rect.left)+'px';list.style.top=(above?Math.max(0,rect.top-maxH-3):rect.bottom+3)+'px';list.style.width=rect.width+'px';list.style.maxHeight=maxH+'px';list.style.zIndex='10000'}; |
| 59 | const close=()=>{list.style.display='none';input.setAttribute('aria-expanded','false');input.removeAttribute('aria-activedescendant');activeIndex=-1;if(isProduct&&list.parentNode!==wrap)wrap.appendChild(list)}; |
| 60 | const render=()=>{ |
| 61 | if(isProduct){syncProductSelectOptions(select);if(list.parentNode!==document.body)document.body.appendChild(list);placeList()} |
| 62 | const rows=comboOptions(select,input.value);list.replaceChildren(); |
| 63 | if(!rows.length){const empty=document.createElement('div');empty.className='finora-combobox-empty';empty.textContent='موردی پیدا نشد';empty.style.cssText='padding:10px;color:var(--text-muted)';list.appendChild(empty)} |
| 64 | else rows.forEach((o,i)=>{const b=document.createElement('button');b.type='button';b.id=listId+'-item-'+i;b.className='finora-combobox-option';b.dataset.value=o.value;b.textContent=comboLabel(o);b.setAttribute('role','option');b.setAttribute('aria-selected','false');b.style.cssText='display:block;width:100%;text-align:right;border:0;border-bottom:1px solid var(--border,#e2e8f0);background:transparent;padding:9px 10px;cursor:pointer;color:inherit';list.appendChild(b)}); |
| 65 | list.style.display='block';input.setAttribute('aria-expanded','true');activate(0,false); |
| 66 | }; |
| 67 | const sync=()=>{const o=select.options[select.selectedIndex];if(document.activeElement===input&&input.dataset.searchDirty==='1')return;input.value=o&&o.value?comboLabel(o):''}; |
| 68 | const choose=(b)=>{if(!b)return false;select.value=b.dataset.value;input.dataset.searchDirty='0';select.dispatchEvent(new Event('change',{bubbles:true}));sync();close();return true}; |
| 69 | input.addEventListener('focus',()=>{input.dataset.searchDirty='1';input.value='';render()}); |
| 70 | input.addEventListener('click',()=>{if(list.style.display==='none'){input.dataset.searchDirty='1';input.value='';render()}}); |
| 71 | input.addEventListener('input',()=>{input.dataset.searchDirty='1';render()}); |
| 72 | input.addEventListener('keydown',e=>{ |
| 73 | if(e.key==='Escape'){if(list.style.display!=='none'){e.preventDefault();e.stopPropagation();close();input.dataset.searchDirty='0';sync();input.blur()}return} |
| 74 | if(['ArrowDown','ArrowUp','PageDown','PageUp','Home','End'].includes(e.key)){ |
| 75 | e.preventDefault();e.stopPropagation(); |
| 76 | if(list.style.display==='none')render(); |
| 77 | const step=e.key==='PageDown'?Math.max(1,Math.floor(list.clientHeight/(options()[0]?.offsetHeight||38))):e.key==='PageUp'?-Math.max(1,Math.floor(list.clientHeight/(options()[0]?.offsetHeight||38))):e.key==='ArrowDown'?1:e.key==='ArrowUp'?-1:0; |
| 78 | activate(e.key==='Home'?0:e.key==='End'?options().length-1:activeIndex+step,true);return; |
| 79 | } |
| 80 | if(e.key==='Enter'&&list.style.display!=='none'){e.preventDefault();e.stopPropagation();choose(options()[activeIndex]);} |
| 81 | }); |
| 82 | list.addEventListener('mousemove',e=>{const b=e.target instanceof Element?e.target.closest('.finora-combobox-option'):null;if(b)activate(options().indexOf(b),false)}); |
| 83 | list.addEventListener('wheel',e=>{ |
| 84 | if(list.style.display==='none')return; |
| 85 | e.preventDefault();e.stopPropagation(); |
| 86 | list.scrollTop+=e.deltaY; |
| 87 | const rows=options(),firstVisible=rows.findIndex(b=>b.offsetTop+b.offsetHeight>list.scrollTop); |
| 88 | if(firstVisible>=0)activate(firstVisible,false); |
| 89 | },{passive:false}); |
| 90 | list.addEventListener('mousedown',e=>{const b=e.target instanceof Element?e.target.closest('.finora-combobox-option'):null;if(!b)return;e.preventDefault();choose(b)}); |
| 91 | select.addEventListener('change',()=>{input.dataset.searchDirty='0';sync()});document.addEventListener('mousedown',e=>{if(!wrap.contains(e.target)){close();input.dataset.searchDirty='0';sync()}});new MutationObserver(()=>{if(input.dataset.searchDirty!=='1')sync();if(list.style.display==='block')render()}).observe(select,{childList:true,subtree:true});if(isProduct){document.addEventListener('scroll',()=>{if(list.style.display==='block')placeList()},true);window.addEventListener('resize',()=>{if(list.style.display==='block')placeList()})}sync(); |
| 92 | } |
| 93 | function refreshProductOptionMetadata(){document.querySelectorAll('.row-product-select,.pur-prod').forEach(syncProductSelectOptions)} |
| 94 | function enhanceAll(){refreshProductOptionMetadata();document.querySelectorAll('select').forEach(finoraRefreshSearchableSelect)} |
| 95 | function closeTopModal(){ |
| 96 | const modals=[...document.querySelectorAll('.modal-backdrop.active')];if(!modals.length)return false;const m=modals[modals.length-1],cancel=[...m.querySelectorAll('button')].find(b=>/انصراف|بستن|لغو|✕/.test(b.textContent||''));if(cancel){cancel.click();return true}m.classList.remove('active');return true; |
| 97 | } |
| 98 | window.finoraCloseTopModal=closeTopModal; |
| 99 | // A delegated close contract also covers late-rendered organization/access dialogs. |
| 100 | // Execute before inline handlers so one broken/stale onclick cannot trap the user. |
| 101 | function dismissModal(modal){ |
| 102 | if(!modal?.classList.contains('modal-backdrop'))return false; |
| 103 | modal.classList.remove('active'); |
| 104 | modal.setAttribute('aria-hidden','true'); |
| 105 | const focused=document.activeElement; |
| 106 | if(focused&&modal.contains(focused)&&typeof focused.blur==='function')focused.blur(); |
| 107 | return true; |
| 108 | } |
| 109 | document.addEventListener('click',e=>{ |
| 110 | const target=e.target instanceof Element?e.target:null; |
| 111 | if(!target)return; |
| 112 | const modal=target.closest('.modal-backdrop.active'); |
| 113 | if(!modal)return; |
| 114 | const button=target.closest('button'); |
| 115 | const closeButton=!!button&&modal.contains(button)&&(button.matches('[data-finora-close-modal]')||/^(?:✕|×|\u2715)?\s*(?:بستن|انصراف)\s*(?:✕|×)?$/.test((button.textContent||'').trim())); |
| 116 | if(closeButton||target===modal){ |
| 117 | e.preventDefault(); |
| 118 | e.stopImmediatePropagation(); |
| 119 | dismissModal(modal); |
| 120 | } |
| 121 | },true); |
| 122 | |
| 123 | const THEME_CSS=`body.finora-theme-dark{ |
| 124 | --bg:#07111f;--surface:#0f1b2d;--card:#122238;--card-bg:#122238; |
| 125 | --text:#f1f5f9;--text-muted:#b8c7da;--border:#405675; |
| 126 | --primary:#38c6d4;--primary-hover:#22aebb; |
| 127 | color:var(--text);background:var(--bg);color-scheme:dark |
| 128 | } |
| 129 | body.finora-theme-dark .main-surface, |
| 130 | body.finora-theme-dark .view-pane{color:var(--text)} |
| 131 | body.finora-theme-dark .sidebar, |
| 132 | body.finora-theme-dark .app-shell-nav.sidebar, |
| 133 | body.finora-theme-dark .module-panel, |
| 134 | body.finora-theme-dark .module-panel-handle, |
| 135 | body.finora-theme-dark .card, |
| 136 | body.finora-theme-dark .modal-card, |
| 137 | body.finora-theme-dark .accordion-item, |
| 138 | body.finora-theme-dark .accordion-body, |
| 139 | body.finora-theme-dark .kpi-unit, |
| 140 | body.finora-theme-dark .table-responsive{ |
| 141 | background:#122238!important;color:#f1f5f9!important;border-color:#405675!important |
| 142 | } |
| 143 | body.finora-theme-dark h1, |
| 144 | body.finora-theme-dark h2, |
| 145 | body.finora-theme-dark h3, |
| 146 | body.finora-theme-dark h4, |
| 147 | body.finora-theme-dark h5, |
| 148 | body.finora-theme-dark h6, |
| 149 | body.finora-theme-dark label, |
| 150 | body.finora-theme-dark .form-group label, |
| 151 | body.finora-theme-dark td, |
| 152 | body.finora-theme-dark .kpi-val, |
| 153 | body.finora-theme-dark .report-bar-value{color:#f1f5f9!important} |
| 154 | body.finora-theme-dark p, |
| 155 | body.finora-theme-dark small, |
| 156 | body.finora-theme-dark .text-muted, |
| 157 | body.finora-theme-dark .kpi-lbl, |
| 158 | body.finora-theme-dark .report-bar-label, |
| 159 | body.finora-theme-dark .sidebar-footer, |
| 160 | body.finora-theme-dark .module-group-title, |
| 161 | body.finora-theme-dark .module-panel-head small{color:#b8c7da!important} |
| 162 | body.finora-theme-dark .app-shell-nav .brand-copy h2, |
| 163 | body.finora-theme-dark .module-panel-head h3, |
| 164 | body.finora-theme-dark .module-tab, |
| 165 | body.finora-theme-dark .module-link, |
| 166 | body.finora-theme-dark .shell-logout{color:#f1f5f9!important} |
| 167 | body.finora-theme-dark .module-tab:hover, |
| 168 | body.finora-theme-dark .module-link:hover, |
| 169 | body.finora-theme-dark .module-link.active, |
| 170 | body.finora-theme-dark .sidebar-menu li a:hover, |
| 171 | body.finora-theme-dark .sidebar-menu li a.active{ |
| 172 | background:#1b3552!important;color:#a5f3fc!important |
| 173 | } |
| 174 | body.finora-theme-dark .module-group, |
| 175 | body.finora-theme-dark .module-panel-head, |
| 176 | body.finora-theme-dark .app-shell-nav .brand-box{border-color:#405675!important} |
| 177 | body.finora-theme-dark input, |
| 178 | body.finora-theme-dark select, |
| 179 | body.finora-theme-dark textarea, |
| 180 | body.finora-theme-dark .form-control{ |
| 181 | background:#0b1728!important;color:#f8fafc!important;border-color:#526985!important |
| 182 | } |
| 183 | body.finora-theme-dark input::placeholder, |
| 184 | body.finora-theme-dark textarea::placeholder{color:#b8c7da!important;opacity:1} |
| 185 | body.finora-theme-dark .form-control:disabled, |
| 186 | body.finora-theme-dark input:disabled, |
| 187 | body.finora-theme-dark select:disabled{ |
| 188 | background:#17263a!important;color:#b8c7da!important;opacity:1 |
| 189 | } |
| 190 | body.finora-theme-dark table th{ |
| 191 | background:#1a2b42!important;color:#f8fafc!important;border-color:#405675!important |
| 192 | } |
| 193 | body.finora-theme-dark table td{ |
| 194 | background:#122238!important;color:#f1f5f9!important;border-color:#405675!important |
| 195 | } |
| 196 | body.finora-theme-dark .accordion-header{ |
| 197 | background:#182940!important;color:#f1f5f9!important |
| 198 | } |
| 199 | body.finora-theme-dark .btn-secondary{ |
| 200 | background:#263b55!important;color:#f8fafc!important;border-color:#526985!important |
| 201 | } |
| 202 | body.finora-theme-dark .finora-combobox-list{ |
| 203 | background:#0b1728!important;border-color:#526985!important;color:#f8fafc!important |
| 204 | } |
| 205 | body.finora-theme-dark .finora-combobox-option{ |
| 206 | background:#0b1728!important;color:#f8fafc!important;border-color:#334a67!important |
| 207 | } |
| 208 | body.finora-theme-dark .finora-combobox-option:hover, |
| 209 | body.finora-theme-dark .finora-combobox-option:focus{ |
| 210 | background:#1b3552!important;color:#f8fafc!important |
| 211 | } |
| 212 | body.finora-theme-dark .form-row[style*="background"], |
| 213 | body.finora-theme-dark .form-group[style*="background"]{ |
| 214 | background:#0d1a2c!important |
| 215 | }`; |
| 216 | function ensureThemeCss(){if($('finora-theme-r2-css'))return;const s=document.createElement('style');s.id='finora-theme-r2-css';s.textContent=THEME_CSS;document.head.appendChild(s)} |
| 217 | function resolveTheme(mode){if(mode==='dark'||mode==='light')return mode;const h=new Date().getHours();return h>=7&&h<19?'light':'dark'} |
| 218 | window.finoraApplyTheme=function(){ensureThemeCss();const mode=getMySettings()?.ui_theme||'auto',r=resolveTheme(mode);document.body.classList.toggle('finora-theme-dark',r==='dark');document.documentElement.dataset.finoraTheme=r} |
| 219 | function saveExperience(){ |
| 220 | if(!requireWrite())return;const s=getMySettings();s.ui_theme=$('finora-theme-select').value;s.hotkey_ctrl_s=$('finora-hotkey-ctrls').checked;s.hotkey_ctrl_enter=$('finora-hotkey-ctrlenter').checked;s.hotkey_enter_save=$('finora-hotkey-enter').checked;s.hotkey_quick_zeros=$('finora-hotkey-zeros').checked;saveDatastore();finoraApplyTheme();alert('تنظیمات تجربه کاربری ذخیره شد.'); |
| 221 | } |
| 222 | window.finoraSaveExperienceSettings=saveExperience; |
| 223 | function settingsSaveAction(){ |
| 224 | const focused=document.activeElement,task=focused?.closest('[data-finora-task]')?.dataset.finoraTask; |
| 225 | if(task)return {experience:'finoraSaveExperienceSettings','excel-templates':'finoraSaveExcelFields',company:'commitSaveCompany','invoice-defaults':'commitSaveDefaultSettings','ops-settings':'p5SaveCompanyOpsSettings'}[task]||null; |
| 226 | if($('company-save-btn')?.closest('.accordion-item')?.contains(focused))return 'commitSaveCompany'; |
| 227 | if(focused?.closest('#p5-data-root .card')?.querySelector('#p5-set-default-wh'))return 'p5SaveCompanyOpsSettings'; |
| 228 | return document.querySelector('.view-pane.active')?.id==='view-settings'?'commitSaveDefaultSettings':null; |
| 229 | } |
| 230 | function activeSave(){ |
| 231 | const v=document.querySelector('.view-pane.active')?.id;if(v==='view-invoices'&&typeof commitSaveInvoice==='function')return commitSaveInvoice();if(v==='view-purchases'&&typeof purSave==='function')return purSave();if(v==='view-products'&&typeof commitSaveProduct==='function')return commitSaveProduct();if(v==='view-contacts'&&typeof commitSaveContact==='function')return commitSaveContact();if(v==='view-journal'&&typeof jeSaveManual==='function')return jeSaveManual();if(v==='view-settings'||v==='view-data-center'){const action=settingsSaveAction();if(typeof window[action]==='function')return window[action]()} |
| 232 | } |
| 233 | // F2 saves the *active entry form*, never posts the accounting journal or clicks destructive actions. |
| 234 | // Use the form's original validation/save function so its exact rejection reason remains visible. |
| 235 | let f2Running=false; |
| 236 | function f2Error(message){alert(message);return false} |
| 237 | // Discover only explicitly safe save commands in modular forms. Never infer a |
| 238 | // delete, approval, posting, membership or finalization action from button text. |
| 239 | function f2SafeSaveButton(scope){ |
| 240 | const focused=document.activeElement; |
| 241 | const section=focused&&scope.contains(focused)?focused.closest('form,.card,.accordion-item,[data-finora-task],.modal-card'):null; |
| 242 | const root=section&&scope.contains(section)?section:scope; |
| 243 | const candidates=[...root.querySelectorAll('button')].filter(button=>{ |
| 244 | if(button.disabled||!button.getClientRects().length)return false; |
| 245 | const call=(button.getAttribute('onclick')||'').trim(); |
| 246 | const action=call.match(/^([A-Za-z][A-Za-z0-9_]*)\s*\(\s*\)\s*;?$/)?.[1]||''; |
| 247 | return /^(?:afSave|entSave|p5Save|p6Save|commitSave)[A-Za-z0-9_]*$/.test(action) |
| 248 | && !/حذف|ابطال|برگشت|قطعی|لغو|اعطای دسترسی|حذف کاربر/.test(button.textContent||''); |
| 249 | }); |
| 250 | return candidates.length===1?candidates[0]:null; |
| 251 | } |
| 252 | async function f2ConfirmCurrentForm(){ |
| 253 | if(f2Running)return false; |
| 254 | if(!currentUser)return f2Error('ابتدا وارد حساب کاربری شوید.'); |
| 255 | const openModal=[...document.querySelectorAll('.modal-backdrop.active')].at(-1); |
| 256 | if(openModal){ |
| 257 | const safe=f2SafeSaveButton(openModal); |
| 258 | if(!safe)return f2Error('این پنجره عملیات ذخیره قابلتشخیص و ایمن ندارد. از دکمه اختصاصی همان پنجره استفاده کنید.'); |
| 259 | const invalid=[...openModal.querySelectorAll('input,select,textarea')].find(el=>el.getClientRects().length&&!el.disabled&&!el.checkValidity()); |
| 260 | if(invalid){invalid.focus();return f2Error('این فیلد پنجره معتبر نیست: '+(invalid.labels?.[0]?.textContent?.trim()||invalid.placeholder||invalid.id||'فیلد'))} |
| 261 | safe.click();return true; |
| 262 | } |
| 263 | const view=document.querySelector('.view-pane.active')?.id; |
| 264 | if(!view)return f2Error('هیچ فرم فعالی برای تأیید پیدا نشد.'); |
| 265 | const ids={ |
| 266 | 'view-invoices':'commitSaveInvoice', |
| 267 | 'view-purchases':'purSave', |
| 268 | 'view-products':'commitSaveProduct', |
| 269 | 'view-contacts':'commitSaveContact', |
| 270 | 'view-cheques':'commitSaveCheque', |
| 271 | 'view-expenses':'commitSaveExpense', |
| 272 | 'view-journal':'jeSaveManual', |
| 273 | 'view-settings':'commitSaveDefaultSettings' |
| 274 | }; |
| 275 | const actionId=view==='view-settings'||view==='view-data-center'?settingsSaveAction():ids[view]; |
| 276 | const handler=window[actionId]; |
| 277 | if(typeof handler!=='function'){ |
| 278 | const safe=f2SafeSaveButton(document.getElementById(view)); |
| 279 | if(!safe)return f2Error('برای این صفحه، فرم قابل ذخیره مشخص نیست یا چند عملیات وجود دارد. روی فیلد فرم موردنظر کلیک کنید و دوباره F2 بزنید.'); |
| 280 | safe.click();return true; |
| 281 | } |
| 282 | // Do not turn approval of the manual voucher or a sales invoice into an implicit posting. |
| 283 | if(view==='view-journal'&&document.querySelector('[data-finora-task="documents"]')?.getClientRects().length>0) |
| 284 | return f2Error('قطعیسازی سند مالی فقط از مدیریت اسناد و با تأیید صریح انجام میشود؛ F2 برای ثبت پیشنویس است.'); |
| 285 | // Accessible native inputs supply field-specific errors before any write is attempted. |
| 286 | const visibleView=view==='view-settings'?(document.activeElement?.closest('.accordion-item')||document.getElementById(view)):document.getElementById(view); |
| 287 | const invalid=[...(visibleView?.querySelectorAll('input,select,textarea')||[])].find(el=>{ |
| 288 | if(el.disabled||el.type==='hidden'||el.closest('[hidden]'))return false; |
| 289 | if(el.offsetParent===null&&!el.getClientRects().length)return false; |
| 290 | return typeof el.checkValidity==='function'&&!el.checkValidity(); |
| 291 | }); |
| 292 | if(invalid){invalid.focus();return f2Error('اطلاعات این فیلد معتبر نیست: '+(invalid.labels?.[0]?.textContent?.trim()||invalid.placeholder||invalid.id||'فیلد انتخابشده'))} |
| 293 | if(view==='view-products'&&!$('prod-name-input')?.value.trim())return f2Error('عنوان کالا یا خدمت الزامی است.'); |
| 294 | if(view==='view-contacts'&&!$('contact-name-input')?.value.trim())return f2Error('نام طرف حساب الزامی است.'); |
| 295 | if(view==='view-invoices'){ |
| 296 | const items=[...document.querySelectorAll('#invoice-items-table-body tr')]; |
| 297 | if(!items.some(row=>row.querySelector('.row-product-select')?.value&&Number(row.querySelector('.row-quantity')?.value)>0)) |
| 298 | return f2Error('حداقل یک کالا یا خدمت معتبر و تعداد بیشتر از صفر انتخاب کنید.'); |
| 299 | } |
| 300 | if(view==='view-purchases'){ |
| 301 | const items=[...document.querySelectorAll('#pur-items-body tr')]; |
| 302 | if(!items.some(row=>row.querySelector('.pur-prod')?.value&&Number(row.querySelector('.pur-qty')?.value)>0)) |
| 303 | return f2Error('حداقل یک ردیف کالا یا خدمت با تعداد معتبر وارد کنید.'); |
| 304 | if(!$('pur-supplier')?.value)return f2Error('تأمینکننده را انتخاب کنید.'); |
| 305 | } |
| 306 | // Unlike sales drafts, the current purchase Save posts its financial voucher. |
| 307 | // Require an explicit second confirmation rather than silently posting through a hotkey. |
| 308 | if(view==='view-purchases'&&!confirm('ثبت فاکتور خرید در نسخه فعلی سند حسابداری را قطعی میکند. با ثبت قطعی موافقید؟')) |
| 309 | return f2Error('عملیات متوقف شد؛ قطعیسازی خرید نیازمند تأیید صریح است.'); |
| 310 | f2Running=true; |
| 311 | try{await Promise.resolve(handler());return true} |
| 312 | catch(error){return f2Error('فرم ذخیره نشد: '+(error?.message||String(error)))} |
| 313 | finally{f2Running=false} |
| 314 | } |
| 315 | window.finoraConfirmActiveFormF2=f2ConfirmCurrentForm; |
| 316 | document.addEventListener('keydown',e=>{ |
| 317 | const s=typeof getMySettings==='function'?getMySettings():{};if(e.key==='F2'&&!e.altKey&&!e.ctrlKey&&!e.metaKey){e.preventDefault();e.stopPropagation();if(!e.repeat)void f2ConfirmCurrentForm();return}if(e.key==='Escape'){if(closeTopModal()){e.preventDefault();return}} |
| 318 | if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='s'&&s.hotkey_ctrl_s!==false){e.preventDefault();activeSave();return} |
| 319 | if((e.ctrlKey||e.metaKey)&&e.key==='Enter'&&s.hotkey_ctrl_enter!==false){e.preventDefault();activeSave();return} |
| 320 | const t=e.target;if(s.hotkey_quick_zeros&&t?.matches?.('input[inputmode="decimal"],input[type="number"]')&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&(e.code==='NumpadAdd'||e.code==='NumpadSubtract'||e.key==='+'||e.key==='-')){e.preventDefault();const zeros=(e.code==='NumpadSubtract'||e.key==='-')?'00':'000',raw=String(t.value||'').replace(/,/g,'');t.value=raw+zeros;t.dispatchEvent(new Event('input',{bubbles:true}));return} |
| 321 | if(s.hotkey_enter_save&&e.key==='Enter'&&!e.shiftKey&&!e.ctrlKey&&!e.altKey&&!t?.matches?.('textarea,select,button')){e.preventDefault();activeSave()} |
| 322 | }); |
| 323 | const EXCEL_SCHEMAS={ |
| 324 | products:[['code','کد کالا'],['name','نام کالا',1],['spec','مشخصه و نوع'],['category','دستهبندی'],['unit','واحد'],['buy_price','قیمت خرید (ریال)'],['sale_price','قیمت فروش (ریال)'],['barcode','بارکد'],['internal_id','شناسه کالا/خدمت داخلی'],['official_id','شناسه کالا/خدمت سامانه مالیاتی'],['min_stock','حداقل موجودی']], |
| 325 | contacts:[['name','نام شخص یا شرکت',1],['entity_type','نوع (حقیقی/حقوقی)'],['role','نقش (مشتری/تأمینکننده/هر دو)'],['mobile','شماره همراه'],['national_id','شناسه یا کد ملی'],['economic_code','کد اقتصادی'],['reg_number','شماره ثبت'],['postal_code','کد پستی'],['address','نشانی']], |
| 326 | accounts:[['code','کد حساب',1],['title','عنوان',1],['level','سطح',1],['parent_code','کد والد'],['normal_balance','ماهیت'],['account_type','نوع حساب'],['system_role','نقش سیستمی']], |
| 327 | saleItems:[['code','کد کالا'],['name','شرح',1],['qty','تعداد'],['unit','واحد'],['price','فی']], |
| 328 | purchaseItems:[['code','کد کالا'],['name','شرح',1],['qty','تعداد'],['unit','واحد'],['price','فی']] |
| 329 | }; |
| 330 | function excelSelection(type){const s=getMySettings(),saved=s.excel_template_fields?.[type],schema=EXCEL_SCHEMAS[type]||[];return Array.isArray(saved)&&saved.length?saved:schema.map(x=>x[0])} |
| 331 | let excelSettingsRender=null; |
| 332 | function renderExcelFields(force=true){ |
| 333 | const type=$('finora-excel-type')?.value||'products',host=$('finora-excel-fields');if(!host)return;const record=getMySettings(); |
| 334 | if(!force&&excelSettingsRender?.host===host&&excelSettingsRender?.record===record&&excelSettingsRender?.type===type)return; |
| 335 | const selected=new Set(excelSelection(type));host.innerHTML=(EXCEL_SCHEMAS[type]||[]).map(([k,l,req])=>'<label style="display:flex;gap:6px;align-items:center;margin:5px 0"><input type="checkbox" data-excel-field="'+k+'" '+(selected.has(k)?'checked':'')+' '+(req?'disabled':'')+'> '+l+(req?' *':'')+'</label>').join(''); |
| 336 | excelSettingsRender={host,record,type}; |
| 337 | } |
| 338 | window.finoraRenderExcelFields=renderExcelFields; |
| 339 | function saveExcelFields(){ |
| 340 | if(!requireWrite())return; |
| 341 | const type=$('finora-excel-type').value,s=getMySettings(),keys=[...document.querySelectorAll('#finora-excel-fields input:checked')].map(x=>x.dataset.excelField);s.excel_template_fields=s.excel_template_fields||{};s.excel_template_fields[type]=keys;saveDatastore();alert('فیلدهای قالب ذخیره شد.'); |
| 342 | } |
| 343 | window.finoraSaveExcelFields=saveExcelFields; |
| 344 | function templateSample(type,key){const samples={products:{code:'101',name:'بلوک سایز ۱۰',spec:'سبک',category:'مصالح',unit:'عدد',buy_price:80000,sale_price:100000,barcode:'6260000000000',internal_id:'INT-101',official_id:'',min_stock:20},contacts:{name:'شرکت نمونه',entity_type:'حقوقی',role:'هر دو',mobile:'09120000000',national_id:'14000000000',economic_code:'411111111111',reg_number:'12345',postal_code:'1234567890',address:'تهران'},accounts:{code:'1101',title:'صندوق و بانک',level:'تفصیلی',parent_code:'11',normal_balance:'بدهکار',account_type:'دارایی',system_role:'cash_default'},saleItems:{code:'101',name:'بلوک سایز ۱۰',qty:2,unit:'عدد',price:100000},purchaseItems:{code:'101',name:'بلوک سایز ۱۰',qty:2,unit:'عدد',price:80000}};return samples[type]?.[key]??''} |
| 345 | window.finoraDownloadConfiguredTemplate=function(type){ |
| 346 | if(typeof XLSX==='undefined')return alert('موتور Excel در دسترس نیست.');const schema=EXCEL_SCHEMAS[type]||[],keys=excelSelection(type),cols=schema.filter(x=>keys.includes(x[0])),headers=cols.map(x=>x[1]),sample=cols.map(x=>templateSample(type,x[0])),ws=XLSX.utils.aoa_to_sheet([headers,sample]),wb=XLSX.utils.book_new();XLSX.utils.book_append_sheet(wb,ws,'قالب');XLSX.writeFile(wb,'Finora_'+type+'_Template.xlsx') |
| 347 | } |
| 348 | window.finoraExportConfiguredData=function(type){ |
| 349 | if(typeof XLSX==='undefined')return alert('موتور Excel در دسترس نیست.');let rows=[];if(type==='products')rows=getMyProducts();else if(type==='contacts')rows=getMyContacts();else if(type==='accounts')rows=getMyAccounts();else return alert('برای اقلام فاکتور از قالب نمونه استفاده کنید.');const schema=EXCEL_SCHEMAS[type],keys=excelSelection(type),out=rows.map(r=>Object.fromEntries(schema.filter(x=>keys.includes(x[0])).map(([k,l])=>[l,r[k]??'']))),ws=XLSX.utils.json_to_sheet(out),wb=XLSX.utils.book_new();XLSX.utils.book_append_sheet(wb,ws,'خروجی');XLSX.writeFile(wb,'Finora_'+type+'_Export.xlsx') |
| 350 | } |
| 351 | function statsHtml(){const stats=[['کالا/خدمت',ownedRows('products').length],['اشخاص',ownedRows('contacts').length],['فاکتور فروش',ownedRows('invoices').length],['فاکتور خرید',ownedRows('purchases').length],['چک',ownedRows('cheques').length],['حساب',ownedRows('accounts').length],['پروژه',ownedRows('projects').length],['اسناد حسابداری',ownedRows('journalVouchers').length]];return '<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:8px">'+stats.map(x=>'<div style="border:1px solid var(--border);border-radius:10px;padding:12px"><small>'+x[0]+'</small><div style="font-size:22px;font-weight:800">'+Number(x[1]).toLocaleString('fa-IR')+'</div></div>').join('')+'</div>'} |
| 352 | window.finoraRefreshDataStats=function(){const h=$('finora-data-stats');if(h)h.innerHTML=statsHtml()} |
| 353 | let experienceSettingsRender=null; |
| 354 | function renderExperienceSettings(){ |
| 355 | const card=$('finora-experience-card');if(!card)return;const s=getMySettings(); |
| 356 | if(experienceSettingsRender?.card===card&&experienceSettingsRender?.record===s)return; |
| 357 | $('finora-theme-select').value=s.ui_theme||'auto';$('finora-hotkey-ctrls').checked=s.hotkey_ctrl_s!==false;$('finora-hotkey-ctrlenter').checked=s.hotkey_ctrl_enter!==false;$('finora-hotkey-enter').checked=!!s.hotkey_enter_save;$('finora-hotkey-zeros').checked=!!s.hotkey_quick_zeros; |
| 358 | experienceSettingsRender={card,record:s}; |
| 359 | } |
| 360 | function installSettings(){ |
| 361 | const root=$('view-settings');if(!root||$('finora-experience-card'))return;try{if(typeof FINORA_MODULES!=='undefined'&&!FINORA_MODULES.settings.groups.some(g=>g.title==='تجربه کاربری'))FINORA_MODULES.settings.groups.splice(2,0,{title:'تجربه کاربری',items:[['ظاهر و میانبرها','view-settings','⌨','','experience'],['قالبهای Excel','view-settings','▦','','excel-templates'],['آمار دادهها','view-settings','◎','','data-stats']]})}catch(_){} |
| 362 | const exp=document.createElement('div');exp.id='finora-experience-card';exp.className='accordion-item open';exp.dataset.finoraTask='experience';exp.innerHTML='<div class="accordion-header" onclick="toggleAccordion(this)"><span>⌨ ظاهر و میانبرهای صفحهکلید</span><span>▼</span></div><div class="accordion-body"><div class="form-row"><div class="form-group"><label>تم ظاهری</label><select id="finora-theme-select" class="form-control"><option value="auto">خودکار (روز روشن / شب تاریک)</option><option value="light">روشن</option><option value="dark">تاریک</option></select></div></div><label><input type="checkbox" id="finora-hotkey-ctrls"> Ctrl+S برای ذخیره</label><br><label><input type="checkbox" id="finora-hotkey-ctrlenter"> Ctrl+Enter برای ذخیره</label><br><strong>F2 برای ذخیره یا تأیید فرم فعال</strong> (بدون قطعیکردن خودکار اسناد مالی)<br><label><input type="checkbox" id="finora-hotkey-enter"> Enter برای ذخیره فرم فعال</label><br><label><input type="checkbox" id="finora-hotkey-zeros"> + افزودن سه صفر و − افزودن دو صفر در فیلد مبلغ</label><p class="af-hint">Escape همیشه پنجره باز را میبندد. میانبرهای عددی فقط داخل فیلدهای مبلغ عمل میکنند.</p><button class="btn btn-primary" onclick="finoraSaveExperienceSettings()">ذخیره تنظیمات</button></div>';root.insertBefore(exp,root.firstElementChild?.nextSibling||null); |
| 363 | const ex=document.createElement('div');ex.className='accordion-item';ex.dataset.finoraTask='excel-templates';ex.innerHTML='<div class="accordion-header" onclick="toggleAccordion(this)"><span>▦ قالبهای Excel و فیلدهای قابل انتخاب</span><span>▼</span></div><div class="accordion-body"><div class="form-group"><label>نوع قالب</label><select id="finora-excel-type" class="form-control" onchange="finoraRenderExcelFields()"><option value="products">کالا و خدمات</option><option value="contacts">اشخاص</option><option value="accounts">کدینگ حسابها</option><option value="saleItems">اقلام فاکتور فروش</option><option value="purchaseItems">اقلام فاکتور خرید</option></select></div><div id="finora-excel-fields"></div><div style="display:flex;gap:8px;flex-wrap:wrap"><button class="btn btn-primary" onclick="finoraSaveExcelFields()">ذخیره فیلدها</button><button class="btn btn-secondary" onclick="finoraDownloadConfiguredTemplate(document.getElementById(\'finora-excel-type\').value)">دانلود قالب نمونه</button><button class="btn btn-secondary" onclick="finoraExportConfiguredData(document.getElementById(\'finora-excel-type\').value)">خروجی دادههای فعلی</button></div></div>';root.appendChild(ex);renderExcelFields(); |
| 364 | const st=document.createElement('div');st.className='accordion-item';st.dataset.finoraTask='data-stats';st.innerHTML='<div class="accordion-header" onclick="toggleAccordion(this)"><span>◎ آمار دادههای شرکت فعال</span><span>▼</span></div><div class="accordion-body"><div id="finora-data-stats"></div><button class="btn btn-secondary" style="margin-top:10px" onclick="finoraRefreshDataStats()">بهروزرسانی آمار</button></div>';root.appendChild(st);finoraRefreshDataStats(); |
| 365 | } |
| 366 | window.finoraOpenInvoiceType=function(type){if(type==='purchase'){if(typeof navigateShell==='function')navigateShell('commerce','view-purchases');else switchView('view-purchases');return}if(typeof navigateShell==='function')navigateShell('commerce','view-invoices');else switchView('view-invoices');const kind=$('invoice-kind');if(kind){kind.value=type==='pre_invoice'?'pre_invoice':type==='contract_statement'?'contract_statement':'non_formal';if(typeof handleInvoiceKindChange==='function')handleInvoiceKindChange()}} |
| 367 | const oldProductTpl=window.downloadProductsExcelTemplate,oldContactTpl=window.downloadContactsExcelTemplate;window.downloadProductsExcelTemplate=()=>finoraDownloadConfiguredTemplate('products');window.downloadContactsExcelTemplate=()=>finoraDownloadConfiguredTemplate('contacts'); |
| 368 | window.downloadAccountsExcelTemplate=()=>finoraDownloadConfiguredTemplate('accounts');window.downloadInvoiceItemsExcelTemplate=()=>finoraDownloadConfiguredTemplate('saleItems');window.purDownloadExcelTemplate=()=>finoraDownloadConfiguredTemplate('purchaseItems'); |
| 369 | function boot(){installSettings();renderExperienceSettings();renderExcelFields(false);enhanceAll();finoraApplyTheme();finoraRefreshDataStats()} |
| 370 | const oldRefresh=window.refreshAllSurfaces;if(typeof oldRefresh==='function')window.refreshAllSurfaces=function(){const r=oldRefresh.apply(this,arguments);setTimeout(boot,0);return r}; |
| 371 | document.addEventListener('DOMContentLoaded',()=>setTimeout(boot,0));setInterval(()=>{if((getMySettings()?.ui_theme||'auto')==='auto')finoraApplyTheme()},15*60*1000); |
| 372 | })(); |