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

Add js/invoices.js (part 2/4)

davoodmehraban89 committed Sep 26, 2026 at 08:11 UTC d31dda3a9b6a00a88c93c73a63e51c5afc9ae06e
1 file changed +1
js/invoices.js new
+1
@@ -0,0 +1 @@
1 +function handleInvoiceKindChange(){\n const kind=document.getElementById('invoice-kind').value;\n const vatModeRow=document.getElementById('box-invoice-vat-mode-row');\n const vatModeSelect=document.getElementById('invoice-vat-mode');\n if(kind==='non_formal'){\n if(vatModeRow)vatModeRow.style.display='none';\n if(vatModeSelect)vatModeSelect.value='none';\n }else{\n if(vatModeRow)vatModeRow.style.display='flex';\n }\n const boxEdoc=document.getElementById('box-enable-electronic-doc');\n if(boxEdoc){\n if(kind==='formal'){\n boxEdoc.style.display='block';\n }else{\n boxEdoc.style.display='none';\n const cb=document.getElementById('enable-electronic-doc');\n if(cb)cb.checked=false;\n window.pendingElectronicDoc=null;\n const st=document.getElementById('edoc-status');\n if(st)st.innerText='';\n }\n }\n handleVatModeChange();\n recomputeTotals();\n}\nfunction handleVatModeChange(){\n const mode=document.getElementById('invoice-vat-mode').value;\n const kind=document.getElementById('invoice-kind').value;\n const rateBox=document.getElementById('box-invoice-vat-rate');\n if(kind==='non_formal'){rateBox.style.display='none';document.getElementById('invoice-vat-mode').value='none';}\n else{rateBox.style.display=(mode==='with_vat')?'flex':'none';}\n recomputeTotals();\n}\nfunction handleVatTypeChange(){const type=document.getElementById('invoice-vat-type').value;document.getElementById('invoice-vat-rate-input').value=(type==='percent')?10:0;recomputeTotals();}\nfunction handleDiscountTypeChange(){\n const type=document.getElementById('invoice-discount-type').value;\n const label=document.getElementById('label-invoice-discount-value');\n const cur=getCurrencyLabel();\n label.innerText=(type==='percent')?'درصد تخفیف (٪)':`مبلغ تخفیف (${cur})`;\n document.getElementById('invoice-discount-fixed').value=0;\n recomputeTotals();\n}\nfunction applyDefaultSettingsToForm(){\n const def=getMySettings();\n const defKind=document.getElementById('def-invoice-kind');\n const defVat=document.getElementById('def-vat-mode');\n const defRate=document.getElementById('def-vat-rate');\n const defCurMode=document.getElementById('def-currency-mode');\n const defCurCustom=document.getElementById('def-currency-custom');\n if(defKind)defKind.value=def.invoice_kind||'non_formal';\n if(defVat)defVat.value=def.vat_mode||'none';\n if(defRate)defRate.value=def.vat_rate||10;\n if(defCurMode)defCurMode.value=def.currency_mode||'rial';\n if(defCurCustom)defCurCustom.value=def.currency_custom||'';\n handleCurrencyModeChange();\n const editId=document.getElementById('edit-invoice-id')?.value;\n if(!editId){\n const kindEl=document.getElementById('invoice-kind');\n if(kindEl)kindEl.value=def.invoice_kind||'non_formal';\n handleInvoiceKindChange();\n if((def.invoice_kind||'non_formal')!=='non_formal'){\n document.getElementById('invoice-vat-mode').value=def.vat_mode||'none';\n document.getElementById('invoice-vat-rate-input').value=def.vat_rate||10;\n handleVatModeChange();\n }\n }\n}\nfunction commitSaveDefaultSettings(){\n if(!requireWrite())return;\n const s=getMySettings();\n s.invoice_kind=document.getElementById('def-invoice-kind').value;\n s.vat_mode=document.getElementById('def-vat-mode').value;\n s.vat_rate=parseFloat(document.getElementById('def-vat-rate').value)||0;\n s.currency_mode=document.getElementById('def-currency-mode').value;\n s.currency_custom=document.getElementById('def-currency-custom').value||'';\n saveDatastore();\n refreshCurrencyLabels();\n alert('پیش‌فرض‌ها ذخیره شد.');\n}\nfunction renderDashboard(){\n let salesSum=0;let debtorsSum=0;\n const myInvoices=getMyInvoices();\n const myCheques=getMyCheques();\n const myCompanies=getMyCompanies();\n const mySettings=getMySettings();\n const activeCompId=mySettings.default_company_id||document.getElementById('invoice-company-id')?.value||(myCompanies[0]?.id);\n const filteredInvoices=activeCompId?myInvoices.filter(inv=>inv.companyId===activeCompId):myInvoices;\n const cur=getCurrencyLabel();\n filteredInvoices.forEach(inv=>{salesSum+=inv.grandTotal;if(inv.paymentMethod==='credit')debtorsSum+=inv.grandTotal;});\n const salesEl=document.getElementById('kpi-sales-sum');\n const settledEl=document.getElementById('kpi-settled-sum');\n const debtorsEl=document.getElementById('kpi-debtors-sum');\n const chequesEl=document.getElementById('kpi-cheques-count');\n if(salesEl)salesEl.innerText=salesSum.toLocaleString('fa-IR')+' '+cur;\n if(settledEl)settledEl.innerText=(salesSum-debtorsSum).toLocaleString('fa-IR')+' '+cur;\n if(debtorsEl)debtorsEl.innerText=debtorsSum.toLocaleString('fa-IR')+' '+cur;\n if(chequesEl)chequesEl.innerText=myCheques.filter(c=>c.status==='registered').length.toLocaleString('fa-IR')+' فقره';\n const recentTbody=document.getElementById('dashboard-recent-table');\n if(recentTbody){\n if(filteredInvoices.length===0){recentTbody.innerHTML='<tr><td colspan=\"7\" style=\"text-align:center;color:var(--text-muted);padding:20px\">هیچ فاکتوری صادر نشده است.</td></tr>';return;}\n recentTbody.innerHTML=filteredInvoices.slice(-5).reverse().map(inv=>`\n <tr>\n <td><strong>#${esc(inv.number)}</strong></td>\n <td>${esc(inv.companyName||'—')}</td>\n <td>${esc(inv.contactName)}</td>\n <td><span class=\"badge ${inv.kind==='formal'?'badge-danger':'badge-success'}\">${esc(inv.kindLabel)}</span></td>\n <td>${inv.vat>0?'با ارزش افزوده':'بدون مالیات'}</td>\n <td>${inv.grandTotal.toLocaleString('fa-IR')}</td>\n <td><button class=\"btn btn-secondary btn-inline\" style=\"padding:4px 10px;font-size:12px\" onclick=\"renderAndPrintDirect('${inv.id}')\">🖨️ چاپ</button></td>\n </tr>`).join('');\n }\n}\nfunction onActiveCompanyFilterChange(){\n const activeCompId=document.getElementById('invoice-company-id').value;\n const filterSelect=document.getElementById('filter-invoice-company');\n if(filterSelect)filterSelect.value=activeCompId;\n renderInvoices();renderDashboard();\n}\nfunction startNewInvoice(){cancelInvoiceEdit();switchView('view-invoices');}\nfunction updateInvoiceItemRowNumbers(){\n const rows=document.querySelectorAll('#invoice-items-table-body tr');\n rows.forEach((tr,index)=>{const numCell=tr.querySelector('.row-item-number');if(numCell)numCell.innerText=(index+1).toLocaleString('fa-IR');});\n}\nfunction addInvoiceItemRow(selectedProdId='',initialQty=1,initialPrice=null){\n const tbody=document.getElementById('invoice-items-table-body');\n const rowKey='item_'+Date.now()+'_'+Math.random().toString(36).substr(2,4);\n const tr=document.createElement('tr');\n tr.id=rowKey;\n const myProducts=getMyProducts();\n 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('');\n tr.innerHTML=`\n <td class=\"row-item-number\" style=\"width:40px;text-align:center;font-weight:bold;vertical-align:middle\"></td>\n <td><select class=\"form-control row-product-select\" onchange=\"onRowProductChange('${rowKey}')\"><option value=\"\">-- انتخاب کالا / خدمات --</option>${productOptions}</select></td>\n <td style=\"width:90px\"><input type=\"text\" class=\"form-control row-unit-input\" value=\"عدد\" style=\"text-align:center\" /></td>\n <td style=\"width:100px\"><input type=\"number\" class=\"form-control row-quantity\" value=\"${initialQty}\" min=\"1\" oninput=\"recomputeTotals()\" style=\"text-align:center\" /></td>\n <td style=\"width:160px\"><input type=\"number\" class=\"form-control row-price\" value=\"${initialPrice!==null?initialPrice:0}\" oninput=\"recomputeTotals()\" style=\"text-align:left\" /></td>\n <td class=\"row-linetotal\" style=\"width:170px;font-weight:bold;text-align:left;vertical-align:middle;direction:ltr\">۰</td>\n <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>`;\n tbody.appendChild(tr);\n updateInvoiceItemRowNumbers();\n if(selectedProdId&&initialPrice===null)onRowProductChange(rowKey);\n else recomputeTotals();\n}\nfunction onRowProductChange(rowKey){\n const tr=document.getElementById(rowKey);if(!tr)return;\n const sel=tr.querySelector('.row-product-select');\n const opt=sel.options[sel.selectedIndex];\n const prc=opt?.getAttribute('data-price')||0;\n const unt=opt?.getAttribute('data-unit');\n tr.querySelector('.row-price').value=prc;\n if(unt){const unitInput=tr.querySelector('.row-unit-input');if(unitInput)unitInput.value=unt;}\n recomputeTotals();\n}\nfunction recomputeTotals(){\n let subtotal=0;\n document.querySelectorAll('#invoice-items-table-body tr').forEach(tr=>{\n const qty=parseFloat(tr.querySelector('.row-quantity')?.value)||0;\n const prc=parseFloat(tr.querySelector('.row-price')?.value)||0;\n const line=qty*prc;\n const lineEl=tr.querySelector('.row-linetotal');\n if(lineEl)lineEl.innerText=line.toLocaleString('fa-IR');\n subtotal+=line;\n });\n const discountType=document.getElementById('invoice-discount-type')?.value||'fixed';\n const discountInput=parseFloat(document.getElementById('invoice-discount-fixed')?.value)||0;\n const rawDiscount=(discountType==='percent')?Math.round(subtotal*(discountInput/100)):discountInput;\n const fixedDiscount=Math.max(0,Math.min(rawDiscount,subtotal));\n const kind=document.getElementById('invoice-kind')?.value||'non_formal';\n const vatMode=(kind==='non_formal')?'none':(document.getElementById('invoice-vat-mode')?.value||'none');\n const vatType=document.getElementById('invoice-vat-type')?.value||'percent';\n const vatRate=parseFloat(document.getElementById('invoice-vat-rate-input')?.value)||0;\n const afterDiscount=Math.max(0,subtotal-fixedDiscount);\n let vatAmount=0;\n if(vatMode==='with_vat'){vatAmount=(vatType==='fixed')?Math.max(0,Math.round(vatRate)):Math.round(afterDiscount*(vatRate/100));}\n const grandTotal=afterDiscount+vatAmount;\n const cur=getCurrencyLabel();\n const subtotalEl=document.getElementById('summary-subtotal');\n const vatEl=document.getElementById('summary-vat');\n const grandEl=document.getElementById('summary-grandtotal');\n const wordsEl=document.getElementById('summary-words');\n if(subtotalEl)subtotalEl.innerText=subtotal.toLocaleString('fa-IR')+' '+cur;\n if(vatEl)vatEl.innerText=vatAmount.toLocaleString('fa-IR')+' '+cur;\n if(grandEl)grandEl.innerText=grandTotal.toLocaleString('fa-IR')+' '+cur;\n if(wordsEl)wordsEl.innerText='به حروف: '+numberToPersianWords(grandTotal,cur);\n return {subtotal,fixedDiscount,discountType,discountInput,vatAmount,vatType,grandTotal,vatRate};\n}\n\n// ================== سند الکترونیکی سامانه مودیان ==================\nfunction toggleElectronicDoc(){\n const checked=document.getElementById('enable-electronic-doc').checked;\n if(checked){\n openElectronicDocModal();\n }else{\n window.pendingElectronicDoc=null;\n document.getElementById('edoc-status').innerText='';\n }\n}\nfunction openElectronicDocModal(){\n const itemsContainer=document.getElementById('edoc-items-container');\n const rows=document.querySelectorAll('#invoice-items-table-body tr');\n let html='';\n if(rows.length===0){\n html='<p style=\"color:var(--text-muted);font-size:12.5px;padding:8px\">ابتدا اقلام فاکتور را اضافه کنید.</p>';\n }else{\n rows.forEach((tr,idx)=>{\n const sel=tr.querySelector('.row-product-select');\n const prodId=sel?sel.value:'';\n const prod=getMyProducts().find(p=>p.id===prodId)||{};\n const prodName=sel&&sel.options[sel.selectedIndex]?sel.options[sel.selectedIndex].text:'';\n html+=`<div style=\"border:1px solid var(--border);border-radius:8px;padding:10px;margin-bottom:8px;background:#f8fafc\">\n <div style=\"font-weight:bold;font-size:13px;margin-bottom:8px\">ردیف ${toPersianDigits(idx+1)}: ${prodName||'—'}</div>\n <div class=\"form-row\">\n <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>\n <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>\n </div>\n </div>`;\n });\n }\n itemsContainer.innerHTML=html;\n\n const p=window.pendingElectronicDoc;\n if(p){\n document.getElementById('edoc-unique-number').value=p.uniqueNumber||'';\n document.getElementById('edoc-tax-number').value=p.taxNumber||'';\n document.getElementById('edoc-issue-datetime').value=p.issueDateTime||'';\n document.getElementById('edoc-original-date').value=p.originalDate||'';\n document.getElementById('edoc-original-number').value=p.originalNumber||'';\n document.getElementById('edoc-kind').value=p.kind||'اصل';\n document.getElementById('edoc-pattern').value=p.pattern||'کالا';\n document.getElementById('edoc-contract-id').value=p.contractId||'';\n if(p.items){\n p.items.forEach((it,idx)=>{\n const intEl=document.querySelector(`.edoc-row-internal[data-row=\"${idx}\"]`);\n const offEl=document.querySelector(`.edoc-row-official[data-row=\"${idx}\"]`);\n if(intEl)intEl.value=it.internalId||'';\n if(offEl)offEl.value=it.officialId||'';\n });\n }\n }else{\n const now=new Date();\n const timeStr=now.getHours().toString().padStart(2,'0')+':'+now.getMinutes().toString().padStart(2,'0')+':00';\n document.getElementById('edoc-issue-datetime').value=getJalaliNumeric()+' '+timeStr;\n document.getElementById('edoc-original-date').value='';\n document.getElementById('edoc-original-number').value='';\n document.getElementById('edoc-unique-number').value='';\n document.getElementById('edoc-tax-number').value='';\n document.getElementById('edoc-kind').value='اصل';\n document.getElementById('edoc-pattern').value='کالا';\n document.getElementById('edoc-contract-id').value='';\n }\n handleEdocPatternChange();\n document.getElementById('modal-electronic-doc').classList.add('active');\n}\nfunction closeElectronicDocModal(){\n document.getElementById('modal-electronic-doc').classList.remove('active');\n}\nfunction cancelElectronicDoc(){\n document.getElementById('enable-electronic-doc').checked=false;\n window.pendingElectronicDoc=null;\n document.getElementById('edoc-status').innerText='';\n closeElectronicDocModal();\n}\nfunction handleEdocPatternChange(){\n const pattern=document.getElementById('edoc-pattern').value;\n const box=document.getElementById('box-edoc-contract');\n const hint=document.getElementById('edoc-contract-hint');\n if(pattern==='پیمانکاری'){\n box.style.display='block';\n hint.style.display='none';\n }else{\n box.style.display='none';\n hint.style.display='block';\n }\n}\nfunction saveElectronicDocToPending(){\n const pattern=document.getElementById('edoc-pattern').value;\n const contractId=document.getElementById('edoc-contract-id').value.trim();\n if(pattern==='پیمانکاری'&&!contractId){\n alert('برای الگوی «قرارداد پیمانکاری»، وارد کردن «شناسه یکتای ثبت قرارداد» اجباری است.');\n return;\n }\n const items=[];\n const rows=document.querySelectorAll('#invoice-items-table-body tr');\n for(let idx=0;idx<rows.length;idx++){\n const intEl=document.querySelector(`.edoc-row-internal[data-row=\"${idx}\"]`);\n const offEl=document.querySelector(`.edoc-row-official[data-row=\"${idx}\"]`);\n const offVal=offEl?offEl.value.trim():'';\n if(!offVal){\n alert(`«شناسه کالا/خدمت» برای ردیف ${toPersianDigits(idx+1)} اجباری است.`);\n return;\n }\n items.push({internalId:intEl?intEl.value.trim():'',officialId:offVal});\n }\n const p={\n uniqueNumber:document.getElementById('edoc-unique-number').value.trim(),\n taxNumber:document.getElementById('edoc-tax-number').value.trim(),\n issueDateTime:document.getElementById('edoc-issue-datetime').value.trim(),\n originalDate:document.getElementById('edoc-original-date').value.trim(),\n originalNumber:document.getElementById('edoc-original-number').value.trim(),\n kind:document.getElementById('edoc-kind').value,\n pattern:pattern,\n contractId:contractId,\n items:items\n };\n window.pendingElectronicDoc=p;\n document.getElementById('edoc-status').innerText='✓ اطلاعات سند الکترونیکی ذخیره شد. با ثبت فاکتور، سند نیز ذخیره می‌شود.';\n closeElectronicDocModal();\n}\n\nfunction commitSaveInvoice(){\n if(!requireWrite())return;\n if(!currentUser)return;\n const myCompanies=getMyCompanies();\n const mySettings=getMySettings();\n const companySelect=document.getElementById('invoice-company-id');\n const selectedCompanyId=companySelect?companySelect.value:mySettings.default_company_id;\n const sellerCompany=myCompanies.find(c=>c.id===selectedCompanyId)||myCompanies.find(c=>c.id===mySettings.default_company_id)||myCompanies[0];\n if(!sellerCompany){alert('لطفاً ابتدا حداقل یک شرکت در بخش تنظیمات ثبت فرمایید.');return;}\n const companyId=sellerCompany.id;\n const companyName=sellerCompany.name;\n const contactSelect=document.getElementById('invoice-contact-id');\n const contactId=contactSelect?contactSelect.value:'';\n const contactName=contactSelect?.options[contactSelect.selectedIndex]?.text||'مشتری آزاد';\n const number=document.getElementById('invoice-number')?.value.trim()||('PINV-'+(getMyInvoices().length+31));\n const date=document.getElementById('invoice-date-input')?.value.trim()||getJalaliNumeric();\n const kind=document.getElementById('invoice-kind')?.value||'non_formal';\n const description=document.getElementById('invoice-desc-input')?.value.trim()||'';\n const editId=document.getElementById('edit-invoice-id')?.value;\n if(kind==='non_formal'){document.getElementById('invoice-vat-mode').value='none';}\n const items=[];\n document.querySelectorAll('#invoice-items-table-body tr').forEach(tr=>{\n const sel=tr.querySelector('.row-product-select');\n const prodId=sel?sel.value:'';\n const prodName=sel?sel.options[sel.selectedIndex]?.text:'';\n const unit=tr.querySelector('.row-unit-input')?.value||'عدد';\n const qty=parseFloat(tr.querySelector('.row-quantity')?.value)||0;\n const price=parseFloat(tr.querySelector('.row-price')?.value)||0;\n if(prodId&&qty>0){items.push({prodId,prodName,unit,qty,price,lineTotal:qty*price});}\n });\n if(items.length===0){alert('لطفاً حداقل یک ردیف کالا به فاکتور اضافه کنید.');return;}\n\n // بررسی سند الکترونیکی\n let edoc=null;\n if(kind==='formal'){\n const cb=document.getElementById('enable-electronic-doc');\n if(cb&&cb.checked){\n if(!window.pendingElectronicDoc){\n alert('برای صدور سند الکترونیکی، ابتدا باید اطلاعات سند را تکمیل و ذخیره کنید.');\n return;\n }\n edoc=window.pendingElectronicDoc;\n if(edoc.pattern==='پیمانکاری'&&!edoc.contractId){\n alert('برای الگوی «قرارداد پیمانکاری»، وارد کردن «شناسه یکتای ثبت قرارداد» اجباری است.');\n return;\n }\n }\n }\n\n const totals=recomputeTotals();\n const kindLabels={formal:'رسمی',non_formal:'غیررسمی',pre_invoice:'پیش‌فاکتور'};\n const cur=getCurrencyLabel();\n if(editId){\n const existingIndex=datastore.invoices.findIndex(i=>i.id===editId&&i.ownerUserId===currentUser.id);\n if(existingIndex!==-1){\n const prev=datastore.invoices[existingIndex];\n const finalEdoc=edoc?edoc:(prev.electronicDoc||null);\n datastore.invoices[existingIndex]={...prev,ownerUserId:currentUser.id,number,date,companyId,companyName,kind,kindLabel:kindLabels[kind],contactId,contactName,paymentMethod:'cash',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};\n alert('فاکتور با موفقیت ویرایش شد.');\n }\n cancelInvoiceEdit();\n }else{\n const record={id:'INV_'+Date.now(),ownerUserId:currentUser.id,number,date,companyId,companyName,kind,kindLabel:kindLabels[kind],contactId,contactName,paymentMethod:'cash',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};\n datastore.invoices.push(record);\n alert('فاکتور با موفقیت ثبت شد.');\n cancelInvoiceEdit();\n renderAndPrintDirect(record.id);\n }\n window.pendingElectronicDoc=null;\n saveDatastore();\n refreshAllSurfaces();\n}\nfunction editInvoice(invId){\n const inv=getMyInvoices().find(i=>i.id===invId);\n if(!inv)return;\n switchView('view-invoices');\n document.getElementById('edit-invoice-id').value=inv.id;\n document.getElementById('invoice-form-title').innerText=`✏️ ویرایش فاکتور #${inv.number}`;\n document.getElementById('btn-cancel-edit').style.display='inline-flex';\n document.getElementById('btn-save-invoice').innerText='💾 ذخیره تغییرات';\n document.getElementById('invoice-company-id').value=inv.companyId;\n document.getElementById('invoice-kind').value=inv.kind;\n document.getElementById('invoice-vat-mode').value=inv.vat>0?'with_vat':'none';\n document.getElementById('invoice-vat-type').value=inv.vatType||'percent';\n document.getElementById('invoice-vat-rate-input').value=inv.vatRate||10;\n document.getElementById('invoice-number').value=inv.number;\n document.getElementById('invoice-contact-id').value=inv.contactId;\n document.getElementById('invoice-date-input').value=inv.date;\n document.getElementById('invoice-discount-type').value=inv.discountType||'fixed';\n document.getElementById('label-invoice-discount-value').innerText=(inv.discountType==='percent')?'درصد تخفیف (٪)':`مبلغ تخفیف (${getCurrencyLabel()})`;\n document.getElementById('invoice-discount-fixed').value=(inv.discountType==='percent')?(inv.discountInput||0):(inv.discount||0);\n document.getElementById('invoice-desc-input').value=inv.description||'';\n handleInvoiceKindChange();\n // بارگذاری سند الکترونیکی در صورت وجود\n window.pendingElectronicDoc=inv.electronicDoc||null;\n const cb=document.getElementById('enable-electronic-doc');\n if(cb){\n if(inv.kind==='formal'&&inv.electronicDoc){\n cb.checked=true;\n document.getElementById('edoc-status').innerText='✓ اطلاعات سند الکترونیکی قبلاً ذخیره شده است.';\n }else{\n cb.checked=false;\n document.getElementById('edoc-status').innerText='';\n }\n }\n const tbody=document.getElementById('invoice-items-table-body');\n tbody.innerHTML='';\n inv.items.forEach(it=>{\n addInvoiceItemRow(it.prodId,it.qty,it.price);\n const lastRow=tbody.lastElementChild;\n if(lastRow)lastRow.querySelector('.row-unit-input').value=it.unit||'عدد';\n });\n updateInvoiceItemRowNumbers();\n recomputeTotals();\n}\nfunction cancelInvoiceEdit(){\n document.getElementById('edit-invoice-id').value='';\n document.getElementById('invoice-form-title').innerText='صدور فاکتور جدید';\n document.getElementById('btn-cancel-edit').style.display='none';\n document.getElementById('btn-save-invoice').innerText='💾 ثبت فاکتور';\n document.getElementById('invoice-items-table-body').innerHTML='';\n document.getElementById('invoice-number').value='';\n document.getElementById('invoice-discount-type').value='fixed';\n document.getElementById('label-invoice-discount-value').innerText=`مبلغ تخفیف (${getCurrencyLabel()})`;\n document.getElementById('invoice-discount-fixed').value=0;\n document.getElementById('invoice-vat-type').value='percent';\n document.getElementById('invoice-desc-input').value='';\n window.pendingElectronicDoc=null;\n const cb=document.getElementById('enable-electronic-doc');\n if(cb)cb.checked=false;\n const st=document.getElementById('edoc-status');\n if(st)st.innerText='';\n addInvoiceItemRow();\n applyDefaultSettingsToForm();\n}\nfunction renderInvoices(){\n const tbody=document.getElementById('invoice-archive-table-body');\n const filterSelect=document.getElementById('filter-invoice-company');\n const selectedFilter=filterSelect?.value||document.getElementById('invoice-company-id')?.value||'ALL';\n let list=getMyInvoices();\n if(selectedFilter!=='ALL')list=list.filter(i=>i.companyId===selectedFilter);\n if(list.length===0){tbody.innerHTML='<tr><td colspan=\"7\" style=\"text-align:center;color:var(--text-muted);padding:20px\">هیچ فاکتوری ثبت نشده است.</td></tr>';return;}\n tbody.innerHTML=list.map(inv=>`\n <tr>\n <td><strong>#${esc(inv.number)}</strong></td>\n <td>${esc(inv.companyName||'—')}</td>\n <td>${esc(inv.contactName)}</td>\n <td><span class=\"badge ${inv.kind==='formal'?'badge-danger':'badge-success'}\">${esc(inv.kindLabel)}</span></td>\n <td>${esc(inv.date)}</td>\n <td>${inv.grandTotal.toLocaleString('fa-IR')}</td>\n <td>\n <button class=\"btn btn-secondary btn-inline\" style=\"padding:4px 8px;font-size:12px;min-height:30px\" onclick=\"editInvoice('${inv.id}')\">✏️ ویرایش</button>\n <button class=\"btn btn-secondary btn-inline\" style=\"padding:4px 8px;font-size:12px;min-height:30px\" onclick=\"renderAndPrintDirect('${inv.id}')\">🖨️ چاپ</button>\n ${inv.electronicDoc?`<button class=\"btn btn-primary btn-inline\" style=\"padding:4px 8px;font-size:12px;min-height:30px\" onclick=\"printElectronicDoc('${inv.id}')\">📄 سند مودیان</button>`:''}\n </td>\n </tr>`).join('');\n}\n
\ No newline at end of file