function ReceiptModal({ customer, onClose, onSave, lang }){ const t = STR[lang]; const tr = t.receiptModal; const f = nd(lang); const [r, setR] = useState(emptyReceipt(customer)); const recalc = (next) => { const consumption = Math.max(0, (Number(next.currentReading)||0) - (Number(next.prevReading)||0)); const tier1Qty = Math.min(consumption, 20); const tier2Qty = Math.max(0, Math.min(consumption - 20, 180)); const tier1Amount = tier1Qty * (Number(next.tier1.price)||0); const tier2Amount = tier2Qty * (Number(next.tier2.price)||0); const currentMonthAmount = tier1Amount + tier2Amount + (Number(next.serviceFee)||0) + (Number(next.penalty)||0); const total = currentMonthAmount + (Number(next.arrears)||0); // باقیداری انشعاب is separate return { ...next, consumption, tier1:{...next.tier1, qty:tier1Qty, amount:tier1Amount}, tier2:{...next.tier2, qty:tier2Qty, amount:tier2Amount}, currentMonthAmount, total }; }; useEffect(()=>{ setR(prev => recalc(prev)); /* eslint-disable-next-line */ }, [r.currentReading, r.prevReading, r.tier1.price, r.tier2.price, r.serviceFee, r.penalty, r.arrears, r.disconnectionDeposit]); const update = (key, val) => setR(prev => ({...prev, [key]: val})); const handleSave = () => { if(!r.date.trim()){ alert(tr.needDate); return; } onSave({...r, id:"rc"+Date.now()}); }; return (
{ if(e.target===e.currentTarget) onClose(); }}>

{tr.title} {customer.fullName}

update("sn", e.target.value)} />
update("date", v)} lang={lang} placeholder={tr.datePh} />
update("prevReading", e.target.value)} />
update("currentReading", e.target.value)} />
update("tier1", {...r.tier1, price:e.target.value})} />
update("tier2", {...r.tier2, price:e.target.value})} />
update("serviceFee", e.target.value)} />
update("penalty", e.target.value)} />
update("arrears", e.target.value)} />
update("disconnectionDeposit", e.target.value)} />
{tr.totalConsumption}{r.consumption}
{tr.tier1Line} ({r.tier1.qty} m³ × {f(fmtMoney(r.tier1.price))}){f(fmtMoney(r.tier1.amount))}
{tr.tier2Line} ({r.tier2.qty} m³ × {f(fmtMoney(r.tier2.price))}){f(fmtMoney(r.tier2.amount))}
{tr.currentMonth}{f(fmtMoney(r.currentMonthAmount))}
{tr.totalPayable}{f(fmtMoney(r.total))} {STR[lang].dash.currency}
update("signedBy", e.target.value)} placeholder={tr.signedByPh} />
); } /* ============ Customer Detail ============ */ function CustomerDetail({ customer, onBack, backLabel, onEdit, onAddReceipt, onDeleteReceipt, onDeleteCustomer, onMarkReceiptPaid, company, areas, lang, onNext, onPrev, currentIndex, totalCount, receiptSeqNo, autoOpenReceipt, autoOpenPeriod, onGoToMeterReg, onGoToPaymentReg, onUpdateCustomerSubType, onUpdateCustomerPlak }){ const t = STR[lang]; const tc = t.cust; const tp = t.receiptPrint; const f = nd(lang); const isDari = lang === "dari"; const [editingReceipt, setEditingReceipt] = useState(null); // null = list view, object = edit/new receipt inline const [thermalReceipt, setThermalReceipt] = useState(null); const [printingReceipt, setPrintingReceipt] = useState(null); const [filterMonth, setFilterMonth] = useState("all"); const [autoNextReceipt, setAutoNextReceipt] = useState(false); const [confirmDeleteCustomer, setConfirmDeleteCustomer] = useState(false); // Remembers the last تاریخ صدور chosen, so it automatically carries over to // the next customer's new receipt instead of needing to be picked every time. const [lastUsedDate, setLastUsedDateRaw] = useState(()=>{ try{ return localStorage.getItem("shvm_last_receipt_date") || ""; }catch(e){ return ""; } }); const setLastUsedDate = (d) => { setLastUsedDateRaw(d); try{ localStorage.setItem("shvm_last_receipt_date", d); }catch(e){} }; const companyName = lang === "dari" ? company.nameDari : company.nameEn; const areaObj = areas.find(a=>a.id===customer.area); const areaLabel = areaObj ? (lang==="dari" ? areaObj.label : areaObj.labelEn) : tc.areaNone; const tr = t.receiptModal; // After "Save & Next" moves to the next customer, automatically open a fresh // receipt form for them so the whole registration flow never leaves this page. useEffect(()=>{ if(autoNextReceipt){ setEditingReceipt({...emptyReceipt(customer), date: lastUsedDate, _isNew:true}); setAutoNextReceipt(false); } // eslint-disable-next-line }, [customer.id]); // Arriving here via ثبت میتر's "ویرایش" button — jump straight into the // receipt editor (the customer's latest receipt, or a fresh one) so the // user reaches the kvitto directly, with no extra clicks. useEffect(()=>{ if(autoOpenReceipt && autoOpenPeriod && autoOpenPeriod.receipt){ // Opened from ثبت میتر / ثبت رسیدها "ویرایش": show exactly that receipt // (same month, date and data). If it was saved there, use the stored copy // so both pages show identical data; otherwise it is that month's new, // still-empty receipt with the date/month chosen there. const want = autoOpenPeriod.receipt; const stored = want.id ? customer.receipts.find(r => r.id === want.id) : null; setEditingReceipt(stored ? {...stored, _isNew:false} : {...want, _isNew: !!want._isNew}); } else if(autoOpenReceipt){ // Opened from تمام مشتریان with a month filter → that month's receipt // (same matching as the list); otherwise the latest receipt as before. const periodReceipt = autoOpenPeriod ? customer.receipts.find(r=>{ if(!r.date || !r.date.includes("-")) return false; const [y, m] = r.date.split("-"); const mo = r.receiptMonth || m; return (autoOpenPeriod.year==="all" || y===autoOpenPeriod.year) && (autoOpenPeriod.month==="all" || mo===autoOpenPeriod.month); }) : null; const last = periodReceipt || customer.receipts[customer.receipts.length-1]; setEditingReceipt(last ? {...last, _isNew:false} : {...emptyReceipt(customer), _isNew:true}); } // eslint-disable-next-line }, []); // When navigating to the next/previous customer while a print view is open, // load THAT customer's own latest receipt instead of leaving the old one shown. // (Must stay above any early return below, so hook order never changes.) useEffect(()=>{ if(thermalReceipt){ setThermalReceipt(customer.receipts[customer.receipts.length-1] || null); } // eslint-disable-next-line }, [customer.id]); useEffect(()=>{ if(printingReceipt){ setPrintingReceipt(customer.receipts[customer.receipts.length-1] || null); } // eslint-disable-next-line }, [customer.id]); const receiptMonths = useMemo(()=>{ const months = new Set(); customer.receipts.forEach(r=>{ if(r.date && r.date.includes("-")) months.add(r.date.slice(0,7)); }); return Array.from(months).sort().reverse(); }, [customer.receipts]); const filteredReceipts = useMemo(()=>{ const monthOf = (r) => r.receiptMonth || (r.date ? r.date.split("-")[1] : ""); let list = [...customer.receipts]; if(filterMonth !== "all"){ list = list.filter(r => monthOf(r) === filterMonth); } // Only one receipt per month is ever shown here — printing the same // receipt multiple times must never create duplicate entries in the // history. If more than one receipt exists for the same month, the // most recently saved one is kept. const byMonth = new Map(); list.forEach(r => { byMonth.set(monthOf(r), r); }); return Array.from(byMonth.values()).reverse(); }, [customer.receipts, filterMonth]); /* Recalculate all derived amounts whenever inputs change */ const recalc = (next) => { const prevReading = Number(next.prevReading)||0; const currentReading = Number(next.currentReading)||0; const arrears = Number(next.arrears)||0; const penalty = Number(next.penalty)||0; const serviceFee = Number(next.serviceFee)||0; const disconnectionDeposit = Number(next.disconnectionDeposit)||0; const consumption = next._consumptionManual ? Math.max(0, Number(next.consumption)||0) : Math.max(0, currentReading - prevReading); const tier1Qty = Math.min(consumption, 20); const tier2Qty = Math.max(0, consumption - 20); const tier3Enabled = !!next.tier3?.enabled; const tier3Qty = tier3Enabled ? consumption : 0; const tier1Price = Number(next.tier1.price)||0; const tier2Price = Number(next.tier2.price)||0; const tier3Price = Number(next.tier3?.price)||70; const tier1Amount = tier3Enabled ? 0 : tier1Qty * tier1Price; const tier2Amount = tier3Enabled ? 0 : tier2Qty * tier2Price; const tier3Amount = tier3Qty * tier3Price; // جبران خسارت (penalty) is kept separate from مبلغ ماه جاری and is only // added to مبلغ قابل پرداخت (total). const currentMonthAmount = next._currentMonthManual ? Math.max(0, Number(next.currentMonthAmount)||0) : (tier1Amount + tier2Amount + tier3Amount); const total = currentMonthAmount + arrears + penalty + serviceFee; // + جبران خسارت + اجرت خدمات; باقیداری انشعاب is separate return { ...next, prevReading, currentReading, arrears, penalty, serviceFee, disconnectionDeposit, consumption, tier1:{...next.tier1, price:tier1Price, qty:tier1Qty, amount:tier1Amount}, tier2:{...next.tier2, price:tier2Price, qty:tier2Qty, amount:tier2Amount}, tier3:{...(next.tier3||{}), price:tier3Price, enabled:tier3Enabled, qty:tier3Qty, amount:tier3Amount}, currentMonthAmount, total }; }; const updateReceipt = (key, val) => { if(key === "date" && val) setLastUsedDate(val); setEditingReceipt(prev => { const patch = { [key]: val }; if(key === "prevReading" || key === "currentReading"){ // Editing a reading returns مصرف کل to its auto-calculated value. patch._consumptionManual = false; patch._currentMonthManual = false; } else if(key === "consumption"){ patch._consumptionManual = true; patch._currentMonthManual = false; } else if(key === "currentMonthAmount"){ patch._currentMonthManual = true; } const next = recalc({...prev, ...patch}); // Auto-update tier prices when subscription type changes if(key === "rcSubType"){ const { tier1Price, tier2Price } = getTierPrices(val); next.tier1 = {...next.tier1, price: tier1Price}; next.tier2 = {...next.tier2, price: tier2Price}; return recalc(next); } // When switching to a genuinely DIFFERENT month, roll شماره فعلی into // شماره قبلی and clear شماره فعلی so a new reading can be entered. // Compare against the same effective month shown in the dropdown // (receiptMonth, falling back to the date's month) — not just the raw // receiptMonth field, which is often unset on older receipts and would // otherwise make this fire even when the selected month didn't change. if(key === "receiptMonth" && val){ const prevEffectiveMonth = prev.receiptMonth || (prev.date ? prev.date.split("-")[1] : ""); if(val !== prevEffectiveMonth){ return recalc({...next, prevReading: prev.currentReading, currentReading: 0}); } } return next; }); }; const updateTier = (tier, key, val) => setEditingReceipt(prev => recalc({...prev, _currentMonthManual:false, [tier]:{...prev[tier], [key]:val}})); useEffect(()=>{ if(editingReceipt) setEditingReceipt(prev => recalc(prev)); }, [editingReceipt?.currentReading, editingReceipt?.prevReading, editingReceipt?.tier1?.price, editingReceipt?.tier2?.price, editingReceipt?.tier3?.price, editingReceipt?.tier3?.enabled, editingReceipt?.serviceFee, editingReceipt?.penalty, editingReceipt?.arrears, editingReceipt?.disconnectionDeposit]); const handleSaveReceipt = () => { if(!editingReceipt.date || !editingReceipt.date.trim()){ alert(tr.needDate); return; } const today = new Date().toISOString().slice(0,10); const base = { ...editingReceipt, paidDate: editingReceipt.paid ? (editingReceipt.paidDate || today) : "" }; const finalReceipt = editingReceipt._isNew ? {...base, id:"rc"+Date.now()} : base; if(editingReceipt._isNew){ onAddReceipt(customer.id, finalReceipt); } else { onDeleteReceipt(customer.id, editingReceipt.id); onAddReceipt(customer.id, finalReceipt); } setEditingReceipt(null); // Render receipt into portal OUTSIDE React tree — avoids state conflicts const portal = document.getElementById("print-portal"); if(portal){ portal.innerHTML = ""; portal.style.display = "block"; try { ReactDOM.render( React.createElement(ReceiptPrintPage, { receipt: finalReceipt, customer: customer, company: company, areas: areas, lang: lang, receiptSeqNo: receiptSeqNo, currentIndex: currentIndex, totalCount: totalCount, onBack: ()=>{ ReactDOM.unmountComponentAtNode(portal); portal.style.display="none"; }, onNext: onNext ? ()=>{ ReactDOM.unmountComponentAtNode(portal); portal.style.display = "none"; setAutoNextReceipt(true); onNext(); } : undefined, onPrev: onPrev ? ()=>{ ReactDOM.unmountComponentAtNode(portal); portal.style.display = "none"; onPrev(); } : undefined, }), portal ); } catch(e) { portal.innerHTML = '

خطا در نمایش قبض

' + e.message + '\n\n' + e.stack + '
'; console.error("Portal render error:", e); } const el = document.querySelector('.content'); if(el) el.scrollTop = 0; // Save & Print now also advances to the next customer right away — the // saved receipt shows/prints in the portal while the page underneath is // already switched and primed with the next customer's fresh receipt. if(onNext){ setAutoNextReceipt(true); onNext(); } } }; const handleSaveAndGoToMeterReg = () => { if(!editingReceipt.date || !editingReceipt.date.trim()){ alert(tr.needDate); return; } const today = new Date().toISOString().slice(0,10); const base = { ...editingReceipt, paidDate: editingReceipt.paid ? (editingReceipt.paidDate || today) : "" }; const finalReceipt = editingReceipt._isNew ? {...base, id:"rc"+Date.now()} : base; if(editingReceipt._isNew){ onAddReceipt(customer.id, finalReceipt); } else { onDeleteReceipt(customer.id, editingReceipt.id); onAddReceipt(customer.id, finalReceipt); } const month = finalReceipt.receiptMonth || (finalReceipt.date ? finalReceipt.date.split("-")[1] : ""); setEditingReceipt(null); onGoToMeterReg && onGoToMeterReg(customer.id, month); }; const handleSaveAndGoToPaymentReg = () => { if(!editingReceipt.date || !editingReceipt.date.trim()){ alert(tr.needDate); return; } const today = new Date().toISOString().slice(0,10); const base = { ...editingReceipt, paidDate: editingReceipt.paid ? (editingReceipt.paidDate || today) : "" }; const finalReceipt = editingReceipt._isNew ? {...base, id:"rc"+Date.now()} : base; if(editingReceipt._isNew){ onAddReceipt(customer.id, finalReceipt); } else { onDeleteReceipt(customer.id, editingReceipt.id); onAddReceipt(customer.id, finalReceipt); } const month = finalReceipt.receiptMonth || (finalReceipt.date ? finalReceipt.date.split("-")[1] : ""); setEditingReceipt(null); onGoToPaymentReg && onGoToPaymentReg(customer.id, month); }; const handleReceiptPageKeyDown = (e) => { if(e.key !== "Enter") return; if(e.target && (e.target.tagName === "SELECT" || (e.target.tagName === "INPUT" && e.target.type !== "checkbox"))){ e.preventDefault(); handleSaveReceipt(); } }; const handleSaveAndNext = () => { if(!editingReceipt.date || !editingReceipt.date.trim()){ alert(tr.needDate); return; } const today = new Date().toISOString().slice(0,10); const base = { ...editingReceipt, paidDate: editingReceipt.paid ? (editingReceipt.paidDate || today) : "" }; const finalReceipt = editingReceipt._isNew ? {...base, id:"rc"+Date.now()} : base; if(editingReceipt._isNew){ onAddReceipt(customer.id, finalReceipt); } else { onDeleteReceipt(customer.id, editingReceipt.id); onAddReceipt(customer.id, finalReceipt); } setAutoNextReceipt(true); onNext(); }; /* ── Inline editable receipt view ── */ if(editingReceipt){ const r = editingReceipt; const fieldStyle = { background:"var(--paper)", border:"1px solid var(--line-strong)", borderRadius:"6px", padding:"6px 10px", color:"var(--ink)", fontSize:"13px", fontFamily:"var(--font-fa)", width:"100%", outline:"none", boxSizing:"border-box" }; const rowStyle = { display:"flex", justifyContent:"space-between", alignItems:"center", padding:"8px 20px", borderBottom:"1px solid var(--line)", gap:"8px" }; const labelStyle = { color:"var(--muted)", fontSize:"12px", minWidth:"120px" }; return (
{/* Toolbar */}
{/* Back: a clear button to exactly where this page was opened from (e.g. ثبت رسیدها) */} {backLabel ? ( ) : ( )}
{/* The receipt — editable fields replace static values */}
{/* HEADER — reference design: light blue, info left, logo+name right, dark banner */}
{isDari?"شرکت خدمات آبرسانی":"Water Supply Services"}
{isDari?"شهید وحدت ملی":"Shahid Wahdat Milli"}
{company.phone &&
{company.phone}
}
{isDari?"شماره قبض:":"Receipt No:"}
{isDari?"تاریخ صدور:":"Issue Date:"} updateReceipt("date",v)} lang={lang} placeholder={tr.datePh}/>
{isDari?"برج:":"Month:"}
{isDari?"پلاک:":"Plak:"} { updateReceipt("plak", e.target.value); onUpdateCustomerPlak && onUpdateCustomerPlak(customer.id, e.target.value); }}/>
{isDari?"کد اشتراک:":"Account:"} updateReceipt("rcAccount", e.target.value)}/>
{/* CUSTOMER — all editable */}
{isDari?"مشتری":"Customer"}
{isDari?"نام مشتری:":"Name:"} updateReceipt("rcName", e.target.value)}/>
{isDari?"نام پدر:":"Father:"} updateReceipt("rcFather", e.target.value)}/>
{isDari?"منطقه:":"Area:"} {areaLabel}
{isDari?"نوعیت اشتراک:":"Subscription:"}
{/* METER — editable */}
{isDari?"محاسبه مصرف دوره جاری":"Current Period Consumption Calculation"}
{isDari?"شماره قبلی:":"Previous:"} updateReceipt("prevReading", e.target.value)}/>
{isDari?"شماره فعلی:":"Current:"} updateReceipt("currentReading", e.target.value)}/>
{isDari?"مصرف کل:":"Consumption:"} updateReceipt("consumption", e.target.value)} style={{...fieldStyle, width:"90px", textAlign:"center", color:"var(--accent-1)", fontWeight:700}}/> m³
{/* Note field under مصرف کل */}
updateReceipt("consumptionNote", e.target.value)} placeholder={isDari?"توضیحات (اختیاری)...":"Notes (optional)..."} style={{width:"100%", padding:"7px 10px", borderRadius:"7px", border:"1px solid var(--line-strong)", background:"var(--paper-card)", color:"var(--ink)", fontSize:"12px", fontFamily:"var(--font-fa)", outline:"none", boxSizing:"border-box"}} />
{/* CONSUMPTION DETAIL — prices editable */}
{isDari?"توضیحات مصارف":"Consumption Details"}
{/* Header row */}
{isDari?"واحد":"Units"} {isDari?"قیمت":"Price"} {isDari?"مبلغ":"Amount"}
{/* Tier 1 */}
{isDari?"۰-۲۰ م³":"0–20 m³"} {f(r.tier1.qty)} updateTier("tier1","price",e.target.value)}/> {f(fmtMoney(r.tier1.amount))}
{/* Tier 2 */}
{isDari?"۲۱- م³":"21- m³"} {f(r.tier2.qty)} updateTier("tier2","price",e.target.value)}/> {f(fmtMoney(r.tier2.amount))}
{isDari?"مجموعه مصارف:":"Total Consumption:"} {f(fmtMoney(r.tier1.amount + r.tier2.amount + (r.tier3?.amount||0)))}
{/* CHARGES SUMMARY — editable */}
{isDari?"جمع کل":"Summary"}
{isDari?"مبلغ ماه جاری:":"Current Month:"} updateReceipt("currentMonthAmount", e.target.value)}/>
{isDari?"باقیمانده قبلی:":"Prev. Balance:"} updateReceipt("arrears", e.target.value)}/>
{isDari?"جبران خسارت:":"Compensation:"}
updateReceipt("penalty", e.target.value)}/>
{isDari?"اجرت خدمات:":"Service Fee:"} updateReceipt("serviceFee", e.target.value)}/>
{isDari?"این مبلغ فقط جهت معلومات نمایش داده می‌شود و در مجموع محاسبه نمی‌گردد":"This amount is shown for information only and is not included in the total"}
{/* باقیداری انشعاب + حق الامتیاز (سالانه) — shared panels (src/03b-payment-panels.jsx), same as ثبت رسیدها */}
setEditingReceipt(prev => recalc({...prev, ...patch}))}/> setEditingReceipt(prev => recalc({...prev, ...patch}))}/>
{/* OPTIONAL NOTE */}