سامانه صدور فاکتور و حسابداری

fix/office-c7-source-ref-binding-v2
audit-remediation-wave3-4-20261002 audit-remediation-wave3-verify-20261002 audit-remediation-wave4-20261002 audit-remediation-wave4b-20261002 audit-remediation-wave5a-identity-20261002 audit-remediation-wave5b-offboarding-20261002 audit-remediation-wave5c-authorization-20261002 audit-security-intent-review-20261002 audit/finora-financial-core-20261115 audit/finora-master-prompt-phase0-20261016 audit/finora-stage3-legacy-source-readonly-20261023 audit/full-controls-20261030 audit/owner-live-state-reconcile-20261012 audit/owner-review-20261007 audit/phase1-live-permissions-readonly-20261013 audit/reconcile-live-state-20261006 audit/reconcile-state-20261002 audit/wp0-hardening-baseline-20261102 branding-login-favicon-20261002 c8-workflow-task1 c8-workflow-task2 c8-workflow-task3 chore/wave0-pages-gate-closeout claude-code-plugins-setup design/finora-c01-authoritative-source-draft-20261124 docs-wave4b-verified-20261002 docs/active-company-invoice-release-evidence-20261014 docs/agent-operating-model-20261114 docs/chart-taxpayer-release-evidence-20261004 docs/cloud-only-agent-orchestration-20261115 docs/confirm-finora-product-charter-20261115 docs/continuation-20261030 docs/d4a-verified docs/external-work-review-20261121 docs/finora-audit-continuity-20261014 docs/finora-backup-merge-evidence-20261014 docs/finora-ci-reconciliation-20261122 docs/finora-codex-master-prompt docs/finora-eight-phase-plan-20261011 docs/finora-f002-live-buyer-filter-verified-20261015 docs/finora-license-race-release-evidence-20261014 docs/finora-license-rollout-acceptance-20261015 docs/finora-phase0-repeat-and-pages-nav-verified-20261015 docs/finora-phase0-repeat-evidence-20261015 docs/finora-selectors-release-and-fixture-qa-20261015 docs/finora-stagea-pr240-ci-triage-20261123 docs/finora-test-license-live-pass-20261015 docs/finora-v2-m01-coverage-20261124 docs/handoff-charter-v2-20261124 docs/invoice-product-search-release-20261011 docs/invoice-workspace-release-20261007 docs/phase-status-20261031 docs/phase0-acceptance-release-evidence-20261012 docs/phase0-admin-provision-release-evidence-20261012 docs/phase0-core-bundle-owner-login-open-20261013 docs/phase0-duplicate-js-release-20261016 docs/phase0-f001-auth-rest-shared-timeout-20261013 docs/phase0-f001-owner-login-observed-20261013 docs/phase0-f001-second-device-fail-40s-20261013 docs/phase0-f003-release-verification-20261011 docs/phase0-f004-print-release-evidence-20261012 docs/phase0-f004-watermark-release-evidence-20261012 docs/phase0-f005-large-selector-release-20261012 docs/phase0-f005-release-evidence-20261012 docs/phase0-f006-dark-release-evidence-20261012 docs/phase0-f008-final-pr-closure-evidence-20261012 docs/phase0-f008-reconcile-stale-prs-20261012 docs/phase0-f107-production-evidence-20261012 docs/phase0-kavenegar-otp-preflight-release-20261012 docs/phase0-login-release-evidence-20261012 docs/phase0-login-rest-bootstrap-stage-release-20261012 docs/phase0-owner-app-assets-bundle-release-20261013 docs/phase0-owner-login-csp-release-20261012 docs/phase0-reconcile-postmerge-evidence-20261012 docs/phase0-site-probe-release-evidence-20261012 docs/phase0-startup-release-evidence-20261012 docs/phase3-treasury-release-evidence-20261014 docs/pilot-posted-correction-release-evidence-20261014 docs/pilot-purchase-correction-release-evidence-20261014 docs/print-persian-release-verification-20261011 docs/qa-ci-triage-218-20261122 docs/real-account-qa-20261030 docs/release-state-20261007 docs/seamless-amendment-release-20261014 docs/seamless-document-correction-release-20261014 docs/settings-login-release-20261025 docs/stripe-qa-deployment-evidence-20261011 docs/ux-f2-release-evidence-20261011 docs/ux-f2-release-verification-20261011 docs/wave0-closeout docs/wave2-closeout exec-phase1-architecture exec-phase1-implementation exec-phase1-qa exec-phase1-security-release exec-phase1-ux feat/accounting-document-draft-approval-20261011 feat/accounting-document-release-candidate-20261011 feat/active-company-strict-isolation-20261014 feat/admin-provisioning-reconciled-20261011 feat/admin-secure-user-provisioning-20261011 feat/admin-user-provisioning-merged-20261011 feat/d4a-request-work-queue feat/document-lifecycle-atf-20261118 feat/document-lifecycle-temp-permanent-atef feat/draft-first-attachment-lifecycle-216 feat/finora-offline-encrypted-backup-20261014 feat/finora-phase-a-navigation-20261023 feat/finora-stripe-sandbox-edge-gate feat/immutable-attachment-temporary-vouchers feat/iran-accounting-design-audit feat/journal-document-lifecycle-20261118 feat/journal-rpc-repository-adapter-20261117 feat/office-c7-fulltext-ocr-provenance feat/password-recovery-admin-reset-20261025 feat/pilot-expense-income-inplace-amendment-20261014 feat/pilot-journal-invoice-correction-20261014 feat/pilot-purchase-correction-20261014 feat/pilot-treasury-unallocated-correction-20261014 feat/retain-document-editor-after-save-20261014 feat/seamless-financial-document-correction-20261014 feat/slice-b-tenant-rbac feat/stripe-sandbox-invoice-probe feature/accounting-core-p0 feature/accounting-product-guidance feature/admin-identity-phone-auth feature/commercial-rnd feature/finora-phase1a-supabase-cli-20261016 feature/finora-stage2-manual-canary-20261017 feature/finora-stage3-commercial-payload-20261023 feature/finora-stage3-enforce-invoice-rpc-20261023 feature/finora-stage3-enforce-purchase-red-20261023 feature/invoice-workspace-cleanup feature/phase0-kavenegar-otp-preflight-20261012 feature/ux-commerce-settings-r2 fix-shell-scroll-live-cache-20261002 fix-shell-scrollbar-explicit-ownership-20261002 fix-shell-scrollbar-ownership-20261002 fix-shell-scrollbar-right-edge-20261002 fix/about-bug-report-20261114 fix/active-company-invoice-scope-20261014 fix/active-company-isolation-reconcile-20261014 fix/admin-central-password-reset-20261028 fix/auth-network-diagnostics fix/chart-taxpayer-reference-20261003 fix/combobox-enter-reliability fix/combobox-live-search fix/combobox-production-cache fix/combobox-release-asset-v2 fix/company-edit-action-20261028 fix/company-edit-pilot-delete-20261014 fix/company-form-action-state-20261014 fix/company-form-action-state-rebased-20261014 fix/contact-operational-balance-20261111 fix/dark-theme-contrast fix/financial-lifecycle-recovery-20261124 fix/finora-accounting-test-organization-readiness-20261015 fix/finora-b01-safe-org-switch-20261124 fix/finora-b02-sync-recovery-20261124 fix/finora-b03-conflict-review-20261124 fix/finora-org-license-bootstrap-race-20261014 fix/finora-stage3-posted-source-immutable-20261023 fix/finora-v2-b03-r2-qa-20261124 fix/finora-v2-b03-r3-readonly-20261124 fix/g01-asof-financial-position-20261128 fix/invoice-product-search-rehydrate-20261011 fix/invoice-search-cache-bust fix/issue229-linked-draft-status-20261122 fix/login-assets-retry-20261014 fix/login-inert-startup-20261110 fix/login-member-access-20261101 fix/login-resilience-20261017 fix/login-short-viewport-20261028 fix/login-startup-readiness-20261024 fix/navigation-utilities-placement-20261105 fix/office-c7-source-ref-binding fix/office-c7-source-ref-binding-v2 fix/owner-login-network-20261026 fix/password-recovery-invalid-cancel-20261026 fix/payment-amount-format-20261111 fix/phase0-admin-provision-seat-bootstrap-20261012 fix/phase0-auth-bundled-assets-for-unstable-isp-20261013 fix/phase0-auth-handler-binding-stalled-session-20261012 fix/phase0-login-context-stage-visibility-20261012 fix/phase0-login-single-local-bundle-20261013 fix/phase0-login-site-probe-clarity-20261012 fix/phase0-login-ui-ready-20261012 fix/phase0-modal-dashboard-drill-20261011 fix/phase0-pages-blocking-core-bundles-20261013 fix/phase0-print-no-draft-watermark-20261012 fix/phase0-startup-parallel-asset-load-20261012 fix/phase3-behavioral-verification fix/preserve-pending-edits-20261121 fix/print-persian-digit-consistency-20261011 fix/recovery-login-startup-20261027 fix/report-opening-balance-release-20261130 fix/settings-checkbox-persistence-20261024 fix/taxpayer-arithmetic-20261004 fix/ux-keyboard-search-f2-20261011 fix/wave2-request-input-integrity hardening/c01-source-draft-20261129 hardening/global-draft-conversion-20261113 hardening/wp1-ledger-integrity-20261102 integration/finora-execution-20261124 integration/issue229-ui-qa-20261122 integration/wp1-ledger-core-20261115 integration/wp2-manual-journal-rpc-20261116 main ops-heartbeat-v2-20261002 ops-progress-heartbeat-rule-20261002 ops/wave4-production-20261003 plan/financial-core-phase1-approval-20261016 qa/attachment-allocator-two-session-20261122 qa/draft-first-save-red-evidence-20261122 qa/finora-autopost-retry-identity-red-20261122 qa/finora-identity-rpc-security-tripwire-20261122 qa/finora-issue223-manual-kardex-browser-red-20261123 qa/finora-issue223-stock-real-jwt-20261123 qa/finora-issue238-inventory-count-browser-red-20261123 qa/finora-issue238-save-browser-red-20261122 qa/finora-login-cors-header-preflight-20261025 qa/finora-phase0-saved-session-repeat-20261015 qa/finora-phase5-posted-insert-jwt-red-20261123 qa/finora-stage3-ui-jwt-autopost-20261023 qa/finora-v2-g01-report-reconciliation-20261125 qa/free-supabase-local-wp2-20261116 qa/issue229-approval-boundary-jwt-20261122 qa/issue229-sale-save-linked-draft-red-20261122 qa/phase0-acceptance-start-20261012 qa/phase0-f005-account-project-contract-stress-20261012 qa/phase0-f005-selector-stress-20261012 qa/phase0-f006-dark-contrast-20261012 qa/post-wave4-verification-20261003 qa/posted-source-immutable-jwt-20261122 qa/pr219-wp1-disposable-dburl-proof-20261123 qa/purchase-source-jwt-20261122 qa/real-settings-acceptance-20261025 qa/recovery-mail-acceptance-20261026 qa/source-autopost-jwt-atomicity-20261122 qa/wave0-negative-gate-proof qa/wp2-auth-tenant-e2e-20261117 qa/wp2-authorized-journal-write-20261122 qa/wp2-financial-paths-reconciliation-20261122 qa/wp3-financial-tenant-isolation-20261117 remediation/wave0-liveqa-wave1 remediation/wave2-request-integrity staging/finora-stage22-free-20261022 state-scroll-verified-20261002 state-wave4b-production-20261002 state-wave5a-production-20261002 test/finora-accounting-boot-readiness-20261015 test/finora-f0-02-production-selectors-20261015 test/finora-pages-commerce-event-wiring-20261015 test/finora-pages-invoice-selectors-readonly-20261015 test/finora-stage3-jwt-source-post-20261023 test/phase0-invoice-fixture-bootstrap-20261016 test/phase0-invoice-persistence-20261011 test/phase0-pages-delayed-dispatcher-20261016 ux-scroll-ownership-20261002 work/finora-stage3-enforce-purchase-green-20261023 work/finora-stage3-enforce-sale-green-20261023 work/finora-stage3-payload-green-20261023
js 142 lines 40.5 KB
Raw
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 function afCompanyId(){const s=getMySettings(),c=getMyCompanies();return s.default_company_id||c[0]?.id||'';}
30 function afOwned(k){const cid=afCompanyId();return(datastore[k]||[]).filter(x=>x.ownerUserId===currentUser?.id&&(!x.companyId||x.companyId===cid));}
31 function getMyFiscalYears(){return afOwned('fiscalYears')} function getMyAccounts(){return afOwned('accounts')}
32 function getMyDimensionTypes(){return afOwned('dimensionTypes')} function getMyDimensionValues(){return afOwned('dimensionValues')}
33 function getMyAccountDimensionRules(){return afOwned('accountDimensionRules')} function getMyBranches(){return afOwned('branches')}
34 function getMyGlobalProjects(){return afOwned('projects')}
35 function afId(p){return p+'_'+Date.now().toString(36)+'_'+Math.random().toString(36).slice(2,7)}
36 function afCode(v){return String(v||'').trim().replace(/\s+/g,'-').slice(0,32)}
37 function afAccountTypeForCode(code){return({'1':'asset','2':'liability','3':'equity','4':'revenue','5':'expense','6':'expense'})[String(code||'').charAt(0)]||'control'}
38 function afNeedCompany(){const id=afCompanyId();if(!id)alert('ابتدا یک شرکت تعریف و فعال کنید.');return id}
39 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)}
40 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)}))}
41 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)}
42 function afDimensionHasValues(typeId){return getMyDimensionValues().some(x=>x.dimensionTypeId===typeId)}
43 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}}))}
44 function afEnsureContractingPhase4Accounts(){
45 if(!currentUser||!afCompanyId())return;const company=getMyCompanies().find(x=>x.id===afCompanyId());if(company?.accountingTemplate?.type!=='contracting'||Number(company.accountingTemplate.phase4Version||0)>=1)return;
46 const specs=[['1106','مطالبات کسور بیمه پیمان','11','debit'],['1107','مطالبات مالیات تکلیفی پیمان','11','debit'],['2105','پیش‌دریافت و علی‌الحساب پیمان','21','credit'],['6109','جرایم و کسورات غیرقابل وصول پیمان','61','debit']];let changed=false;
47 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});
48 company.accountingTemplate.phase4Version=1;company.accountingTemplate.phase4MigratedAt=new Date().toISOString();if(changed)saveDatastore();else saveDatastore();
49 }
50 function afEnsureIranComplianceTemplateV3(){
51 if(!currentUser||!afCompanyId())return;const company=getMyCompanies().find(x=>x.id===afCompanyId());if(!company?.accountingTemplate||Number(company.accountingTemplate.complianceVersion||0)>=3)return;
52 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']];
53 if(company.activityType==='manufacturing')specs.push(['1113','کالای در جریان ساخت','11','debit','asset'],['5205','انحرافات جذب سربار','52','debit','expense']);
54 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}
55 // Legacy manufacturing template incorrectly classified WIP 5204 under expense/cost. Never rewrite used history.
56 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}}
57 company.accountingTemplate.complianceVersion=3;company.accountingTemplate.complianceMigratedAt=new Date().toISOString();if(changed)saveDatastore();else saveDatastore();
58 }
59 function afSeed(){
60 if(!currentUser||!afCompanyId())return;afEnsureFloatingSlotCompatibility();afEnsureContractingPhase4Accounts();afEnsureIranComplianceTemplateV3();let ch=false,cid=afCompanyId();
61 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}
62 if(ch)saveDatastore();
63 }
64 function afMigrateLegacyProjects(){
65 if(!currentUser||!afCompanyId())return;const s=getMySettings();const key='accountingFoundationMigrationV2_'+afCompanyId();if(s[key])return;let ch=false;
66 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}})}));
67 s[key]={completedAt:new Date().toISOString(),mode:'copy-preserve-ids'};if(ch||!s[key])saveDatastore();else saveDatastore();
68 }
69 function afCreateDimension(cid,code,title,sourceEntity,maxDepth=1,slot=0){
70 const existing=getMyDimensionTypes().find(x=>x.code===code);if(existing){if(slot&&!existing.slot)existing.slot=Number(slot);return existing}
71 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};
72 datastore.dimensionTypes.push(d);return d;
73 }
74 function afEnsureFloatingSlotCompatibility(){
75 if(!currentUser||!afCompanyId())return false;const cid=afCompanyId(),company=getMyCompanies().find(x=>x.id===cid);if(!company)return false;let changed=false;
76 const defs=[['BRANCH','شعبه','branch',1],['COUNTERPARTY','طرف حساب','contact',2],['PROJECT','پروژه','project',3],['CONTRACT','قرارداد / پیمان','contract',4]];
77 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(Number(d.slot||0)!==slot){d.slot=slot;changed=true}});
78 if(changed)saveDatastore();return changed;
79 }
80 function afApplyTemplate(companyId,type){
81 if(!requireWrite()||!companyId)return false;const company=getMyCompanies().find(x=>x.id===companyId);if(!company)return false;
82 if((datastore.accounts||[]).some(x=>x.ownerUserId===currentUser.id&&x.companyId===companyId)){alert('برای این شرکت کدینگ وجود دارد؛ قالب روی کدینگ موجود اعمال نشد.');return false}
83 const previous=getMySettings().default_company_id;getMySettings().default_company_id=companyId;
84 try{
85 const rows=[...AF_BASE_ACCOUNTS,...(AF_SPECIAL_ACCOUNTS[type]||[])],byCode={};
86 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});
87 const branch=afCreateDimension(companyId,'BRANCH','شعبه','branch',1,1);
88 const party=afCreateDimension(companyId,'COUNTERPARTY','طرف حساب','contact',1,2);
89 const project=afCreateDimension(companyId,'PROJECT','پروژه','project',1,3);
90 const contract=afCreateDimension(companyId,'CONTRACT','قرارداد / پیمان','contract',1,4);
91 const cost=afCreateDimension(companyId,'COST_ELEMENT','عناصر هزینه','manual',3);
92 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})};
93 ['1102','2101'].forEach(c=>addRule(c,party,'required'));['1101','4101','5101','6101','6102','6103'].forEach(c=>addRule(c,branch,'optional'));
94 if(type==='contracting'){['4301','5301','5302','1105','1106','1107','2104','2105','6109'].forEach(c=>{addRule(c,project,'required');addRule(c,contract,'required')})}
95 if(['service','manufacturing','contracting','professional'].includes(type)){['6101','6102','6103','5101'].forEach(c=>addRule(c,cost,'optional'))}
96 company.activityType=type;company.accountingTemplate={type,appliedAt:new Date().toISOString(),version:3,complianceVersion:3,jurisdiction:'IR'};saveDatastore();if(typeof jeEnsureDefaultProfiles==='function')jeEnsureDefaultProfiles();return true;
97 }finally{getMySettings().default_company_id=previous;saveDatastore()}
98 }
99 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 ''}
100 function afNormalizeAccountImportRows(rows){
101 const levelMap={gl:'gl','کل':'gl',subsidiary:'subsidiary','معین':'subsidiary',detail:'detail','تفصیلی':'detail'},natureMap={debit:'debit','بدهکار':'debit',credit:'credit','بستانکار':'credit',both:'both','دوماهیتی':'both','دو ماهیتی':'both'};
102 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})}
103 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;
104 }
105 function afImportAccountsFromExcel(event){
106 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);
107 }
108 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')}
109 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)}
110 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();}
111 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=''})}
112 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()}
113 function afSaveAccount(){
114 if(!requireWrite())return;const cid=afNeedCompany();if(!cid)return;
115 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;
116 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('برای این نقش سیستمی قبلاً یک حساب پیش‌فرض تعیین شده است.');
117 const need=level==='subsidiary'?'gl':level==='detail'?'subsidiary':'';if(need&&!getMyAccounts().some(x=>x.id===parentId&&x.level===need))return alert('حساب والد معتبر انتخاب کنید.');
118 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});
119 saveDatastore();renderAccountingFoundation();
120 }
121 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()}}
122 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()}
123 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()}
124 function afSaveDimension(){if(!requireWrite())return;const cid=afNeedCompany(),code=afCode(document.getElementById('af-dim-code').value).toUpperCase(),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||!code||!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()}
125 function afChangeDimensionDepth(id){
126 if(!requireWrite())return;const t=getMyDimensionTypes().find(x=>x.id===id);if(!t||t.sourceEntity!=='manual')return alert('عمق تفصیلی متصل به داده پایه ثابت است.');
127 if(afDimensionHasValues(id))return alert('تا وقتی حتی یک مقدار در این تفصیلی وجود دارد، عمق ساختار قابل تغییر نیست. ابتدا مقادیر بدون ارجاع را حذف کنید.');
128 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('عمق باید عدد صحیح بین ۱ تا ۸ باشد.');
129 t.maxDepth=n;t.depthLocked=false;t.updatedAt=new Date().toISOString();saveDatastore();renderAccountingFoundation();
130 }
131 function afDeleteDimension(id){
132 if(!requireWrite())return;if(afDimensionHasValues(id))return alert('این تفصیلی دارای مقدار است و قابل حذف نیست.');if(getMyAccountDimensionRules().some(x=>x.dimensionTypeId===id))return alert('این تفصیلی به حساب‌ها متصل است؛ ابتدا قواعد حساب را حذف کنید.');
133 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()}
134 }
135 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 code=afCode(document.getElementById('af-value-code').value),title=document.getElementById('af-value-title').value.trim(),parentId=document.getElementById('af-value-parent').value;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()}
136 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()}
137 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()}
138 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()}
139 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,active:true});saveDatastore();renderAccountingFoundation()}
140 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()}
141 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,parentId:parentId||'',branchId:branchId||'',linkedContactIds,direction:'both',active:true});saveDatastore();renderAccountingFoundation()}
142 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()}