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

invoices.js: thousand separators on price fields, contract-statement kind with mandatory contract number, project selection wiring

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