سامانه صدور فاکتور و حسابداری
Mirrored from https://github.com/davoodmehraban89/Factor-easy.git
Synced Dec 3, 18:15 UTC
exec-phase1-qa
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 | (function(){ |
| 2 | const IDLE_TIMEOUT_MS = 30*60*1000; // ۳۰ دقیقه |
| 3 | const WARN_LEAD_MS = 60*1000; // ۱ دقیقه قبل هشدار |
| 4 | const DRAFT_KEY = 'factoreasy_invoice_draft_v1'; |
| 5 | let idleTimer=null, warnTimer=null, countdownInterval=null, warningVisible=false, lastActivityReset=0; |
| 6 | |
| 7 | function ensureIdleModal(){ |
| 8 | if(document.getElementById('modal-idle-warning'))return; |
| 9 | const div=document.createElement('div'); |
| 10 | div.className='modal-backdrop'; |
| 11 | div.id='modal-idle-warning'; |
| 12 | div.innerHTML=`<div class="modal-card" style="max-width:420px;text-align:center"> |
| 13 | <h3 style="font-size:16px;margin-bottom:10px">⏰ عدم فعالیت</h3> |
| 14 | <p style="font-size:13px;color:var(--text-muted);margin-bottom:14px">به دلیل عدم فعالیت، تا <span id="idle-countdown" style="font-weight:bold;color:#dc2626">60</span> ثانیه دیگر از حساب خارج میشوید.</p> |
| 15 | <div style="display:flex;gap:10px;justify-content:center"> |
| 16 | <button class="btn btn-success" onclick="window.__idleContinueWorking()">✅ ادامه کار</button> |
| 17 | <button class="btn btn-secondary" onclick="window.__idleLogoutNow()">🚪 خروج فوری</button> |
| 18 | </div> |
| 19 | </div>`; |
| 20 | document.body.appendChild(div); |
| 21 | } |
| 22 | function hideWarning(){ |
| 23 | warningVisible=false; |
| 24 | clearInterval(countdownInterval); |
| 25 | const el=document.getElementById('modal-idle-warning'); |
| 26 | if(el)el.classList.remove('active'); |
| 27 | } |
| 28 | function showWarning(){ |
| 29 | ensureIdleModal(); |
| 30 | warningVisible=true; |
| 31 | let remain=Math.round(WARN_LEAD_MS/1000); |
| 32 | const cd=document.getElementById('idle-countdown'); |
| 33 | if(cd)cd.innerText=remain; |
| 34 | document.getElementById('modal-idle-warning').classList.add('active'); |
| 35 | countdownInterval=setInterval(()=>{ |
| 36 | remain--; |
| 37 | const el=document.getElementById('idle-countdown'); |
| 38 | if(el)el.innerText=Math.max(remain,0); |
| 39 | if(remain<=0)clearInterval(countdownInterval); |
| 40 | },1000); |
| 41 | } |
| 42 | |
| 43 | function getInvoiceFormSnapshot(){ |
| 44 | const rows=[...document.querySelectorAll('#invoice-items-table-body tr')].map(tr=>({ |
| 45 | prodId: tr.querySelector('.row-product-select')?.value||'', |
| 46 | unit: tr.querySelector('.row-unit-input')?.value||'', |
| 47 | qty: tr.querySelector('.row-quantity')?.value||'', |
| 48 | price: tr.querySelector('.row-price')?.value||'' |
| 49 | })).filter(r=>r.prodId); |
| 50 | return { |
| 51 | editId: document.getElementById('edit-invoice-id')?.value||'', |
| 52 | companyId: document.getElementById('invoice-company-id')?.value||'', |
| 53 | kind: document.getElementById('invoice-kind')?.value||'', |
| 54 | vatMode: document.getElementById('invoice-vat-mode')?.value||'', |
| 55 | vatType: document.getElementById('invoice-vat-type')?.value||'', |
| 56 | vatRate: document.getElementById('invoice-vat-rate-input')?.value||'', |
| 57 | number: document.getElementById('invoice-number')?.value||'', |
| 58 | contactId: document.getElementById('invoice-contact-id')?.value||'', |
| 59 | paymentMethod: document.getElementById('invoice-payment-method')?.value||'cash', |
| 60 | projectId: document.getElementById('invoice-project-id')?.value||'', |
| 61 | date: document.getElementById('invoice-date-input')?.value||'', |
| 62 | discountType: document.getElementById('invoice-discount-type')?.value||'', |
| 63 | discountFixed: document.getElementById('invoice-discount-fixed')?.value||'', |
| 64 | desc: document.getElementById('invoice-desc-input')?.value||'', |
| 65 | items: rows, |
| 66 | savedAt: Date.now(), |
| 67 | userId: (typeof currentUser!=='undefined'&¤tUser)?currentUser.id:null |
| 68 | }; |
| 69 | } |
| 70 | function isSnapshotWorthSaving(snap){ |
| 71 | return !!(snap.contactId || (snap.desc&&snap.desc.trim()) || (snap.items&&snap.items.length>0)); |
| 72 | } |
| 73 | function saveInvoiceDraftIfNeeded(){ |
| 74 | try{ |
| 75 | const snap=getInvoiceFormSnapshot(); |
| 76 | if(!isSnapshotWorthSaving(snap))return; |
| 77 | localStorage.setItem(DRAFT_KEY, JSON.stringify(snap)); |
| 78 | }catch(e){console.error('draft save failed',e);} |
| 79 | } |
| 80 | |
| 81 | async function performIdleLogout(){ |
| 82 | hideWarning(); |
| 83 | saveInvoiceDraftIfNeeded(); |
| 84 | try{await sb.auth.signOut();}catch(e){} |
| 85 | } |
| 86 | window.__idleContinueWorking=function(){ hideWarning(); resetIdleTimer(); }; |
| 87 | window.__idleLogoutNow=async function(){ |
| 88 | hideWarning(); |
| 89 | saveInvoiceDraftIfNeeded(); |
| 90 | try{await sb.auth.signOut();}catch(e){} |
| 91 | }; |
| 92 | |
| 93 | function resetIdleTimer(){ |
| 94 | if(!window.__idleWatcherActive)return; |
| 95 | clearTimeout(idleTimer); |
| 96 | clearTimeout(warnTimer); |
| 97 | warnTimer=setTimeout(showWarning, IDLE_TIMEOUT_MS-WARN_LEAD_MS); |
| 98 | idleTimer=setTimeout(performIdleLogout, IDLE_TIMEOUT_MS); |
| 99 | } |
| 100 | function onActivity(){ |
| 101 | if(!window.__idleWatcherActive)return; |
| 102 | const now=Date.now(); |
| 103 | if(warningVisible)hideWarning(); |
| 104 | if(now-lastActivityReset<3000)return; |
| 105 | lastActivityReset=now; |
| 106 | resetIdleTimer(); |
| 107 | } |
| 108 | ['mousemove','mousedown','keydown','scroll','touchstart','click'].forEach(evt=>{ |
| 109 | window.addEventListener(evt, onActivity, {passive:true}); |
| 110 | }); |
| 111 | |
| 112 | window.startIdleWatcher=function(){ window.__idleWatcherActive=true; resetIdleTimer(); }; |
| 113 | window.stopIdleWatcher=function(){ |
| 114 | window.__idleWatcherActive=false; |
| 115 | clearTimeout(idleTimer); clearTimeout(warnTimer); hideWarning(); |
| 116 | }; |
| 117 | |
| 118 | window.offerInvoiceDraftRestoreIfAny=function(){ |
| 119 | try{ |
| 120 | const raw=localStorage.getItem(DRAFT_KEY); |
| 121 | if(!raw)return; |
| 122 | const snap=JSON.parse(raw); |
| 123 | const uid=(typeof currentUser!=='undefined'&¤tUser)?currentUser.id:null; |
| 124 | if(!uid||snap.userId!==uid){localStorage.removeItem(DRAFT_KEY);return;} |
| 125 | const ageMin=Math.max(1,Math.round((Date.now()-(snap.savedAt||0))/60000)); |
| 126 | if(!confirm(`یک فاکتور پیشنویس ذخیرهنشده (حدود ${ageMin} دقیقه پیش، بهدلیل خروج خودکار بهخاطر عدم فعالیت) پیدا شد. بازیابی شود؟`)){ |
| 127 | localStorage.removeItem(DRAFT_KEY); return; |
| 128 | } |
| 129 | switchView('view-invoices'); |
| 130 | document.getElementById('edit-invoice-id').value=snap.editId||''; |
| 131 | if(snap.editId){ |
| 132 | document.getElementById('invoice-form-title').innerText='✏️ ویرایش فاکتور (پیشنویس بازیابیشده)'; |
| 133 | document.getElementById('btn-cancel-edit').style.display='inline-flex'; |
| 134 | document.getElementById('btn-save-invoice').innerText='💾 ذخیره تغییرات'; |
| 135 | }else{ |
| 136 | document.getElementById('invoice-form-title').innerText='📝 فاکتور پیشنویس بازیابیشده'; |
| 137 | } |
| 138 | document.getElementById('invoice-company-id').value=snap.companyId||''; |
| 139 | document.getElementById('invoice-kind').value=snap.kind||'non_formal'; |
| 140 | document.getElementById('invoice-vat-mode').value=snap.vatMode||'none'; |
| 141 | document.getElementById('invoice-vat-type').value=snap.vatType||'percent'; |
| 142 | document.getElementById('invoice-vat-rate-input').value=snap.vatRate||10; |
| 143 | document.getElementById('invoice-number').value=snap.number||''; |
| 144 | document.getElementById('invoice-contact-id').value=snap.contactId||''; |
| 145 | if(document.getElementById('invoice-payment-method'))document.getElementById('invoice-payment-method').value=snap.paymentMethod||'cash'; |
| 146 | if(typeof handleInvoiceContactChange==='function'){handleInvoiceContactChange();if(document.getElementById('invoice-project-id'))document.getElementById('invoice-project-id').value=snap.projectId||'';} |
| 147 | document.getElementById('invoice-date-input').value=snap.date||''; |
| 148 | document.getElementById('invoice-discount-type').value=snap.discountType||'fixed'; |
| 149 | document.getElementById('invoice-discount-fixed').value=snap.discountFixed||0; |
| 150 | document.getElementById('invoice-desc-input').value=snap.desc||''; |
| 151 | if(typeof handleInvoiceKindChange==='function')handleInvoiceKindChange(); |
| 152 | const tbody=document.getElementById('invoice-items-table-body'); |
| 153 | tbody.innerHTML=''; |
| 154 | (snap.items||[]).forEach(it=>{ |
| 155 | addInvoiceItemRow(it.prodId, parseFloat(it.qty)||1, it.price!==''?parseFloat(it.price):null); |
| 156 | const lastRow=tbody.lastElementChild; |
| 157 | if(lastRow&&it.unit)lastRow.querySelector('.row-unit-input').value=it.unit; |
| 158 | }); |
| 159 | if(typeof updateInvoiceItemRowNumbers==='function')updateInvoiceItemRowNumbers(); |
| 160 | if(typeof recomputeTotals==='function')recomputeTotals(); |
| 161 | localStorage.removeItem(DRAFT_KEY); |
| 162 | }catch(e){console.error('draft restore failed',e);} |
| 163 | }; |
| 164 | |
| 165 | // اتصال بدون دستزدن به کد اصلی enterApp/handleLogout |
| 166 | const oldEnterApp=window.enterApp; |
| 167 | window.enterApp=async function(authUser){ |
| 168 | await oldEnterApp(authUser); |
| 169 | if(typeof currentUser!=='undefined'&¤tUser){ |
| 170 | window.startIdleWatcher(); |
| 171 | window.offerInvoiceDraftRestoreIfAny(); |
| 172 | } |
| 173 | }; |
| 174 | const oldHandleLogout=window.handleLogout; |
| 175 | window.handleLogout=async function(){ |
| 176 | window.stopIdleWatcher(); |
| 177 | return oldHandleLogout(); |
| 178 | }; |
| 179 | })(); |
| 180 | |
| 181 | // ============== گزارشات مالی ============== |
| 182 | function toEnglishDigits(str){ |
| 183 | if(str===null||str===undefined)return ''; |
| 184 | const map={'۰':'0','۱':'1','۲':'2','۳':'3','۴':'4','۵':'5','۶':'6','۷':'7','۸':'8','۹':'9'}; |
| 185 | return String(str).replace(/[۰-۹]/g,d=>map[d]); |
| 186 | } |
| 187 | const persianMonthNames=['فروردین','اردیبهشت','خرداد','تیر','مرداد','شهریور','مهر','آبان','آذر','دی','بهمن','اسفند']; |
| 188 | function populateReportYearSelect(years){ |
| 189 | const sel=document.getElementById('report-year-select'); |
| 190 | if(!sel)return; |
| 191 | const current=sel.value; |
| 192 | sel.innerHTML=years.map(y=>`<option value="${y}">سال ${toPersianDigits(y)}</option>`).join(''); |
| 193 | if(current&&years.includes(parseInt(current)))sel.value=current; |
| 194 | } |
| 195 | function renderFinancialReports(){ |
| 196 | const cur=(typeof getCurrencyLabel==='function')?getCurrencyLabel():'ریال'; |
| 197 | const invoices=(typeof getMyInvoices==='function')?getMyInvoices():[]; |
| 198 | const parsed=invoices.map(inv=>{ |
| 199 | const d=toEnglishDigits(inv.date||''); |
| 200 | const parts=d.split('/'); |
| 201 | if(parts.length<2)return null; |
| 202 | const y=parseInt(parts[0]),m=parseInt(parts[1]); |
| 203 | if(!y||!m)return null; |
| 204 | return {year:y,month:m,inv}; |
| 205 | }).filter(Boolean); |
| 206 | |
| 207 | let years=[...new Set(parsed.map(p=>p.year))].sort((a,b)=>b-a); |
| 208 | if(years.length===0){ |
| 209 | const fallback=parseInt(toEnglishDigits((typeof getJalaliNumeric==='function'?getJalaliNumeric():'').split('/')[0]))||1404; |
| 210 | years=[fallback]; |
| 211 | } |
| 212 | populateReportYearSelect(years); |
| 213 | const sel=document.getElementById('report-year-select'); |
| 214 | const selectedYear=(sel&&sel.value)?parseInt(sel.value):years[0]; |
| 215 | |
| 216 | const yearInvoices=parsed.filter(p=>p.year===selectedYear); |
| 217 | const monthTotals=Array(12).fill(0); |
| 218 | yearInvoices.forEach(p=>{ if(p.month>=1&&p.month<=12) monthTotals[p.month-1]+=(p.inv.grandTotal||0); }); |
| 219 | const yearTotal=monthTotals.reduce((a,b)=>a+b,0); |
| 220 | const avg=yearTotal/12; |
| 221 | const maxVal=Math.max(...monthTotals,1); |
| 222 | const maxIdx=monthTotals.indexOf(maxVal); |
| 223 | |
| 224 | const setTxt=(id,txt)=>{const el=document.getElementById(id);if(el)el.innerText=txt;}; |
| 225 | setTxt('rep-year-total',yearTotal.toLocaleString('fa-IR')+' '+cur); |
| 226 | setTxt('rep-year-avg',Math.round(avg).toLocaleString('fa-IR')+' '+cur); |
| 227 | setTxt('rep-best-month',monthTotals[maxIdx]>0?persianMonthNames[maxIdx]:'—'); |
| 228 | setTxt('rep-invoice-count',yearInvoices.length.toLocaleString('fa-IR')); |
| 229 | |
| 230 | const chartEl=document.getElementById('report-monthly-chart'); |
| 231 | if(chartEl){ |
| 232 | chartEl.innerHTML=monthTotals.map((v,i)=>{ |
| 233 | const h=Math.max(4,Math.round((v/maxVal)*130)); |
| 234 | return `<div class="report-bar-col"> |
| 235 | <div class="report-bar-value">${v>0?(v/1000000).toLocaleString('fa-IR',{maximumFractionDigits:1})+'M':''}</div> |
| 236 | <div class="report-bar" style="height:${h}px"></div> |
| 237 | <div class="report-bar-label">${persianMonthNames[i].slice(0,3)}</div> |
| 238 | </div>`; |
| 239 | }).join(''); |
| 240 | } |
| 241 | |
| 242 | const byCustomer={}; |
| 243 | yearInvoices.forEach(p=>{ |
| 244 | const key=p.inv.contactId||p.inv.contactName||'—'; |
| 245 | if(!byCustomer[key])byCustomer[key]={id:p.inv.contactId||'',name:p.inv.contactName||'—',count:0,sum:0}; |
| 246 | byCustomer[key].count++; |
| 247 | byCustomer[key].sum+=(p.inv.grandTotal||0); |
| 248 | }); |
| 249 | const topList=Object.values(byCustomer).sort((a,b)=>b.sum-a.sum).slice(0,10); |
| 250 | const tbody=document.getElementById('report-top-customers'); |
| 251 | if(tbody){ |
| 252 | if(topList.length===0){ |
| 253 | tbody.innerHTML='<tr><td colspan="3" style="text-align:center;color:var(--text-muted);padding:20px">دادهای برای نمایش وجود ندارد.</td></tr>'; |
| 254 | }else{ |
| 255 | tbody.innerHTML=topList.map(c=>`<tr data-contact-id="${typeof esc==='function'?esc(c.id):c.id}"><td>${(typeof esc==='function'?esc(c.name):c.name)}</td><td>${c.count.toLocaleString('fa-IR')}</td><td>${c.sum.toLocaleString('fa-IR')}</td></tr>`).join(''); |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | let formalCount=0,formalSum=0,informalCount=0,informalSum=0; |
| 260 | yearInvoices.forEach(p=>{ |
| 261 | if(p.inv.kind==='formal'){formalCount++;formalSum+=(p.inv.grandTotal||0);} |
| 262 | else{informalCount++;informalSum+=(p.inv.grandTotal||0);} |
| 263 | }); |
| 264 | setTxt('rep-formal-count',formalCount.toLocaleString('fa-IR')); |
| 265 | setTxt('rep-formal-sum',formalSum.toLocaleString('fa-IR')+' '+cur); |
| 266 | setTxt('rep-informal-count',informalCount.toLocaleString('fa-IR')); |
| 267 | setTxt('rep-informal-sum',informalSum.toLocaleString('fa-IR')+' '+cur); |
| 268 | } |
| 269 | |
| 270 | // ============== تغییر/تعیین رمز عبور از داخل تنظیمات (برای کاربران گوگل هم کار میکند) ============== |
| 271 | async function changeAccountPassword(){ |
| 272 | const p1=document.getElementById('acct-newpass').value; |
| 273 | const p2=document.getElementById('acct-newpass2').value; |
| 274 | if(typeof isStrongPassword==='function'?!isStrongPassword(p1):p1.length<8){alert('رمز عبور باید حداقل ۸ کاراکتر و شامل حداقل یک حرف و یک عدد باشد.');return;} |
| 275 | if(p1!==p2){alert('تکرار رمز عبور با رمز اصلی یکی نیست.');return;} |
| 276 | try{ |
| 277 | const {error}=await sb.auth.updateUser({password:p1,data:{has_password:true}}); |
| 278 | if(error)throw error; |
| 279 | document.getElementById('acct-newpass').value=''; |
| 280 | document.getElementById('acct-newpass2').value=''; |
| 281 | alert('رمز عبور با موفقیت ذخیره شد. دفعات بعد میتوانید با ایمیل و همین رمز هم وارد شوید.'); |
| 282 | }catch(err){ |
| 283 | alert(typeof authMsg==='function'?authMsg(err):(err.message||'خطا در ذخیره رمز عبور.')); |
| 284 | } |
| 285 | } |