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

feat/document-lifecycle-temp-permanent-atef
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 740 lines 51 KB
Raw
1 function handleInvoiceKindChange(){
2 const kind=document.getElementById('invoice-kind').value;
3 const salesType=document.querySelector('#view-invoices .finora-invoice-type select');
4 if(salesType)salesType.value=['pre_invoice','contract_statement'].includes(kind)?kind:'sale';
5 const vatModeRow=document.getElementById('box-invoice-vat-mode-row');
6 const vatModeSelect=document.getElementById('invoice-vat-mode');
7 if(kind==='non_formal'){
8 if(vatModeRow)vatModeRow.style.display='none';
9 if(vatModeSelect)vatModeSelect.value='none';
10 }else{
11 if(vatModeRow)vatModeRow.style.display='flex';
12 }
13 const boxEdoc=document.getElementById('box-enable-electronic-doc');
14 if(boxEdoc){
15 if(kind==='formal'){
16 boxEdoc.style.display='block';
17 }else{
18 boxEdoc.style.display='none';
19 const cb=document.getElementById('enable-electronic-doc');
20 if(cb)cb.checked=false;
21 window.pendingElectronicDoc=null;
22 const st=document.getElementById('edoc-status');
23 if(st)st.innerText='';
24 }
25 }
26 const contractBox=document.getElementById('box-invoice-contract-number');
27 if(contractBox)contractBox.style.display=(kind==='contract_statement')?'flex':'none';
28 handleVatModeChange();
29 recomputeTotals();
30 }
31 function handleVatModeChange(){
32 const mode=document.getElementById('invoice-vat-mode').value;
33 const kind=document.getElementById('invoice-kind').value;
34 const rateBox=document.getElementById('box-invoice-vat-rate');
35 if(kind==='non_formal'){rateBox.style.display='none';document.getElementById('invoice-vat-mode').value='none';}
36 else{rateBox.style.display=(mode==='with_vat')?'flex':'none';}
37 recomputeTotals();
38 }
39 function handleVatTypeChange(){const type=document.getElementById('invoice-vat-type').value;document.getElementById('invoice-vat-rate-input').value=(type==='percent')?10:0;recomputeTotals();}
40 function handleDiscountTypeChange(){
41 const type=document.getElementById('invoice-discount-type').value;
42 const label=document.getElementById('label-invoice-discount-value');
43 const cur=getCurrencyLabel();
44 label.innerText=(type==='percent')?'درصد تخفیف (٪)':`مبلغ تخفیف (${cur})`;
45 document.getElementById('invoice-discount-fixed').value=0;
46 recomputeTotals();
47 }
48 function applyDefaultSettingsToForm(){
49 const def=getMySettings();
50 const defKind=document.getElementById('def-invoice-kind');
51 const defVat=document.getElementById('def-vat-mode');
52 const defRate=document.getElementById('def-vat-rate');
53 const defCurMode=document.getElementById('def-currency-mode');
54 const defCurCustom=document.getElementById('def-currency-custom');
55 if(defKind)defKind.value=def.invoice_kind||'non_formal';
56 if(defVat)defVat.value=def.vat_mode||'none';
57 if(defRate)defRate.value=def.vat_rate??10;
58 if(defCurMode)defCurMode.value=def.currency_mode||'rial';
59 if(defCurCustom)defCurCustom.value=def.currency_custom||'';
60 handleCurrencyModeChange();
61 const editId=document.getElementById('edit-invoice-id')?.value;
62 if(!editId){
63 const kindEl=document.getElementById('invoice-kind');
64 if(kindEl)kindEl.value=def.invoice_kind||'non_formal';
65 handleInvoiceKindChange();
66 if((def.invoice_kind||'non_formal')!=='non_formal'){
67 document.getElementById('invoice-vat-mode').value=def.vat_mode||'none';
68 document.getElementById('invoice-vat-rate-input').value=def.vat_rate??10;
69 handleVatModeChange();
70 }
71 }
72 }
73 function commitSaveDefaultSettings(){
74 if(!requireWrite())return;
75 const s=getMySettings();
76 s.invoice_kind=document.getElementById('def-invoice-kind').value;
77 s.vat_mode=document.getElementById('def-vat-mode').value;
78 s.vat_rate=parseFormattedNumber(document.getElementById('def-vat-rate').value);
79 s.currency_mode=document.getElementById('def-currency-mode').value;
80 s.currency_custom=document.getElementById('def-currency-custom').value||'';
81 saveDatastore();
82 refreshCurrencyLabels();
83 alert('پیش‌فرض‌ها ذخیره شد.');
84 }
85 function renderDashboard(){
86 const cur=getCurrencyLabel(),myInvoices=getMyInvoices(),myPurchases=typeof getMyPurchases==='function'?getMyPurchases():[],myPayments=typeof getMyPayments==='function'?getMyPayments():[],companies=getMyCompanies(),settings=getMySettings(),activeCompId=settings.default_company_id||document.getElementById('invoice-company-id')?.value||(companies[0]?.id);
87 const companyOk=x=>!activeCompId||x.companyId===activeCompId,inv=myInvoices.filter(x=>companyOk(x)&&invoiceCreatesAccountingEntry(x.kind)&&invoiceDocumentStatus(x)==='posted'),pur=myPurchases.filter(companyOk),pay=myPayments.filter(companyOk);
88 const receivable=inv.filter(x=>x.paymentMethod==='credit').reduce((s,x)=>s+(typeof invoiceOutstanding==='function'?invoiceOutstanding(x):Number(x.grandTotal||0)),0);
89 const payable=pur.filter(x=>x.paymentMethod==='credit').reduce((s,x)=>s+(typeof purchaseOutstanding==='function'?purchaseOutstanding(x):Number(x.grandTotal||0)),0);
90 let assets=0,cash=0;try{if(window.P6Reports){const f=P6Reports.financials('','');assets=Number(f.assets||0);const cashId=typeof jeCashAccount==='function'?jeCashAccount()?.id||'':'';if(cashId){const row=P6Reports.rollup('','').find(x=>x.accountId===cashId);cash=Number(row?.balance||0)}}}catch(_){}
91 const setMoney=(id,v)=>{const e=document.getElementById(id);if(e)e.textContent=Math.round(v||0).toLocaleString('fa-IR')+' '+cur};
92 setMoney('kpi-assets-sum',assets);setMoney('kpi-cash-sum',cash);setMoney('kpi-receivable-sum',receivable);setMoney('kpi-payable-sum',payable);
93 const months=['فروردین','اردیبهشت','خرداد','تیر','مرداد','شهریور','مهر','آبان','آذر','دی','بهمن','اسفند'],now=String(getJalaliNumeric()).split('/'),cy=+now[0]||1405,cm=+now[1]||1,slots=[];for(let k=5;k>=0;k--){let y=cy,m=cm-k;while(m<1){m+=12;y--}slots.push({key:y+'/'+String(m).padStart(2,'0'),label:months[m-1],in:0,out:0})}
94 pay.forEach(p=>{const key=String(p.date||'').slice(0,7),slot=slots.find(x=>x.key===key);if(slot){const amount=Number(p.amount||0);if(p.direction==='inbound')slot.in+=amount;else if(p.direction==='outbound')slot.out+=amount}});
95 const chart=document.getElementById('dashboard-cashflow-chart');if(chart){const max=Math.max(1,...slots.flatMap(x=>[x.in,x.out])),W=720,H=220,pad=34,step=(W-pad*2)/Math.max(1,slots.length-1),y=v=>H-pad-(v/max)*(H-pad*2),pts=kind=>slots.map((x,i)=>(pad+i*step)+','+y(x[kind])).join(' '),labels=slots.map((x,i)=>'<text x="'+(pad+i*step)+'" y="'+(H-8)+'" text-anchor="middle" font-size="10" fill="#64748b">'+x.label+'</text>').join('');chart.innerHTML='<svg viewBox="0 0 '+W+' '+H+'" role="img" aria-label="گردش شش ماهه نقدینگی"><line x1="'+pad+'" y1="'+(H-pad)+'" x2="'+(W-pad)+'" y2="'+(H-pad)+'" stroke="#e5eaf1"/><polyline points="'+pts('in')+'" fill="none" stroke="#0a9baa" stroke-width="3"/><polyline points="'+pts('out')+'" fill="none" stroke="#1685d1" stroke-width="3"/>'+slots.map((x,i)=>'<circle cx="'+(pad+i*step)+'" cy="'+y(x.in)+'" r="4" fill="#0a9baa"/><circle cx="'+(pad+i*step)+'" cy="'+y(x.out)+'" r="4" fill="#1685d1"/>').join('')+labels+'</svg><div class="fin-chart-legend"><span><i class="fin-chart-dot" style="background:#0a9baa"></i>ورود</span><span><i class="fin-chart-dot" style="background:#1685d1"></i>خروج</span></div>'}
96 const status=document.getElementById('dashboard-account-status');if(status){const rows=[['حساب‌های دریافتنی',receivable],['حساب‌های پرداختنی',payable],['موجودی نقد و بانک',Math.abs(cash)],['جمع دارایی‌ها',Math.abs(assets)]],mx=Math.max(1,...rows.map(x=>x[1]));status.innerHTML=rows.map(([title,value])=>'<div class="fin-status-row"><div class="fin-status-line"><span>'+title+'</span><b>'+Math.round(value).toLocaleString('fa-IR')+' '+cur+'</b></div><div class="fin-status-track"><div class="fin-status-fill" style="width:'+Math.round((value/mx)*100)+'%"></div></div></div>').join('')}
97 const body=document.getElementById('dashboard-recent-journals');if(body){const vs=typeof getMyJournalVouchers==='function'?getMyJournalVouchers().filter(companyOk).slice().sort((a,b)=>String(b.createdAt||b.date||'').localeCompare(String(a.createdAt||a.date||''))).slice(0,5):[];body.innerHTML=vs.length?vs.map(v=>'<tr><td>'+esc(v.number||'—')+'</td><td>'+esc(v.date||'—')+'</td><td>'+esc(v.description||'—')+'</td><td>'+Number(v.totalDebit||0).toLocaleString('fa-IR')+'</td><td>'+Number(v.totalCredit||0).toLocaleString('fa-IR')+'</td><td><span class="badge '+(v.status==='posted'?'badge-success':v.status==='reversed'?'badge-danger':'badge-warning')+'">'+esc(v.status==='posted'?'قطعی':v.status==='reversed'?'برگشت‌شده':'پیش‌نویس')+'</span></td></tr>').join(''):'<tr><td colspan="6" class="af-empty">سند حسابداری ثبت نشده است.</td></tr>'}
98 }
99 function onActiveCompanyFilterChange(){
100 // The invoicing seller follows Settings and cannot change invoice scope.
101 const active=typeof afCompanyId==='function'?afCompanyId():'';
102 const header=document.getElementById('invoice-company-id');
103 if(header&&header.value!==active)header.value=active;
104 renderInvoices();renderDashboard();
105 }
106 function startNewInvoice(){cancelInvoiceEdit();switchView('view-invoices');}
107 function updateInvoiceItemRowNumbers(){
108 const rows=document.querySelectorAll('#invoice-items-table-body tr');
109 rows.forEach((tr,index)=>{const numCell=tr.querySelector('.row-item-number');if(numCell)numCell.innerText=(index+1).toLocaleString('fa-IR');});
110 }
111 function addInvoiceItemRow(selectedProdId='',initialQty=1,initialPrice=null){
112 const tbody=document.getElementById('invoice-items-table-body');
113 const rowKey='item_'+Date.now()+'_'+Math.random().toString(36).substr(2,4);
114 const tr=document.createElement('tr');
115 tr.id=rowKey;
116 const myProducts=getMyProducts();
117 const productOptions=myProducts.map(p=>`<option value="${p.id}" data-price="${esc(p.sale_price||0)}" data-unit="${esc(p.unit||'عدد')}" data-search="${esc([p.code,p.name,p.spec,p.barcode,p.internal_id,p.official_id,p.category,p.subcategory].filter(Boolean).join(' ').toLowerCase())}" ${p.id===selectedProdId?'selected':''}>${esc(p.name)} ${esc(p.spec?'('+p.spec+')':'')}</option>`).join('');
118 const priceVal=(initialPrice!==null?Number(initialPrice):0);
119 tr.innerHTML=`
120 <td class="row-item-number" style="width:40px;text-align:center;font-weight:bold;vertical-align:middle"></td>
121 <td><select class="form-control row-product-select" onchange="onRowProductChange('${rowKey}')"><option value="">-- انتخاب کالا / خدمات --</option>${productOptions}</select></td>
122 <td style="width:90px"><input type="text" class="form-control row-unit-input" value="عدد" style="text-align:center" /></td>
123 <td style="width:100px"><input type="number" class="form-control row-quantity" value="${initialQty}" min="1" oninput="recomputeTotals()" style="text-align:center" /></td>
124 <td style="width:160px"><input type="text" inputmode="decimal" class="form-control row-price" value="${priceVal?priceVal.toLocaleString('en-US'):''}" oninput="handleMoneyInput(this);recomputeTotals()" style="text-align:left" /></td>
125 <td class="row-linetotal" style="width:170px;font-weight:bold;text-align:left;vertical-align:middle;direction:ltr">۰</td>
126 <td style="width:50px;text-align:center;vertical-align:middle"><button class="btn btn-danger btn-inline" style="min-height:36px;padding:4px 10px" onclick="document.getElementById('${rowKey}').remove();updateInvoiceItemRowNumbers();recomputeTotals()">✕</button></td>`;
127 tbody.appendChild(tr);
128 if(typeof finoraRefreshSearchableSelect==='function')finoraRefreshSearchableSelect(tr.querySelector('.row-product-select'));
129 updateInvoiceItemRowNumbers();
130 if(selectedProdId&&initialPrice===null)onRowProductChange(rowKey);
131 else recomputeTotals();
132 }
133 function onRowProductChange(rowKey){
134 const tr=document.getElementById(rowKey);if(!tr)return;
135 const sel=tr.querySelector('.row-product-select');
136 const opt=sel.options[sel.selectedIndex];
137 const prc=parseFormattedNumber(opt?.getAttribute('data-price')||0);
138 const unt=opt?.getAttribute('data-unit');
139 tr.querySelector('.row-price').value=prc?prc.toLocaleString('en-US'):'';
140 if(unt){const unitInput=tr.querySelector('.row-unit-input');if(unitInput)unitInput.value=unt;}
141 recomputeTotals();
142 }
143 function recomputeTotals(){
144 let subtotal=0;
145 document.querySelectorAll('#invoice-items-table-body tr').forEach(tr=>{
146 const qty=parseFloat(tr.querySelector('.row-quantity')?.value)||0;
147 const prc=parseFormattedNumber(tr.querySelector('.row-price')?.value);
148 const line=qty*prc;
149 const lineEl=tr.querySelector('.row-linetotal');
150 if(lineEl)lineEl.innerText=line.toLocaleString('fa-IR');
151 subtotal+=line;
152 });
153 const discountType=document.getElementById('invoice-discount-type')?.value||'fixed';
154 const discountInput=parseFormattedNumber(document.getElementById('invoice-discount-fixed')?.value);
155 const rawDiscount=(discountType==='percent')?Math.round(subtotal*(discountInput/100)):discountInput;
156 const fixedDiscount=Math.max(0,Math.min(rawDiscount,subtotal));
157 const kind=document.getElementById('invoice-kind')?.value||'non_formal';
158 const vatMode=(kind==='non_formal')?'none':(document.getElementById('invoice-vat-mode')?.value||'none');
159 const vatType=document.getElementById('invoice-vat-type')?.value||'percent';
160 const vatRate=parseFormattedNumber(document.getElementById('invoice-vat-rate-input')?.value);
161 const afterDiscount=Math.max(0,subtotal-fixedDiscount);
162 let vatAmount=0;
163 if(vatMode==='with_vat'){vatAmount=(vatType==='fixed')?Math.max(0,Math.round(vatRate)):Math.round(afterDiscount*(vatRate/100));}
164 const grandTotal=afterDiscount+vatAmount;
165 const cur=getCurrencyLabel();
166 const subtotalEl=document.getElementById('summary-subtotal');
167 const vatEl=document.getElementById('summary-vat');
168 const grandEl=document.getElementById('summary-grandtotal');
169 const wordsEl=document.getElementById('summary-words');
170 if(subtotalEl)subtotalEl.innerText=subtotal.toLocaleString('fa-IR')+' '+cur;
171 if(vatEl)vatEl.innerText=vatAmount.toLocaleString('fa-IR')+' '+cur;
172 if(grandEl)grandEl.innerText=grandTotal.toLocaleString('fa-IR')+' '+cur;
173 if(wordsEl)wordsEl.innerText='به حروف: '+numberToPersianWords(grandTotal,cur);
174 return {subtotal,fixedDiscount,discountType,discountInput,vatAmount,vatType,grandTotal,vatRate};
175 }
176
177 // ================== سند الکترونیکی سامانه مودیان ==================
178 function toggleElectronicDoc(){
179 const checked=document.getElementById('enable-electronic-doc').checked;
180 if(checked){
181 openElectronicDocModal();
182 }else{
183 window.pendingElectronicDoc=null;
184 document.getElementById('edoc-status').innerText='';
185 }
186 }
187 function openElectronicDocModal(){
188 const itemsContainer=document.getElementById('edoc-items-container');
189 const rows=document.querySelectorAll('#invoice-items-table-body tr');
190 let html='';
191 if(rows.length===0){
192 html='<p style="color:var(--text-muted);font-size:12.5px;padding:8px">ابتدا اقلام فاکتور را اضافه کنید.</p>';
193 }else{
194 rows.forEach((tr,idx)=>{
195 const sel=tr.querySelector('.row-product-select');
196 const prodId=sel?sel.value:'';
197 const prod=getMyProducts().find(p=>p.id===prodId)||{};
198 const prodName=sel&&sel.options[sel.selectedIndex]?sel.options[sel.selectedIndex].text:'';
199 html+=`<div style="border:1px solid var(--border);border-radius:8px;padding:10px;margin-bottom:8px;background:#f8fafc">
200 <div style="font-weight:bold;font-size:13px;margin-bottom:8px">ردیف ${toPersianDigits(idx+1)}: ${prodName||'—'}</div>
201 <div class="form-row">
202 <div class="form-group" style="margin-bottom:6px"><label style="font-size:12px">شناسه کالا/خدمت داخلی</label><input type="text" class="form-control edoc-row-internal" data-row="${idx}" value="${esc(prod.code||'')}" readonly /><small style="color:var(--text-muted)">از تعریف کالا/خدمت خوانده می‌شود.</small></div>
203 <div class="form-group" style="margin-bottom:6px"><label style="font-size:12px">شناسه کالا/خدمت سامانه مالیاتی <span style="color:var(--danger)">*</span></label><input type="text" class="form-control edoc-row-official" data-row="${idx}" value="${esc(prod.official_id||'')}" /><small style="color:var(--text-muted)">اگر در تعریف کالا ثبت نشده، اینجا تکمیل آن الزامی است.</small></div>
204 </div>
205 </div>`;
206 });
207 }
208 itemsContainer.innerHTML=html;
209
210 const p=window.pendingElectronicDoc;
211 if(p){
212 document.getElementById('edoc-unique-number').value=p.uniqueNumber||'';
213 document.getElementById('edoc-tax-number').value=p.taxNumber||'';
214 document.getElementById('edoc-issue-datetime').value=p.issueDateTime||'';
215 document.getElementById('edoc-original-date').value=p.originalDate||'';
216 document.getElementById('edoc-original-number').value=p.originalNumber||'';
217 document.getElementById('edoc-kind').value=p.kind||'اصل';
218 document.getElementById('edoc-pattern').value=p.pattern||'کالا';
219 document.getElementById('edoc-contract-id').value=p.contractId||'';
220 if(p.items){
221 p.items.forEach((it,idx)=>{
222 const intEl=document.querySelector(`.edoc-row-internal[data-row="${idx}"]`);
223 const offEl=document.querySelector(`.edoc-row-official[data-row="${idx}"]`);
224 if(intEl){const row=document.querySelectorAll('#invoice-items-table-body tr')[idx],sel=row?.querySelector('.row-product-select'),prod=getMyProducts().find(x=>x.id===sel?.value);intEl.value=prod?.code||it.internalId||'';}
225 if(offEl){const row=document.querySelectorAll('#invoice-items-table-body tr')[idx],sel=row?.querySelector('.row-product-select'),prod=getMyProducts().find(x=>x.id===sel?.value);offEl.value=prod?.official_id||it.officialId||'';}
226 });
227 }
228 }else{
229 const now=new Date();
230 const timeStr=now.getHours().toString().padStart(2,'0')+':'+now.getMinutes().toString().padStart(2,'0')+':00';
231 document.getElementById('edoc-issue-datetime').value=getJalaliNumeric()+' '+timeStr;
232 document.getElementById('edoc-original-date').value='';
233 document.getElementById('edoc-original-number').value='';
234 document.getElementById('edoc-unique-number').value='';
235 document.getElementById('edoc-tax-number').value='';
236 document.getElementById('edoc-kind').value='اصل';
237 document.getElementById('edoc-pattern').value='کالا';
238 document.getElementById('edoc-contract-id').value='';
239 }
240 handleEdocPatternChange();
241 document.getElementById('modal-electronic-doc').classList.add('active');
242 }
243 function closeElectronicDocModal(){
244 document.getElementById('modal-electronic-doc').classList.remove('active');
245 }
246 function cancelElectronicDoc(){
247 document.getElementById('enable-electronic-doc').checked=false;
248 window.pendingElectronicDoc=null;
249 document.getElementById('edoc-status').innerText='';
250 closeElectronicDocModal();
251 }
252 function handleEdocPatternChange(){
253 const pattern=document.getElementById('edoc-pattern').value;
254 const box=document.getElementById('box-edoc-contract');
255 const hint=document.getElementById('edoc-contract-hint');
256 if(pattern==='پیمانکاری'){
257 box.style.display='block';
258 hint.style.display='none';
259 }else{
260 box.style.display='none';
261 hint.style.display='block';
262 }
263 }
264 function saveElectronicDocToPending(){
265 const pattern=document.getElementById('edoc-pattern').value;
266 const contractId=document.getElementById('edoc-contract-id').value.trim();
267 if(pattern==='پیمانکاری'&&!contractId){
268 alert('برای الگوی «قرارداد پیمانکاری»، وارد کردن «شناسه یکتای ثبت قرارداد» اجباری است.');
269 return;
270 }
271 const items=[];
272 const rows=document.querySelectorAll('#invoice-items-table-body tr');
273 for(let idx=0;idx<rows.length;idx++){
274 const intEl=document.querySelector(`.edoc-row-internal[data-row="${idx}"]`);
275 const offEl=document.querySelector(`.edoc-row-official[data-row="${idx}"]`);
276 const row=rows[idx],sel=row?.querySelector('.row-product-select'),prod=getMyProducts().find(x=>x.id===sel?.value)||{};const offVal=(prod.official_id||offEl?.value||'').trim();
277 if(!offVal){
278 alert(`«شناسه کالا/خدمت» برای ردیف ${toPersianDigits(idx+1)} اجباری است.`);
279 return;
280 }
281 items.push({internalId:String(prod.code||intEl?.value||'').trim(),officialId:offVal});
282 }
283 const p={
284 uniqueNumber:document.getElementById('edoc-unique-number').value.trim(),
285 taxNumber:document.getElementById('edoc-tax-number').value.trim(),
286 issueDateTime:document.getElementById('edoc-issue-datetime').value.trim(),
287 originalDate:document.getElementById('edoc-original-date').value.trim(),
288 originalNumber:document.getElementById('edoc-original-number').value.trim(),
289 kind:document.getElementById('edoc-kind').value,
290 pattern:pattern,
291 contractId:contractId,
292 items:items
293 };
294 window.pendingElectronicDoc=p;
295 document.getElementById('edoc-status').innerText='✓ اطلاعات سند الکترونیکی ذخیره شد. با ثبت فاکتور، سند نیز ذخیره می‌شود.';
296 closeElectronicDocModal();
297 }
298
299 function invoiceCreatesAccountingEntry(kind){return kind==='formal'||kind==='non_formal';}
300
301 function invoiceLogicalRoot(inv){
302 if(!inv)return null;
303 const rows=getMyInvoices(),seen=new Set();let current=inv;
304 while(current?.correctsInvoiceId&&!seen.has(current.id)){
305 seen.add(current.id);const parent=rows.find(x=>x.id===current.correctsInvoiceId);
306 if(!parent)break;current=parent;
307 }
308 return current;
309 }
310 function invoiceVisibleNumber(inv){const v=invoiceLogicalRoot(inv)||inv;return v?.number||v?.temporaryNumber||'';}
311 function invoiceVisibleRecords(){
312 const active=typeof afCompanyId==='function'?afCompanyId():getMySettings().default_company_id;
313 if(!active||!getMyCompanies().some(c=>c.id===active))return [];
314 const all=getMyInvoices(),children=new Set(all.map(x=>x.correctsInvoiceId).filter(Boolean));
315 return all.filter(x=>x.companyId===active&&!children.has(x.id));
316 }
317 function invoiceCurrentVisible(invId){
318 const all=getMyInvoices();let current=all.find(x=>x.id===invId);
319 if(!current)return null;
320 const seen=new Set();
321 while(current&&!seen.has(current.id)){
322 seen.add(current.id);const next=all.filter(x=>x.correctsInvoiceId===current.id)
323 .sort((a,b)=>String(b.createdAt||'').localeCompare(String(a.createdAt||'')))[0];
324 if(!next)break;current=next;
325 }
326 return current;
327 }
328 function invoicePrintView(record){
329 if(!record)return null;
330 const current=invoiceCurrentVisible(record.id)||record;
331 return {...current,number:invoiceVisibleNumber(current)};
332 }
333 let finoraSaleAmendmentId='';
334 function beginInvoiceAmendment(id){
335 const source=invoiceCurrentVisible(id);
336 if(!source)return alert('فاکتور پیدا نشد.');
337 try{
338 invoicePilotCorrectionEligible(source);
339 finoraSaleAmendmentId=source.id;
340 editInvoice(source.id,true);
341 }catch(e){finoraSaleAmendmentId='';alert(e.message)}
342 }
343 async function commitInvoiceSeamlessAmendment(id,changes){
344 if(!requireWrite())throw new Error('مجوز اصلاح ندارید.');
345 const current=invoiceCurrentVisible(id),root=invoiceLogicalRoot(current);
346 if(!current||current.id!==id||!root)throw new Error('نسخه جاری سند با درخواست ویرایش مطابقت ندارد.');
347 invoicePilotCorrectionEligible(current);
348 if(changes.companyId!==current.companyId||changes.kind!==current.kind||changes.number!==root.number)
349 throw new Error('شماره اصلی، نوع سند و شرکت را در اصلاح سند قطعی تغییر ندهید.');
350 if(!Number.isFinite(changes.grandTotal)||changes.grandTotal<=0||!changes.items?.length)
351 throw new Error('مبلغ و اقلام فاکتور معتبر نیست.');
352 // Zero accounting writes occurred when the employee merely opened the form.
353 const idNew=await reopenPostedInvoiceAsDraft(id,'اصلاح اطلاعات فاکتور در دوره پایلوت');
354 const copy=getMyInvoices().find(x=>x.id===idNew);
355 if(!copy)throw new Error('فاکتور اصلاح‌شده بارگذاری نشد.');
356 Object.assign(copy,changes,{number:copy.number,documentStatus:'draft',accountingStatus:'draft',
357 electronicDoc:current.electronicDoc||null,documentVersion:Number(current.documentVersion||1)+1,
358 correctsInvoiceId:current.id,correctionOriginalNumber:root.number,updatedAt:new Date().toISOString()});
359 saveDatastore();
360 await invoicePilotAwaitSync(['invoices|'+idNew]);
361 await finalizeInvoiceDocument(idNew);
362 finoraSaleAmendmentId='';
363 cancelInvoiceEdit();refreshAllSurfaces();
364 return idNew;
365 }
366
367 function invoiceDocumentStatus(inv){
368 if(!inv)return 'unknown';
369 const linked=inv.journalVoucherId&&typeof jeSourceVoucher==='function'?jeSourceVoucher(inv):null;
370 if(linked?.status==='reversed'||inv.accountingStatus==='reversed'||inv.documentStatus==='reversed')return 'reversed';
371 if(linked?.status==='posted')return 'posted';
372 if(linked?.status==='draft'||inv.documentStatus==='draft'||inv.accountingStatus==='draft')return 'draft';
373 if(inv.journalVoucherId||inv.accountingStatus==='posted'||inv.documentStatus==='posted')return 'posted';
374 if(invoiceCreatesAccountingEntry(inv.kind))return 'legacy_review';
375 return 'operational';
376 }
377 function invoiceDocumentStatusLabel(inv){
378 return ({posted:'قطعی',draft:'پیش‌نویس قابل ویرایش',reversed:'برگشت‌شده',legacy_review:'قدیمی — نیازمند تطبیق',operational:'سند عملیاتی',unknown:'نامشخص'})[invoiceDocumentStatus(inv)]||'نامشخص';
379 }
380 function invoiceMayEdit(inv){
381 return !!inv&&!inv.accountingPostingPending&&(invoiceDocumentStatus(inv)==='draft'||invoiceDocumentStatus(inv)==='operational');
382 }
383 async function finalizeInvoiceDocument(invoiceId){
384 if(!requireWrite()||!currentUser)throw new Error('مجوز قطعی‌سازی ندارید.');
385 const inv=getMyInvoices().find(i=>i.id===invoiceId);
386 if(!inv||inv.ownerUserId!==currentUser.id)throw new Error('فاکتور برای این حساب یافت نشد.');
387 if(!invoiceCreatesAccountingEntry(inv.kind))throw new Error('این سند عملیاتی قابلیت قطعی‌سازی حسابداری فروش ندارد.');
388 const status=invoiceDocumentStatus(inv);
389 if(status==='posted')return inv.journalVoucherId;
390 if(status!=='draft')throw new Error('فقط پیش‌نویس جدید و معتبر قابل قطعی‌سازی است؛ اسناد قدیمی ابتدا باید تطبیق داده شوند.');
391 const activeCompany=typeof afCompanyId==='function'?afCompanyId():getMySettings().default_company_id;
392 if(!activeCompany||inv.companyId!==activeCompany)throw new Error('ابتدا شرکت ثبت‌کننده فاکتور را در سربرگ انتخاب کنید.');
393 if(!Array.isArray(inv.items)||!inv.items.length||!Number.isFinite(inv.grandTotal)||inv.grandTotal<=0)throw new Error('ردیف‌ها و مبلغ فاکتور معتبر نیست.');
394 // Persist the source draft first, then let the server derive and post its
395 // accounting lines atomically. The journal itself never goes through generic sync.
396 const v=await jeRpcAutoPost('sale',invoiceId);
397 const savedInvoice=getMyInvoices().find(x=>x.id===invoiceId);
398 if(!savedInvoice||savedInvoice.journalVoucherId!==v.id||invoiceDocumentStatus(savedInvoice)!=='posted')
399 throw new Error('ثبت سند حسابداری انجام شد اما ارتباط فاکتور و سند از سرور تأیید نشد؛ پیش از تکرار وضعیت را بررسی کنید.');
400 if(typeof syncProductDefaultPrices==='function')syncProductDefaultPrices(savedInvoice.items,'sale');
401 // Journal and invoice link are already committed atomically by the RPC.
402 // This generic sync is only for ancillary product default-price updates.
403 saveDatastore();
404 refreshAllSurfaces();
405 return v.id;
406 }
407 async function finalizeInvoiceDocumentUi(id){
408 const inv=getMyInvoices().find(i=>i.id===id);
409 if(!inv||invoiceDocumentStatus(inv)!=='draft')return alert('فقط پیش‌نویس قابل قطعی‌سازی است.');
410 if(!confirm('فاکتور '+(inv.number||'')+' قطعی و در دفترکل ثبت شود؟ پس از آن اصلاح مستقیم ممکن نیست.'))return;
411 try{await finalizeInvoiceDocument(id);alert('فاکتور و سند حسابداری روی سرور قطعی شد.');renderDocumentManagement();}
412 catch(e){alert('قطعی‌سازی تأیید نشد: '+e.message)}
413 }
414
415 // Pilot only: a posted sale is NEVER turned back into a mutable posted record.
416 // Compensate the original posting and create a new, traceable, editable invoice.
417 function invoicePilotCorrectionEligible(inv){
418 if(!inv||inv.ownerUserId!==currentUser?.id||!invoiceCreatesAccountingEntry(inv.kind))throw new Error('فاکتور فروش معتبر برای حساب جاری انتخاب نشده است.');
419 if(inv.companyId!==afCompanyId())throw new Error('شرکت فعلی با سند مطابقت ندارد.');
420 if(invoiceDocumentStatus(inv)!=='posted')throw new Error('فقط فاکتور قطعی قابل برگشت به موقت است.');
421 const v=typeof jeActiveSourceVoucher==='function'?jeActiveSourceVoucher(inv):null;
422 if(!v||v.sourceType!=='sale'||v.sourceId!==inv.id)throw new Error('سند حسابداری قطعی و متصل به این فاکتور یافت نشد؛ ابتدا سند را تطبیق دهید.');
423 const fy=getMyFiscalYears().find(x=>x.id===v.fiscalYearId);
424 const newFY=jeFiscalForDate(getJalaliNumeric());
425 if(!fy||fy.status==='locked'||!newFY||newFY.status==='locked')throw new Error('اصلاح در سال مالی قفل‌شده یا بدون سال مالی باز مجاز نیست.');
426 // Electronic tax references and settled receipts require their own controlled workflow.
427 if(inv.electronicDoc)throw new Error('این فاکتور سند الکترونیکی مرتبط دارد؛ ابتدا وضعیت مالیاتی آن بررسی شود.');
428 if(typeof getMyPayments==='function'&&getMyPayments().some(p=>p.invoiceId===inv.id||p.sourceInvoiceId===inv.id||p.relatedInvoiceId===inv.id))
429 throw new Error('این فاکتور به دریافت/پرداخت متصل است؛ اصلاح ابتدا نیازمند تطبیق تسویه است.');
430 return v;
431 }
432 function invoicePilotCorrectionNumber(inv){
433 const initial=String(inv.number||inv.id).trim()+'-اصلاح';
434 let n=1,number=initial+'-'+n;
435 while(getMyInvoices().some(x=>x.companyId===inv.companyId&&String(x.number||'').trim()===number)){
436 n++;number=initial+'-'+n;
437 if(n>10000)throw new Error('ایجاد شماره نسخه اصلاحی یکتا ممکن نیست.');
438 }
439 return number;
440 }
441 async function invoicePilotAwaitSync(entries){
442 if(typeof runSync!=='function'||typeof syncSnap==='undefined')return;
443 await runSync();
444 const deadline=Date.now()+20000;
445 while(Date.now()<deadline){
446 if(!syncRunning&&!syncPending&&entries.every(key=>syncSnap.has(key)))return;
447 if(syncFailCount>0)break;
448 await new Promise(resolve=>setTimeout(resolve,200));
449 }
450 throw new Error('سرور هنوز تغییرات را تأیید نکرده است. بدون بررسی همگام‌سازی، عملیات را تکرار نکنید.');
451 }
452 async function reopenPostedInvoiceAsDraft(invoiceId,reason){
453 if(!requireWrite())throw new Error('مجوز اصلاح ندارید.');
454 const why=String(reason||'').trim();if(!why)throw new Error('دلیل برگشت سند الزامی است.');
455 const inv=getMyInvoices().find(x=>x.id===invoiceId);
456 if(!inv||inv.ownerUserId!==currentUser?.id||inv.companyId!==afCompanyId()||!invoiceCreatesAccountingEntry(inv.kind))
457 throw new Error('فاکتور فروش معتبر برای حساب جاری انتخاب نشده است.');
458 const v=jeSourceVoucher(inv);
459 if(!v||v.sourceType!=='sale'||v.sourceId!==inv.id||v.status!=='posted')
460 throw new Error('سند حسابداری قطعی و متصل به این فاکتور یافت نشد.');
461 const effective=jeRpcEffectiveStatus(v);
462 if(effective==='posted')invoicePilotCorrectionEligible(inv);
463 else if(effective!=='reversed')throw new Error('وضعیت برگشت فاکتور برای اصلاح قابل قبول نیست.');
464 if(effective==='reversed'){
465 const existing=getMyInvoices().find(x=>x.correctsInvoiceId===inv.id&&x.correctionReversalId);
466 if(existing){
467 await invoicePilotAwaitSync(['journalVouchers|'+v.id,'journalVouchers|'+existing.correctionReversalId,'invoices|'+existing.id]);
468 refreshAllSurfaces();return existing.id;
469 }
470 }
471 // Resolve number/clone before reversing, so validation failures do not touch posting.
472 const number=invoicePilotCorrectionNumber(inv);
473 const id=afId('INV'),now=new Date().toISOString();
474 const draft={...inv,id,number,createdAt:now,updatedAt:now,documentStatus:'draft',accountingStatus:'draft',documentVersion:1,accountingVersion:1,
475 correctsInvoiceId:inv.id,correctsVoucherId:v.id,correctionReason:why,
476 correctionOriginalNumber:inv.number};
477 for(const key of ['journalVoucherId','accountingPostedAt','documentPostedAt','documentPostedBy','postedAt','postedBy','reversalVoucherId'])delete draft[key];
478 // The reversal RPC creates the compensating voucher without mutating posted journal rows.
479 const reversal=await jeRpcReverse(v.id,getJalaliNumeric(),why);
480 draft.correctionReversalId=reversal.id;
481 datastore.invoices.push(draft);saveDatastore();
482 await invoicePilotAwaitSync(['journalVouchers|'+v.id,'journalVouchers|'+reversal.id,'invoices|'+draft.id]);
483 refreshAllSurfaces();return draft.id;
484 }
485 async function cancelPostedInvoicePilot(invoiceId,reason){
486 if(!requireWrite())throw new Error('مجوز ابطال ندارید.');
487 const why=String(reason||'').trim();if(!why)throw new Error('دلیل ابطال الزامی است.');
488 const inv=getMyInvoices().find(x=>x.id===invoiceId);
489 if(!inv||inv.ownerUserId!==currentUser?.id||inv.companyId!==afCompanyId()||!invoiceCreatesAccountingEntry(inv.kind))
490 throw new Error('فاکتور فروش معتبر برای حساب جاری انتخاب نشده است.');
491 const v=jeSourceVoucher(inv);
492 if(!v||v.sourceType!=='sale'||v.sourceId!==inv.id||v.status!=='posted')
493 throw new Error('سند حسابداری قطعی و متصل به این فاکتور یافت نشد.');
494 const effective=jeRpcEffectiveStatus(v);
495 if(effective==='posted')invoicePilotCorrectionEligible(inv);
496 else if(effective!=='reversed')throw new Error('وضعیت برگشت فاکتور برای ابطال قابل قبول نیست.');
497 const reversal=await jeRpcReverse(v.id,getJalaliNumeric(),'ابطال پایلوت: '+why);
498 await invoicePilotAwaitSync(['journalVouchers|'+v.id,'journalVouchers|'+reversal.id]);
499 refreshAllSurfaces();return reversal.id;
500 }
501 async function deleteInvoicePilotDraft(invoiceId){
502 if(!requireWrite())throw new Error('مجوز حذف ندارید.');
503 const inv=getMyInvoices().find(x=>x.id===invoiceId);
504 if(!inv||inv.ownerUserId!==currentUser?.id||inv.companyId!==afCompanyId()||invoiceDocumentStatus(inv)!=='draft'||inv.accountingPostingPending)
505 throw new Error('فقط پیش‌نویس همین شرکت قابل حذف است.');
506 if(inv.electronicDoc)throw new Error('سند الکترونیکی مرتبط ابتدا باید بررسی شود.');
507 if(typeof getMyPayments==='function'&&getMyPayments().some(p=>p.invoiceId===inv.id||p.sourceInvoiceId===inv.id||p.relatedInvoiceId===inv.id))
508 throw new Error('این فاکتور ارجاع دریافت/پرداخت دارد و قابل حذف نیست.');
509 const org=await jeRpcAssertContext();
510 const {error}=await sb.rpc('finora_delete_draft_source',{p_organization_id:org,p_collection:'invoices',p_source_id:inv.id});
511 if(error)throw error;
512 await pullAll();refreshAllSurfaces();return true;
513 }
514 function commitSaveInvoice(){
515 if(!requireWrite())return;
516 if(!currentUser)return;
517 const myCompanies=getMyCompanies();
518 const mySettings=getMySettings();
519 const companySelect=document.getElementById('invoice-company-id');
520 const selectedCompanyId=companySelect?companySelect.value:mySettings.default_company_id;
521 const activeCompanyId=typeof afCompanyId==='function'?afCompanyId():mySettings.default_company_id;
522 const sellerCompany=myCompanies.find(c=>c.id===activeCompanyId);
523 if(!sellerCompany){alert('ابتدا شرکت فعال را در بخش تنظیمات انتخاب کنید.');return;}
524 if(selectedCompanyId!==sellerCompany.id){alert('شرکت فاکتور با شرکت فعال در تنظیمات یکسان نیست.');return;}
525 const editSource=getMyInvoices().find(i=>i.id===document.getElementById('edit-invoice-id')?.value);
526 if(editSource&&editSource.companyId!==sellerCompany.id){
527 alert('برای اصلاح این فاکتور، شرکت مربوطه را از تنظیمات انتخاب کنید.');return;
528 }
529 const companyId=sellerCompany.id;
530 const companyName=sellerCompany.name;
531 const contactSelect=document.getElementById('invoice-contact-id');
532 const contactId=contactSelect?contactSelect.value:'';
533 const contactName=contactSelect?.options[contactSelect.selectedIndex]?.text||'مشتری آزاد';
534 let number=document.getElementById('invoice-number')?.value.trim()||('PINV-'+(getMyInvoices().length+31));
535 const date=document.getElementById('invoice-date-input')?.value.trim()||getJalaliNumeric();
536 const kind=document.getElementById('invoice-kind')?.value||'non_formal';
537 const description=document.getElementById('invoice-desc-input')?.value.trim()||'';
538 const paymentMethod=document.getElementById('invoice-payment-method')?.value||'cash';
539 const paymentMethodLabel=paymentMethod==='credit'?'نسیه':'نقدی';
540 const warehouseId=document.getElementById('invoice-warehouse-id')?.value||'';
541 const editId=document.getElementById('edit-invoice-id')?.value;
542 const previousDraft=getMyInvoices().find(i=>i.id===editId);
543 // Old in-progress correction drafts show the original business number;
544 // preserve their private unique storage number while updating them.
545 if(previousDraft?.correctsInvoiceId&&invoiceDocumentStatus(previousDraft)==='draft'
546 &&number===invoiceVisibleNumber(previousDraft))number=previousDraft.number;
547 if(getMyInvoices().some(i=>i.id!==editId&&i.companyId===companyId&&String(i.number||'').trim()===number)&&!(finoraSaleAmendmentId===editId&&invoiceVisibleNumber(getMyInvoices().find(i=>i.id===editId))===number)){alert('شماره فاکتور برای این شرکت قبلاً ثبت شده است.');return;}
548 if(kind==='non_formal'){document.getElementById('invoice-vat-mode').value='none';}
549
550 const contractNumber=document.getElementById('invoice-contract-number')?.value.trim()||'';
551 if(kind==='contract_statement'&&!contractNumber){
552 alert('برای «صورت وضعیت پیمان»، وارد کردن شماره پیمان اجباری است.');
553 return;
554 }
555 const projectSelect=document.getElementById('invoice-project-id');
556 const projectRow=document.getElementById('box-invoice-project-row');
557 const projectId=(projectRow&&projectRow.style.display!=='none'&&projectSelect)?projectSelect.value:'';
558 const projectName=(projectId&&projectSelect)?(projectSelect.options[projectSelect.selectedIndex]?.text||''):'';
559
560 const items=[];
561 document.querySelectorAll('#invoice-items-table-body tr').forEach(tr=>{
562 const sel=tr.querySelector('.row-product-select');
563 const prodId=sel?sel.value:'';
564 const prodName=sel?sel.options[sel.selectedIndex]?.text:'';
565 const unit=tr.querySelector('.row-unit-input')?.value||'عدد';
566 const qty=parseFloat(tr.querySelector('.row-quantity')?.value)||0;
567 const price=parseFormattedNumber(tr.querySelector('.row-price')?.value);
568 if(prodId&&qty>0){items.push({prodId,prodName,unit,qty,price,lineTotal:qty*price});}
569 });
570 if(items.length===0){alert('لطفاً حداقل یک ردیف کالا به فاکتور اضافه کنید.');return;}
571
572 // بررسی سند الکترونیکی
573 let edoc=null;
574 if(kind==='formal'){
575 const cb=document.getElementById('enable-electronic-doc');
576 if(cb&&cb.checked){
577 if(!window.pendingElectronicDoc){
578 alert('برای صدور سند الکترونیکی، ابتدا باید اطلاعات سند را تکمیل و ذخیره کنید.');
579 return;
580 }
581 edoc=window.pendingElectronicDoc;
582 if(edoc.pattern==='پیمانکاری'&&!edoc.contractId){
583 alert('برای الگوی «قرارداد پیمانکاری»، وارد کردن «شناسه یکتای ثبت قرارداد» اجباری است.');
584 return;
585 }
586 }
587 }
588
589 const totals=recomputeTotals();
590 const kindLabels={formal:'رسمی',non_formal:'غیررسمی',pre_invoice:'پیش‌فاکتور',contract_statement:'صورت وضعیت پیمان'};
591 const cur=getCurrencyLabel();
592 if(editId&&finoraSaleAmendmentId===editId){
593 const changes={number,date,companyId,companyName,kind,kindLabel:kindLabels[kind],contactId,contactName,
594 projectId,projectName,contractNumber,paymentMethod,paymentMethodLabel,warehouseId,
595 subtotal:totals.subtotal,discount:totals.fixedDiscount,discountType:totals.discountType,
596 discountInput:totals.discountInput,vat:totals.vatAmount,vatType:totals.vatType,
597 vatRate:totals.vatRate,grandTotal:totals.grandTotal,description,items,currencyLabel:cur,
598 electronicDoc:edoc};
599 const btn=document.getElementById('btn-save-invoice');if(btn)btn.disabled=true;
600 void commitInvoiceSeamlessAmendment(editId,changes).then(()=>{
601 alert('اصلاحات فاکتور '+number+' ذخیره و تأیید شد. چاپ از همین فاکتور امکان‌پذیر است.');
602 }).catch(e=>{
603 finoraSaleAmendmentId='';
604 // If sync failed mid-correction, do not silently retry a reversal.
605 cancelInvoiceEdit();refreshAllSurfaces();
606 alert('اصلاح فاکتور تکمیل نشد؛ وضعیت سند را تازه‌سازی و بررسی کنید: '+e.message);
607 }).finally(()=>{if(btn)btn.disabled=false;});
608 return;
609 }
610 if(editId){
611 const lockedExisting=getMyInvoices().find(i=>i.id===editId);
612 if(!invoiceMayEdit(lockedExisting)){alert('این سند قطعی شده یا نیازمند تطبیق سوابق قدیمی است و قابل ویرایش مستقیم نیست.');return;}
613 if(typeof jeGuardSourceMutation==='function'){try{jeGuardSourceMutation(lockedExisting,'فاکتور فروش');}catch(e){alert(e.message);return;}}
614 const existingIndex=datastore.invoices.findIndex(i=>i.id===editId&&i.ownerUserId===currentUser.id);
615 if(existingIndex!==-1){
616 const prev=datastore.invoices[existingIndex];
617 const finalEdoc=edoc?edoc:(prev.electronicDoc||null);
618 datastore.invoices[existingIndex]={...prev,ownerUserId:currentUser.id,number,date,companyId,companyName,kind,kindLabel:kindLabels[kind],contactId,contactName,projectId,projectName,contractNumber,paymentMethod,paymentMethodLabel,warehouseId,subtotal:totals.subtotal,discount:totals.fixedDiscount,discountType:totals.discountType,discountInput:totals.discountInput,vat:totals.vatAmount,vatType:totals.vatType,vatRate:totals.vatRate,grandTotal:totals.grandTotal,description,items,currencyLabel:cur,electronicDoc:finalEdoc,documentStatus:'draft',accountingStatus:'draft',documentVersion:Number(prev.documentVersion||1)+1,updatedAt:new Date().toISOString()};
619 alert('فاکتور با موفقیت ویرایش شد.');
620 }
621 cancelInvoiceEdit();
622 }else{
623 const record={id:'INV_'+Date.now(),ownerUserId:currentUser.id,documentStatus:'draft',accountingStatus:'draft',documentVersion:1,createdAt:new Date().toISOString(),number,date,companyId,companyName,kind,kindLabel:kindLabels[kind],contactId,contactName,projectId,projectName,contractNumber,paymentMethod,paymentMethodLabel,warehouseId,subtotal:totals.subtotal,discount:totals.fixedDiscount,discountType:totals.discountType,discountInput:totals.discountInput,vat:totals.vatAmount,vatType:totals.vatType,vatRate:totals.vatRate,grandTotal:totals.grandTotal,description,items,currencyLabel:cur,electronicDoc:edoc};
624 datastore.invoices.push(record);
625 alert(invoiceCreatesAccountingEntry(kind)?'فاکتور به‌صورت پیش‌نویس ذخیره شد. از حسابداری ← مدیریت اسناد می‌توانید آن را بازبینی و قطعی کنید.':'سند عملیاتی ذخیره شد؛ ثبت حسابداری قطعی ایجاد نمی‌شود.');
626 cancelInvoiceEdit();
627 renderAndPrintDirect(record.id);
628 }
629 // Draft edits must not update the posted sales price defaults.
630 window.pendingElectronicDoc=null;
631 saveDatastore();
632 refreshAllSurfaces();
633 }
634 function editInvoice(invId,allowPostedCorrection=false){
635 const inv=getMyInvoices().find(i=>i.id===invId);
636 if(!inv)return;
637 if(!afCompanyId()||inv.companyId!==afCompanyId()){
638 alert('برای مشاهده این فاکتور، ابتدا شرکت مربوطه را در تنظیمات فعال کنید.');return;
639 }
640 if(!invoiceMayEdit(inv)&&!(allowPostedCorrection&&invoiceDocumentStatus(inv)==='posted')){alert('فاکتور برای اصلاح در این وضعیت قابل دسترس نیست.');return;}
641 switchView('view-invoices');
642 document.getElementById('edit-invoice-id').value=inv.id;
643 document.getElementById('invoice-form-title').innerText=`✏️ اصلاح فاکتور #${invoiceVisibleNumber(inv)}`;
644 document.getElementById('btn-cancel-edit').style.display='inline-flex';
645 document.getElementById('btn-save-invoice').innerText='💾 ذخیره تغییرات';
646 document.getElementById('invoice-company-id').value=inv.companyId;
647 document.getElementById('invoice-kind').value=inv.kind;
648 document.getElementById('invoice-vat-mode').value=inv.vat>0?'with_vat':'none';
649 document.getElementById('invoice-vat-type').value=inv.vatType||'percent';
650 document.getElementById('invoice-vat-rate-input').value=inv.vatRate||10;
651 document.getElementById('invoice-number').value=invoiceVisibleNumber(inv);
652 document.getElementById('invoice-contact-id').value=inv.contactId;
653 document.getElementById('invoice-date-input').value=inv.date;
654 if(document.getElementById('invoice-payment-method'))document.getElementById('invoice-payment-method').value=inv.paymentMethod||'cash';if(document.getElementById('invoice-warehouse-id'))document.getElementById('invoice-warehouse-id').value=inv.warehouseId||p5DefaultWarehouse()?.id||'';
655 document.getElementById('invoice-discount-type').value=inv.discountType||'fixed';
656 document.getElementById('label-invoice-discount-value').innerText=(inv.discountType==='percent')?'درصد تخفیف (٪)':`مبلغ تخفیف (${getCurrencyLabel()})`;
657 document.getElementById('invoice-discount-fixed').value=(inv.discountType==='percent')?(inv.discountInput||0):(inv.discount||0);
658 document.getElementById('invoice-desc-input').value=inv.description||'';
659 const contractInput=document.getElementById('invoice-contract-number');
660 if(contractInput)contractInput.value=inv.contractNumber||'';
661 handleInvoiceKindChange();
662 if(typeof handleInvoiceContactChange==='function'){
663 handleInvoiceContactChange();
664 const projSel=document.getElementById('invoice-project-id');
665 if(projSel&&inv.projectId)projSel.value=inv.projectId;
666 }
667 // بارگذاری سند الکترونیکی در صورت وجود
668 window.pendingElectronicDoc=inv.electronicDoc||null;
669 const cb=document.getElementById('enable-electronic-doc');
670 if(cb){
671 if(inv.kind==='formal'&&inv.electronicDoc){
672 cb.checked=true;
673 document.getElementById('edoc-status').innerText='✓ اطلاعات سند الکترونیکی قبلاً ذخیره شده است.';
674 }else{
675 cb.checked=false;
676 document.getElementById('edoc-status').innerText='';
677 }
678 }
679 const tbody=document.getElementById('invoice-items-table-body');
680 tbody.innerHTML='';
681 inv.items.forEach(it=>{
682 addInvoiceItemRow(it.prodId,it.qty,it.price);
683 const lastRow=tbody.lastElementChild;
684 if(lastRow)lastRow.querySelector('.row-unit-input').value=it.unit||'عدد';
685 });
686 updateInvoiceItemRowNumbers();
687 recomputeTotals();
688 }
689 function cancelInvoiceEdit(){
690 finoraSaleAmendmentId='';
691 document.getElementById('edit-invoice-id').value='';
692 document.getElementById('invoice-form-title').innerText='صدور فاکتور جدید';
693 document.getElementById('btn-cancel-edit').style.display='none';
694 document.getElementById('btn-save-invoice').innerText='💾 ثبت فاکتور';
695 document.getElementById('invoice-items-table-body').innerHTML='';
696 document.getElementById('invoice-number').value='';
697 document.getElementById('invoice-discount-type').value='fixed';
698 document.getElementById('label-invoice-discount-value').innerText=`مبلغ تخفیف (${getCurrencyLabel()})`;
699 document.getElementById('invoice-discount-fixed').value=0;
700 document.getElementById('invoice-vat-type').value='percent';
701 document.getElementById('invoice-desc-input').value='';
702 if(document.getElementById('invoice-payment-method'))document.getElementById('invoice-payment-method').value='cash';
703 const contractInput=document.getElementById('invoice-contract-number');
704 if(contractInput)contractInput.value='';
705 const contractBox=document.getElementById('box-invoice-contract-number');
706 if(contractBox)contractBox.style.display='none';
707 const projectRow=document.getElementById('box-invoice-project-row');
708 if(projectRow)projectRow.style.display='none';
709 window.pendingElectronicDoc=null;
710 const cb=document.getElementById('enable-electronic-doc');
711 if(cb)cb.checked=false;
712 const st=document.getElementById('edoc-status');
713 if(st)st.innerText='';
714 addInvoiceItemRow();
715 applyDefaultSettingsToForm();
716 }
717 function renderInvoices(){
718 const tbody=document.getElementById('invoice-archive-table-body');
719 if(!tbody)return;
720 // Filtering is authoritative from Settings; no independent ALL/stale filter.
721 const list=invoiceVisibleRecords();
722 if(list.length===0){tbody.innerHTML='<tr><td colspan="7" style="text-align:center;color:var(--text-muted);padding:20px">هیچ فاکتوری ثبت نشده است.</td></tr>';return;}
723 tbody.innerHTML=list.map(inv=>`
724 <tr>
725 <td><strong>#${esc(invoiceVisibleNumber(inv))}</strong></td>
726 <td>${esc(inv.companyName||'—')}</td>
727 <td>${esc(inv.contactName)}${inv.projectName?' <span class="badge badge-info">'+esc(inv.projectName)+'</span>':''}</td>
728 <td><span class="badge ${inv.kind==='formal'?'badge-danger':(inv.kind==='contract_statement'?'badge-warning':'badge-success')}">${esc(inv.kindLabel)}</span></td>
729 <td>${esc(inv.date)}</td>
730 <td>${inv.grandTotal.toLocaleString('fa-IR')}<div class="af-hint">${esc(invoiceDocumentStatusLabel(inv))}</div></td>
731 <td>
732 <button class="btn btn-secondary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="navigateShell('accounting','view-journal','documents')">▤ مدیریت سند</button>${invoiceMayEdit(inv)?` <button class="btn btn-secondary btn-inline" onclick="editInvoice('${inv.id}')">✏️ ویرایش</button>` : (invoiceDocumentStatus(inv)==='posted'?` <button class="btn btn-secondary btn-inline" onclick="beginInvoiceAmendment('${inv.id}')">✏️ اصلاح</button>`:'')}
733 <button class="btn btn-secondary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="renderAndPrintDirect('${inv.id}')">🖨️ چاپ</button>
734 ${inv.electronicDoc?`<button class="btn btn-primary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="printElectronicDoc('${inv.id}')">📄 سند مودیان</button>`:''}
735 </td>
736 </tr>`).join('');
737 }
738
739 function finoraEnsureInitialInvoiceRow(){const body=document.getElementById('invoice-items-table-body');if(body&&!body.querySelector('tr')&&!document.getElementById('edit-invoice-id')?.value)addInvoiceItemRow()}
740 if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',finoraEnsureInitialInvoiceRow,{once:true});else finoraEnsureInitialInvoiceRow();