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

fix/phase3-behavioral-verification
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 100 lines 21.5 KB
Raw
1 /* Phase 2: accounting foundation — safety-first master data */
2 const AF_LEVELS={gl:'کل',subsidiary:'معین',detail:'تفصیلی'},AF_NATURE={debit:'بدهکار',credit:'بستانکار',both:'دوماهیتی'};
3 const AF_COMPANY_TYPES={
4 trading:'بازرگانی',service:'خدماتی',manufacturing:'تولیدی',contracting:'پیمانکاری',
5 retail:'فروشگاهی',distribution:'پخش',nonprofit:'غیرانتفاعی',professional:'خدمات حرفه‌ای'
6 };
7 const AF_BASE_ACCOUNTS=[
8 ['1','دارایی‌ها','gl','debit',''],['11','دارایی‌های جاری','subsidiary','debit','1'],['1101','صندوق و بانک','detail','debit','11'],['1102','حساب‌های دریافتنی','detail','debit','11'],['1103','موجودی کالا و مواد','detail','debit','11'],['1104','پیش‌پرداخت‌ها','detail','debit','11'],
9 ['2','بدهی‌ها','gl','credit',''],['21','بدهی‌های جاری','subsidiary','credit','2'],['2101','حساب‌های پرداختنی','detail','credit','21'],['2102','مالیات و عوارض پرداختنی','detail','credit','21'],['2103','سپرده‌ها و کسورات پرداختنی','detail','credit','21'],
10 ['3','حقوق مالکانه','gl','credit',''],['31','سرمایه و اندوخته‌ها','subsidiary','credit','3'],['3101','سرمایه','detail','credit','31'],['3102','سود و زیان انباشته','detail','credit','31'],
11 ['4','درآمدها','gl','credit',''],['41','درآمد عملیاتی','subsidiary','credit','4'],['4101','فروش / درآمد خدمات','detail','credit','41'],['42','سایر درآمدها','subsidiary','credit','4'],['4201','سایر درآمدهای عملیاتی و غیرعملیاتی','detail','credit','42'],
12 ['5','بهای تمام‌شده','gl','debit',''],['51','بهای تمام‌شده عملیات','subsidiary','debit','5'],['5101','بهای تمام‌شده کالای فروش‌رفته / خدمات','detail','debit','51'],
13 ['6','هزینه‌ها','gl','debit',''],['61','هزینه‌های اداری و عمومی','subsidiary','debit','6'],['6101','حقوق و دستمزد','detail','debit','61'],['6102','اجاره و خدمات محل','detail','debit','61'],['6103','هزینه‌های عمومی','detail','debit','61']
14 ];
15 const AF_SPECIAL_ACCOUNTS={
16 manufacturing:[['52','تولید و ساخت','subsidiary','debit','5'],['5201','مواد مستقیم مصرفی','detail','debit','52'],['5202','دستمزد مستقیم','detail','debit','52'],['5203','سربار تولید','detail','debit','52'],['5204','کالای در جریان ساخت','detail','debit','52']],
17 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'],['2104','سپرده حسن انجام کار','detail','credit','21']],
18 retail:[['4102','فروش خرده‌فروشی','detail','credit','41'],['6104','تخفیفات و پروموشن','detail','debit','61']],
19 distribution:[['4103','فروش پخش','detail','credit','41'],['6105','هزینه توزیع و حمل','detail','debit','61']],
20 nonprofit:[['4104','کمک‌ها و درآمدهای غیرانتفاعی','detail','credit','41'],['6106','هزینه برنامه‌ها و مأموریت','detail','debit','61']],
21 professional:[['4105','درآمد خدمات حرفه‌ای','detail','credit','41'],['6107','حق‌الزحمه همکاران و متخصصان','detail','debit','61']],
22 service:[['4106','درآمد خدمات','detail','credit','41'],['6108','هزینه ارائه خدمات','detail','debit','61']],
23 trading:[['4107','فروش کالا','detail','credit','41'],['5102','خرید و بهای کالای فروش‌رفته','detail','debit','51']]
24 };
25 function afCompanyId(){const s=getMySettings(),c=getMyCompanies();return s.default_company_id||c[0]?.id||'';}
26 function afOwned(k){const cid=afCompanyId();return(datastore[k]||[]).filter(x=>x.ownerUserId===currentUser?.id&&(!x.companyId||x.companyId===cid));}
27 function getMyFiscalYears(){return afOwned('fiscalYears')} function getMyAccounts(){return afOwned('accounts')}
28 function getMyDimensionTypes(){return afOwned('dimensionTypes')} function getMyDimensionValues(){return afOwned('dimensionValues')}
29 function getMyAccountDimensionRules(){return afOwned('accountDimensionRules')} function getMyBranches(){return afOwned('branches')}
30 function getMyGlobalProjects(){return afOwned('projects')}
31 function afId(p){return p+'_'+Date.now().toString(36)+'_'+Math.random().toString(36).slice(2,7)}
32 function afCode(v){return String(v||'').trim().replace(/\s+/g,'-').slice(0,32)}
33 function afNeedCompany(){const id=afCompanyId();if(!id)alert('ابتدا یک شرکت تعریف و فعال کنید.');return id}
34 function afProjectUsed(id){return 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)}
35 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}));return getMyDimensionValues().filter(x=>x.dimensionTypeId===t.id).map(x=>({...x,postable:afDimensionValuePostable(x,t)}))}
36 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)}
37 function afDimensionHasValues(typeId){return getMyDimensionValues().some(x=>x.dimensionTypeId===typeId)}
38 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}}))}
39 function afSeed(){
40 if(!currentUser||!afCompanyId())return;let ch=false,cid=afCompanyId();
41 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}
42 if(ch)saveDatastore();
43 }
44 function afMigrateLegacyProjects(){
45 if(!currentUser||!afCompanyId())return;const s=getMySettings();const key='accountingFoundationMigrationV2_'+afCompanyId();if(s[key])return;let ch=false;
46 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}})}));
47 s[key]={completedAt:new Date().toISOString(),mode:'copy-preserve-ids'};if(ch||!s[key])saveDatastore();else saveDatastore();
48 }
49 function afCreateDimension(cid,code,title,sourceEntity,maxDepth=1){
50 if(getMyDimensionTypes().some(x=>x.code===code))return getMyDimensionTypes().find(x=>x.code===code);
51 const d={id:afId('DIM'),ownerUserId:currentUser.id,companyId:cid,code,title,maxDepth:Number(maxDepth),depthLocked:false,leafOnlyPosting:true,active:true,sourceType:sourceEntity==='manual'?'manual':'entity-backed',sourceEntity};
52 datastore.dimensionTypes.push(d);return d;
53 }
54 function afApplyTemplate(companyId,type){
55 if(!requireWrite()||!companyId)return false;const company=getMyCompanies().find(x=>x.id===companyId);if(!company)return false;
56 if(getMyAccounts().some(x=>x.companyId===companyId)){alert('برای این شرکت کدینگ وجود دارد؛ قالب روی کدینگ موجود اعمال نشد.');return false}
57 const previous=getMySettings().default_company_id;getMySettings().default_company_id=companyId;
58 try{
59 const rows=[...AF_BASE_ACCOUNTS,...(AF_SPECIAL_ACCOUNTS[type]||[])],byCode={};
60 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,postingAllowed:level==='detail',active:true,template:type};datastore.accounts.push(a);byCode[code]=a});
61 const branch=afCreateDimension(companyId,'BRANCH','شعبه','branch',1);
62 const party=afCreateDimension(companyId,'COUNTERPARTY','طرف حساب','contact',1);
63 const project=afCreateDimension(companyId,'PROJECT','پروژه','project',1);
64 const cost=afCreateDimension(companyId,'COST_ELEMENT','عناصر هزینه','manual',3);
65 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})};
66 ['1102','2101'].forEach(c=>addRule(c,party,'required'));['1101','4101','5101','6101','6102','6103'].forEach(c=>addRule(c,branch,'optional'));
67 if(type==='contracting'){['4301','5301','5302','1105','2104'].forEach(c=>addRule(c,project,'required'))}
68 if(['service','manufacturing','contracting','professional'].includes(type)){['6101','6102','6103','5101'].forEach(c=>addRule(c,cost,'optional'))}
69 company.activityType=type;company.accountingTemplate={type,appliedAt:new Date().toISOString(),version:1};saveDatastore();return true;
70 }finally{getMySettings().default_company_id=companyId;saveDatastore()}
71 }
72 function afSaveAccount(){
73 if(!requireWrite())return;const cid=afNeedCompany();if(!cid)return;
74 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,parentId=document.getElementById('af-account-parent').value;
75 if(!code||!title)return alert('کد و عنوان حساب الزامی است.');if(getMyAccounts().some(x=>x.code===code))return alert('کد حساب تکراری است.');
76 const need=level==='subsidiary'?'gl':level==='detail'?'subsidiary':'';if(need&&!getMyAccounts().some(x=>x.id===parentId&&x.level===need))return alert('حساب والد معتبر انتخاب کنید.');
77 datastore.accounts.push({id:afId('ACC'),ownerUserId:currentUser.id,companyId:cid,code,title,level,parentId:parentId||'',normalBalance,postingAllowed:level==='detail',active:true});saveDatastore();renderAccountingFoundation();
78 }
79 function afDeleteAccount(id){if(!requireWrite())return;if((datastore.journalLines||[]).some(x=>x.accountId===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()}}
80 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)&&(datastore.journalLines||[]).some(l=>l.ownerUserId===currentUser.id&&l.accountId===accountId))return alert('حساب دارای سابقه دفتر است؛ تغییر قواعد تفصیلی نیاز به نسخه‌بندی دارد.');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()}
81 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()}
82 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()}
83 function afChangeDimensionDepth(id){
84 if(!requireWrite())return;const t=getMyDimensionTypes().find(x=>x.id===id);if(!t||t.sourceEntity!=='manual')return alert('عمق تفصیلی متصل به داده پایه ثابت است.');
85 if(afDimensionHasValues(id))return alert('تا وقتی حتی یک مقدار در این تفصیلی وجود دارد، عمق ساختار قابل تغییر نیست. ابتدا مقادیر بدون ارجاع را حذف کنید.');
86 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('عمق باید عدد صحیح بین ۱ تا ۸ باشد.');
87 t.maxDepth=n;t.depthLocked=false;t.updatedAt=new Date().toISOString();saveDatastore();renderAccountingFoundation();
88 }
89 function afDeleteDimension(id){
90 if(!requireWrite())return;if(afDimensionHasValues(id))return alert('این تفصیلی دارای مقدار است و قابل حذف نیست.');if(getMyAccountDimensionRules().some(x=>x.dimensionTypeId===id))return alert('این تفصیلی به حساب‌ها متصل است؛ ابتدا قواعد حساب را حذف کنید.');
91 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()}
92 }
93 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()}
94 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()}
95 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()}
96 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()}
97 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()}
98 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()}
99 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()}
100 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()}