سامانه صدور فاکتور و حسابداری
main
audit-remediation-wave3-4-20261002
audit-remediation-wave3-verify-20261002
audit-remediation-wave4-20261002
audit-remediation-wave4b-20261002
audit-remediation-wave5a-identity-20261002
audit-remediation-wave5b-offboarding-20261002
audit-remediation-wave5c-authorization-20261002
audit-security-intent-review-20261002
audit/finora-financial-core-20261115
audit/finora-master-prompt-phase0-20261016
audit/finora-stage3-legacy-source-readonly-20261023
audit/full-controls-20261030
audit/owner-live-state-reconcile-20261012
audit/owner-review-20261007
audit/phase1-live-permissions-readonly-20261013
audit/reconcile-live-state-20261006
audit/reconcile-state-20261002
audit/wp0-hardening-baseline-20261102
branding-login-favicon-20261002
c8-workflow-task1
c8-workflow-task2
c8-workflow-task3
chore/wave0-pages-gate-closeout
claude-code-plugins-setup
design/finora-c01-authoritative-source-draft-20261124
docs-wave4b-verified-20261002
docs/active-company-invoice-release-evidence-20261014
docs/agent-operating-model-20261114
docs/chart-taxpayer-release-evidence-20261004
docs/cloud-only-agent-orchestration-20261115
docs/confirm-finora-product-charter-20261115
docs/continuation-20261030
docs/d4a-verified
docs/external-work-review-20261121
docs/finora-audit-continuity-20261014
docs/finora-backup-merge-evidence-20261014
docs/finora-ci-reconciliation-20261122
docs/finora-codex-master-prompt
docs/finora-eight-phase-plan-20261011
docs/finora-f002-live-buyer-filter-verified-20261015
docs/finora-license-race-release-evidence-20261014
docs/finora-license-rollout-acceptance-20261015
docs/finora-phase0-repeat-and-pages-nav-verified-20261015
docs/finora-phase0-repeat-evidence-20261015
docs/finora-selectors-release-and-fixture-qa-20261015
docs/finora-stagea-pr240-ci-triage-20261123
docs/finora-test-license-live-pass-20261015
docs/finora-v2-m01-coverage-20261124
docs/handoff-charter-v2-20261124
docs/invoice-product-search-release-20261011
docs/invoice-workspace-release-20261007
docs/phase-status-20261031
docs/phase0-acceptance-release-evidence-20261012
docs/phase0-admin-provision-release-evidence-20261012
docs/phase0-core-bundle-owner-login-open-20261013
docs/phase0-duplicate-js-release-20261016
docs/phase0-f001-auth-rest-shared-timeout-20261013
docs/phase0-f001-owner-login-observed-20261013
docs/phase0-f001-second-device-fail-40s-20261013
docs/phase0-f003-release-verification-20261011
docs/phase0-f004-print-release-evidence-20261012
docs/phase0-f004-watermark-release-evidence-20261012
docs/phase0-f005-large-selector-release-20261012
docs/phase0-f005-release-evidence-20261012
docs/phase0-f006-dark-release-evidence-20261012
docs/phase0-f008-final-pr-closure-evidence-20261012
docs/phase0-f008-reconcile-stale-prs-20261012
docs/phase0-f107-production-evidence-20261012
docs/phase0-kavenegar-otp-preflight-release-20261012
docs/phase0-login-release-evidence-20261012
docs/phase0-login-rest-bootstrap-stage-release-20261012
docs/phase0-owner-app-assets-bundle-release-20261013
docs/phase0-owner-login-csp-release-20261012
docs/phase0-reconcile-postmerge-evidence-20261012
docs/phase0-site-probe-release-evidence-20261012
docs/phase0-startup-release-evidence-20261012
docs/phase3-treasury-release-evidence-20261014
docs/pilot-posted-correction-release-evidence-20261014
docs/pilot-purchase-correction-release-evidence-20261014
docs/print-persian-release-verification-20261011
docs/qa-ci-triage-218-20261122
docs/real-account-qa-20261030
docs/release-state-20261007
docs/seamless-amendment-release-20261014
docs/seamless-document-correction-release-20261014
docs/settings-login-release-20261025
docs/stripe-qa-deployment-evidence-20261011
docs/ux-f2-release-evidence-20261011
docs/ux-f2-release-verification-20261011
docs/wave0-closeout
docs/wave2-closeout
exec-phase1-architecture
exec-phase1-implementation
exec-phase1-qa
exec-phase1-security-release
exec-phase1-ux
feat/accounting-document-draft-approval-20261011
feat/accounting-document-release-candidate-20261011
feat/active-company-strict-isolation-20261014
feat/admin-provisioning-reconciled-20261011
feat/admin-secure-user-provisioning-20261011
feat/admin-user-provisioning-merged-20261011
feat/d4a-request-work-queue
feat/document-lifecycle-atf-20261118
feat/document-lifecycle-temp-permanent-atef
feat/draft-first-attachment-lifecycle-216
feat/finora-offline-encrypted-backup-20261014
feat/finora-phase-a-navigation-20261023
feat/finora-stripe-sandbox-edge-gate
feat/immutable-attachment-temporary-vouchers
feat/iran-accounting-design-audit
feat/journal-document-lifecycle-20261118
feat/journal-rpc-repository-adapter-20261117
feat/office-c7-fulltext-ocr-provenance
feat/password-recovery-admin-reset-20261025
feat/pilot-expense-income-inplace-amendment-20261014
feat/pilot-journal-invoice-correction-20261014
feat/pilot-purchase-correction-20261014
feat/pilot-treasury-unallocated-correction-20261014
feat/retain-document-editor-after-save-20261014
feat/seamless-financial-document-correction-20261014
feat/slice-b-tenant-rbac
feat/stripe-sandbox-invoice-probe
feature/accounting-core-p0
feature/accounting-product-guidance
feature/admin-identity-phone-auth
feature/commercial-rnd
feature/finora-phase1a-supabase-cli-20261016
feature/finora-stage2-manual-canary-20261017
feature/finora-stage3-commercial-payload-20261023
feature/finora-stage3-enforce-invoice-rpc-20261023
feature/finora-stage3-enforce-purchase-red-20261023
feature/invoice-workspace-cleanup
feature/phase0-kavenegar-otp-preflight-20261012
feature/ux-commerce-settings-r2
fix-shell-scroll-live-cache-20261002
fix-shell-scrollbar-explicit-ownership-20261002
fix-shell-scrollbar-ownership-20261002
fix-shell-scrollbar-right-edge-20261002
fix/about-bug-report-20261114
fix/active-company-invoice-scope-20261014
fix/active-company-isolation-reconcile-20261014
fix/admin-central-password-reset-20261028
fix/auth-network-diagnostics
fix/chart-taxpayer-reference-20261003
fix/combobox-enter-reliability
fix/combobox-live-search
fix/combobox-production-cache
fix/combobox-release-asset-v2
fix/company-edit-action-20261028
fix/company-edit-pilot-delete-20261014
fix/company-form-action-state-20261014
fix/company-form-action-state-rebased-20261014
fix/contact-operational-balance-20261111
fix/dark-theme-contrast
fix/financial-lifecycle-recovery-20261124
fix/finora-accounting-test-organization-readiness-20261015
fix/finora-b01-safe-org-switch-20261124
fix/finora-b02-sync-recovery-20261124
fix/finora-b03-conflict-review-20261124
fix/finora-org-license-bootstrap-race-20261014
fix/finora-stage3-posted-source-immutable-20261023
fix/finora-v2-b03-r2-qa-20261124
fix/finora-v2-b03-r3-readonly-20261124
fix/g01-asof-financial-position-20261128
fix/invoice-product-search-rehydrate-20261011
fix/invoice-search-cache-bust
fix/issue229-linked-draft-status-20261122
fix/login-assets-retry-20261014
fix/login-inert-startup-20261110
fix/login-member-access-20261101
fix/login-resilience-20261017
fix/login-short-viewport-20261028
fix/login-startup-readiness-20261024
fix/navigation-utilities-placement-20261105
fix/office-c7-source-ref-binding
fix/office-c7-source-ref-binding-v2
fix/owner-login-network-20261026
fix/password-recovery-invalid-cancel-20261026
fix/payment-amount-format-20261111
fix/phase0-admin-provision-seat-bootstrap-20261012
fix/phase0-auth-bundled-assets-for-unstable-isp-20261013
fix/phase0-auth-handler-binding-stalled-session-20261012
fix/phase0-login-context-stage-visibility-20261012
fix/phase0-login-single-local-bundle-20261013
fix/phase0-login-site-probe-clarity-20261012
fix/phase0-login-ui-ready-20261012
fix/phase0-modal-dashboard-drill-20261011
fix/phase0-pages-blocking-core-bundles-20261013
fix/phase0-print-no-draft-watermark-20261012
fix/phase0-startup-parallel-asset-load-20261012
fix/phase3-behavioral-verification
fix/preserve-pending-edits-20261121
fix/print-persian-digit-consistency-20261011
fix/recovery-login-startup-20261027
fix/report-opening-balance-release-20261130
fix/settings-checkbox-persistence-20261024
fix/taxpayer-arithmetic-20261004
fix/ux-keyboard-search-f2-20261011
fix/wave2-request-input-integrity
hardening/c01-source-draft-20261129
hardening/global-draft-conversion-20261113
hardening/wp1-ledger-integrity-20261102
integration/finora-execution-20261124
integration/issue229-ui-qa-20261122
integration/wp1-ledger-core-20261115
integration/wp2-manual-journal-rpc-20261116
main
ops-heartbeat-v2-20261002
ops-progress-heartbeat-rule-20261002
ops/wave4-production-20261003
plan/financial-core-phase1-approval-20261016
qa/attachment-allocator-two-session-20261122
qa/draft-first-save-red-evidence-20261122
qa/finora-autopost-retry-identity-red-20261122
qa/finora-identity-rpc-security-tripwire-20261122
qa/finora-issue223-manual-kardex-browser-red-20261123
qa/finora-issue223-stock-real-jwt-20261123
qa/finora-issue238-inventory-count-browser-red-20261123
qa/finora-issue238-save-browser-red-20261122
qa/finora-login-cors-header-preflight-20261025
qa/finora-phase0-saved-session-repeat-20261015
qa/finora-phase5-posted-insert-jwt-red-20261123
qa/finora-stage3-ui-jwt-autopost-20261023
qa/finora-v2-g01-report-reconciliation-20261125
qa/free-supabase-local-wp2-20261116
qa/issue229-approval-boundary-jwt-20261122
qa/issue229-sale-save-linked-draft-red-20261122
qa/phase0-acceptance-start-20261012
qa/phase0-f005-account-project-contract-stress-20261012
qa/phase0-f005-selector-stress-20261012
qa/phase0-f006-dark-contrast-20261012
qa/post-wave4-verification-20261003
qa/posted-source-immutable-jwt-20261122
qa/pr219-wp1-disposable-dburl-proof-20261123
qa/purchase-source-jwt-20261122
qa/real-settings-acceptance-20261025
qa/recovery-mail-acceptance-20261026
qa/source-autopost-jwt-atomicity-20261122
qa/wave0-negative-gate-proof
qa/wp2-auth-tenant-e2e-20261117
qa/wp2-authorized-journal-write-20261122
qa/wp2-financial-paths-reconciliation-20261122
qa/wp3-financial-tenant-isolation-20261117
remediation/wave0-liveqa-wave1
remediation/wave2-request-integrity
staging/finora-stage22-free-20261022
state-scroll-verified-20261002
state-wave4b-production-20261002
state-wave5a-production-20261002
test/finora-accounting-boot-readiness-20261015
test/finora-f0-02-production-selectors-20261015
test/finora-pages-commerce-event-wiring-20261015
test/finora-pages-invoice-selectors-readonly-20261015
test/finora-stage3-jwt-source-post-20261023
test/phase0-invoice-fixture-bootstrap-20261016
test/phase0-invoice-persistence-20261011
test/phase0-pages-delayed-dispatcher-20261016
ux-scroll-ownership-20261002
work/finora-stage3-enforce-purchase-green-20261023
work/finora-stage3-enforce-sale-green-20261023
work/finora-stage3-payload-green-20261023
| 1 | let editingAccountId=''; |
| 2 | /* Phase 2: accounting foundation — safety-first master data */ |
| 3 | const AF_LEVELS={gl:'کل',subsidiary:'معین',detail:'تفصیلی'},AF_NATURE={debit:'بدهکار',credit:'بستانکار',both:'دوماهیتی'}; |
| 4 | const AF_COMPANY_TYPES={ |
| 5 | trading:'بازرگانی',service:'خدماتی',manufacturing:'تولیدی',contracting:'پیمانکاری', |
| 6 | retail:'فروشگاهی',distribution:'پخش',nonprofit:'غیرانتفاعی',professional:'خدمات حرفهای' |
| 7 | }; |
| 8 | const AF_SYSTEM_ROLES={cash_default:'نقد/بانک پیشفرض',receivable_control:'دریافتنی تجاری',payable_control:'پرداختنی تجاری',revenue_default:'درآمد/فروش پیشفرض',purchase_default:'خرید/بهای تمامشده پیشفرض',expense_default:'هزینه پیشفرض',other_income_default:'سایر درآمد پیشفرض',vat_payable:'مالیات پرداختنی',vat_recoverable:'مالیات دریافتنی'}; |
| 9 | // Iran-first starter chart: an editable accelerator, not a statutory universal chart. Iranian accounting standards govern recognition/presentation, not one mandatory account-number catalogue. |
| 10 | function afDefaultSystemRole(code,type){const revenue={trading:'4107',service:'4106',retail:'4102',distribution:'4103',nonprofit:'4104',professional:'4105'}[type]||'4101',purchase=type==='trading'?'5102':'5101';if(code===revenue)return'revenue_default';if(code===purchase)return'purchase_default';return({'1101':'cash_default','1102':'receivable_control','1108':'vat_recoverable','2101':'payable_control','2102':'vat_payable','6103':'expense_default','4201':'other_income_default'})[code]||''} |
| 11 | const AF_BASE_ACCOUNTS=[ |
| 12 | ['1','داراییها','gl','debit',''],['11','داراییهای جاری','subsidiary','debit','1'],['1101','صندوق و بانک','detail','debit','11'],['1102','حسابهای دریافتنی','detail','debit','11'],['1103','موجودی کالا و مواد','detail','debit','11'],['1104','پیشپرداختها','detail','debit','11'],['1108','مالیات و عوارض دریافتنی','detail','debit','11'],['1109','تنخواهگردان','detail','debit','11'],['1110','صندوق ریالی','detail','debit','11'],['1111','صندوق ارزی','detail','debit','11'],['1112','حسابهای دریافتنی فیمابین','detail','debit','11'], |
| 13 | ['2','بدهیها','gl','credit',''],['21','بدهیهای جاری','subsidiary','credit','2'],['2101','حسابهای پرداختنی','detail','credit','21'],['2102','مالیات و عوارض پرداختنی','detail','credit','21'],['2103','سپردهها و کسورات پرداختنی','detail','credit','21'],['2106','حقوق و مزایای پرداختنی','detail','credit','21'],['2107','حق بیمه پرداختنی','detail','credit','21'],['2108','مالیات حقوق پرداختنی','detail','credit','21'],['2109','ذخیره مرخصی استفادهنشده','detail','credit','21'],['2110','حسابهای پرداختنی فیمابین','detail','credit','21'],['22','بدهیهای غیرجاری','subsidiary','credit','2'],['2201','ذخیره مزایای پایان خدمت کارکنان','detail','credit','22'], |
| 14 | ['3','حقوق مالکانه','gl','credit',''],['31','سرمایه و اندوختهها','subsidiary','credit','3'],['3101','سرمایه','detail','credit','31'],['3102','سود و زیان انباشته','detail','credit','31'], |
| 15 | ['4','درآمدها','gl','credit',''],['41','درآمد عملیاتی','subsidiary','credit','4'],['4101','فروش / درآمد خدمات','detail','credit','41'],['42','سایر درآمدها','subsidiary','credit','4'],['4201','سایر درآمدهای عملیاتی و غیرعملیاتی','detail','credit','42'], |
| 16 | ['5','بهای تمامشده','gl','debit',''],['51','بهای تمامشده عملیات','subsidiary','debit','5'],['5101','بهای تمامشده کالای فروشرفته / خدمات','detail','debit','51'], |
| 17 | ['6','هزینهها','gl','debit',''],['61','هزینههای اداری و عمومی','subsidiary','debit','6'],['6101','حقوق و دستمزد','detail','debit','61'],['6102','اجاره و خدمات محل','detail','debit','61'],['6103','هزینههای عمومی','detail','debit','61'],['6110','هزینه بیمه سهم کارفرما','detail','debit','61'],['6111','هزینه مزایای پایان خدمت کارکنان','detail','debit','61'],['6112','هزینه مرخصی استحقاقی','detail','debit','61'] |
| 18 | ]; |
| 19 | const AF_SPECIAL_ACCOUNTS={ |
| 20 | manufacturing:[['52','تولید و ساخت','subsidiary','debit','5'],['5201','مواد مستقیم مصرفی','detail','debit','52'],['5202','دستمزد مستقیم','detail','debit','52'],['5203','سربار تولید','detail','debit','52'],['5205','انحرافات جذب سربار','detail','debit','52'],['1113','کالای در جریان ساخت','detail','debit','11']], |
| 21 | contracting:[['43','درآمد پیمان','subsidiary','credit','4'],['4301','درآمد صورتوضعیت پیمان','detail','credit','43'],['53','هزینه پیمان','subsidiary','debit','5'],['5301','هزینه مستقیم پیمان','detail','debit','53'],['5302','پیمانکاران جزء','detail','debit','53'],['1105','مطالبات حسن انجام کار','detail','debit','11'],['1106','مطالبات کسور بیمه پیمان','detail','debit','11'],['1107','مطالبات مالیات تکلیفی پیمان','detail','debit','11'],['2104','سپرده حسن انجام کار','detail','credit','21'],['2105','پیشدریافت و علیالحساب پیمان','detail','credit','21'],['6109','جرایم و کسورات غیرقابل وصول پیمان','detail','debit','61']], |
| 22 | retail:[['4102','فروش خردهفروشی','detail','credit','41'],['6104','تخفیفات و پروموشن','detail','debit','61']], |
| 23 | distribution:[['4103','فروش پخش','detail','credit','41'],['6105','هزینه توزیع و حمل','detail','debit','61']], |
| 24 | nonprofit:[['4104','کمکها و درآمدهای غیرانتفاعی','detail','credit','41'],['6106','هزینه برنامهها و مأموریت','detail','debit','61']], |
| 25 | professional:[['4105','درآمد خدمات حرفهای','detail','credit','41'],['6107','حقالزحمه همکاران و متخصصان','detail','debit','61']], |
| 26 | service:[['4106','درآمد خدمات','detail','credit','41'],['6108','هزینه ارائه خدمات','detail','debit','61']], |
| 27 | trading:[['4107','فروش کالا','detail','credit','41'],['5102','خرید و بهای کالای فروشرفته','detail','debit','51']] |
| 28 | }; |
| 29 | // Finora chart v4: additive operational coverage; numbers are local conventions, not statutory codes. |
| 30 | // Contra accounts retain the underlying account type, independently of their normal balance. |
| 31 | const AF_CHART_ADDITIONS=[ |
| 32 | ['12','داراییهای غیرجاری','subsidiary','debit','1'], |
| 33 | ['1201','زمین','detail','debit','12'],['1202','ساختمان','detail','debit','12'],['1203','ماشینآلات و تجهیزات','detail','debit','12'],['1204','وسائط نقلیه','detail','debit','12'],['1205','اثاثه و منصوبات','detail','debit','12'],['1206','داراییهای در جریان تکمیل','detail','debit','12'],['1207','داراییهای نامشهود','detail','debit','12'],['1208','سرمایهگذاریهای بلندمدت','detail','debit','12'],['1209','سپردههای بلندمدت','detail','debit','12'],['1210','دریافتنیهای بلندمدت','detail','debit','12'],['1291','استهلاک انباشته داراییهای مشهود','detail','credit','12'],['1292','استهلاک انباشته داراییهای نامشهود','detail','credit','12'],['1293','کاهش ارزش داراییهای غیرجاری','detail','credit','12'], |
| 34 | ['1114','اسناد دریافتنی','detail','debit','11'],['1115','اسناد در جریان وصول','detail','debit','11'],['1116','سرمایهگذاریهای کوتاهمدت','detail','debit','11'],['1117','سایر دریافتنیها','detail','debit','11'],['1118','سپردههای کوتاهمدت','detail','debit','11'],['1119','پیشپرداخت مالیات عملکرد','detail','debit','11'],['1120','مساعده و وام کوتاهمدت کارکنان','detail','debit','11'],['1191','ذخیره مطالبات مشکوکالوصول','detail','credit','11'],['1192','کاهش ارزش موجودی مواد و کالا','detail','credit','11'], |
| 35 | ['2111','اسناد پرداختنی','detail','credit','21'],['2112','تسهیلات مالی کوتاهمدت','detail','credit','21'],['2113','حصه جاری تسهیلات مالی بلندمدت','detail','credit','21'],['2114','مالیات عملکرد پرداختنی','detail','credit','21'],['2115','سود سهام پرداختنی','detail','credit','21'],['2116','هزینههای پرداختنی','detail','credit','21'],['2117','پیشدریافت از مشتریان','detail','credit','21'],['2118','سایر پرداختنیها','detail','credit','21'],['2202','تسهیلات مالی بلندمدت','detail','credit','22'],['2203','اسناد پرداختنی بلندمدت','detail','credit','22'],['2204','سپردههای دریافتی بلندمدت','detail','credit','22'], |
| 36 | ['3103','اندوخته قانونی','detail','credit','31'],['3104','سایر اندوختهها','detail','credit','31'],['3105','مازاد تجدید ارزیابی','detail','credit','31'],['3106','صرف سهام','detail','credit','31'], |
| 37 | ['4191','برگشت از فروش و تخفیفات فروش','detail','debit','41'],['4202','درآمد سپرده و سرمایهگذاری','detail','credit','42'],['4203','سود فروش داراییهای غیرجاری','detail','credit','42'],['4204','سود تسعیر ارز','detail','credit','42'], |
| 38 | ['6113','هزینه استهلاک داراییهای مشهود','detail','debit','61'],['6114','هزینه استهلاک داراییهای نامشهود','detail','debit','61'],['6115','هزینه مطالبات مشکوکالوصول','detail','debit','61'],['6116','تعمیر و نگهداری','detail','debit','61'],['6117','آب، برق و گاز','detail','debit','61'],['6118','ارتباطات و اینترنت','detail','debit','61'],['6119','خدمات حرفهای و مشاوره','detail','debit','61'],['6120','بیمه عمومی','detail','debit','61'],['6121','زیان کاهش ارزش داراییها','detail','debit','61'],['6122','زیان فروش داراییهای غیرجاری','detail','debit','61'], |
| 39 | ['62','هزینههای فروش و توزیع','subsidiary','debit','6'],['6201','حمل و توزیع فروش','detail','debit','62'],['6202','بازاریابی و تبلیغات','detail','debit','62'],['6203','پورسانت فروش','detail','debit','62'], |
| 40 | ['63','هزینههای مالی','subsidiary','debit','6'],['6301','سود و کارمزد تسهیلات مالی','detail','debit','63'],['6302','کارمزد خدمات بانکی','detail','debit','63'],['6303','زیان تسعیر ارز','detail','debit','63'], |
| 41 | ['64','هزینه مالیات بر درآمد','subsidiary','debit','6'],['6401','هزینه مالیات عملکرد','detail','debit','64'] |
| 42 | ]; |
| 43 | function afChartUpgradePlan(companyId=afCompanyId()){ |
| 44 | const fail=message=>({ok:false,message,additions:[]}),owner=currentUser?.id,company=getMyCompanies().find(c=>c.id===companyId),type=company?.accountingTemplate?.type; |
| 45 | if(!owner||!companyId||companyId!==afCompanyId()||!company||!Object.prototype.hasOwnProperty.call(AF_COMPANY_TYPES,type)||company.accountingTemplate.source==='excel')return fail('تکمیل کدینگ فقط برای شرکت فعال با قالب پیشنهادی فینورا در دسترس است؛ کدینگ اختصاصی باید جداگانه بررسی شود.'); |
| 46 | if((datastore.accounts||[]).some(a=>a.ownerUserId===owner&&!a.companyId))return fail('حساب قدیمی بدون شرکت مشخص وجود دارد؛ ابتدا انتساب شرکت بررسی شود.'); |
| 47 | const rows=(datastore.accounts||[]).filter(a=>a.ownerUserId===owner&&a.companyId===companyId),byCode=new Map(),ids=new Set(); |
| 48 | if(!rows.length)return fail('ابتدا قالب کدینگ شرکت را ایجاد کنید.'); |
| 49 | for(const a of rows){if(byCode.has(a.code)||ids.has(a.id)||!a.id)return fail('کد یا شناسه تکراری در کدینگ شرکت وجود دارد.');byCode.set(a.code,a);ids.add(a.id)} |
| 50 | const specs=new Map([...AF_BASE_ACCOUNTS,...(AF_SPECIAL_ACCOUNTS[type]||[]),...AF_CHART_ADDITIONS].map(r=>[r[0],r])),newCodes=new Set(AF_CHART_ADDITIONS.map(r=>r[0])),validated=new Set(),visiting=new Set(),additions=[]; |
| 51 | function validate(code){ |
| 52 | if(validated.has(code))return true;if(visiting.has(code))return false;visiting.add(code); |
| 53 | const spec=specs.get(code);if(!spec)return false;const [,title,level,normalBalance,parentCode]=spec; |
| 54 | if(parentCode&&!validate(parentCode))return false; |
| 55 | const a=byCode.get(code); |
| 56 | if(a){const p=parentCode?byCode.get(parentCode):null;if(a.title!==title||a.level!==level||a.normalBalance!==normalBalance||(a.accountType||afAccountTypeForCode(code))!==afAccountTypeForCode(code)||a.active===false||a.postingAllowed!==(level==='detail')||(a.parentId||'')!==(p?.id||'')||(parentCode&&!p))return false;} |
| 57 | else if(!newCodes.has(code))return false; |
| 58 | visiting.delete(code);validated.add(code);return true; |
| 59 | } |
| 60 | for(const spec of AF_CHART_ADDITIONS){if(!validate(spec[0]))return fail('تعارض کد یا ساختار حساب '+spec[0]+'؛ ابتدا حساب و والدهای آن بررسی شوند. هیچ حسابی اضافه نشد.');if(!byCode.has(spec[0]))additions.push(spec)} |
| 61 | return {ok:true,ownerUserId:owner,companyId,type,additions,snapshot:JSON.stringify({rows,template:company.accountingTemplate}),message:additions.length?'حسابهای زیر به کدینگ شرکت افزوده میشوند.':'کدینگ پیشنهادی شرکت کامل است.'}; |
| 62 | } |
| 63 | function afApplyChartUpgrade(preview){ |
| 64 | if(!requireWrite())return {ok:false,message:'اجازه تغییر کدینگ وجود ندارد.'}; |
| 65 | const plan=afChartUpgradePlan(); |
| 66 | if(!plan.ok)return plan; |
| 67 | if(!preview?.ok||preview.ownerUserId!==plan.ownerUserId||preview.companyId!==plan.companyId||preview.snapshot!==plan.snapshot)return {ok:false,message:'شرکت یا کدینگ از زمان پیشنمایش تغییر کرده است؛ دوباره پیشنمایش بگیرید.'}; |
| 68 | if(!plan.additions.length)return {ok:true,added:0,message:'کدینگ پیشنهادی شرکت کامل است.'}; |
| 69 | const byCode=new Map(datastore.accounts.filter(a=>a.ownerUserId===plan.ownerUserId&&a.companyId===plan.companyId).map(a=>[a.code,a])),created=[]; |
| 70 | for(const [code,title,level,normalBalance,parentCode] of plan.additions){const a={id:afId('ACC'),ownerUserId:plan.ownerUserId,companyId:plan.companyId,code,title,level,normalBalance,parentId:byCode.get(parentCode)?.id||'',accountType:afAccountTypeForCode(code),systemRole:'',postingAllowed:level==='detail',active:true,template:plan.type,chartVersion:4};created.push(a);byCode.set(code,a)} |
| 71 | datastore.accounts.push(...created);const company=getMyCompanies().find(c=>c.id===plan.companyId);company.accountingTemplate={...company.accountingTemplate,chartVersion:4,chartUpgradedAt:new Date().toISOString()};saveDatastore(); |
| 72 | return {ok:true,added:created.length,message:created.length.toLocaleString('fa-IR')+' حساب افزوده شد؛ سوابق قبلی حفظ شدند.'}; |
| 73 | } |
| 74 | function afCompanyId(){const s=getMySettings(),c=getMyCompanies();return s.default_company_id||c[0]?.id||'';} |
| 75 | function afOwned(k){const cid=afCompanyId();return(datastore[k]||[]).filter(x=>x.ownerUserId===currentUser?.id&&(!x.companyId||x.companyId===cid));} |
| 76 | function getMyFiscalYears(){return afOwned('fiscalYears')} function getMyAccounts(){return afOwned('accounts')} |
| 77 | function getMyDimensionTypes(){return afOwned('dimensionTypes')} function getMyDimensionValues(){return afOwned('dimensionValues')} |
| 78 | function getMyAccountDimensionRules(){return afOwned('accountDimensionRules')} function getMyBranches(){return afOwned('branches')} |
| 79 | function getMyGlobalProjects(){return afOwned('projects')} |
| 80 | function afId(p){return p+'_'+Date.now().toString(36)+'_'+Math.random().toString(36).slice(2,7)} |
| 81 | function afCode(v){return String(v||'').trim().replace(/\s+/g,'-').slice(0,32)} |
| 82 | function afNextFloatingCode(slot,group=1){ |
| 83 | const s=Math.max(1,Math.min(9,Number(slot)||1)),g=Math.max(1,Math.min(9,Number(group)||1)),prefix=String(s)+String(g),used=[]; |
| 84 | Object.values(datastore||{}).forEach(rows=>(Array.isArray(rows)?rows:[]).forEach(x=>{const code=String(x.floatingCode||'');if(/^\d{8}$/.test(code)&&code.startsWith(prefix))used.push(Number(code.slice(2)))})); |
| 85 | const seq=Math.min(999999,Math.max(0,...used)+1);return prefix+String(seq).padStart(6,'0') |
| 86 | } |
| 87 | window.afNextFloatingCode=afNextFloatingCode; |
| 88 | function afAccountTypeForCode(code){return({'1':'asset','2':'liability','3':'equity','4':'revenue','5':'expense','6':'expense'})[String(code||'').charAt(0)]||'control'} |
| 89 | function afNeedCompany(){const id=afCompanyId();if(!id)alert('ابتدا یک شرکت تعریف و فعال کنید.');return id} |
| 90 | function afProjectUsed(id){return (typeof getMyContracts==='function'&&getMyContracts().some(x=>x.projectId===id))||getMyInvoices().some(x=>x.projectId===id)||getMyPurchases().some(x=>x.projectId===id||x.costCenterId===id)||getMyExpenses().some(x=>x.projectId===id)||getMyPayments().some(x=>x.projectId===id)} |
| 91 | function afResolvedValues(t){if(t.sourceEntity==='contact')return getMyContacts().map(x=>({id:x.id,title:x.name,depth:1,postable:true}));if(t.sourceEntity==='project')return getMyGlobalProjects().map(x=>({id:x.id,title:x.name,depth:1,postable:true}));if(t.sourceEntity==='branch')return getMyBranches().map(x=>({id:x.id,title:x.name,depth:1,postable:true}));if(t.sourceEntity==='contract'&&typeof getMyContracts==='function')return getMyContracts().filter(x=>x.status!=='cancelled').map(x=>({id:x.id,title:(x.number?x.number+' — ':'')+x.title,depth:1,postable:!['closed','cancelled'].includes(x.status)}));if(t.sourceEntity==='costCenter'&&typeof getMyCostCenters==='function')return getMyCostCenters().map(x=>({id:x.id,title:x.name,depth:1,postable:x.active!==false}));return getMyDimensionValues().filter(x=>x.dimensionTypeId===t.id).map(x=>({...x,postable:afDimensionValuePostable(x,t)}))} |
| 92 | function afDimensionValuePostable(v,t){return !!v&&!!t&&v.active!==false&&(v.depth||1)===Number(t.maxDepth||1)&&!getMyDimensionValues().some(x=>x.dimensionTypeId===t.id&&x.parentId===v.id&&x.active!==false)} |
| 93 | function afDimensionHasValues(typeId){return getMyDimensionValues().some(x=>x.dimensionTypeId===typeId)} |
| 94 | function afDimensionValueReferenced(id){return Object.keys(datastore).some(k=>k!=='dimensionValues'&&(datastore[k]||[]).some(r=>{try{return JSON.stringify(r).includes('"'+id+'"')}catch(_){return false}}))} |
| 95 | function afEnsureContractingPhase4Accounts(){ |
| 96 | if(!currentUser||!afCompanyId())return;const company=getMyCompanies().find(x=>x.id===afCompanyId());if(company?.accountingTemplate?.type!=='contracting'||Number(company.accountingTemplate.phase4Version||0)>=1)return; |
| 97 | const specs=[['1106','مطالبات کسور بیمه پیمان','11','debit'],['1107','مطالبات مالیات تکلیفی پیمان','11','debit'],['2105','پیشدریافت و علیالحساب پیمان','21','credit'],['6109','جرایم و کسورات غیرقابل وصول پیمان','61','debit']];let changed=false; |
| 98 | specs.forEach(([code,title,parentCode,normalBalance])=>{if(getMyAccounts().some(x=>x.code===code))return;const parent=getMyAccounts().find(x=>x.code===parentCode);if(!parent)return;datastore.accounts.push({id:afId('ACC'),ownerUserId:currentUser.id,companyId:afCompanyId(),code,title,level:'detail',parentId:parent.id,normalBalance,postingAllowed:true,active:true,template:'contracting'});changed=true}); |
| 99 | company.accountingTemplate.phase4Version=1;company.accountingTemplate.phase4MigratedAt=new Date().toISOString();if(changed)saveDatastore();else saveDatastore(); |
| 100 | } |
| 101 | function afEnsureIranComplianceTemplateV3(){ |
| 102 | if(!currentUser||!afCompanyId())return;const company=getMyCompanies().find(x=>x.id===afCompanyId());if(!company?.accountingTemplate||Number(company.accountingTemplate.complianceVersion||0)>=3)return; |
| 103 | const specs=[['1109','تنخواهگردان','11','debit','asset'],['1110','صندوق ریالی','11','debit','asset'],['1111','صندوق ارزی','11','debit','asset'],['1112','حسابهای دریافتنی فیمابین','11','debit','asset'],['2106','حقوق و مزایای پرداختنی','21','credit','liability'],['2107','حق بیمه پرداختنی','21','credit','liability'],['2108','مالیات حقوق پرداختنی','21','credit','liability'],['2109','ذخیره مرخصی استفادهنشده','21','credit','liability'],['2110','حسابهای پرداختنی فیمابین','21','credit','liability'],['22','بدهیهای غیرجاری','2','credit','liability'],['2201','ذخیره مزایای پایان خدمت کارکنان','22','credit','liability'],['6110','هزینه بیمه سهم کارفرما','61','debit','expense'],['6111','هزینه مزایای پایان خدمت کارکنان','61','debit','expense'],['6112','هزینه مرخصی استحقاقی','61','debit','expense']]; |
| 104 | if(company.activityType==='manufacturing')specs.push(['1113','کالای در جریان ساخت','11','debit','asset'],['5205','انحرافات جذب سربار','52','debit','expense']); |
| 105 | let changed=false;for(const [code,title,parentCode,normalBalance,accountType] of specs){if(getMyAccounts().some(x=>x.code===code))continue;const parent=getMyAccounts().find(x=>x.code===parentCode);if(!parent)continue;datastore.accounts.push({id:afId('ACC'),ownerUserId:currentUser.id,companyId:afCompanyId(),code,title,level:parentCode==='2'?'subsidiary':'detail',parentId:parent.id,normalBalance,accountType,systemRole:'',postingAllowed:parentCode!=='2',active:true,template:company.accountingTemplate.type,complianceBasis:'IR'});changed=true} |
| 106 | // Legacy manufacturing template incorrectly classified WIP 5204 under expense/cost. Never rewrite used history. |
| 107 | const legacy=getMyAccounts().find(x=>x.code==='5204'&&x.title==='کالای در جریان ساخت');if(legacy){const used=Object.keys(datastore).some(k=>!['accounts','accountDimensionRules'].includes(k)&&(datastore[k]||[]).some(r=>{try{return JSON.stringify(r).includes('"'+legacy.id+'"')}catch(_){return false}}));if(!used){legacy.active=false;legacy.postingAllowed=false;legacy.deprecatedReason='Replaced by asset account 1113 in Iran compliance template v3';changed=true}} |
| 108 | company.accountingTemplate.complianceVersion=3;company.accountingTemplate.complianceMigratedAt=new Date().toISOString();if(changed)saveDatastore();else saveDatastore(); |
| 109 | } |
| 110 | function afSeed(){ |
| 111 | if(!currentUser||!afCompanyId())return;afEnsureFloatingSlotCompatibility();afEnsureAccountingP0Compatibility();afEnsureContractingPhase4Accounts();afEnsureIranComplianceTemplateV3();let ch=false,cid=afCompanyId(); |
| 112 | if(!getMyFiscalYears().length){const y=toEnDigits(String(getJalaliNumeric()).split('/')[0]);datastore.fiscalYears.push({id:afId('FY'),ownerUserId:currentUser.id,companyId:cid,title:'سال مالی '+y,startDate:y+'/01/01',endDate:y+'/12/29',status:'open',createdAt:new Date().toISOString()});ch=true} |
| 113 | if(ch)saveDatastore(); |
| 114 | } |
| 115 | function afMigrateLegacyProjects(){ |
| 116 | if(!currentUser||!afCompanyId())return;const s=getMySettings();const key='accountingFoundationMigrationV2_'+afCompanyId();if(s[key])return;let ch=false; |
| 117 | getMyContacts().forEach(c=>(c.projects||[]).forEach(p=>{let g=datastore.projects.find(x=>x.id===p.id&&x.ownerUserId===currentUser.id);if(!g){g={id:p.id,ownerUserId:currentUser.id,companyId:afCompanyId(),code:p.id,name:p.name,parentId:'',direction:p.direction||'both',linkedContactIds:[c.id],active:true,legacy:true};datastore.projects.push(g);ch=true}else if(!(g.linkedContactIds||[]).includes(c.id)){g.linkedContactIds=[...(g.linkedContactIds||[]),c.id];ch=true}(p.subprojects||[]).forEach(z=>{let q=datastore.projects.find(x=>x.id===z.id&&x.ownerUserId===currentUser.id);if(!q){datastore.projects.push({id:z.id,ownerUserId:currentUser.id,companyId:afCompanyId(),code:z.id,name:z.name,parentId:p.id,direction:z.direction||p.direction||'both',linkedContactIds:[c.id],active:true,legacy:true});ch=true}})})); |
| 118 | s[key]={completedAt:new Date().toISOString(),mode:'copy-preserve-ids'};if(ch||!s[key])saveDatastore();else saveDatastore(); |
| 119 | } |
| 120 | function afCreateDimension(cid,code,title,sourceEntity,maxDepth=1,slot=0){ |
| 121 | const existing=getMyDimensionTypes().find(x=>x.code===code);if(existing){if(slot&&!existing.slot)existing.slot=Number(slot);return existing} |
| 122 | const d={id:afId('DIM'),ownerUserId:currentUser.id,companyId:cid,code,title,maxDepth:Number(maxDepth),slot:Number(slot)||0,depthLocked:false,leafOnlyPosting:true,active:true,sourceType:sourceEntity==='manual'?'manual':'entity-backed',sourceEntity}; |
| 123 | datastore.dimensionTypes.push(d);return d; |
| 124 | } |
| 125 | function afEnsureFloatingSlotCompatibility(){ |
| 126 | if(!currentUser||!afCompanyId())return false;const cid=afCompanyId(),company=getMyCompanies().find(x=>x.id===cid);if(!company)return false;let changed=false; |
| 127 | const defs=[['BRANCH','شعبه','branch',1],['COUNTERPARTY','طرف حساب','contact',2],['PROJECT','پروژه','project',3],['CONTRACT','قرارداد / پیمان','contract',4],['COST_CENTER','مرکز هزینه','costCenter',0]]; |
| 128 | defs.forEach(([code,title,source,slot])=>{let d=getMyDimensionTypes().find(x=>x.code===code);if(!d){d=afCreateDimension(cid,code,title,source,1,slot);changed=true}else if(slot&&Number(d.slot||0)!==slot){d.slot=slot;changed=true}}); |
| 129 | if(changed)saveDatastore();return changed; |
| 130 | } |
| 131 | function afEnsureAccountingP0Compatibility(){ |
| 132 | if(!currentUser||!afCompanyId())return false;const cid=afCompanyId(),dims=Object.fromEntries(getMyDimensionTypes().map(d=>[d.code,d])),used=id=>(datastore.journalLines||[]).some(l=>l.ownerUserId===currentUser.id&&(!l.companyId||l.companyId===cid)&&l.accountId===id);let changed=false; |
| 133 | const ensure=(a,d,app)=>{if(!a||!d)return;const existing=getMyAccountDimensionRules().find(r=>r.accountId===a.id&&r.dimensionTypeId===d.id);if(existing)return;const legacyRequired=app==='required'&&used(a.id);datastore.accountDimensionRules.push({id:afId('ADR'),ownerUserId:currentUser.id,companyId:cid,accountId:a.id,dimensionTypeId:d.id,applicability:legacyRequired?'optional':app,allowedValuesMode:'all',active:true,compatibilityMode:legacyRequired?'legacy-history-preserved':'recommended-p0'});changed=true}; |
| 134 | getMyAccounts().filter(a=>a.active!==false&&a.postingAllowed).forEach(a=>{const role=a.systemRole||'';if(['receivable_control','payable_control'].includes(role))ensure(a,dims.COUNTERPARTY,'required');if(['cash_default','receivable_control','payable_control','revenue_default','purchase_default','expense_default','other_income_default'].includes(role))ensure(a,dims.BRANCH,'optional');if(['revenue_default','purchase_default','expense_default','other_income_default'].includes(role))ensure(a,dims.PROJECT,'optional');if(['purchase_default','expense_default'].includes(role))ensure(a,dims.COST_CENTER,'optional')}); |
| 135 | if(changed)saveDatastore();return changed; |
| 136 | } |
| 137 | function afApplyTemplate(companyId,type){ |
| 138 | if(!requireWrite()||!companyId)return false;const company=getMyCompanies().find(x=>x.id===companyId);if(!company)return false; |
| 139 | if((datastore.accounts||[]).some(x=>x.ownerUserId===currentUser.id&&x.companyId===companyId)){alert('برای این شرکت کدینگ وجود دارد؛ قالب روی کدینگ موجود اعمال نشد.');return false} |
| 140 | const previous=getMySettings().default_company_id;getMySettings().default_company_id=companyId; |
| 141 | try{ |
| 142 | const rows=[...AF_BASE_ACCOUNTS,...(AF_SPECIAL_ACCOUNTS[type]||[]),...AF_CHART_ADDITIONS],byCode={}; |
| 143 | rows.forEach(r=>{const [code,title,level,normalBalance,parentCode]=r;const a={id:afId('ACC'),ownerUserId:currentUser.id,companyId,code,title,level,parentId:parentCode?(byCode[parentCode]?.id||''):'',normalBalance,accountType:afAccountTypeForCode(code),systemRole:afDefaultSystemRole(code,type),postingAllowed:level==='detail',active:true,template:type};datastore.accounts.push(a);byCode[code]=a}); |
| 144 | const branch=afCreateDimension(companyId,'BRANCH','شعبه','branch',1,1); |
| 145 | const party=afCreateDimension(companyId,'COUNTERPARTY','طرف حساب','contact',1,2); |
| 146 | const project=afCreateDimension(companyId,'PROJECT','پروژه','project',1,3); |
| 147 | const contract=afCreateDimension(companyId,'CONTRACT','قرارداد / پیمان','contract',1,4); |
| 148 | afCreateDimension(companyId,'COST_CENTER','مرکز هزینه','costCenter',1,0); |
| 149 | const cost=afCreateDimension(companyId,'COST_ELEMENT','عناصر هزینه','manual',3); |
| 150 | const addRule=(code,d,app)=>{const a=byCode[code];if(a&&!datastore.accountDimensionRules.some(x=>x.accountId===a.id&&x.dimensionTypeId===d.id))datastore.accountDimensionRules.push({id:afId('ADR'),ownerUserId:currentUser.id,companyId,accountId:a.id,dimensionTypeId:d.id,applicability:app,allowedValuesMode:'all',active:true})}; |
| 151 | ['1102','2101'].forEach(c=>addRule(c,party,'required'));['1101','4101','5101','6101','6102','6103'].forEach(c=>addRule(c,branch,'optional')); |
| 152 | if(type==='contracting'){['4301','5301','5302','1105','1106','1107','2104','2105','6109'].forEach(c=>{addRule(c,project,'required');addRule(c,contract,'required')})} |
| 153 | if(['service','manufacturing','contracting','professional'].includes(type)){['6101','6102','6103','5101'].forEach(c=>addRule(c,cost,'optional'))} |
| 154 | company.activityType=type;company.accountingTemplate={type,appliedAt:new Date().toISOString(),version:3,chartVersion:4,complianceVersion:3,jurisdiction:'IR'};saveDatastore();afEnsureAccountingP0Compatibility();if(typeof jeEnsureDefaultProfiles==='function')jeEnsureDefaultProfiles();return true; |
| 155 | }finally{getMySettings().default_company_id=previous;saveDatastore()} |
| 156 | } |
| 157 | function afImportCell(row,names){for(const n of names){if(Object.prototype.hasOwnProperty.call(row,n)&&String(row[n]??'').trim()!=='')return String(row[n]).trim()}return ''} |
| 158 | function afNormalizeAccountImportRows(rows){ |
| 159 | const levelMap={gl:'gl','کل':'gl',subsidiary:'subsidiary','معین':'subsidiary',detail:'detail','تفصیلی':'detail'},natureMap={debit:'debit','بدهکار':'debit',credit:'credit','بستانکار':'credit',both:'both','دوماهیتی':'both','دو ماهیتی':'both'}; |
| 160 | const roleMap={cash_default:'cash_default','نقد/بانک پیشفرض':'cash_default','نقد و بانک':'cash_default',receivable_control:'receivable_control','دریافتنی تجاری':'receivable_control',payable_control:'payable_control','پرداختنی تجاری':'payable_control',revenue_default:'revenue_default','درآمد/فروش پیشفرض':'revenue_default',purchase_default:'purchase_default','خرید/بهای تمامشده پیشفرض':'purchase_default',expense_default:'expense_default','هزینه پیشفرض':'expense_default',other_income_default:'other_income_default','سایر درآمد پیشفرض':'other_income_default',vat_payable:'vat_payable','مالیات پرداختنی':'vat_payable',vat_recoverable:'vat_recoverable','مالیات دریافتنی':'vat_recoverable'},typeMap={asset:'asset','دارایی':'asset',liability:'liability','بدهی':'liability',equity:'equity','حقوق مالکانه':'equity','سرمایه':'equity',revenue:'revenue','درآمد':'revenue',expense:'expense','هزینه':'expense','بهای تمام شده':'expense','بهای تمامشده':'expense',memorandum:'memorandum','انتظامی':'memorandum',control:'control','کنترلی':'control'},out=[],seen=new Set();for(const row of rows||[]){const code=afCode(afImportCell(row,['code','Code','کد','کد حساب'])),title=afImportCell(row,['title','name','Title','Name','عنوان','نام حساب']);if(!code&&!title)continue;if(!code||!title)throw new Error('هر ردیف کد و عنوان حساب لازم دارد.');if(seen.has(code))throw new Error('کد حساب تکراری در فایل: '+code);seen.add(code);const rawLevel=afImportCell(row,['level','Level','سطح']).toLowerCase(),level=levelMap[rawLevel]||levelMap[afImportCell(row,['level','Level','سطح'])];if(!level)throw new Error('سطح حساب نامعتبر برای '+code+'؛ فقط کل، معین یا تفصیلی مجاز است.');const rawNature=afImportCell(row,['normal_balance','nature','Normal Balance','Nature','ماهیت']).toLowerCase(),normalBalance=natureMap[rawNature]||natureMap[afImportCell(row,['normal_balance','nature','Normal Balance','Nature','ماهیت'])]||'both';const parentCode=afCode(afImportCell(row,['parent_code','parent','Parent Code','کد والد'])),rawType=afImportCell(row,['account_type','type','Account Type','نوع حساب']),accountType=rawType?(typeMap[rawType.toLowerCase()]||typeMap[rawType]):afAccountTypeForCode(code),rawRole=afImportCell(row,['system_role','posting_role','System Role','نقش سیستمی']),systemRole=rawRole?(roleMap[rawRole.toLowerCase()]||roleMap[rawRole]):'';if(rawType&&!accountType)throw new Error('نوع حساب نامعتبر برای '+code+'؛ از دارایی، بدهی، حقوق مالکانه، درآمد، هزینه، انتظامی یا کنترلی استفاده کنید.');if(rawRole&&!systemRole)throw new Error('نقش سیستمی نامعتبر برای '+code+'.');if(systemRole&&level!=='detail')throw new Error('نقش سیستمی فقط برای حساب تفصیلی/ثبتپذیر مجاز است: '+code);out.push({code,title,level,parentCode,normalBalance,accountType,systemRole})} |
| 161 | if(!out.length)throw new Error('فایل کدینگ فاقد ردیف معتبر است.');const usedRoles=new Set();for(const a of out){if(a.systemRole){if(usedRoles.has(a.systemRole))throw new Error('نقش سیستمی تکراری در فایل: '+a.systemRole);usedRoles.add(a.systemRole)}}const byCode=new Map(out.map(x=>[x.code,x]));for(const a of out){const need=a.level==='subsidiary'?'gl':a.level==='detail'?'subsidiary':'';if(!need){if(a.parentCode)throw new Error('حساب کل '+a.code+' نباید والد داشته باشد.');continue}const p=byCode.get(a.parentCode);if(!p||p.level!==need)throw new Error('والد '+a.code+' باید '+(need==='gl'?'حساب کل':'حساب معین')+' معتبر داخل همان فایل باشد.')}return out; |
| 162 | } |
| 163 | function afImportAccountsFromExcel(event){ |
| 164 | if(!requireWrite())return;const file=event.target.files?.[0];if(!file)return;if(file.size>5*1024*1024){event.target.value='';return alert('حجم فایل کدینگ نباید بیشتر از ۵ مگابایت باشد.')}if(getMyAccounts().length){event.target.value='';return alert('ورود کدینگ فقط روی کدینگ خالی مجاز است؛ برای جلوگیری از ادغام ناامن، ابتدا شرکت با «شروع با کدینگ خالی» ایجاد شود.')}if(typeof XLSX==='undefined'){event.target.value='';return alert('موتور Excel در دسترس نیست.')}const reader=new FileReader();reader.onload=()=>{try{const wb=XLSX.read(reader.result,{type:'array'}),ws=wb.Sheets[wb.SheetNames[0]],rows=XLSX.utils.sheet_to_json(ws,{defval:''});if(rows.length>10000)throw new Error('حداکثر ۱۰٬۰۰۰ ردیف کدینگ در هر فایل مجاز است.');const items=afNormalizeAccountImportRows(rows),counts=items.reduce((m,x)=>(m[x.level]=(m[x.level]||0)+1,m),{});if(!confirm('پیشنمایش کدینگ: '+items.length.toLocaleString('fa-IR')+' حساب — کل '+(counts.gl||0).toLocaleString('fa-IR')+'، معین '+(counts.subsidiary||0).toLocaleString('fa-IR')+'، تفصیلی '+(counts.detail||0).toLocaleString('fa-IR')+'.\nپس از تأیید، فایل بهصورت افزایشی روی کدینگ خالی وارد میشود.'))return;const cid=afNeedCompany();if(!cid)return;const byCode={};['gl','subsidiary','detail'].forEach(level=>items.filter(x=>x.level===level).forEach(x=>{const parentId=x.parentCode?byCode[x.parentCode]?.id||'':'';const a={id:afId('ACC'),ownerUserId:currentUser.id,companyId:cid,code:x.code,title:x.title,level,parentId,normalBalance:x.normalBalance,accountType:x.accountType||afAccountTypeForCode(x.code),systemRole:x.systemRole||'',postingAllowed:level==='detail',active:true,importedFrom:'excel',createdAt:new Date().toISOString()};datastore.accounts.push(a);byCode[x.code]=a}));saveDatastore();if(typeof jeEnsureDefaultProfiles==='function')jeEnsureDefaultProfiles();renderAccountingFoundation();alert(items.length.toLocaleString('fa-IR')+' حساب با موفقیت وارد شد.')}catch(e){alert('ورود کدینگ انجام نشد: '+e.message)}finally{event.target.value=''}};reader.readAsArrayBuffer(file); |
| 165 | } |
| 166 | function downloadAccountsExcelTemplate(){if(typeof XLSX==='undefined')return alert('موتور Excel در دسترس نیست.');const rows=[{code:'1',title:'داراییها',level:'کل',parent_code:'',normal_balance:'بدهکار',account_type:'دارایی'},{code:'11',title:'داراییهای جاری',level:'معین',parent_code:'1',normal_balance:'بدهکار',account_type:'دارایی'},{code:'1101',title:'بانک',level:'تفصیلی',parent_code:'11',normal_balance:'بدهکار',account_type:'دارایی',system_role:'cash_default'}],ws=XLSX.utils.json_to_sheet(rows),wb=XLSX.utils.book_new();XLSX.utils.book_append_sheet(wb,ws,'ChartOfAccounts');XLSX.writeFile(wb,'Finora-Chart-Of-Accounts-Template.xlsx')} |
| 167 | function afAccountStructuralUse(id){return (datastore.journalLines||[]).some(x=>x.accountId===id)||(datastore.postingProfiles||[]).some(x=>x.debitAccountId===id||x.creditAccountId===id)||getMyAccounts().some(x=>x.parentId===id)||getMyAccountDimensionRules().some(x=>x.accountId===id)} |
| 168 | function afStartAccountEdit(id){if(!requireWrite())return;const a=getMyAccounts().find(x=>x.id===id);if(!a)return;if(afAccountStructuralUse(id))return alert('این حساب در ساختار یا سوابق مالی استفاده شده است. برای حفظ تاریخچه، مشخصات ساختاری آن قابل بازتعریف نیست؛ در صورت نیاز آن را غیرفعال و حساب جدید ایجاد کنید.');editingAccountId=id;const vals={'af-account-level':a.level,'af-account-code':a.code,'af-account-title':a.title,'af-account-nature':a.normalBalance,'af-account-type':a.accountType||afAccountTypeForCode(a.code),'af-account-role':a.systemRole||''};Object.entries(vals).forEach(([id,v])=>{const el=document.getElementById(id);if(el)el.value=v});afParents();const parent=document.getElementById('af-account-parent');if(parent)parent.value=a.parentId||'';const b=document.getElementById('af-account-save-btn'),c=document.getElementById('af-account-edit-cancel');if(b)b.textContent='ذخیره اصلاح حساب';if(c)c.style.display='inline-flex';document.getElementById('af-account-code')?.focus();} |
| 169 | function afCancelAccountEdit(){editingAccountId='';const b=document.getElementById('af-account-save-btn'),c=document.getElementById('af-account-edit-cancel');if(b)b.textContent='ثبت حساب';if(c)c.style.display='none';['af-account-code','af-account-title'].forEach(id=>{const el=document.getElementById(id);if(el)el.value=''})} |
| 170 | function afToggleAccountActive(id){if(!requireWrite())return;const a=getMyAccounts().find(x=>x.id===id);if(!a)return;if(a.active===false)a.active=true;else{if(getMyAccounts().some(x=>x.parentId===id&&x.active!==false))return alert('ابتدا زیرحسابهای فعال را غیرفعال کنید.');a.active=false;}a.updatedAt=new Date().toISOString();saveDatastore();renderAccountingFoundation()} |
| 171 | function afSaveAccount(){ |
| 172 | if(!requireWrite())return;const cid=afNeedCompany();if(!cid)return; |
| 173 | const level=document.getElementById('af-account-level').value,code=afCode(document.getElementById('af-account-code').value),title=document.getElementById('af-account-title').value.trim(),normalBalance=document.getElementById('af-account-nature').value,accountType=document.getElementById('af-account-type')?.value||afAccountTypeForCode(code),systemRole=document.getElementById('af-account-role')?.value||'',parentId=document.getElementById('af-account-parent').value; |
| 174 | if(!code||!title)return alert('کد و عنوان حساب الزامی است.');if(getMyAccounts().some(x=>x.code===code&&x.id!==editingAccountId))return alert('کد حساب تکراری است.');if(systemRole&&level!=='detail')return alert('نقش سیستمی فقط برای حساب تفصیلی/ثبتپذیر مجاز است.');if(systemRole&&getMyAccounts().some(x=>x.systemRole===systemRole&&x.id!==editingAccountId))return alert('برای این نقش سیستمی قبلاً یک حساب پیشفرض تعیین شده است.'); |
| 175 | const need=level==='subsidiary'?'gl':level==='detail'?'subsidiary':'';if(need&&!getMyAccounts().some(x=>x.id===parentId&&x.level===need))return alert('حساب والد معتبر انتخاب کنید.'); |
| 176 | if(editingAccountId){const a=getMyAccounts().find(x=>x.id===editingAccountId);if(!a)return afCancelAccountEdit();if(afAccountStructuralUse(a.id))return alert('حساب در این فاصله مورد استفاده قرار گرفته و دیگر قابل بازتعریف نیست.');Object.assign(a,{code,title,level,parentId:parentId||'',normalBalance,accountType,systemRole,postingAllowed:level==='detail',updatedAt:new Date().toISOString()});afCancelAccountEdit();}else datastore.accounts.push({id:afId('ACC'),ownerUserId:currentUser.id,companyId:cid,code,title,level,parentId:parentId||'',normalBalance,accountType,systemRole,postingAllowed:level==='detail',active:true}); |
| 177 | saveDatastore();renderAccountingFoundation(); |
| 178 | } |
| 179 | function afDeleteAccount(id){if(!requireWrite())return;if((datastore.journalLines||[]).some(x=>x.accountId===id))return alert('این حساب در دفتر حسابداری استفاده شده و قابل حذف نیست؛ فقط غیرفعالسازی مجاز است.');if((datastore.postingProfiles||[]).some(x=>x.debitAccountId===id||x.creditAccountId===id))return alert('این حساب در پروفایل ثبت خودکار استفاده شده و قابل حذف نیست. ابتدا پروفایل مرتبط را جایگزین کنید.');if(getMyAccounts().some(x=>x.parentId===id))return alert('حساب دارای زیرحساب است.');if(getMyAccountDimensionRules().some(x=>x.accountId===id))return alert('ابتدا قواعد تفصیلی حساب را حذف کنید.');if(confirm('حساب حذف شود؟')){datastore.accounts=datastore.accounts.filter(x=>x.id!==id);saveDatastore();renderAccountingFoundation()}} |
| 180 | function afSaveRule(){if(!requireWrite())return;const cid=afNeedCompany(),accountId=document.getElementById('af-rule-account').value,dimensionTypeId=document.getElementById('af-rule-dimension').value,applicability=document.getElementById('af-rule-app').value,a=getMyAccounts().find(x=>x.id===accountId),d=getMyDimensionTypes().find(x=>x.id===dimensionTypeId);if(!cid||!a?.postingAllowed||!d?.active)return alert('حساب ثبتپذیر و تفصیلی فعال انتخاب کنید.');let r=getMyAccountDimensionRules().find(x=>x.accountId===accountId&&x.dimensionTypeId===dimensionTypeId);if(r)r.applicability=applicability;else datastore.accountDimensionRules.push({id:afId('ADR'),ownerUserId:currentUser.id,companyId:cid,accountId,dimensionTypeId,applicability,allowedValuesMode:'all',active:true});saveDatastore();renderAccountingFoundation()} |
| 181 | function afDeleteRule(id){if(!requireWrite())return;const rule=getMyAccountDimensionRules().find(x=>x.id===id);if(rule&&(datastore.journalLines||[]).some(l=>l.accountId===rule.accountId))return alert('این حساب دارای سابقه دفتر است؛ تغییر ساختار تفصیلی باید از مسیر نسخهبندی/دوره جدید انجام شود.');datastore.accountDimensionRules=datastore.accountDimensionRules.filter(x=>x.id!==id);saveDatastore();renderAccountingFoundation()} |
| 182 | function afNextDimensionCode(){const used=getMyDimensionTypes().map(x=>String(x.code||'')).filter(x=>/^DIM-\d{3}$/.test(x)).map(x=>Number(x.slice(4)));return 'DIM-'+String(Math.max(0,...used)+1).padStart(3,'0')} |
| 183 | function afNextDimensionValueCode(dimensionTypeId,parentId=''){const siblings=getMyDimensionValues().filter(x=>x.dimensionTypeId===dimensionTypeId&&String(x.parentId||'')===String(parentId||'')),used=siblings.map(x=>String(x.code||'').split('.').pop()).filter(x=>/^\d+$/.test(x)).map(Number),seq=String(Math.max(0,...used)+1).padStart(3,'0'),parent=parentId?getMyDimensionValues().find(x=>x.id===parentId):null;return parent?.code?parent.code+'.'+seq:seq} |
| 184 | function afSaveDimension(){if(!requireWrite())return;const cid=afNeedCompany(),code=afNextDimensionCode(),title=document.getElementById('af-dim-title').value.trim(),sourceEntity=document.getElementById('af-dim-source').value,maxDepth=Math.max(1,Math.min(8,+document.getElementById('af-dim-depth').value||1));if(!cid||!title)return alert('عنوان تفصیلی الزامی است.');if(getMyDimensionTypes().some(x=>x.code===code))return alert('کد خودکار تکراری شد؛ صفحه را تازهسازی و دوباره تلاش کنید.');if(sourceEntity!=='manual'&&maxDepth!==1)return alert('تفصیلی متصل به داده پایه در این فاز عمق ۱ دارد؛ برای ساختار چندسطحی نوع «دستی» را انتخاب کنید.');datastore.dimensionTypes.push({id:afId('DIM'),ownerUserId:currentUser.id,companyId:cid,code,title,maxDepth,depthLocked:false,leafOnlyPosting:true,active:true,sourceType:sourceEntity==='manual'?'manual':'entity-backed',sourceEntity});saveDatastore();renderAccountingFoundation()} |
| 185 | function afChangeDimensionDepth(id){ |
| 186 | if(!requireWrite())return;const t=getMyDimensionTypes().find(x=>x.id===id);if(!t||t.sourceEntity!=='manual')return alert('عمق تفصیلی متصل به داده پایه ثابت است.'); |
| 187 | if(afDimensionHasValues(id))return alert('تا وقتی حتی یک مقدار در این تفصیلی وجود دارد، عمق ساختار قابل تغییر نیست. ابتدا مقادیر بدون ارجاع را حذف کنید.'); |
| 188 | const raw=prompt('عمق جدید ساختار را از ۱ تا ۸ وارد کنید:',String(t.maxDepth||1));if(raw===null)return;const n=Number(toEnDigits(raw));if(!Number.isInteger(n)||n<1||n>8)return alert('عمق باید عدد صحیح بین ۱ تا ۸ باشد.'); |
| 189 | t.maxDepth=n;t.depthLocked=false;t.updatedAt=new Date().toISOString();saveDatastore();renderAccountingFoundation(); |
| 190 | } |
| 191 | function afDeleteDimension(id){ |
| 192 | if(!requireWrite())return;if(afDimensionHasValues(id))return alert('این تفصیلی دارای مقدار است و قابل حذف نیست.');if(getMyAccountDimensionRules().some(x=>x.dimensionTypeId===id))return alert('این تفصیلی به حسابها متصل است؛ ابتدا قواعد حساب را حذف کنید.'); |
| 193 | const t=getMyDimensionTypes().find(x=>x.id===id);if(!t)return;if(confirm('تفصیلی «'+t.title+'» حذف شود؟')){datastore.dimensionTypes=datastore.dimensionTypes.filter(x=>x.id!==id);saveDatastore();renderAccountingFoundation()} |
| 194 | } |
| 195 | function afSaveDimensionValue(){if(!requireWrite())return;const cid=afNeedCompany(),dimensionTypeId=document.getElementById('af-value-dim').value,t=getMyDimensionTypes().find(x=>x.id===dimensionTypeId);if(!cid||t?.sourceEntity!=='manual')return alert('فقط تفصیلی دستی مقدار مستقل میپذیرد.');const title=document.getElementById('af-value-title').value.trim(),parentId=document.getElementById('af-value-parent').value,code=afNextDimensionValueCode(dimensionTypeId,parentId);let depth=1;if(parentId){const p=getMyDimensionValues().find(x=>x.id===parentId&&x.dimensionTypeId===dimensionTypeId);if(!p)return alert('والد معتبر نیست.');if((p.depth||1)>=Number(t.maxDepth||1))return alert('این گره در آخرین سطح ساختار است و نمیتواند زیرشاخه داشته باشد.');depth=(p.depth||1)+1}if(!code||!title||depth>t.maxDepth)return alert('کد، عنوان یا عمق معتبر نیست.');if(getMyDimensionValues().some(x=>x.dimensionTypeId===dimensionTypeId&&x.code===code))return alert('کد مقدار در این تفصیلی تکراری است.');datastore.dimensionValues.push({id:afId('DV'),ownerUserId:currentUser.id,companyId:cid,dimensionTypeId,code,title,parentId:parentId||'',depth,active:true,createdAt:new Date().toISOString()});t.depthLocked=true;saveDatastore();renderAccountingFoundation()} |
| 196 | function afDeleteValue(id){if(!requireWrite())return;const v=getMyDimensionValues().find(x=>x.id===id);if(!v)return;if(getMyDimensionValues().some(x=>x.parentId===id))return alert('این مقدار زیرمجموعه دارد.');if(afDimensionValueReferenced(id))return alert('این مقدار در رکورد دیگری استفاده شده و برای حفظ تاریخچه قابل حذف نیست؛ در فاز ثبت اسناد فقط غیرفعالسازی مجاز خواهد بود.');datastore.dimensionValues=datastore.dimensionValues.filter(x=>x.id!==id);const t=getMyDimensionTypes().find(x=>x.id===v.dimensionTypeId);if(t&&!afDimensionHasValues(t.id))t.depthLocked=false;saveDatastore();renderAccountingFoundation()} |
| 197 | function afSaveFiscal(){if(!requireWrite())return;const cid=afNeedCompany(),title=document.getElementById('af-fy-title').value.trim(),startDate=toEnDigits(document.getElementById('af-fy-start').value),endDate=toEnDigits(document.getElementById('af-fy-end').value);if(!cid||!title||!/^\d{4}\/\d{2}\/\d{2}$/.test(startDate)||!/^\d{4}\/\d{2}\/\d{2}$/.test(endDate)||startDate>=endDate)return alert('عنوان و بازه تاریخ شمسی معتبر وارد کنید.');if(getMyFiscalYears().some(x=>!(endDate<x.startDate||startDate>x.endDate)))return alert('بازه سال مالی با سال مالی موجود همپوشانی دارد.');datastore.fiscalYears.push({id:afId('FY'),ownerUserId:currentUser.id,companyId:cid,title,startDate,endDate,status:'open',createdAt:new Date().toISOString()});saveDatastore();renderAccountingFoundation()} |
| 198 | function afToggleFiscal(id){if(!requireWrite())return;const f=getMyFiscalYears().find(x=>x.id===id);if(!f)return;if(f.status==='locked'&&!confirm('بازکردن دوره مالی یک عملیات کنترلی حساس است. ادامه میدهید؟'))return;f.status=f.status==='locked'?'open':'locked';f.lockedAt=f.status==='locked'?new Date().toISOString():'';saveDatastore();renderAccountingFoundation()} |
| 199 | function afSaveBranch(){if(!requireWrite())return;const cid=afNeedCompany(),code=afCode(document.getElementById('af-branch-code').value),name=document.getElementById('af-branch-name').value.trim();if(!cid||!code||!name)return alert('کد و نام شعبه الزامی است.');if(getMyBranches().some(x=>x.code===code))return alert('کد شعبه تکراری است.');datastore.branches.push({id:afId('BR'),ownerUserId:currentUser.id,companyId:cid,code,name,floatingCode:afNextFloatingCode(1,1),active:true});saveDatastore();renderAccountingFoundation()} |
| 200 | function afDeleteBranch(id){if(!requireWrite())return;if(getMyGlobalProjects().some(x=>x.branchId===id))return alert('شعبه در پروژه استفاده شده است.');if(afDimensionValueReferenced(id))return alert('شعبه در رکورد دیگری استفاده شده و قابل حذف نیست.');datastore.branches=datastore.branches.filter(x=>x.id!==id);saveDatastore();renderAccountingFoundation()} |
| 201 | function afSaveProject(){if(!requireWrite())return;const cid=afNeedCompany(),code=afCode(document.getElementById('af-project-code').value),name=document.getElementById('af-project-name').value.trim(),parentId=document.getElementById('af-project-parent').value,branchId=document.getElementById('af-project-branch').value;if(!cid||!code||!name)return alert('کد و نام پروژه الزامی است.');if(getMyGlobalProjects().some(x=>x.code===code))return alert('کد پروژه تکراری است.');if(parentId&&!getMyGlobalProjects().some(x=>x.id===parentId))return alert('پروژه والد معتبر نیست.');const linkedContactIds=[...document.getElementById('af-project-contacts').selectedOptions].map(x=>x.value);datastore.projects.push({id:afId('PRJ'),ownerUserId:currentUser.id,companyId:cid,code,name,floatingCode:afNextFloatingCode(3,1),parentId:parentId||'',branchId:branchId||'',linkedContactIds,direction:'both',active:true});saveDatastore();renderAccountingFoundation()} |
| 202 | function afDeleteProject(id){if(!requireWrite())return;if(getMyGlobalProjects().some(x=>x.parentId===id))return alert('پروژه زیرمجموعه دارد.');if(afProjectUsed(id)||afDimensionValueReferenced(id))return alert('پروژه در رکورد مالی/عملیاتی استفاده شده و قابل حذف نیست.');datastore.projects=datastore.projects.filter(x=>x.id!==id);saveDatastore();renderAccountingFoundation()} |