/* ============ Main App ============ */ function ConsumptionListsPage({ lang, consumptionLists, setPage, onAddCustom }){ const isDari = lang === "dari"; const [showAdd, setShowAdd] = useState(false); const [newName, setNewName] = useState(""); const t = STR[lang]; const fixedLists = [ { id:"cl-arbaab", label:t.nav.clArbaab, count:(consumptionLists?.arbaab||[]).length }, { id:"cl-mataraffe", label:t.nav.clMataraffe, count:(consumptionLists?.mataraffe||[]).length }, { id:"cl-khorak", label:t.nav.clKhorak, count:(consumptionLists?.khorak||[]).length }, { id:"cl-barq", label:t.nav.clBarq, count:(consumptionLists?.barq||[]).length }, { id:"cl-teel", label:t.nav.clTeel, count:(consumptionLists?.teel||[]).length }, ]; const customLists = consumptionLists?.custom || []; const handleAddCustom = () => { if(newName.trim()){ onAddCustom(newName.trim()); setNewName(""); setShowAdd(false); } }; return (

{t.nav.consumptionLists}

{isDari?"انتخاب کنید کدام لیست را می‌خواهید باز کنید":"Select which list to open"}

{showAdd && (
setNewName(e.target.value)} onKeyDown={e=>e.key==="Enter"&&handleAddCustom()} placeholder={isDari?"مثال: لیست ناحیه جدید":"e.g. New Area List"} autoFocus/>
)}
{[...fixedLists, ...customLists.map(c=>({ id:c.id, label:c.name, count:c.items.length }))].map(list=>(
setPage(list.id)}>
{list.label}
{isDari?`${list.count} ردیف ثبت شده`:`${list.count} entries`}
))}
); } function AddCustomListPage({ lang, onSave, onCancel }){ const isDari = lang === "dari"; const [name, setName] = useState(""); return (

{isDari?"افزودن لیست معرف جدید":"Add New Custom List"}

setName(e.target.value)} placeholder={isDari?"مثال: لیست مصرف ناحیه جدید":"e.g. New Area Consumption List"} autoFocus/>
); } /* ══════════ AddRowForm — reusable inline add row ══════════ */ function AddRowForm({ isDari, onAdd }){ const [form, setForm] = React.useState({date:"", amount:"", note:""}); const f = (k,v) => setForm(p=>({...p,[k]:v})); const submit = () => { if(!form.date || !form.amount){ return; } onAdd({id:"r"+Date.now(), title:form.note||"—", date:form.date, amount:Number(form.amount)||0, note:form.note}); setForm({date:"",amount:"",note:""}); }; const inp = {border:"1px solid var(--line-strong)", borderRadius:"6px", padding:"6px 8px", fontSize:"12px", fontFamily:"var(--font-fa)", background:"var(--paper)", color:"var(--ink)", outline:"none", width:"100%", boxSizing:"border-box"}; return (
+ {isDari?"افزودن ردیف جدید":"Add New Row"}
{isDari?"تاریخ":"Date"}
f("date",e.target.value)} placeholder="1405-02-01"/>
{isDari?"مبلغ (AFN)":"Amount (AFN)"}
f("amount",e.target.value)} placeholder="0"/>
{isDari?"یادداشت":"Note"}
f("note",e.target.value)} placeholder={isDari?"توضیحات...":"Description..."}/>
); } /* ══════════ ArbaabReportPage ══════════ */ /* ══════════ EditableList — reusable editable table ══════════ */ function EditableList({ title, items, onSave, color, lang }){ const isDari = lang==="dari"; const f = nd(lang); const [adding, setAdding] = React.useState(false); const [form, setForm] = React.useState({date:"", amount:"", note:""}); const total = items.reduce((s,x)=>s+(Number(x.amount)||0),0); const addRow = () => { if(!form.amount){ alert(isDari?"مبلغ را وارد کنید":"Enter amount"); return; } const newItem = { id:"item"+Date.now(), title: form.note||(isDari?"جدید":"New"), date: form.date, amount: Number(form.amount)||0, note: form.note }; onSave([...items, newItem]); setForm({date:"", amount:"", note:""}); setAdding(false); }; const delRow = (idx) => onSave(items.filter((_,i)=>i!==idx)); return (
{title}
{f(total)} AFN
{adding && (
setForm(f=>({...f,date:v}))} lang={lang} placeholder={isDari?"تاریخ":"Date"}/>
setForm(f=>({...f,amount:e.target.value}))} placeholder="0" style={{width:"110px", padding:"7px 10px", border:"1px solid var(--line-strong)", borderRadius:"7px", fontFamily:"var(--font-mono)", fontSize:"13px", background:"var(--paper-card)", color:"var(--ink)"}}/>
setForm(f=>({...f,note:e.target.value}))} placeholder={isDari?"یادداشت...":"Note..."} style={{width:"100%", padding:"7px 10px", border:"1px solid var(--line-strong)", borderRadius:"7px", fontSize:"13px", background:"var(--paper-card)", color:"var(--ink)", fontFamily:"var(--font-fa)"}}/>
)} {items.length > 0 ? ( {items.map((x,i)=>( ))}
{isDari?"تاریخ":"Date"} {isDari?"یادداشت":"Note"} {isDari?"مبلغ":"Amount"}
{x.date||"—"} {x.note||x.title||x.name||x.fullName||"—"} {f(Number(x.amount)||0)}
) : (
{isDari?"موردی ثبت نشده":"No entries yet"}
)}
); } /* ══════════ PrintableListPage — shared print layout for the three lists ══════════ */ function PrintableListPage({ title, monthLabel, sections, resultLabel, resultValue, lang, onClose }){ const isDari = lang === "dari"; const f = nd(lang); return (

{title}

{monthLabel}
{sections.map((sec,i)=>{ const secTotal = sec.items.reduce((s,x)=>s+(Number(x.amount)||0),0); return (

{sec.title}

{sec.items.length === 0 ? (
{isDari?"موردی ثبت نشده":"No entries"}
) : ( {sec.items.map((x,j)=>( ))}
{isDari?"تاریخ":"Date"} {isDari?"یادداشت":"Note"} {isDari?"مبلغ":"Amount"}
{x.date||"—"} {x.note||x.title||x.name||x.fullName||"—"} {f(fmtMoney(Number(x.amount)||0))}
)}
{isDari?"مجموع:":"Total:"} {f(fmtMoney(secTotal))} AFN
); })} {resultLabel && (
{resultLabel} {resultValue<0?"-":""}{f(fmtMoney(Math.abs(resultValue)))} AFN
)}
); } function printListSummary({ title, monthLabel, sections, resultLabel, resultValue, lang }){ const portal = document.getElementById("print-portal"); if(!portal) return; portal.innerHTML = ""; portal.style.display = "block"; const close = ()=>{ ReactDOM.unmountComponentAtNode(portal); portal.style.display="none"; }; ReactDOM.render( React.createElement(PrintableListPage, { title, monthLabel, sections, resultLabel, resultValue, lang, onClose: close }), portal ); } /* ══════════ ArbaabReportPage ══════════ */ function ArbaabReportPage({ consumptionLists, lang, setPage, onUpdate }){ const isDari = lang==="dari"; const f = nd(lang); const [selMonth, setSelMonth] = React.useState("all"); const monthNames = jalaliMonthNamesFa; const filterByMonth = (items) => selMonth==="all" ? items : items.filter(x=>{ if(!x.date) return false; const m = String(x.date).split("-")[1]||String(x.date).split("/")[1]||""; return m === selMonth.padStart(2,"0"); }); const arbaab = filterByMonth(consumptionLists?.arbaab||[]); const barq = filterByMonth(consumptionLists?.barq||[]); const teel = filterByMonth(consumptionLists?.teel||[]); const incomeTotal = arbaab.reduce((s,x)=>s+(Number(x.amount)||0),0); const paymentTotal = [...barq,...teel].reduce((s,x)=>s+(Number(x.amount)||0),0); const result = incomeTotal - paymentTotal; const MonthPicker = () => ( ); const monthLabelText = selMonth==="all" ? (isDari?"همه برج‌ها":"All Months") : monthNames[parseInt(selMonth,10)-1]; const handlePrint = () => { printListSummary({ title: isDari?"📋 لیست دریافت ارباب":"Arbaab Receipt List", monthLabel: monthLabelText, sections: [ { title: isDari?"📥 دریافتی — لیست دریافت ارباب":"Income — Arbaab List", items: arbaab, color:"#15803d" }, { title: isDari?"📤 پرداختی — لیست مصرف برق":"Payment — Electricity", items: barq, color:"#e85d04" }, { title: isDari?"📤 پرداختی — لیست مصرف تیل":"Payment — Fuel", items: teel, color:"#b45309" }, ], resultLabel: isDari?"نتیجه (دریافتی − پرداختی)":"Result (Income − Payments)", resultValue: result, lang, }); }; return (

{isDari?"📋 لیست دریافت ارباب":"📋 Arbaab Receipt List"}

onUpdate("arbaab",items)}/> onUpdate("barq",items)}/> onUpdate("teel",items)}/>
{isDari?"نتیجه (دریافتی − پرداختی)":"Result (Income − Payments)"} =0?"#15803d":"#C0392B", fontFamily:"var(--font-mono)"}}>{result<0?"-":""}{f(Math.abs(result))} AFN
{f(incomeTotal)} − {f(paymentTotal)} = {f(result)}
); } /* ══════════ OfficeExpensesPage ══════════ */ function OfficeExpensesPage({ expenses, consumptionLists, lang, setPage, onUpdateList, onUpdateExpense }){ const isDari = lang==="dari"; const f = nd(lang); const [selMonth, setSelMonth] = React.useState("all"); const monthNames = jalaliMonthNamesFa; const filterByMonth = (items) => selMonth==="all" ? items : items.filter(x=>{ if(!x.date) return false; const m = String(x.date).split("-")[1]||String(x.date).split("/")[1]||""; return m === selMonth.padStart(2,"0"); }); const employees = filterByMonth(expenses?.employee||[]); const mataraffe = filterByMonth(consumptionLists?.mataraffe||[]); const khorak = filterByMonth(consumptionLists?.khorak||[]); const total = [...employees,...mataraffe,...khorak].reduce((s,x)=>s+(Number(x.amount)||0),0); const MonthPicker = () => ( ); const barqFiltered = filterByMonth(consumptionLists?.barq||[]); const teelFiltered = filterByMonth(consumptionLists?.teel||[]); const monthLabelText = selMonth==="all" ? (isDari?"همه برج‌ها":"All Months") : monthNames[parseInt(selMonth,10)-1]; const handlePrint = () => { printListSummary({ title: isDari?"🏢 لیست مصارف دفتر":"Office Expenses List", monthLabel: monthLabelText, sections: [ { title: isDari?"👥 هزینه‌های کارمندان":"Employee Expenses", items: employees, color:"#0FA4AF" }, { title: isDari?"📦 لیست مصرف متفرقه":"Miscellaneous Expenses", items: mataraffe, color:"#7c3aed" }, { title: isDari?"🍽️ لیست مصرف خرج خوراک":"Food Expenses", items: khorak, color:"#b45309" }, { title: isDari?"⚡ لیست مصرف برق":"Electricity Consumption List", items: barqFiltered, color:"#e85d04" }, { title: isDari?"🛢️ لیست مصرف تیل":"Fuel Consumption List", items: teelFiltered, color:"#b45309" }, ], resultLabel: isDari?"مجموع کل مصارف دفتر":"Total Office Expenses", resultValue: [...employees,...mataraffe,...khorak,...barqFiltered,...teelFiltered].reduce((s,x)=>s+(Number(x.amount)||0),0), lang, }); }; return (

{isDari?"🏢 لیست مصارف دفتر":"🏢 Office Expenses List"}

onUpdateExpense("employee",items)}/> onUpdateList("mataraffe",items)}/> onUpdateList("khorak",items)}/> onUpdateList("barq",items)}/> onUpdateList("teel",items)}/>
{isDari?"مجموع کل مصارف دفتر":"Total Office Expenses"} {f(total)} AFN
); } /* ══════════ ArbaabPaymentsPage ══════════ */ function ArbaabPaymentsPage({ consumptionLists, lang, setPage, onUpdate }){ const isDari = lang==="dari"; const f = nd(lang); const barq = consumptionLists?.barq||[]; const teel = consumptionLists?.teel||[]; const total = [...barq,...teel].reduce((s,x)=>s+(Number(x.amount)||0),0); const [selMonth, setSelMonth] = React.useState("all"); const monthNames = jalaliMonthNamesFa; const filterByMonth = (items) => selMonth==="all" ? items : items.filter(x=>{ if(!x.date) return false; const m = String(x.date).split("-")[1]||String(x.date).split("/")[1]||""; return m === selMonth.padStart(2,"0"); }); const monthLabelText = selMonth==="all" ? (isDari?"همه برج‌ها":"All Months") : monthNames[parseInt(selMonth,10)-1]; const handlePrint = () => { const barqM = filterByMonth(barq); const teelM = filterByMonth(teel); printListSummary({ title: isDari?"💸 لیست مصرف برق و تیل":"Electricity & Fuel List", monthLabel: monthLabelText, sections: [ { title: isDari?"📤 پرداختی — لیست مصرف برق":"Payment — Electricity", items: barqM, color:"#e85d04" }, { title: isDari?"📤 پرداختی — لیست مصرف تیل":"Payment — Fuel", items: teelM, color:"#b45309" }, ], resultLabel: isDari?"مجموع پرداختی‌ها":"Total Payments", resultValue: [...barqM,...teelM].reduce((s,x)=>s+(Number(x.amount)||0),0), lang, }); }; return (

{isDari?"💸 لیست مصرف برق و تیل":"💸 Electricity & Fuel List"}

onUpdate("barq",items)}/> onUpdate("teel",items)}/>
{isDari?"مجموع پرداختی‌ها":"Total Payments"} {f(total)} AFN
); } /* ============ Imported Customer-Code List Page (کد ضامن / کد عمومی / کد موقت) ============ */ const EMPTY_CODE_BASE = []; function CodeListPage({ page, lang, onBack, baseData, extraItems, setExtraItems, edits, setEdits, onWriteReceipt }){ const isDari = lang === "dari"; const f = nd(lang); // baseData = the list's original rows (from Firestore app/codeBase) const base = baseData || EMPTY_CODE_BASE; const CONFIG = { "code-zamin": { title: isDari?"کد ضامن":"Guarantor Code", baseData: base, hasReceived:false, color:"#0FA4AF" }, "code-omomi": { title: isDari?"کد عمومی":"General Code", baseData: base, hasReceived:true, color:"#7c3aed" }, "code-mawaqat": { title: isDari?"کد موقت":"Temporary Code", baseData: base, hasReceived:true, color:"#b45309" }, }; const cfg = CONFIG[page]; const items = extraItems || []; const baseEdits = edits || {}; const allData = useMemo(()=> [ ...cfg.baseData.map((r,idx)=> ({ ...r, ...(baseEdits[idx]||{}), _baseIndex: idx })), ...items, ], [cfg.baseData, items, baseEdits]); const [query, setQuery] = useState(""); const [showAdd, setShowAdd] = useState(false); const emptyForm = () => { const maxCode = allData.reduce((m,r)=> Math.max(m, parseInt(r.code)||0), 0); return cfg.hasReceived ? { code:String(maxCode+1), date:"", name:"", father:"", province:"", district:"", received:"", remaining:"", address:"" } : { code:String(maxCode+1), date:"", name:"", father:"", province:"", district:"", amount:"", address:"" }; }; const [form, setForm] = useState(emptyForm); useEffect(()=>{ setForm(emptyForm()); setShowAdd(false); setQuery(""); /* eslint-disable-next-line */ }, [page]); const openAdd = () => { setForm(emptyForm()); setShowAdd(true); }; const addRecord = () => { if(!form.name.trim()){ alert(isDari?"لطفاً اسم را داخل کنید.":"Please enter a name."); return; } const rec = { ...form, code: form.code || "", _custom:true }; if(!cfg.hasReceived) rec.amount = Number(form.amount)||0; setExtraItems([...items, rec]); setForm(emptyForm()); setShowAdd(false); }; const removeRecord = (idx) => { if(!window.confirm(isDari?"این مورد حذف شود؟":"Delete this record?")) return; setExtraItems(items.filter((_,i)=>i!==idx)); }; const updateField = (r, field, value) => { if(r._custom){ const idx = items.indexOf(r); if(idx === -1) return; const next = items.slice(); next[idx] = { ...next[idx], [field]: value }; setExtraItems(next); } else { const cur = baseEdits[r._baseIndex] || {}; setEdits({ ...baseEdits, [r._baseIndex]: { ...cur, [field]: value } }); } }; const filtered = useMemo(()=>{ const q = query.trim().toLowerCase(); if(!q) return allData; return allData.filter(r => String(r.code).includes(q) || (r.name||"").toLowerCase().includes(q) || (r.father||"").toLowerCase().includes(q) || (r.province||"").toLowerCase().includes(q) || (r.district||"").toLowerCase().includes(q) || (r.address||"").toLowerCase().includes(q) ); }, [allData, query]); const totalAmount = useMemo(()=>{ if(cfg.hasReceived){ return allData.reduce((s,r)=> s + (parseInt(String(r.received||"").replace(/\D/g,""))||0), 0); } return allData.reduce((s,r)=> s + (Number(r.amount)||0), 0); }, [allData, cfg.hasReceived]); const fieldStyle = { border:"1px solid var(--line-strong)", borderRadius:"7px", padding:"7px 10px", fontSize:"12.5px", fontFamily:"var(--font-fa)", background:"var(--paper)", color:"var(--ink)", outline:"none", width:"100%", boxSizing:"border-box" }; const labelStyle = { fontSize:"12px", color:"var(--muted)", marginBottom:"3px", display:"block" }; const cellInputStyle = { border:"1px solid transparent", borderRadius:"5px", padding:"4px 6px", fontSize:"12.5px", fontFamily:"var(--font-fa)", background:"transparent", color:"var(--ink)", outline:"none", width:"100%", boxSizing:"border-box" }; const cellFocusProps = { onFocus: e=>{ e.currentTarget.style.background="#fffde7"; e.currentTarget.style.borderColor="var(--line-strong)"; }, onBlur: e=>{ e.currentTarget.style.background="transparent"; e.currentTarget.style.borderColor="transparent"; }, }; return (

🔖 {cfg.title}

{isDari ? `مجموع ${f(allData.length)} ثبت` : `${f(allData.length)} records`} · {isDari?"مجموع مبلغ:":"Total:"} {f(fmtMoney(totalAmount))} {isDari?"افغانی":"AFN"}

{showAdd && (

{isDari?"افزودن مورد جدید":"Add New Record"}

setForm({...form, code:e.target.value})}/>
setForm({...form, date:v})} lang={lang} placeholder={isDari?"تاریخ را انتخاب کنید":"Select date"}/>
setForm({...form, name:e.target.value})}/>
setForm({...form, father:e.target.value})}/>
setForm({...form, province:e.target.value})}/>
setForm({...form, district:e.target.value})}/>
{cfg.hasReceived ? ( <>
setForm({...form, received:e.target.value})}/>
setForm({...form, remaining:e.target.value})}/>
) : (
setForm({...form, amount:e.target.value})}/>
)}
setForm({...form, address:e.target.value})}/>
)}
setQuery(e.target.value)} />
{filtered.length === 0 ? (

{isDari?"موردی پیدا نشد":"No records found"}

) : (
{cfg.hasReceived ? ( <> ) : ( )} {filtered.map((r,i)=>( {cfg.hasReceived ? ( <> ) : ( )} ))}
{isDari?"کد":"Code"} {isDari?"تاریخ":"Date"} {isDari?"اسم":"Name"} {isDari?"ولد":"Father"} {isDari?"ولایت":"Province"} {isDari?"ولسوالی":"District"}{isDari?"دریافتی":"Received"} {isDari?"باقیمانده":"Remaining"}{isDari?"رسید":"Amount"}{isDari?"آدرس":"Address"}
updateField(r,"code",e.target.value)}/> updateField(r,"date",e.target.value)}/>
updateField(r,"name",e.target.value)}/> {r._custom && {isDari?"جدید":"New"}}
updateField(r,"father",e.target.value)}/> updateField(r,"province",e.target.value)}/> updateField(r,"district",e.target.value)}/> updateField(r,"received",e.target.value)}/> updateField(r,"remaining",e.target.value)}/> updateField(r,"amount",e.target.value)}/> updateField(r,"address",e.target.value)}/>
{r._custom && ( )}
)}
); }