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

feat/draft-first-attachment-lifecycle-216
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 134 lines 36.4 KB
Raw
1 /* Phase 5 — complementary ERP: inventory, assets, FX, analytics, import/backup and integration outbox */
2 const P5_LABELS={opening:'افتتاحیه',adjustment_in:'تعدیل افزایشی',adjustment_out:'تعدیل کاهشی',transfer:'انتقال'};
3 function p5Owned(k){const cid=afCompanyId();return(datastore[k]||[]).filter(x=>x.ownerUserId===currentUser?.id&&(!x.companyId||x.companyId===cid))}
4 function getMyWarehouses(){return p5Owned('warehouses')} function getMyStockMovements(){return p5Owned('stockMovements')}
5 function getMyInventoryCounts(){return p5Owned('inventoryCounts')} function getMyFixedAssets(){return p5Owned('fixedAssets')}
6 function getMyAssetDepreciations(){return p5Owned('assetDepreciations')} function getMyCurrencies(){return p5Owned('currencies')}
7 function getMyExchangeRates(){return p5Owned('exchangeRates')} function getMyCostCenters(){return p5Owned('costCenters')}
8 function getMyImportBatches(){return p5Owned('importBatches')} function getMyIntegrationConnections(){return p5Owned('integrationConnections')}
9 function getMyIntegrationOutbox(){return p5Owned('integrationOutbox')} function getMyPhase5Audit(){return p5Owned('phase5Audit')}
10 function p5Id(p){return p+'_'+Date.now().toString(36)+'_'+Math.random().toString(36).slice(2,7)}
11 function p5Audit(action,entity,entityId,before,after){if(!currentUser)return;datastore.phase5Audit.push({id:p5Id('P5A'),ownerUserId:currentUser.id,companyId:afCompanyId(),action,entity,entityId,before:before||null,after:after||null,at:new Date().toISOString()})}
12 function p5Need(){if(!requireWrite())return'';const c=afCompanyId();if(!c)alert('ابتدا شرکت فعال را انتخاب کنید.');return c}
13 function p5EnsureSeed(){
14 if(!currentUser||!afCompanyId())return;let ch=false,cid=afCompanyId();
15 if(!getMyWarehouses().length){datastore.warehouses.push({id:p5Id('WH'),ownerUserId:currentUser.id,companyId:cid,code:'MAIN',name:'انبار اصلی',active:true,createdAt:new Date().toISOString()});ch=true}
16 if(!getMyCurrencies().some(x=>x.code==='IRR')){datastore.currencies.push({id:p5Id('CUR'),ownerUserId:currentUser.id,companyId:cid,code:'IRR',title:'ریال ایران',symbol:'ریال',decimals:0,base:true,active:true});ch=true}
17 const s=getMySettings();if(!s.baseCurrencyCode){s.baseCurrencyCode='IRR';ch=true}if(!s.inventoryCostMethod){s.inventoryCostMethod='weighted_average';ch=true}
18 if(ch)saveDatastore();
19 }
20 function p5PopulateWarehouseSelects(){p5EnsureSeed();const rows=getMyWarehouses().filter(x=>x.active!==false),def=p5DefaultWarehouse();['invoice-warehouse-id','pur-warehouse'].forEach(id=>{const el=document.getElementById(id);if(!el)return;const keep=el.value;el.innerHTML=p5Options(rows);el.value=keep&&rows.some(x=>x.id===keep)?keep:(def?.id||'')})}
21 function p5DefaultWarehouse(){p5EnsureSeed();return getMyWarehouses().find(x=>x.id===getMySettings().defaultWarehouseId)||getMyWarehouses().find(x=>x.active!==false)||null}
22 function p5OperationalEvents(productId,warehouseId){
23 const wh=p5DefaultWarehouse();if(!wh||warehouseId!==wh.id)return[];
24 const out=[];
25 getMyPurchases().forEach(d=>{if((d.warehouseId||wh.id)!==warehouseId)return;(d.items||[]).forEach(i=>{if((i.prodId||i.productId)===productId)out.push({delta:Number(i.qty??i.quantity)||0,qty:Number(i.qty??i.quantity)||0,unitCost:Number(i.price??i.unitPrice)||0,date:d.date||'',source:'purchase',sourceId:d.id})})});
26 getMyInvoices().filter(d=>(typeof invoiceCreatesAccountingEntry!=='function'||invoiceCreatesAccountingEntry(d.kind))&&typeof invoiceDocumentStatus==='function'&&invoiceDocumentStatus(d)==='posted').forEach(d=>{if((d.warehouseId||wh.id)!==warehouseId)return;(d.items||[]).forEach(i=>{if((i.prodId||i.productId)===productId)out.push({delta:-(Number(i.qty??i.quantity)||0),qty:Number(i.qty??i.quantity)||0,unitCost:0,date:d.date||'',source:'sale',sourceId:d.id})})});
27 return out;
28 }
29 function p5ManualEvents(productId,warehouseId){
30 const out=[];getMyStockMovements().filter(m=>m.status==='posted'&&m.productId===productId).forEach(m=>{
31 const q=Number(m.qty)||0;if(m.kind==='transfer'){if(m.warehouseId===warehouseId)out.push({delta:-q,...m});if(m.toWarehouseId===warehouseId)out.push({delta:q,...m});}
32 else if(m.warehouseId===warehouseId)out.push({delta:m.kind==='adjustment_out'?-q:q,...m});
33 });return out;
34 }
35 function p5Stock(productId,warehouseId){return P5Domain.stockFromEvents([...p5OperationalEvents(productId,warehouseId),...p5ManualEvents(productId,warehouseId)])}
36 function p5AverageCost(productId){
37 const p=getMyProducts().find(x=>x.id===productId);if(!p)return 0;const wh=p5DefaultWarehouse();if(!wh)return Number(p.buy_price)||0;
38 const opening=getMyStockMovements().filter(m=>m.status==='posted'&&m.productId===productId&&m.warehouseId===wh.id&&m.kind==='opening');
39 const oq=opening.reduce((s,m)=>s+(Number(m.qty)||0),0),oc=oq?opening.reduce((s,m)=>s+(Number(m.qty)||0)*(Number(m.unitCost)||0),0)/oq:(Number(p.buy_price)||0);
40 const receipts=[];getMyPurchases().forEach(d=>(d.items||[]).forEach(i=>{if((i.prodId||i.productId)===productId)receipts.push({qty:Number(i.qty??i.quantity)||0,unitCost:Number(i.price??i.unitPrice)||0})}));
41 getMyStockMovements().filter(m=>m.status==='posted'&&m.productId===productId&&m.kind==='adjustment_in').forEach(m=>receipts.push({qty:m.qty,unitCost:m.unitCost}));
42 return P5Domain.weightedAverage(oq,oc,receipts);
43 }
44 function p5InventorySnapshot(){p5EnsureSeed();return getMyProducts().filter(p=>p.type!=='service').flatMap(p=>getMyWarehouses().filter(w=>w.active!==false).map(w=>({product:p,warehouse:w,qty:p5Stock(p.id,w.id),avgCost:p5AverageCost(p.id)})))}
45 function p5SaveWarehouse(){
46 const cid=p5Need();if(!cid)return;const code=document.getElementById('p5-wh-code').value.trim().toUpperCase(),name=document.getElementById('p5-wh-name').value.trim();if(!code||!name)return alert('کد و نام انبار الزامی است.');if(getMyWarehouses().some(x=>x.code===code))return alert('کد انبار تکراری است.');
47 const r={id:p5Id('WH'),ownerUserId:currentUser.id,companyId:cid,code,name,active:true,createdAt:new Date().toISOString()};datastore.warehouses.push(r);p5Audit('create','warehouse',r.id,null,r);saveDatastore();p5RenderInventory();
48 }
49 function p5PostMovement(){
50 const cid=p5Need();if(!cid)return;const m={id:p5Id('SM'),ownerUserId:currentUser.id,companyId:cid,kind:document.getElementById('p5-mv-kind').value,productId:document.getElementById('p5-mv-product').value,warehouseId:document.getElementById('p5-mv-from').value,toWarehouseId:document.getElementById('p5-mv-to').value,qty:Number(toEnDigits(document.getElementById('p5-mv-qty').value))||0,unitCost:Number(toEnDigits(document.getElementById('p5-mv-cost').value))||0,date:document.getElementById('p5-mv-date').value||getJalaliNumeric(),reference:document.getElementById('p5-mv-ref').value.trim(),status:'posted',postedAt:new Date().toISOString()};
51 try{P5Domain.validateMovement(m);if(['adjustment_out','transfer'].includes(m.kind)&&p5Stock(m.productId,m.warehouseId)<m.qty)throw new Error('موجودی انبار برای خروج کافی نیست.');}catch(e){return alert(e.message)}
52 datastore.stockMovements.push(m);try{p5PostInventoryValue(m);p5Audit('post','stockMovement',m.id,null,m);saveDatastore();p5RenderInventory();}catch(e){datastore.stockMovements=datastore.stockMovements.filter(x=>x.id!==m.id);saveDatastore();alert(e.message)}
53 }
54 function p5PostInventoryValue(m){
55 if(!['adjustment_in','adjustment_out'].includes(m.kind)||!(Number(m.unitCost)>0))return null;const inv=jeAccountByCode('1103'),other=jeAccountByCode(m.kind==='adjustment_in'?'4201':'5101'),value=Number(m.qty)*Number(m.unitCost);if(!inv||!other)throw new Error('حساب موجودی/تعدیل در کدینگ تکمیل نیست.');
56 const lines=m.kind==='adjustment_in'?[{accountId:inv.id,debit:value,credit:0,description:'تعدیل موجودی',dimensions:[]},{accountId:other.id,debit:0,credit:value,description:'تعدیل افزایشی موجودی',dimensions:[]}]:[{accountId:other.id,debit:value,credit:0,description:'تعدیل کاهشی موجودی',dimensions:[]},{accountId:inv.id,debit:0,credit:value,description:'خروج تعدیلی موجودی',dimensions:[]}];
57 const v=jeCreateDraft({date:m.date,description:'تعدیل موجودی — '+(m.reference||m.id),sourceType:'inventory_adjustment',sourceId:m.id,lines});jePost(v.id);m.journalVoucherId=v.id;m.accountingStatus='posted';return v;
58 }
59 function p5SaveCount(){
60 const cid=p5Need();if(!cid)return;const productId=document.getElementById('p5-count-product').value,warehouseId=document.getElementById('p5-count-wh').value,physicalQty=Number(toEnDigits(document.getElementById('p5-count-qty').value));if(!productId||!warehouseId||!Number.isFinite(physicalQty)||physicalQty<0)return alert('اطلاعات شمارش معتبر نیست.');
61 const systemQty=p5Stock(productId,warehouseId),diff=physicalQty-systemQty,r={id:p5Id('IC'),ownerUserId:currentUser.id,companyId:cid,productId,warehouseId,date:getJalaliNumeric(),systemQty,physicalQty,difference:diff,status:'posted',postedAt:new Date().toISOString()};let m=null;datastore.inventoryCounts.push(r);
62 try{if(diff){m={id:p5Id('SM'),ownerUserId:currentUser.id,companyId:cid,kind:diff>0?'adjustment_in':'adjustment_out',productId,warehouseId,toWarehouseId:'',qty:Math.abs(diff),unitCost:p5AverageCost(productId),date:r.date,reference:'انبارگردانی '+r.id,status:'posted',sourceType:'inventory_count',sourceId:r.id,postedAt:r.postedAt};datastore.stockMovements.push(m);p5PostInventoryValue(m);r.journalVoucherId=m.journalVoucherId||''}p5Audit('post','inventoryCount',r.id,null,r);saveDatastore();p5RenderInventory()}catch(e){datastore.inventoryCounts=datastore.inventoryCounts.filter(x=>x.id!==r.id);if(m)datastore.stockMovements=datastore.stockMovements.filter(x=>x.id!==m.id);saveDatastore();alert(e.message)}
63 }
64 function p5EnsureAssetAccounts(){
65 const cid=afCompanyId();if(!cid)return;const specs=[['15','دارایی‌های ثابت','subsidiary','debit','1'],['1501','دارایی ثابت مشهود','detail','debit','15'],['1502','استهلاک انباشته دارایی ثابت','detail','credit','15'],['62','هزینه استهلاک','subsidiary','debit','6'],['6201','هزینه استهلاک دارایی ثابت','detail','debit','62']];const byCode=Object.fromEntries(getMyAccounts().map(a=>[a.code,a]));let ch=false;
66 specs.forEach(([code,title,level,normalBalance,parentCode])=>{if(byCode[code])return;const parent=byCode[parentCode];if(!parent)return;const a={id:afId('ACC'),ownerUserId:currentUser.id,companyId:cid,code,title,level,parentId:parent.id,normalBalance,accountType:typeof afAccountTypeForCode==='function'?afAccountTypeForCode(code):((code.startsWith('1'))?'asset':'expense'),postingAllowed:level==='detail',active:true,template:'phase5'};datastore.accounts.push(a);byCode[code]=a;ch=true});if(ch)saveDatastore();
67 }
68 function p5SaveAsset(){
69 const cid=p5Need();if(!cid)return;const code=document.getElementById('p5-asset-code').value.trim(),name=document.getElementById('p5-asset-name').value.trim(),cost=Number(toEnDigits(document.getElementById('p5-asset-cost').value))||0,salvage=Number(toEnDigits(document.getElementById('p5-asset-salvage').value))||0,usefulMonths=Number(toEnDigits(document.getElementById('p5-asset-months').value))||0,acquisitionDate=document.getElementById('p5-asset-date').value||getJalaliNumeric();if(!code||!name||cost<=0||usefulMonths<=0||salvage<0||salvage>cost)return alert('اطلاعات دارایی معتبر نیست.');if(getMyFixedAssets().some(x=>x.code===code))return alert('کد دارایی تکراری است.');
70 const a={id:p5Id('FA'),ownerUserId:currentUser.id,companyId:cid,code,name,cost,salvage,usefulMonths,acquisitionDate,status:'active',createdAt:new Date().toISOString()};datastore.fixedAssets.push(a);p5Audit('create','fixedAsset',a.id,null,a);p5EnsureAssetAccounts();saveDatastore();p5RenderAssets();
71 }
72 function p5DepreciationVoucher(d){return d?.journalVoucherId&&typeof getMyJournalVouchers==='function'?getMyJournalVouchers().find(v=>v.id===d.journalVoucherId):null}
73 function p5DepreciationActive(d){if(!d||d.status!=='posted')return false;const v=p5DepreciationVoucher(d);return !d.journalVoucherId||!v||v.status==='posted'}
74 function p5ReverseDepreciation(id){
75 const cid=p5Need(),d=getMyAssetDepreciations().find(x=>x.id===id);if(!cid||!d)return;const v=p5DepreciationVoucher(d);if(!v||v.status!=='posted')return alert('سند استهلاک فعال برای برگشت پیدا نشد.');if(!confirm('سند استهلاک این دوره برگشت داده شود؟ سابقه اصلی حذف نمی‌شود.'))return;
76 try{const rv=jeReverse(v.id,getJalaliNumeric(),'برگشت استهلاک '+d.period);p5Audit('reverse','assetDepreciation',d.id,{journalVoucherId:v.id,status:'posted'},{journalVoucherId:v.id,journalStatus:'reversed',reversalVoucherId:rv.id});saveDatastore();p5RenderAssets()}catch(e){alert(e.message)}
77 }
78 function p5RunDepreciation(assetId){
79 const cid=p5Need(),a=getMyFixedAssets().find(x=>x.id===assetId);if(!cid||!a||a.status!=='active')return;const period=prompt('دوره استهلاک (مثلاً 1405/07):',String(getJalaliNumeric()).slice(0,7));if(!period)return;if(getMyAssetDepreciations().some(x=>x.assetId===assetId&&x.period===period&&p5DepreciationActive(x)))return alert('استهلاک این دوره قبلاً ثبت شده است.');
80 const monthly=P5Domain.monthlyDepreciation(a.cost,a.salvage,a.usefulMonths),posted=getMyAssetDepreciations().filter(x=>x.assetId===assetId&&p5DepreciationActive(x)).reduce((s,x)=>s+(Number(x.amount)||0),0),amount=Math.max(0,Math.min(monthly,a.cost-a.salvage-posted));if(amount<=0)return alert('دارایی به سقف استهلاک رسیده است.');
81 p5EnsureAssetAccounts();const dep=jeAccountByCode('6201'),acc=jeAccountByCode('1502');if(!dep||!acc)return alert('حساب‌های استهلاک در کدینگ قابل ایجاد نیستند.');
82 const r={id:p5Id('DEP'),ownerUserId:currentUser.id,companyId:cid,assetId,period,amount,status:'draft',createdAt:new Date().toISOString()};datastore.assetDepreciations.push(r);
83 try{const v=jeCreateDraft({date:period+'/29',description:'استهلاک '+a.name+' — '+period,sourceType:'asset_depreciation',sourceId:r.id,lines:[{accountId:dep.id,debit:amount,credit:0,description:'هزینه استهلاک',dimensions:[]},{accountId:acc.id,debit:0,credit:amount,description:'استهلاک انباشته',dimensions:[]}]});jePost(v.id);r.status='posted';r.journalVoucherId=v.id;r.postedAt=new Date().toISOString();p5Audit('post','assetDepreciation',r.id,null,r);saveDatastore();p5RenderAssets()}catch(e){datastore.assetDepreciations=datastore.assetDepreciations.filter(x=>x.id!==r.id);saveDatastore();alert(e.message)}
84 }
85 function p5SaveCurrency(){
86 const cid=p5Need();if(!cid)return;const code=document.getElementById('p5-cur-code').value.trim().toUpperCase(),title=document.getElementById('p5-cur-title').value.trim(),symbol=document.getElementById('p5-cur-symbol').value.trim();if(!/^[A-Z]{3}$/.test(code)||!title)return alert('کد سه‌حرفی و عنوان ارز الزامی است.');if(getMyCurrencies().some(x=>x.code===code))return alert('این ارز قبلاً تعریف شده است.');const r={id:p5Id('CUR'),ownerUserId:currentUser.id,companyId:cid,code,title,symbol:symbol||code,decimals:2,base:false,active:true};datastore.currencies.push(r);p5Audit('create','currency',r.id,null,r);saveDatastore();p5RenderCurrency();
87 }
88 function p5SaveRate(){
89 const cid=p5Need();if(!cid)return;const currencyCode=document.getElementById('p5-rate-cur').value,date=document.getElementById('p5-rate-date').value||getJalaliNumeric(),rate=Number(toEnDigits(document.getElementById('p5-rate-value').value))||0;if(!currencyCode||currencyCode==='IRR'||rate<=0)return alert('ارز و نرخ معتبر انتخاب کنید.');const old=getMyExchangeRates().find(x=>x.currencyCode===currencyCode&&x.date===date);if(old)return alert('برای این ارز و تاریخ نرخ ثبت شده است.');const r={id:p5Id('FX'),ownerUserId:currentUser.id,companyId:cid,currencyCode,date,rate,baseCurrencyCode:getMySettings().baseCurrencyCode||'IRR',createdAt:new Date().toISOString()};datastore.exchangeRates.push(r);p5Audit('create','exchangeRate',r.id,null,r);saveDatastore();p5RenderCurrency();
90 }
91 function p5Rate(code,date){if(code===(getMySettings().baseCurrencyCode||'IRR'))return 1;const rows=getMyExchangeRates().filter(x=>x.currencyCode===code&&(!date||x.date<=date)).sort((a,b)=>String(b.date).localeCompare(String(a.date)));return Number(rows[0]?.rate)||0}
92 function p5SaveCostCenter(){
93 const cid=p5Need();if(!cid)return;const code=document.getElementById('p5-cc-code').value.trim(),name=document.getElementById('p5-cc-name').value.trim();if(!code||!name)return alert('کد و عنوان مرکز هزینه الزامی است.');if(getMyCostCenters().some(x=>x.code===code))return alert('کد تکراری است.');const r={id:p5Id('CC'),ownerUserId:currentUser.id,companyId:cid,code,name,active:true};datastore.costCenters.push(r);p5Audit('create','costCenter',r.id,null,r);saveDatastore();p5RenderDataCenter();
94 }
95 function p5SaveCompanyOpsSettings(){const cid=p5Need();if(!cid)return;const s=getMySettings(),warehouseId=document.getElementById('p5-set-default-wh')?.value||'',baseCurrencyCode=document.getElementById('p5-set-base-cur')?.value||'IRR',inventoryCostMethod=document.getElementById('p5-set-cost-method')?.value||'weighted_average';if(!getMyWarehouses().some(x=>x.id===warehouseId))return alert('انبار پیش‌فرض معتبر نیست.');if(!getMyCurrencies().some(x=>x.code===baseCurrencyCode))return alert('ارز پایه معتبر نیست.');if((s.baseCurrencyCode||'IRR')!==baseCurrencyCode&&getMyExchangeRates().length)return alert('پس از ثبت نرخ ارز، تغییر مستقیم ارز پایه مجاز نیست؛ ابتدا باید مهاجرت کنترل‌شده نرخ‌ها انجام شود.');const before={defaultWarehouseId:s.defaultWarehouseId||'',baseCurrencyCode:s.baseCurrencyCode||'IRR',inventoryCostMethod:s.inventoryCostMethod||'weighted_average'};Object.assign(s,{defaultWarehouseId:warehouseId,baseCurrencyCode,inventoryCostMethod});p5Audit('update','companyOpsSettings',cid,before,{defaultWarehouseId:warehouseId,baseCurrencyCode,inventoryCostMethod});saveDatastore();p5PopulateWarehouseSelects();p5RenderDataCenter()}
96 function p5BackupPayload(){const o={formatVersion:5,user:currentUser?.username,exportedAt:new Date().toISOString()};COLLS.forEach(k=>o[k]=(datastore[k]||[]).filter(x=>x.ownerUserId===currentUser?.id).map(x=>{const y={...x};delete y.ownerUserId;return y}));return o}
97 function p5ExportBackup(){const blob=new Blob([JSON.stringify(p5BackupPayload(),null,2)],{type:'application/json'}),a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download='finora-full-backup-'+Date.now()+'.json';a.click();setTimeout(()=>URL.revokeObjectURL(a.href),500)}
98 function p5PreviewRestore(event){
99 const file=event.target.files[0];if(!file)return;if(file.size>20*1024*1024){event.target.value='';return document.getElementById('p5-import-preview').textContent='نامعتبر: حجم فایل پشتیبان نباید بیشتر از ۲۰ مگابایت باشد.'}const r=new FileReader();r.onload=()=>{try{const p=JSON.parse(r.result);P5Domain.validateRestore(p,COLLS);const counts=COLLS.filter(k=>Array.isArray(p[k])&&p[k].length).map(k=>k+': '+p[k].length);window.p5PendingRestore=p;document.getElementById('p5-import-preview').innerHTML='پیش‌نمایش معتبر — '+esc(counts.join(' | '))+' <button class="btn btn-danger btn-inline" onclick="p5ApplyRestore()">اعمال ادغام امن</button>';datastore.importBatches.push({id:p5Id('IMP'),ownerUserId:currentUser.id,companyId:afCompanyId(),fileName:file.name,mode:'preview',counts:Object.fromEntries(COLLS.map(k=>[k,(p[k]||[]).length])),status:'validated',createdAt:new Date().toISOString()});saveDatastore()}catch(e){document.getElementById('p5-import-preview').textContent='نامعتبر: '+e.message}};r.readAsText(file)
100 }
101 function p5ApplyRestore(){
102 const p=window.p5PendingRestore;if(!p||!currentUser||!requireWrite())return;if(!confirm('فایل اعتبارسنجی شده با داده‌های حساب شما ادغام شود؟ سابقه قطعی موجود بازنویسی نمی‌شود.'))return;
103 try{const n=absorbRecords(p);datastore.importBatches.push({id:p5Id('IMP'),ownerUserId:currentUser.id,companyId:afCompanyId(),fileName:'validated-backup.json',mode:'merge',counts:{records:n},status:'applied',createdAt:new Date().toISOString()});p5Audit('restore','backup','merge',null,{records:n});saveDatastore();window.p5PendingRestore=null;refreshAllSurfaces();alert(n.toLocaleString('fa-IR')+' رکورد با موفقیت ادغام شد.')}catch(e){alert('بازگردانی انجام نشد: '+e.message)}
104 }
105 function p5ValidateIntegrationEndpoint(raw){
106 const value=String(raw||'').trim();if(!value)return '';let u;try{u=new URL(value)}catch(_){throw new Error('نشانی اتصال معتبر نیست.')}if(u.protocol!=='https:')throw new Error('نشانی اتصال باید HTTPS باشد.');if(u.username||u.password)throw new Error('قرار دادن نام کاربری/رمز در URL اتصال مجاز نیست.');const h=u.hostname.toLowerCase(),privateHost=h==='localhost'||h==='::1'||h.endsWith('.local')||/^127\./.test(h)||/^10\./.test(h)||/^192\.168\./.test(h)||/^169\.254\./.test(h)||/^172\.(1[6-9]|2\d|3[01])\./.test(h);if(privateHost)throw new Error('Endpoint شبکه خصوصی/محلی برای اتصال خارجی مجاز نیست.');return u.href;
107 }
108 function p5SaveIntegration(){
109 const cid=p5Need();if(!cid)return;const name=document.getElementById('p5-int-name').value.trim(),kind=document.getElementById('p5-int-kind').value;let endpoint='';try{endpoint=p5ValidateIntegrationEndpoint(document.getElementById('p5-int-endpoint').value)}catch(e){return alert(e.message)}if(!name)return alert('نام اتصال الزامی است.');const r={id:p5Id('INT'),ownerUserId:currentUser.id,companyId:cid,name,kind,endpoint,active:true,secretStored:false,createdAt:new Date().toISOString()};datastore.integrationConnections.push(r);p5Audit('create','integrationConnection',r.id,null,r);saveDatastore();p5RenderIntegrations();
110 }
111 function p5QueueEvent(connectionId,eventType){
112 const cid=p5Need(),c=getMyIntegrationConnections().find(x=>x.id===connectionId);if(!cid||!c)return;const r={id:p5Id('OUT'),ownerUserId:currentUser.id,companyId:cid,connectionId,eventType,payload:{companyId:cid,generatedAt:new Date().toISOString()},status:'pending',attempts:0,createdAt:new Date().toISOString()};datastore.integrationOutbox.push(r);p5Audit('queue','integrationOutbox',r.id,null,r);saveDatastore();p5RenderIntegrations();
113 }
114 function p5ExportOutbox(id){const r=getMyIntegrationOutbox().find(x=>x.id===id);if(!r)return;const b=new Blob([JSON.stringify(r,null,2)],{type:'application/json'}),a=document.createElement('a');a.href=URL.createObjectURL(b);a.download='finora-outbox-'+id+'.json';a.click();setTimeout(()=>URL.revokeObjectURL(a.href),500)}
115 function p5Options(rows,label='name'){return rows.map(x=>'<option value="'+esc(x.id)+'">'+esc(x.code?x.code+' — ':'')+esc(x[label]||x.title||'')+'</option>').join('')}
116 function p5RenderInventory(){
117 const root=document.getElementById('p5-inventory-root');if(!root)return;p5EnsureSeed();const wh=getMyWarehouses().filter(x=>x.active!==false),goods=getMyProducts().filter(x=>x.type!=='service'),snap=p5InventorySnapshot();
118 root.innerHTML='<div class="grid-kpi"><div class="kpi-unit"><div><div class="kpi-lbl">انبار فعال</div><div class="kpi-val">'+wh.length.toLocaleString('fa-IR')+'</div></div></div><div class="kpi-unit"><div><div class="kpi-lbl">ارزش تقریبی موجودی</div><div class="kpi-val">'+Math.round(snap.reduce((s,x)=>s+x.qty*x.avgCost,0)).toLocaleString('fa-IR')+'</div></div></div></div>'+
119 '<div class="card"><h3>تعریف انبار</h3><div class="form-row"><div class="form-group"><label>کد</label><input id="p5-wh-code" class="form-control"></div><div class="form-group"><label>نام</label><input id="p5-wh-name" class="form-control"></div></div><button class="btn btn-success" onclick="p5SaveWarehouse()">ثبت انبار</button></div>'+
120 '<div class="card"><h3>گردش انبار</h3><div class="form-row"><div class="form-group"><label>نوع</label><select id="p5-mv-kind" class="form-control"><option value="opening">افتتاحیه</option><option value="adjustment_in">تعدیل افزایشی</option><option value="adjustment_out">تعدیل کاهشی</option><option value="transfer">انتقال</option></select></div><div class="form-group"><label>کالا</label><select id="p5-mv-product" class="form-control">'+p5Options(goods)+'</select></div><div class="form-group"><label>از انبار</label><select id="p5-mv-from" class="form-control">'+p5Options(wh)+'</select></div><div class="form-group"><label>به انبار (انتقال)</label><select id="p5-mv-to" class="form-control"><option value="">—</option>'+p5Options(wh)+'</select></div><div class="form-group"><label>مقدار</label><input id="p5-mv-qty" class="form-control"></div><div class="form-group"><label>بهای واحد</label><input id="p5-mv-cost" class="form-control"></div><div class="form-group"><label>تاریخ</label><input id="p5-mv-date" class="form-control" value="'+esc(getJalaliNumeric())+'"></div><div class="form-group"><label>مرجع</label><input id="p5-mv-ref" class="form-control"></div></div><button class="btn btn-primary" onclick="p5PostMovement()">ثبت قطعی گردش</button></div>'+
121 '<div class="card"><h3>انبارگردانی</h3><div class="form-row"><div class="form-group"><label>کالا</label><select id="p5-count-product" class="form-control">'+p5Options(goods)+'</select></div><div class="form-group"><label>انبار</label><select id="p5-count-wh" class="form-control">'+p5Options(wh)+'</select></div><div class="form-group"><label>موجودی شمارش‌شده</label><input id="p5-count-qty" class="form-control"></div></div><button class="btn btn-secondary" onclick="p5SaveCount()">ثبت شمارش و تعدیل</button></div>'+
122 '<div class="card"><h3>موجودی و بهای میانگین موزون</h3><div class="table-responsive"><table><thead><tr><th>کالا</th><th>انبار</th><th>موجودی</th><th>میانگین بها</th><th>ارزش</th></tr></thead><tbody>'+snap.map(x=>'<tr><td>'+esc(x.product.name)+'</td><td>'+esc(x.warehouse.name)+'</td><td>'+x.qty.toLocaleString('fa-IR')+'</td><td>'+Math.round(x.avgCost).toLocaleString('fa-IR')+'</td><td>'+Math.round(x.qty*x.avgCost).toLocaleString('fa-IR')+'</td></tr>').join('')+'</tbody></table></div></div>';
123 }
124 function p5RenderAssets(){const root=document.getElementById('p5-assets-root');if(!root)return;const rows=getMyFixedAssets(),deps=getMyAssetDepreciations().slice().sort((a,b)=>String(b.period||'').localeCompare(String(a.period||'')));root.innerHTML='<div class="card"><h3>ثبت دارایی ثابت</h3><div class="form-row"><div class="form-group"><label>کد</label><input id="p5-asset-code" class="form-control"></div><div class="form-group"><label>عنوان</label><input id="p5-asset-name" class="form-control"></div><div class="form-group"><label>بهای تمام‌شده</label><input id="p5-asset-cost" class="form-control"></div><div class="form-group"><label>ارزش اسقاط</label><input id="p5-asset-salvage" class="form-control" value="0"></div><div class="form-group"><label>عمر مفید (ماه)</label><input id="p5-asset-months" class="form-control" value="60"></div><div class="form-group"><label>تاریخ تحصیل</label><input id="p5-asset-date" class="form-control" value="'+esc(getJalaliNumeric())+'"></div></div><button class="btn btn-success" onclick="p5SaveAsset()">ثبت دارایی</button></div><div class="card"><h3>دفتر دارایی‌ها</h3><div class="table-responsive"><table><thead><tr><th>کد</th><th>دارایی</th><th>بها</th><th>استهلاک ثبت‌شده</th><th>ارزش دفتری</th><th>عملیات</th></tr></thead><tbody>'+rows.map(a=>{const d=getMyAssetDepreciations().filter(x=>x.assetId===a.id&&p5DepreciationActive(x)).reduce((s,x)=>s+(Number(x.amount)||0),0);return '<tr><td>'+esc(a.code)+'</td><td>'+esc(a.name)+'</td><td>'+Number(a.cost).toLocaleString('fa-IR')+'</td><td>'+Math.round(d).toLocaleString('fa-IR')+'</td><td>'+Math.round(a.cost-d).toLocaleString('fa-IR')+'</td><td><button class="btn btn-secondary btn-inline" onclick="p5RunDepreciation(\''+a.id+'\')">ثبت استهلاک دوره</button></td></tr>'}).join('')+'</tbody></table></div></div><div class="card"><h3>سوابق استهلاک</h3><div class="table-responsive"><table><thead><tr><th>دارایی</th><th>دوره</th><th>مبلغ</th><th>وضعیت سند</th><th>عملیات</th></tr></thead><tbody>'+deps.map(d=>{const a=rows.find(x=>x.id===d.assetId),v=p5DepreciationVoucher(d),active=p5DepreciationActive(d);return '<tr><td>'+esc(a?.name||d.assetId)+'</td><td>'+esc(d.period||'')+'</td><td>'+Number(d.amount||0).toLocaleString('fa-IR')+'</td><td>'+(active?'قطعی':v?.status==='reversed'?'برگشت‌شده':'نامشخص')+'</td><td>'+(active?'<button class="btn btn-secondary btn-inline" onclick="p5ReverseDepreciation(\''+d.id+'\')">برگشت سند</button>':'—')+'</td></tr>'}).join('')+'</tbody></table></div></div>'}
125 function p5RenderCurrency(){const root=document.getElementById('p5-currency-root');if(!root)return;p5EnsureSeed();const cs=getMyCurrencies(),rates=getMyExchangeRates().slice().sort((a,b)=>String(b.date).localeCompare(String(a.date)));root.innerHTML='<div class="card"><h3>ارزها</h3><div class="form-row"><div class="form-group"><label>کد ISO</label><input id="p5-cur-code" class="form-control" placeholder="USD"></div><div class="form-group"><label>عنوان</label><input id="p5-cur-title" class="form-control"></div><div class="form-group"><label>نماد</label><input id="p5-cur-symbol" class="form-control"></div></div><button class="btn btn-success" onclick="p5SaveCurrency()">ثبت ارز</button></div><div class="card"><h3>نرخ تبدیل به ارز پایه</h3><div class="form-row"><div class="form-group"><label>ارز</label><select id="p5-rate-cur" class="form-control">'+cs.filter(x=>!x.base).map(x=>'<option value="'+esc(x.code)+'">'+esc(x.code+' — '+x.title)+'</option>').join('')+'</select></div><div class="form-group"><label>تاریخ</label><input id="p5-rate-date" class="form-control" value="'+esc(getJalaliNumeric())+'"></div><div class="form-group"><label>نرخ</label><input id="p5-rate-value" class="form-control"></div></div><button class="btn btn-primary" onclick="p5SaveRate()">ثبت نرخ</button><div class="table-responsive" style="margin-top:14px"><table><thead><tr><th>ارز</th><th>تاریخ</th><th>نرخ</th></tr></thead><tbody>'+rates.map(x=>'<tr><td>'+esc(x.currencyCode)+'</td><td>'+esc(x.date)+'</td><td>'+Number(x.rate).toLocaleString('fa-IR')+'</td></tr>').join('')+'</tbody></table></div></div>'}
126 function p5RenderDataCenter(){
127 const root=document.getElementById('p5-data-root');if(!root)return;p5EnsureSeed();const cc=getMyCostCenters(),s=getMySettings(),wh=getMyWarehouses().filter(x=>x.active!==false),cur=getMyCurrencies().filter(x=>x.active!==false);
128 root.innerHTML='<div class="card"><h3>تنظیمات عملیاتی و دسترسی شرکت</h3><div class="form-row"><div class="form-group"><label>انبار پیش‌فرض</label><select id="p5-set-default-wh" class="form-control">'+p5Options(wh)+'</select></div><div class="form-group"><label>ارز پایه</label><select id="p5-set-base-cur" class="form-control">'+cur.map(x=>'<option value="'+esc(x.code)+'">'+esc(x.code+' — '+x.title)+'</option>').join('')+'</select></div><div class="form-group"><label>روش بهای موجودی</label><select id="p5-set-cost-method" class="form-control"><option value="weighted_average">میانگین موزون</option></select></div></div><p style="font-size:12px;color:var(--text-muted);margin-bottom:10px">سطح دسترسی مؤثر: '+esc(currentUser?.role==='admin'?'مدیر سیستم':'کاربر مالک داده')+' — دسترسی رکوردها در سرور با RLS مالک‌محور کنترل می‌شود.</p><button class="btn btn-primary" onclick="p5SaveCompanyOpsSettings()">ذخیره تنظیمات</button></div>'+
129 '<div class="card"><h3>مراکز هزینه و تحلیل</h3><div class="form-row"><div class="form-group"><label>کد</label><input id="p5-cc-code" class="form-control"></div><div class="form-group"><label>عنوان</label><input id="p5-cc-name" class="form-control"></div></div><button class="btn btn-success" onclick="p5SaveCostCenter()">ثبت مرکز هزینه</button><div class="table-responsive" style="margin-top:14px"><table><thead><tr><th>کد</th><th>عنوان</th><th>وضعیت</th></tr></thead><tbody>'+cc.map(x=>'<tr><td>'+esc(x.code)+'</td><td>'+esc(x.name)+'</td><td>فعال</td></tr>').join('')+'</tbody></table></div></div>'+
130 '<div class="card"><h3>مرکز ورود، اکسل و پشتیبان</h3><p style="color:var(--text-muted);margin:8px 0 14px">ورود داده و پشتیبان در یک مرکز؛ بازگردانی JSON ابتدا اعتبارسنجی و پیش‌نمایش می‌شود و سپس فقط با تأیید صریح ادغام می‌گردد.</p><div style="display:flex;gap:8px;flex-wrap:wrap"><label class="btn btn-secondary">ورود کالا/خدمت از Excel<input type="file" accept=".xlsx,.xls" style="display:none" onchange="importProductsFromExcel(event)"></label><button class="btn btn-secondary" onclick="switchView(\'view-invoices\')">ورود اکسل فاکتور فروش</button><button class="btn btn-secondary" onclick="switchView(\'view-purchases\')">ورود اکسل فاکتور خرید</button><button class="btn btn-secondary" onclick="p5ExportBackup()">دانلود پشتیبان کامل</button><label class="btn btn-secondary">اعتبارسنجی/بازگردانی JSON<input type="file" accept=".json" style="display:none" onchange="p5PreviewRestore(event)"></label></div><div id="p5-import-preview" style="margin-top:12px;font-size:12px;color:var(--text-muted)"></div></div>';
131 const whSel=document.getElementById('p5-set-default-wh'),curSel=document.getElementById('p5-set-base-cur'),costSel=document.getElementById('p5-set-cost-method');if(whSel)whSel.value=s.defaultWarehouseId||p5DefaultWarehouse()?.id||'';if(curSel)curSel.value=s.baseCurrencyCode||'IRR';if(costSel)costSel.value=s.inventoryCostMethod||'weighted_average';
132 }
133 function p5RenderIntegrations(){const root=document.getElementById('p5-integrations-root');if(!root)return;const cs=getMyIntegrationConnections(),out=getMyIntegrationOutbox().slice(-20).reverse();root.innerHTML='<div class="card"><h3>اتصالات و API</h3><p style="font-size:12px;color:var(--text-muted);margin-bottom:12px">در مرورگر هیچ Secret ذخیره نمی‌شود. اتصال‌ها متادیتا هستند و رویدادها از الگوی Outbox قابل تحویل به سرویس امن سمت سرور پیروی می‌کنند.</p><div class="form-row"><div class="form-group"><label>نام</label><input id="p5-int-name" class="form-control"></div><div class="form-group"><label>نوع</label><select id="p5-int-kind" class="form-control"><option value="webhook">Webhook</option><option value="tax">سامانه مالیاتی</option><option value="bank">بانک/پرداخت</option><option value="custom">سفارشی</option></select></div><div class="form-group"><label>Endpoint HTTPS</label><input id="p5-int-endpoint" class="form-control" dir="ltr"></div></div><button class="btn btn-success" onclick="p5SaveIntegration()">ثبت اتصال</button><div class="table-responsive" style="margin-top:14px"><table><thead><tr><th>نام</th><th>نوع</th><th>Endpoint</th><th>صف</th></tr></thead><tbody>'+cs.map(x=>'<tr><td>'+esc(x.name)+'</td><td>'+esc(x.kind)+'</td><td dir="ltr">'+esc(x.endpoint||'—')+'</td><td><button class="btn btn-secondary btn-inline" onclick="p5QueueEvent(\''+x.id+'\',\'manual.test\')">رویداد آزمایشی</button></td></tr>').join('')+'</tbody></table></div></div><div class="card"><h3>Integration Outbox</h3><div class="table-responsive"><table><thead><tr><th>رویداد</th><th>وضعیت</th><th>زمان</th><th>خروجی</th></tr></thead><tbody>'+out.map(x=>'<tr><td>'+esc(x.eventType)+'</td><td>'+esc(x.status)+'</td><td>'+esc(x.createdAt)+'</td><td><button class="btn btn-secondary btn-inline" onclick="p5ExportOutbox(\''+x.id+'\')">JSON</button></td></tr>').join('')+'</tbody></table></div></div>'}
134 function p5Render(viewId){p5EnsureSeed();if(viewId==='view-inventory')p5RenderInventory();else if(viewId==='view-assets')p5RenderAssets();else if(viewId==='view-currency')p5RenderCurrency();else if(viewId==='view-data-center')p5RenderDataCenter();else if(viewId==='view-integrations')p5RenderIntegrations()}