@davoodmehraban89 / Factor-easy-2 Mirror · read-only
Fork 0

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

Mirrored from https://github.com/davoodmehraban89/Factor-easy.git

Synced Dec 3, 17:00 UTC

exec-phase1-qa
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 501 lines 28.7 KB
Raw
1 function handleInvoiceKindChange(){
2 const kind=document.getElementById('invoice-kind').value;
3 const vatModeRow=document.getElementById('box-invoice-vat-mode-row');
4 const vatModeSelect=document.getElementById('invoice-vat-mode');
5 if(kind==='non_formal'){
6 if(vatModeRow)vatModeRow.style.display='none';
7 if(vatModeSelect)vatModeSelect.value='none';
8 }else{
9 if(vatModeRow)vatModeRow.style.display='flex';
10 }
11 const boxEdoc=document.getElementById('box-enable-electronic-doc');
12 if(boxEdoc){
13 if(kind==='formal'){
14 boxEdoc.style.display='block';
15 }else{
16 boxEdoc.style.display='none';
17 const cb=document.getElementById('enable-electronic-doc');
18 if(cb)cb.checked=false;
19 window.pendingElectronicDoc=null;
20 const st=document.getElementById('edoc-status');
21 if(st)st.innerText='';
22 }
23 }
24 const contractBox=document.getElementById('box-invoice-contract-number');
25 if(contractBox)contractBox.style.display=(kind==='contract_statement')?'flex':'none';
26 handleVatModeChange();
27 recomputeTotals();
28 }
29 function handleVatModeChange(){
30 const mode=document.getElementById('invoice-vat-mode').value;
31 const kind=document.getElementById('invoice-kind').value;
32 const rateBox=document.getElementById('box-invoice-vat-rate');
33 if(kind==='non_formal'){rateBox.style.display='none';document.getElementById('invoice-vat-mode').value='none';}
34 else{rateBox.style.display=(mode==='with_vat')?'flex':'none';}
35 recomputeTotals();
36 }
37 function handleVatTypeChange(){const type=document.getElementById('invoice-vat-type').value;document.getElementById('invoice-vat-rate-input').value=(type==='percent')?10:0;recomputeTotals();}
38 function handleDiscountTypeChange(){
39 const type=document.getElementById('invoice-discount-type').value;
40 const label=document.getElementById('label-invoice-discount-value');
41 const cur=getCurrencyLabel();
42 label.innerText=(type==='percent')?'درصد تخفیف (٪)':`مبلغ تخفیف (${cur})`;
43 document.getElementById('invoice-discount-fixed').value=0;
44 recomputeTotals();
45 }
46 function applyDefaultSettingsToForm(){
47 const def=getMySettings();
48 const defKind=document.getElementById('def-invoice-kind');
49 const defVat=document.getElementById('def-vat-mode');
50 const defRate=document.getElementById('def-vat-rate');
51 const defCurMode=document.getElementById('def-currency-mode');
52 const defCurCustom=document.getElementById('def-currency-custom');
53 if(defKind)defKind.value=def.invoice_kind||'non_formal';
54 if(defVat)defVat.value=def.vat_mode||'none';
55 if(defRate)defRate.value=def.vat_rate||10;
56 if(defCurMode)defCurMode.value=def.currency_mode||'rial';
57 if(defCurCustom)defCurCustom.value=def.currency_custom||'';
58 handleCurrencyModeChange();
59 const editId=document.getElementById('edit-invoice-id')?.value;
60 if(!editId){
61 const kindEl=document.getElementById('invoice-kind');
62 if(kindEl)kindEl.value=def.invoice_kind||'non_formal';
63 handleInvoiceKindChange();
64 if((def.invoice_kind||'non_formal')!=='non_formal'){
65 document.getElementById('invoice-vat-mode').value=def.vat_mode||'none';
66 document.getElementById('invoice-vat-rate-input').value=def.vat_rate||10;
67 handleVatModeChange();
68 }
69 }
70 }
71 function commitSaveDefaultSettings(){
72 if(!requireWrite())return;
73 const s=getMySettings();
74 s.invoice_kind=document.getElementById('def-invoice-kind').value;
75 s.vat_mode=document.getElementById('def-vat-mode').value;
76 s.vat_rate=parseFormattedNumber(document.getElementById('def-vat-rate').value);
77 s.currency_mode=document.getElementById('def-currency-mode').value;
78 s.currency_custom=document.getElementById('def-currency-custom').value||'';
79 saveDatastore();
80 refreshCurrencyLabels();
81 alert('پیش‌فرض‌ها ذخیره شد.');
82 }
83 function renderDashboard(){
84 let salesSum=0;let debtorsSum=0;
85 const myInvoices=getMyInvoices();
86 const myCheques=getMyCheques();
87 const myCompanies=getMyCompanies();
88 const mySettings=getMySettings();
89 const activeCompId=mySettings.default_company_id||document.getElementById('invoice-company-id')?.value||(myCompanies[0]?.id);
90 const filteredInvoices=activeCompId?myInvoices.filter(inv=>inv.companyId===activeCompId):myInvoices;
91 const cur=getCurrencyLabel();
92 filteredInvoices.forEach(inv=>{salesSum+=Number(inv.grandTotal||0);if(inv.paymentMethod==='credit')debtorsSum+=Number(inv.grandTotal||0);});
93 const inboundSettlements=myCheques.filter(q=>q.direction==='inbound'&&q.status==='cleared'&&(!activeCompId||q.companyId===activeCompId||(!q.companyId&&myCompanies.length===1))).reduce((a,q)=>a+Number(q.amount||0),0);
94 debtorsSum=Math.max(0,debtorsSum-inboundSettlements);
95 const salesEl=document.getElementById('kpi-sales-sum');
96 const settledEl=document.getElementById('kpi-settled-sum');
97 const debtorsEl=document.getElementById('kpi-debtors-sum');
98 const chequesEl=document.getElementById('kpi-cheques-count');
99 if(salesEl)salesEl.innerText=salesSum.toLocaleString('fa-IR')+' '+cur;
100 if(settledEl)settledEl.innerText=(salesSum-debtorsSum).toLocaleString('fa-IR')+' '+cur;
101 if(debtorsEl)debtorsEl.innerText=debtorsSum.toLocaleString('fa-IR')+' '+cur;
102 if(chequesEl)chequesEl.innerText=myCheques.filter(c=>c.status==='registered').length.toLocaleString('fa-IR')+' فقره';
103 const recentTbody=document.getElementById('dashboard-recent-table');
104 if(recentTbody){
105 if(filteredInvoices.length===0){recentTbody.innerHTML='<tr><td colspan="7" style="text-align:center;color:var(--text-muted);padding:20px">هیچ فاکتوری صادر نشده است.</td></tr>';return;}
106 recentTbody.innerHTML=filteredInvoices.slice(-5).reverse().map(inv=>`
107 <tr>
108 <td><strong>#${esc(inv.number)}</strong></td>
109 <td>${esc(inv.companyName||'—')}</td>
110 <td>${esc(inv.contactName)}</td>
111 <td><span class="badge ${inv.kind==='formal'?'badge-danger':(inv.kind==='contract_statement'?'badge-warning':'badge-success')}">${esc(inv.kindLabel)}</span></td>
112 <td>${inv.vat>0?'با ارزش افزوده':'بدون مالیات'}</td>
113 <td>${inv.grandTotal.toLocaleString('fa-IR')}</td>
114 <td><button class="btn btn-secondary btn-inline" style="padding:4px 10px;font-size:12px" onclick="renderAndPrintDirect('${inv.id}')">🖨️ چاپ</button></td>
115 </tr>`).join('');
116 }
117 }
118 function onActiveCompanyFilterChange(){
119 const activeCompId=document.getElementById('invoice-company-id').value;
120 const filterSelect=document.getElementById('filter-invoice-company');
121 if(filterSelect)filterSelect.value=activeCompId;
122 renderInvoices();renderDashboard();
123 }
124 function startNewInvoice(){cancelInvoiceEdit();switchView('view-invoices');}
125 function updateInvoiceItemRowNumbers(){
126 const rows=document.querySelectorAll('#invoice-items-table-body tr');
127 rows.forEach((tr,index)=>{const numCell=tr.querySelector('.row-item-number');if(numCell)numCell.innerText=(index+1).toLocaleString('fa-IR');});
128 }
129 function addInvoiceItemRow(selectedProdId='',initialQty=1,initialPrice=null){
130 const tbody=document.getElementById('invoice-items-table-body');
131 const rowKey='item_'+Date.now()+'_'+Math.random().toString(36).substr(2,4);
132 const tr=document.createElement('tr');
133 tr.id=rowKey;
134 const myProducts=getMyProducts();
135 const productOptions=myProducts.map(p=>`<option value="${p.id}" data-price="${esc(p.sale_price)}" data-unit="${esc(p.unit||'عدد')}" ${p.id===selectedProdId?'selected':''}>${esc(p.name)} ${esc(p.spec?'('+p.spec+')':'')}</option>`).join('');
136 const priceVal=(initialPrice!==null?Number(initialPrice):0);
137 tr.innerHTML=`
138 <td class="row-item-number" style="width:40px;text-align:center;font-weight:bold;vertical-align:middle"></td>
139 <td><select class="form-control row-product-select" onchange="onRowProductChange('${rowKey}')"><option value="">-- انتخاب کالا / خدمات --</option>${productOptions}</select></td>
140 <td style="width:90px"><input type="text" class="form-control row-unit-input" value="عدد" style="text-align:center" /></td>
141 <td style="width:100px"><input type="number" class="form-control row-quantity" value="${initialQty}" min="1" oninput="recomputeTotals()" style="text-align:center" /></td>
142 <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>
143 <td class="row-linetotal" style="width:170px;font-weight:bold;text-align:left;vertical-align:middle;direction:ltr">۰</td>
144 <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>`;
145 tbody.appendChild(tr);
146 updateInvoiceItemRowNumbers();
147 if(selectedProdId&&initialPrice===null)onRowProductChange(rowKey);
148 else recomputeTotals();
149 }
150 function onRowProductChange(rowKey){
151 const tr=document.getElementById(rowKey);if(!tr)return;
152 const sel=tr.querySelector('.row-product-select');
153 const opt=sel.options[sel.selectedIndex];
154 const prc=parseFormattedNumber(opt?.getAttribute('data-price')||0);
155 const unt=opt?.getAttribute('data-unit');
156 tr.querySelector('.row-price').value=prc?prc.toLocaleString('en-US'):'';
157 if(unt){const unitInput=tr.querySelector('.row-unit-input');if(unitInput)unitInput.value=unt;}
158 recomputeTotals();
159 }
160 function recomputeTotals(){
161 let subtotal=0;
162 document.querySelectorAll('#invoice-items-table-body tr').forEach(tr=>{
163 const qty=parseFloat(tr.querySelector('.row-quantity')?.value)||0;
164 const prc=parseFormattedNumber(tr.querySelector('.row-price')?.value);
165 const line=qty*prc;
166 const lineEl=tr.querySelector('.row-linetotal');
167 if(lineEl)lineEl.innerText=line.toLocaleString('fa-IR');
168 subtotal+=line;
169 });
170 const discountType=document.getElementById('invoice-discount-type')?.value||'fixed';
171 const discountInput=parseFormattedNumber(document.getElementById('invoice-discount-fixed')?.value);
172 const rawDiscount=(discountType==='percent')?Math.round(subtotal*(discountInput/100)):discountInput;
173 const fixedDiscount=Math.max(0,Math.min(rawDiscount,subtotal));
174 const kind=document.getElementById('invoice-kind')?.value||'non_formal';
175 const vatMode=(kind==='non_formal')?'none':(document.getElementById('invoice-vat-mode')?.value||'none');
176 const vatType=document.getElementById('invoice-vat-type')?.value||'percent';
177 const vatRate=parseFormattedNumber(document.getElementById('invoice-vat-rate-input')?.value);
178 const afterDiscount=Math.max(0,subtotal-fixedDiscount);
179 let vatAmount=0;
180 if(vatMode==='with_vat'){vatAmount=(vatType==='fixed')?Math.max(0,Math.round(vatRate)):Math.round(afterDiscount*(vatRate/100));}
181 const grandTotal=afterDiscount+vatAmount;
182 const cur=getCurrencyLabel();
183 const subtotalEl=document.getElementById('summary-subtotal');
184 const vatEl=document.getElementById('summary-vat');
185 const grandEl=document.getElementById('summary-grandtotal');
186 const wordsEl=document.getElementById('summary-words');
187 if(subtotalEl)subtotalEl.innerText=subtotal.toLocaleString('fa-IR')+' '+cur;
188 if(vatEl)vatEl.innerText=vatAmount.toLocaleString('fa-IR')+' '+cur;
189 if(grandEl)grandEl.innerText=grandTotal.toLocaleString('fa-IR')+' '+cur;
190 if(wordsEl)wordsEl.innerText='به حروف: '+numberToPersianWords(grandTotal,cur);
191 return {subtotal,fixedDiscount,discountType,discountInput,vatAmount,vatType,grandTotal,vatRate};
192 }
193
194 // ================== سند الکترونیکی سامانه مودیان ==================
195 function toggleElectronicDoc(){
196 const checked=document.getElementById('enable-electronic-doc').checked;
197 if(checked){
198 openElectronicDocModal();
199 }else{
200 window.pendingElectronicDoc=null;
201 document.getElementById('edoc-status').innerText='';
202 }
203 }
204 function openElectronicDocModal(){
205 const itemsContainer=document.getElementById('edoc-items-container');
206 const rows=document.querySelectorAll('#invoice-items-table-body tr');
207 let html='';
208 if(rows.length===0){
209 html='<p style="color:var(--text-muted);font-size:12.5px;padding:8px">ابتدا اقلام فاکتور را اضافه کنید.</p>';
210 }else{
211 rows.forEach((tr,idx)=>{
212 const sel=tr.querySelector('.row-product-select');
213 const prodId=sel?sel.value:'';
214 const prod=getMyProducts().find(p=>p.id===prodId)||{};
215 const prodName=sel&&sel.options[sel.selectedIndex]?sel.options[sel.selectedIndex].text:'';
216 html+=`<div style="border:1px solid var(--border);border-radius:8px;padding:10px;margin-bottom:8px;background:#f8fafc">
217 <div style="font-weight:bold;font-size:13px;margin-bottom:8px">ردیف ${toPersianDigits(idx+1)}: ${prodName||'—'}</div>
218 <div class="form-row">
219 <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.internal_id||'')}" /></div>
220 <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="" /></div>
221 </div>
222 </div>`;
223 });
224 }
225 itemsContainer.innerHTML=html;
226
227 const p=window.pendingElectronicDoc;
228 if(p){
229 document.getElementById('edoc-unique-number').value=p.uniqueNumber||'';
230 document.getElementById('edoc-tax-number').value=p.taxNumber||'';
231 document.getElementById('edoc-issue-datetime').value=p.issueDateTime||'';
232 document.getElementById('edoc-original-date').value=p.originalDate||'';
233 document.getElementById('edoc-original-number').value=p.originalNumber||'';
234 document.getElementById('edoc-kind').value=p.kind||'اصل';
235 document.getElementById('edoc-pattern').value=p.pattern||'کالا';
236 document.getElementById('edoc-contract-id').value=p.contractId||'';
237 if(p.items){
238 p.items.forEach((it,idx)=>{
239 const intEl=document.querySelector(`.edoc-row-internal[data-row="${idx}"]`);
240 const offEl=document.querySelector(`.edoc-row-official[data-row="${idx}"]`);
241 if(intEl)intEl.value=it.internalId||'';
242 if(offEl)offEl.value=it.officialId||'';
243 });
244 }
245 }else{
246 const now=new Date();
247 const timeStr=now.getHours().toString().padStart(2,'0')+':'+now.getMinutes().toString().padStart(2,'0')+':00';
248 document.getElementById('edoc-issue-datetime').value=getJalaliNumeric()+' '+timeStr;
249 document.getElementById('edoc-original-date').value='';
250 document.getElementById('edoc-original-number').value='';
251 document.getElementById('edoc-unique-number').value='';
252 document.getElementById('edoc-tax-number').value='';
253 document.getElementById('edoc-kind').value='اصل';
254 document.getElementById('edoc-pattern').value='کالا';
255 document.getElementById('edoc-contract-id').value='';
256 }
257 handleEdocPatternChange();
258 document.getElementById('modal-electronic-doc').classList.add('active');
259 }
260 function closeElectronicDocModal(){
261 document.getElementById('modal-electronic-doc').classList.remove('active');
262 }
263 function cancelElectronicDoc(){
264 document.getElementById('enable-electronic-doc').checked=false;
265 window.pendingElectronicDoc=null;
266 document.getElementById('edoc-status').innerText='';
267 closeElectronicDocModal();
268 }
269 function handleEdocPatternChange(){
270 const pattern=document.getElementById('edoc-pattern').value;
271 const box=document.getElementById('box-edoc-contract');
272 const hint=document.getElementById('edoc-contract-hint');
273 if(pattern==='پیمانکاری'){
274 box.style.display='block';
275 hint.style.display='none';
276 }else{
277 box.style.display='none';
278 hint.style.display='block';
279 }
280 }
281 function saveElectronicDocToPending(){
282 const pattern=document.getElementById('edoc-pattern').value;
283 const contractId=document.getElementById('edoc-contract-id').value.trim();
284 if(pattern==='پیمانکاری'&&!contractId){
285 alert('برای الگوی «قرارداد پیمانکاری»، وارد کردن «شناسه یکتای ثبت قرارداد» اجباری است.');
286 return;
287 }
288 const items=[];
289 const rows=document.querySelectorAll('#invoice-items-table-body tr');
290 for(let idx=0;idx<rows.length;idx++){
291 const intEl=document.querySelector(`.edoc-row-internal[data-row="${idx}"]`);
292 const offEl=document.querySelector(`.edoc-row-official[data-row="${idx}"]`);
293 const offVal=offEl?offEl.value.trim():'';
294 if(!offVal){
295 alert(`«شناسه کالا/خدمت» برای ردیف ${toPersianDigits(idx+1)} اجباری است.`);
296 return;
297 }
298 items.push({internalId:intEl?intEl.value.trim():'',officialId:offVal});
299 }
300 const p={
301 uniqueNumber:document.getElementById('edoc-unique-number').value.trim(),
302 taxNumber:document.getElementById('edoc-tax-number').value.trim(),
303 issueDateTime:document.getElementById('edoc-issue-datetime').value.trim(),
304 originalDate:document.getElementById('edoc-original-date').value.trim(),
305 originalNumber:document.getElementById('edoc-original-number').value.trim(),
306 kind:document.getElementById('edoc-kind').value,
307 pattern:pattern,
308 contractId:contractId,
309 items:items
310 };
311 window.pendingElectronicDoc=p;
312 document.getElementById('edoc-status').innerText='✓ اطلاعات سند الکترونیکی ذخیره شد. با ثبت فاکتور، سند نیز ذخیره می‌شود.';
313 closeElectronicDocModal();
314 }
315
316 function commitSaveInvoice(){
317 if(!requireWrite())return;
318 if(!currentUser)return;
319 const myCompanies=getMyCompanies();
320 const mySettings=getMySettings();
321 const companySelect=document.getElementById('invoice-company-id');
322 const selectedCompanyId=companySelect?companySelect.value:mySettings.default_company_id;
323 const sellerCompany=myCompanies.find(c=>c.id===selectedCompanyId)||myCompanies.find(c=>c.id===mySettings.default_company_id)||myCompanies[0];
324 if(!sellerCompany){alert('لطفاً ابتدا حداقل یک شرکت در بخش تنظیمات ثبت فرمایید.');return;}
325 const companyId=sellerCompany.id;
326 const companyName=sellerCompany.name;
327 const contactSelect=document.getElementById('invoice-contact-id');
328 const contactId=contactSelect?contactSelect.value:'';
329 const contactName=contactSelect?.options[contactSelect.selectedIndex]?.text||'مشتری آزاد';
330 const number=document.getElementById('invoice-number')?.value.trim()||('PINV-'+(getMyInvoices().length+31));
331 const date=document.getElementById('invoice-date-input')?.value.trim()||getJalaliNumeric();
332 const kind=document.getElementById('invoice-kind')?.value||'non_formal';
333 const description=document.getElementById('invoice-desc-input')?.value.trim()||'';
334 const paymentMethod=document.getElementById('invoice-payment-method')?.value||'cash';
335 const paymentMethodLabel=paymentMethod==='credit'?'نسیه':'نقدی';
336 const editId=document.getElementById('edit-invoice-id')?.value;
337 if(getMyInvoices().some(i=>i.id!==editId&&i.companyId===companyId&&String(i.number||'').trim()===number)){alert('شماره فاکتور برای این شرکت قبلاً ثبت شده است.');return;}
338 if(kind==='non_formal'){document.getElementById('invoice-vat-mode').value='none';}
339
340 const contractNumber=document.getElementById('invoice-contract-number')?.value.trim()||'';
341 if(kind==='contract_statement'&&!contractNumber){
342 alert('برای «صورت وضعیت پیمان»، وارد کردن شماره پیمان اجباری است.');
343 return;
344 }
345 const projectSelect=document.getElementById('invoice-project-id');
346 const projectRow=document.getElementById('box-invoice-project-row');
347 const projectId=(projectRow&&projectRow.style.display!=='none'&&projectSelect)?projectSelect.value:'';
348 const projectName=(projectId&&projectSelect)?(projectSelect.options[projectSelect.selectedIndex]?.text||''):'';
349
350 const items=[];
351 document.querySelectorAll('#invoice-items-table-body tr').forEach(tr=>{
352 const sel=tr.querySelector('.row-product-select');
353 const prodId=sel?sel.value:'';
354 const prodName=sel?sel.options[sel.selectedIndex]?.text:'';
355 const unit=tr.querySelector('.row-unit-input')?.value||'عدد';
356 const qty=parseFloat(tr.querySelector('.row-quantity')?.value)||0;
357 const price=parseFormattedNumber(tr.querySelector('.row-price')?.value);
358 if(prodId&&qty>0){items.push({prodId,prodName,unit,qty,price,lineTotal:qty*price});}
359 });
360 if(items.length===0){alert('لطفاً حداقل یک ردیف کالا به فاکتور اضافه کنید.');return;}
361
362 // بررسی سند الکترونیکی
363 let edoc=null;
364 if(kind==='formal'){
365 const cb=document.getElementById('enable-electronic-doc');
366 if(cb&&cb.checked){
367 if(!window.pendingElectronicDoc){
368 alert('برای صدور سند الکترونیکی، ابتدا باید اطلاعات سند را تکمیل و ذخیره کنید.');
369 return;
370 }
371 edoc=window.pendingElectronicDoc;
372 if(edoc.pattern==='پیمانکاری'&&!edoc.contractId){
373 alert('برای الگوی «قرارداد پیمانکاری»، وارد کردن «شناسه یکتای ثبت قرارداد» اجباری است.');
374 return;
375 }
376 }
377 }
378
379 const totals=recomputeTotals();
380 const kindLabels={formal:'رسمی',non_formal:'غیررسمی',pre_invoice:'پیش‌فاکتور',contract_statement:'صورت وضعیت پیمان'};
381 const cur=getCurrencyLabel();
382 if(editId){
383 const existingIndex=datastore.invoices.findIndex(i=>i.id===editId&&i.ownerUserId===currentUser.id);
384 if(existingIndex!==-1){
385 const prev=datastore.invoices[existingIndex];
386 const finalEdoc=edoc?edoc:(prev.electronicDoc||null);
387 datastore.invoices[existingIndex]={...prev,ownerUserId:currentUser.id,number,date,companyId,companyName,kind,kindLabel:kindLabels[kind],contactId,contactName,projectId,projectName,contractNumber,paymentMethod,paymentMethodLabel,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};
388 alert('فاکتور با موفقیت ویرایش شد.');
389 }
390 cancelInvoiceEdit();
391 }else{
392 const record={id:'INV_'+Date.now(),ownerUserId:currentUser.id,number,date,companyId,companyName,kind,kindLabel:kindLabels[kind],contactId,contactName,projectId,projectName,contractNumber,paymentMethod,paymentMethodLabel,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};
393 datastore.invoices.push(record);
394 alert('فاکتور با موفقیت ثبت شد.');
395 cancelInvoiceEdit();
396 renderAndPrintDirect(record.id);
397 }
398 window.pendingElectronicDoc=null;
399 saveDatastore();
400 refreshAllSurfaces();
401 }
402 function editInvoice(invId){
403 const inv=getMyInvoices().find(i=>i.id===invId);
404 if(!inv)return;
405 switchView('view-invoices');
406 document.getElementById('edit-invoice-id').value=inv.id;
407 document.getElementById('invoice-form-title').innerText=`✏️ ویرایش فاکتور #${inv.number}`;
408 document.getElementById('btn-cancel-edit').style.display='inline-flex';
409 document.getElementById('btn-save-invoice').innerText='💾 ذخیره تغییرات';
410 document.getElementById('invoice-company-id').value=inv.companyId;
411 document.getElementById('invoice-kind').value=inv.kind;
412 document.getElementById('invoice-vat-mode').value=inv.vat>0?'with_vat':'none';
413 document.getElementById('invoice-vat-type').value=inv.vatType||'percent';
414 document.getElementById('invoice-vat-rate-input').value=inv.vatRate||10;
415 document.getElementById('invoice-number').value=inv.number;
416 document.getElementById('invoice-contact-id').value=inv.contactId;
417 document.getElementById('invoice-date-input').value=inv.date;
418 if(document.getElementById('invoice-payment-method'))document.getElementById('invoice-payment-method').value=inv.paymentMethod||'cash';
419 document.getElementById('invoice-discount-type').value=inv.discountType||'fixed';
420 document.getElementById('label-invoice-discount-value').innerText=(inv.discountType==='percent')?'درصد تخفیف (٪)':`مبلغ تخفیف (${getCurrencyLabel()})`;
421 document.getElementById('invoice-discount-fixed').value=(inv.discountType==='percent')?(inv.discountInput||0):(inv.discount||0);
422 document.getElementById('invoice-desc-input').value=inv.description||'';
423 const contractInput=document.getElementById('invoice-contract-number');
424 if(contractInput)contractInput.value=inv.contractNumber||'';
425 handleInvoiceKindChange();
426 if(typeof handleInvoiceContactChange==='function'){
427 handleInvoiceContactChange();
428 const projSel=document.getElementById('invoice-project-id');
429 if(projSel&&inv.projectId)projSel.value=inv.projectId;
430 }
431 // بارگذاری سند الکترونیکی در صورت وجود
432 window.pendingElectronicDoc=inv.electronicDoc||null;
433 const cb=document.getElementById('enable-electronic-doc');
434 if(cb){
435 if(inv.kind==='formal'&&inv.electronicDoc){
436 cb.checked=true;
437 document.getElementById('edoc-status').innerText='✓ اطلاعات سند الکترونیکی قبلاً ذخیره شده است.';
438 }else{
439 cb.checked=false;
440 document.getElementById('edoc-status').innerText='';
441 }
442 }
443 const tbody=document.getElementById('invoice-items-table-body');
444 tbody.innerHTML='';
445 inv.items.forEach(it=>{
446 addInvoiceItemRow(it.prodId,it.qty,it.price);
447 const lastRow=tbody.lastElementChild;
448 if(lastRow)lastRow.querySelector('.row-unit-input').value=it.unit||'عدد';
449 });
450 updateInvoiceItemRowNumbers();
451 recomputeTotals();
452 }
453 function cancelInvoiceEdit(){
454 document.getElementById('edit-invoice-id').value='';
455 document.getElementById('invoice-form-title').innerText='صدور فاکتور جدید';
456 document.getElementById('btn-cancel-edit').style.display='none';
457 document.getElementById('btn-save-invoice').innerText='💾 ثبت فاکتور';
458 document.getElementById('invoice-items-table-body').innerHTML='';
459 document.getElementById('invoice-number').value='';
460 document.getElementById('invoice-discount-type').value='fixed';
461 document.getElementById('label-invoice-discount-value').innerText=`مبلغ تخفیف (${getCurrencyLabel()})`;
462 document.getElementById('invoice-discount-fixed').value=0;
463 document.getElementById('invoice-vat-type').value='percent';
464 document.getElementById('invoice-desc-input').value='';
465 if(document.getElementById('invoice-payment-method'))document.getElementById('invoice-payment-method').value='cash';
466 const contractInput=document.getElementById('invoice-contract-number');
467 if(contractInput)contractInput.value='';
468 const contractBox=document.getElementById('box-invoice-contract-number');
469 if(contractBox)contractBox.style.display='none';
470 const projectRow=document.getElementById('box-invoice-project-row');
471 if(projectRow)projectRow.style.display='none';
472 window.pendingElectronicDoc=null;
473 const cb=document.getElementById('enable-electronic-doc');
474 if(cb)cb.checked=false;
475 const st=document.getElementById('edoc-status');
476 if(st)st.innerText='';
477 addInvoiceItemRow();
478 applyDefaultSettingsToForm();
479 }
480 function renderInvoices(){
481 const tbody=document.getElementById('invoice-archive-table-body');
482 const filterSelect=document.getElementById('filter-invoice-company');
483 const selectedFilter=filterSelect?.value||document.getElementById('invoice-company-id')?.value||'ALL';
484 let list=getMyInvoices();
485 if(selectedFilter!=='ALL')list=list.filter(i=>i.companyId===selectedFilter);
486 if(list.length===0){tbody.innerHTML='<tr><td colspan="7" style="text-align:center;color:var(--text-muted);padding:20px">هیچ فاکتوری ثبت نشده است.</td></tr>';return;}
487 tbody.innerHTML=list.map(inv=>`
488 <tr>
489 <td><strong>#${esc(inv.number)}</strong></td>
490 <td>${esc(inv.companyName||'—')}</td>
491 <td>${esc(inv.contactName)}${inv.projectName?' <span class="badge badge-info">'+esc(inv.projectName)+'</span>':''}</td>
492 <td><span class="badge ${inv.kind==='formal'?'badge-danger':(inv.kind==='contract_statement'?'badge-warning':'badge-success')}">${esc(inv.kindLabel)}</span></td>
493 <td>${esc(inv.date)}</td>
494 <td>${inv.grandTotal.toLocaleString('fa-IR')}</td>
495 <td>
496 <button class="btn btn-secondary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="editInvoice('${inv.id}')">✏️ ویرایش</button>
497 <button class="btn btn-secondary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="renderAndPrintDirect('${inv.id}')">🖨️ چاپ</button>
498 ${inv.electronicDoc?`<button class="btn btn-primary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="printElectronicDoc('${inv.id}')">📄 سند مودیان</button>`:''}
499 </td>
500 </tr>`).join('');
501 }