/* ============ All Receipts Page ============ */ function ReceiptPrintPage({ receipt, customer, company, areas, lang, onBack, onMarkPaid, onNext, onPrev, currentIndex, totalCount, receiptSeqNo }){ const t = STR[lang]; const companyName = lang === "dari" ? (company?.nameDari || "") : (company?.nameEn || ""); const defaultBackContent = { intro: "نوت: شرکت فقط صاحب جایداد را به عنوان مسول میشناسد (به کرایه نشین و گرو دار کاری ندارد).", rules: [ "مشترکین عزیز بیل صرفیه آب خود را الی مدت 20 روز پرداخت نمایید تا با شرکت همکاری کرده باشید.", "در صورت عدم پرداخت بیل صرفیه آب به طور متواتر بعد از گذشت مدت سه ماه جریان آب تان قطع میگردد.", "هر کنکشن صرف برای مکان که مساحت آن کمتر از 500 متر مربع میباشد در نظر گرفته شده است. لطفاً از پخش، انتقال و کنکشن بیرون از مکان تعیین شده خودداری کنید.", "هر انشعاب صرف نیم اینچ آب برای یک فامیل در نظر گرفته شده است. در صورت کمبود آب برای بلند منزل‌ها شرکت مسول نیست؛ مشتری میتواند امتیاز دیگری را از شرکت تقاضا نماید.", "حفاظت از میتر در هر شرایط الزامی است. در صورت پیدا شدن عوارض در میتر لطفاً شرکت را اطلاع دهید.", "در نگهداری بیل صرفیه آب خویش کوشا باشید تا در صورت پیدا شدن اشتباهی در محاسبه ما را کمک کند.", ], contacts: [ { role: "ریس شرکت", name: "ارباب حکیم", phone: "0799404347" }, { role: "مسول دفتر", name: "علی رضا حیدری", phone: "0775475084" }, { role: "مسول تخنیک", name: "رضا اکبری", phone: "0772422948" }, { role: "مسول تخنیک", name: "کریم حسینی", phone: "0772566385" }, ], }; const [backContent, setBackContent] = useState(() => { try { const saved = JSON.parse(localStorage.getItem("shvm_receipt_back_content_v1")); if(saved && saved.rules && saved.rules.length===6 && saved.contacts && saved.contacts.length===4) return saved; } catch(e){} return defaultBackContent; }); const updateBackContent = (patch) => { setBackContent(prev => { const next = {...prev, ...patch}; localStorage.setItem("shvm_receipt_back_content_v1", JSON.stringify(next)); return next; }); }; const updateBackRule = (idx, val) => { setBackContent(prev => { const rules = [...prev.rules]; rules[idx] = val; const next = {...prev, rules}; localStorage.setItem("shvm_receipt_back_content_v1", JSON.stringify(next)); return next; }); }; const updateBackContact = (idx, key, val) => { setBackContent(prev => { const contacts = prev.contacts.map((c,i)=> i===idx ? {...c, [key]:val} : c); const next = {...prev, contacts}; localStorage.setItem("shvm_receipt_back_content_v1", JSON.stringify(next)); return next; }); }; const [exportOpen, setExportOpen] = useState(false); if(!receipt || !customer) return
{t.notFound}
; const f = nd(lang); const formatDate = (dateStr) => dateStr ? f(dateStr.replace(/-/g, '/')) : "—"; const isDari = lang === "dari"; const areaObj = areas ? areas.find(a=>a.id===customer.area) : null; const areaLabel = areaObj ? (isDari ? areaObj.label : areaObj.labelEn) : (customer.area || "—"); const labels = isDari ? { receiptNo: "S/N", date: "تاریخ صدور", account: "کد اشتراک", subType: "نوعیت اشتراک", month: "برج", customer: "مشتری", name: "نام مشتری", fatherName: "نام پدر", area: "منطقه", meter: "محاسبه مصرف دوره جاری", previous: "شماره قبلی", current: "شماره فعلی", consumption: "مصرف کل", charges: "توضیحات مصارف", water: "آب", tier1Range: "۰-۲۰ متر مکعب", tier2Range: "۲۱- متر مکعب", tier3Range: "اضافی", extraWater: "آب اضافی", unitHeader: "واحد مصرف شده", priceHeader: "قیمت فی متر", totalConsume: "مجموعه مصارف", currentMonth: "مبلغ ماه جاری", service: "اجرت خدمات", penalty: "جبران خسارت", deposit: "باقیداری انشعاب", debt: "باقیمانده قبلی", summary: "جمع کل", total: "مبلغ قابل پرداخت", signature: "امضای مسئول", back: "بازگشت", printBtn: "چاپ" } : { receiptNo: "S/N", date: "Issue Date", account: "Account Code", subType: "Subscription Type", month: "Period", customer: "Customer", name: "Customer Name", fatherName: "Father Name", area: "Area", meter: "Current Period Consumption Calculation", previous: "Previous Reading", current: "Current Reading", consumption: "Total Consumption", charges: "Consumption Details", water: "Water", tier1Range: "0–20 m³", tier2Range: "21- m³", tier3Range: "Extra", extraWater: "Extra Water", unitHeader: "Units Consumed", priceHeader: "Price per m³", totalConsume: "Total Consumption", currentMonth: "Current Month", service: "Service Fee", penalty: "Compensation", deposit: "Connection Deposit", debt: "Previous Balance", summary: "Summary", total: "Amount Payable", signature: "Signed by (امضای مسئول)", back: "Back", printBtn: "Print" }; const exportFileBase = () => (customer.fullName ? customer.fullName.replace(/\s+/g,"-") : "receipt") + "-" + (receiptSeqNo || receipt.sn || ""); const moNum = receipt.receiptMonth || (receipt.date ? receipt.date.split("-")[1] : ""); const moIdxTop = parseInt(moNum, 10) - 1; const moNameTop = (moIdxTop>=0 && moIdxTop<12) ? (isDari?jalaliMonthNamesFa[moIdxTop]:jalaliMonthNamesEn[moIdxTop]) : "—"; const exportPrint = () => { setExportOpen(false); window.print(); }; const exportDownloadPDF = async () => { setExportOpen(false); if(typeof window.jspdf === "undefined" || typeof html2canvas === "undefined"){ alert(isDari?"کتابخانه PDF بارگذاری نشده":"PDF library not loaded"); return; } // Capture BOTH A4 pages exactly as shown in the receipt view: page 1 is // the front (three receipt copies), page 2 is the back (terms, repeated // three times) — so the PDF matches the on-screen preview completely. const pageEls = document.querySelectorAll(".a4-preview-page"); if(!pageEls.length) return; try{ const { jsPDF } = window.jspdf; let pdf = null; for(let i=0; i { setExportOpen(false); if(typeof XLSX === "undefined"){ alert(isDari?"کتابخانه اکسل بارگذاری نشده":"Excel library not loaded"); return; } const mo = receipt.receiptMonth || (receipt.date ? receipt.date.split("-")[1] : ""); const moIdx = parseInt(mo,10)-1; const moName = (moIdx>=0 && moIdx<12) ? (isDari?jalaliMonthNamesFa[moIdx]:jalaliMonthNamesEn[moIdx]) : "—"; const subTypeName = t.cust.subTypes[receipt.rcSubType||customer.subscriptionType]||customer.subscriptionType; const franchiseYearsList = receipt.franchiseYears||[]; const section = (title) => [title, ""]; const rows = [ [companyName, ""], [isDari?"شاخه نمبر (۵)":"Branch No. (5)", ""], [], section(isDari?"شماره قبض | تاریخ صدور | برج | کد اشتراک | پلاک":"Receipt No. | Issue Date | Month | Account | Plak"), [isDari?"شماره قبض":"Receipt No.", f(receiptSeqNo || receipt.sn || "—")], [isDari?"تاریخ صدور":"Issue Date", formatDate(receipt.date)], [isDari?"برج":"Month", moName], [isDari?"کد اشتراک":"Account No.", receipt.rcAccount || customer.accountNo || "—"], [isDari?"پلاک":"Plak", customerPlak(customer, receipt) || "—"], [], section(labels.customer), [labels.name, customer.fullName||"—"], [labels.fatherName, customer.fatherName||"—"], [labels.area, areaLabel], [isDari?"نوعیت اشتراک":"Subscription Type", subTypeName], [labels.deposit+" — "+(isDari?"مبلغ کل":"Total"), receipt.disconnectionDeposit ?? 0], [labels.deposit+" — "+(isDari?"پرداخت شده":"Paid"), receipt.depositPaidAmount ?? 0], [(isDari?"حق الامتیاز (سالانه)":"Franchise (Annual)")+" — "+(isDari?"سال‌ها":"Years"), franchiseYearsList.map(y=>f(y)).join(isDari?" ، ":", ") || "—"], [(isDari?"حق الامتیاز (سالانه)":"Franchise (Annual)")+" — "+(isDari?"مبلغ کل":"Total"), franchiseYearsList.length*1000], [], section(labels.meter), [labels.previous, receipt.prevReading ?? "—"], [labels.current, receipt.currentReading ?? "—"], [labels.consumption+" (m³)", receipt.consumption ?? "—"], [], section(labels.charges), [labels.tier1Range+" — "+labels.unitHeader, receipt.tier1?.qty ?? 0], [labels.tier1Range+" — "+labels.priceHeader, receipt.tier1?.price ?? 0], [labels.tier1Range+" — "+(isDari?"مبلغ":"Amount"), receipt.tier1?.amount ?? 0], [labels.tier2Range+" — "+labels.unitHeader, receipt.tier2?.qty ?? 0], [labels.tier2Range+" — "+labels.priceHeader, receipt.tier2?.price ?? 0], [labels.tier2Range+" — "+(isDari?"مبلغ":"Amount"), receipt.tier2?.amount ?? 0], ...(receipt.tier3?.enabled ? [ [labels.tier3Range+" — "+labels.unitHeader, receipt.tier3?.qty ?? 0], [labels.tier3Range+" — "+labels.priceHeader, receipt.tier3?.price ?? 0], [labels.tier3Range+" — "+(isDari?"مبلغ":"Amount"), receipt.tier3?.amount ?? 0], ] : []), [labels.totalConsume, (receipt.tier1?.amount||0)+(receipt.tier2?.amount||0)+(receipt.tier3?.amount||0)], [isDari?"توضیحات اختیاری":"Notes", receipt.consumptionNote || ""], [], section(labels.summary), [labels.currentMonth, receipt.currentMonthAmount ?? 0], [labels.debt, receipt.arrears ?? 0], [labels.penalty, receipt.penalty ?? 0], [labels.service, receipt.serviceFee ?? 0], [labels.total, receipt.total ?? 0], [], [isDari?"وضعیت پرداخت":"Payment Status", isPaid(receipt) ? (isDari?"پرداخت شده":"Paid") : (isDari?"پرداخت نشده":"Unpaid")], [labels.signature, receipt.signedBy || ""], [isDari?"آدرس":"Address", isDari?"قلعه نو، کوچه اول مصلی":"Qala-e-Naw, 1st Musalla St."], ]; const ws = XLSX.utils.aoa_to_sheet(rows); ws["!cols"] = [{wch:38},{wch:32}]; const wb = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(wb, ws, isDari?"قبض":"Receipt"); XLSX.writeFile(wb, exportFileBase()+".xlsx"); }; return (
{exportOpen && ( <>
setExportOpen(false)} style={{position:"fixed", inset:0, zIndex:19}}/>
)}
{(onPrev || onNext) && (
{nd(lang)((currentIndex||0)+1)}/{nd(lang)(totalCount||0)}
)}
{(() => { const hasNote = !!(receipt.consumptionNote && receipt.consumptionNote.trim()); // Numbers in the receipt view are always shown with English digits, // regardless of the app's language setting — scoped to this render // only, so number formatting everywhere else in the app is unaffected. const fEn = (val) => String(val ?? ""); const formatDateEn = (dateStr) => dateStr ? dateStr.replace(/-/g, '/') : "—"; const toEnDigits = (str) => String(str ?? "").replace(/[۰-۹]/g, d => "۰۱۲۳۴۵۶۷۸۹".indexOf(d)); const renderReceiptCopy = (copyKey) => (
{/* HEADER */}
{companyName}
{isDari?"شاخه نمبر (5)":"Branch No. (5)"}
{/* 5-FIELD ROW */}
{[ {label: isDari?"برج":"Month", value: moNameTop}, {label: isDari?"تاریخ صدور":"Issue Date", value: formatDateEn(receipt.date)}, {label: isDari?"شماره قبض":"Receipt No.", value: fEn(receiptSeqNo||receipt.sn||"—")}, {label: isDari?"کد اشتراک":"Account", value: fEn(receipt.rcAccount||customer.accountNo||"—")}, {label: isDari?"پلاک":"Plak", value: fEn(customerPlak(customer, receipt)||"—")}, ].map((item,i)=>(
{item.label}
{item.value}
))}
{/* SECTION HEADER BAR */}
{[labels.customer, labels.meter, labels.charges, labels.summary].map((title,i)=>(
0 ? "0.2mm solid #B9E1E7" : "none"}}> {title}
))}
{/* 4-COLUMN BODY */}
{/* مشتری (rightmost) */}
{[ [labels.name, customer.fullName, true], [labels.fatherName, customer.fatherName||"—"], [labels.area, areaLabel], [isDari?"نوعیت اشتراک":"Sub. Type", t.cust.subTypes[receipt.rcSubType||customer.subscriptionType]||customer.subscriptionType], ].map(([lab,val,bold],i)=>(
{lab} {val}
))}
{labels.deposit} {/* unpaid amount carried from last month — on the existing lines so the receipt height never changes */} {(Number(receipt.depositCarried)||0)>0 && ( {isDari?"ماه قبل ":"Prev. "}{fEn(fmtMoney(receipt.depositCarried))} )} {depositTotalOf(receipt)>0 ? fEn(fmtMoney(depositTotalOf(receipt))) : "—"}
{depositTotalOf(receipt)>0 && (
{isDari?"پرداخت شده":"Paid"} {depositRemainingOf(receipt)>0 && ( {isDari?"باقی ":"Rem. "}{fEn(fmtMoney(depositRemainingOf(receipt)))} )} 0 ? "#0B7C87" : "#5A6B72"}}>{fEn(fmtMoney(receipt.depositPaidAmount||0))}
)}
{isDari?"حق الامتیاز (سالانه)":"Franchise (Annual)"} {(Number(receipt.franchiseCarried)||0)>0 && ( {isDari?"ماه قبل ":"Prev. "}{fEn(fmtMoney(receipt.franchiseCarried))} )} {franchiseTotalOf(receipt)>0 ? fEn(fmtMoney(franchiseTotalOf(receipt))) : "—"}
{(() => { const years = receipt.franchiseYears||[]; const carried = Number(receipt.franchiseCarried)||0; // carry-over / partial payment info only when that feature is in use const showExtra = carried > 0 || (Number(receipt.franchisePaidAmount)||0) > 0; if(!years.length && !showExtra) return null; return (
{showExtra ? ( {isDari?"پرداخت ":"Paid "}{fEn(fmtMoney(franchisePaidOf(receipt)))} {franchiseRemainingOf(receipt) > 0 && · {isDari?"باقی ":"Rem. "}{fEn(fmtMoney(franchiseRemainingOf(receipt)))}} ) : } {years.length > 0 && ( {showExtra ? years.map(y=>fEn(y)).join(isDari?" ، ":", ") : years.map(y=>`${fEn(y)}: ${fEn(fmtMoney(1000))}`).join(isDari?" ، ":", ")} )}
); })()}
{/* محاسبه مصرف دوره جاری */}
{[ [labels.previous, fEn(receipt.prevReading||0)], [labels.current, fEn(receipt.currentReading||0)], ].map(([lab,val],i)=>(
{lab} {val}
))}
{labels.consumption} {fEn(receipt.consumption||0)} m³
{/* توضیحات اختیاری — placed directly under مصرف کل, shown only when filled in */} {hasNote && (
{isDari?"توضیحات اختیاری: ":"Notes: "} {receipt.consumptionNote}
)}
{/* توضیحات مصارف */}
{receipt.tier3?.enabled && ( )}
{labels.unitHeader} {labels.priceHeader} {isDari?"مبلغ":"Amount"}
{toEnDigits(labels.tier1Range)} {fEn(receipt.tier1?.qty||0)} {fEn(receipt.tier1?.price||0)} {fEn(fmtMoney(receipt.tier1?.amount||0))}
{toEnDigits(isDari ? "۸۰۰ - ۲۱ متر مکعب" : "800 - 21 m³")} {fEn(receipt.tier2?.qty||0)} {fEn(receipt.tier2?.price||0)} {fEn(fmtMoney(receipt.tier2?.amount||0))}
{labels.tier3Range} {fEn(receipt.tier3?.qty||0)} {fEn(receipt.tier3?.price||0)} {fEn(fmtMoney(receipt.tier3?.amount||0))}
{labels.totalConsume} {fEn(fmtMoney((receipt.tier1?.amount||0)+(receipt.tier2?.amount||0)+(receipt.tier3?.amount||0)))}
{/* جمع کل (leftmost) */}
{[ [labels.currentMonth, receipt.currentMonthAmount], [labels.debt, receipt.arrears], [labels.penalty, receipt.penalty], [labels.service, receipt.serviceFee], ].map(([lab,val],i)=>(
{lab} {fEn(fmtMoney(val||0))}
))}
{labels.total}
{fEn(fmtMoney(receipt.total||0))} {isDari?"افغانی":"AFN"}
{/* SIGNATURE ROW — enlarged now that phone numbers moved to the back */}
{labels.signature} {receipt.signedBy||""}
{/* FOOTER — address only; phone numbers moved to the back side */}
{isDari?"آدرس: ":"Address: "} {isDari?"قلعه نو، کوچه اول مصلی":"Qala-e-Naw, 1st Musalla St."}
); const renderTermsCopy = (copyKey) => (
شرایط و مقررات شرکت خدمات آبرسانی شهید وحدت ملی

نوت: {backContent.intro.replace(/^نوت:\s*/,"")}

    {backContent.rules.slice(0,3).map((r,i)=>(
  1. {r}
  2. ))}
    {backContent.rules.slice(3,6).map((r,i)=>(
  1. {r}
  2. ))}
{/* Contact numbers — organized as a clean 4-card grid */}
{isDari?"تماس با ما":"Contact Us"}
{backContent.contacts.map((c,i)=>(
{c.role}
{c.name}
{c.phone}
))}
); const renderCutLine = (key) => (
✂
); // Absolute top offsets (mm) for each of the 3 receipt slots and the // 2 cut-lines between them, computed once and used identically for // both the front and back page. Explicit absolute positioning is // Each A4 page is built from simple, normally-flowing block elements // stacked top to bottom, spaced with plain top/bottom margins — // deliberately the most basic possible CSS layout technique (no // flexbox, no absolute positioning, no logical inset properties), // because this is the one method print engines across all browsers // handle identically and predictably. 5mm top margin on the first // copy, 2.5mm margin above the 2nd and 3rd copies, 5mm bottom margin // after the last one: 5 + 94 + 2.5 + 94 + 2.5 + 94 + 5 = 297mm. const renderPage = (copies) => (
{copies[0]}
{renderCutLine("a")}
{copies[1]}
{renderCutLine("b")}
{copies[2]}
); return ( {/* A4 PREVIEW — page 1: three identical receipt copies, positioned exactly as they will print (5mm margins, 2.5mm gaps between copies: 5+94+2.5+94+2.5+94+5 = 297mm), shown on screen too so what you see is what prints. */}
{renderPage([renderReceiptCopy(0), renderReceiptCopy(1), renderReceiptCopy(2)])}
{/* A4 PREVIEW — page 2 (back side): شرایط و مقررات, repeated once per receipt slot in the same layout, so that when the sheet is printed double-sided and flipped, the terms line up with the receipt that was on the front of that slot. */}
{renderPage([renderTermsCopy(0), renderTermsCopy(1), renderTermsCopy(2)])}
{/* Screen-only editor for the back side content — terms text and contact numbers, all editable, saved to localStorage and reflected immediately in both the preview above and any print/PDF output */}
{isDari?"ویرایش متن باکسیده (شرایط و مقررات + تماس با ما)":"Edit Back Side (Terms & Contacts)"}