function Topbar({ company, user, page, setPage, onLogout, lang, employees, customers, onOpenCustomer, onUpdatePhoto, consumptionLists }){ const data = { consumptionLists: consumptionLists || { custom:[] } }; const t = STR[lang]; const [openNav, setOpenNav] = useState(null); const [openSubSection, setOpenSubSection] = useState(null); const [userOpen, setUserOpen] = useState(false); const [mobileOpen, setMobileOpen] = useState(false); const [mobileExpandedGroup, setMobileExpandedGroup] = useState(null); const [quickSearchOpen, setQuickSearchOpen] = useState(false); const [quickQuery, setQuickQuery] = useState(""); const photoInputRef = useRef(null); const handlePhotoSelect = (e) => { const file = e.target.files && e.target.files[0]; e.target.value = ""; // allow re-selecting the same file later if(!file) return; if(!file.type.startsWith("image/")){ alert(t.photoTypeError || "Please choose an image file."); return; } // Photos are stored as base64 directly in localStorage (no backend), so // keep the source file small — large photos would bloat saved data fast. if(file.size > 2*1024*1024){ alert(t.photoSizeError || "Image must be smaller than 2MB."); return; } const reader = new FileReader(); reader.onload = () => onUpdatePhoto(reader.result); reader.readAsDataURL(file); }; const quickResults = useMemo(()=>{ const q = quickQuery.trim().toLowerCase(); if(!q || !customers) return []; return customers.filter(c => (c.fullName||"").toLowerCase().includes(q) || String(c.accountNo||"").toLowerCase().includes(q) || String(c.meterNo||"").toLowerCase().includes(q) || String(c.phone||"").toLowerCase().includes(q) ).slice(0, 8); }, [quickQuery, customers]); // ── Permission system ────────────────────────────────────── // Roles: admin = full access | cashier = receipts+customers | viewer = read-only const ROLE_PERMS = { admin: ["dashboard","customers","newcustomer","employees","receipts","settings","expenses","consumption"], cashier: ["customers","receipts"], viewer: ["customers","receipts"], }; const userRole = user?.role || "viewer"; const perms = ROLE_PERMS[userRole] || ROLE_PERMS.viewer; const can = (...ps) => userRole === "admin" || ps.some(p => perms.includes(p)); const isReadOnly = userRole === "viewer"; const navGroups = [ ...(can("dashboard","expenses","consumption") ? [{ id:"home", label:t.nav.home, page:"dashboard", children:[ { id:"arbaab-report", label: lang==="dari"?"📋 لیست دریافت ارباب":"📋 Arbaab Receipt List" }, { id:"office-expenses", label: lang==="dari"?"🏢 لیست مصارف دفتر":"🏢 Office Expenses List" }, { id:"arbaab-payments", label: lang==="dari"?"💸 لیست مصرف برق و تیل":"💸 Electricity & Fuel List" }, ]}] : []), ...(can("customers") ? [{ id:"customers", label:t.nav.customers, children:[ { id:"customers", label:t.nav.allCustomers }, ...(!isReadOnly ? [{ id:"newcustomer", label:t.nav.newCustomer }] : []), { id:"customer-codes", isToggle:true, subId:"customer-codes", label: lang==="dari"?"🔖 کد مشتریان":"🔖 Customer Codes", children:[ { id:"code-omomi", label: lang==="dari"?"کد عمومی":"General Code" }, { id:"code-zamin", label: lang==="dari"?"کد ضامن":"Guarantor Code" }, { id:"code-mawaqat", label: lang==="dari"?"کد موقت":"Temporary Code" }, ]}, ]}] : []), ...(can("employees") ? [{ id:"employees", label:t.nav.employees, page:"employees", children:[ ...employees.slice(0, 8).map(e=>({ id:"employees", label:e.fullName })), { id:"employees", label:t.nav.addEmployee, isAdd:true }, ]}] : []), ...(can("receipts") ? [{ id:"receipts", label:t.nav.receipts, children:[ { id:"receipts", label:t.nav.allReceipts }, { id:"deposit-balance", label: lang==="dari"?"باقیداری انشعاب":"Connection Deposit Balance" }, { id:"annual-license-fee", label: lang==="dari"?"حق الامتیاز (سالانه)":"Annual License Fee" }, ]}] : []), { id:"settings", label:t.nav.settings, children:[ ...(can("settings") ? [ { id:"settings-company", label:(lang==="dari"?"🏢 معلومات شرکت":"🏢 Company Info") }, { id:"settings-users", label:(lang==="dari"?"👥 کاربران سیستم":"👥 System Users") }, { id:"settings-backup", label:(lang==="dari"?"💾 بکاپ / ریستور":"💾 Backup / Restore") }, { id:"settings-cloud", label:(lang==="dari"?"☁️ ذخیره ابری":"☁️ Cloud Sync") }, ] : []), { id:"settings-password", label:(lang==="dari"?"🔐 تبدیل رمز عبور":"🔐 Change Password") }, { id:"settings-language", label:(lang==="dari"?"🌐 زبان":"🌐 Language") }, { id:"settings-theme", label:(lang==="dari"?"🎨 حالت روشن/تاریک":"🎨 Light/Dark Mode") }, ]}, ]; useEffect(()=>{ const handler = ()=>{ setOpenNav(null); setUserOpen(false); setQuickSearchOpen(false); }; document.addEventListener("click", handler); return ()=>document.removeEventListener("click", handler); }, []); const isGroupActive = (g) => (g.page && page === g.page) || (g.children && g.children.some(c=>c.id===page)); const companyName = lang === "dari" ? company.nameDari : company.nameEn; return (
e.stopPropagation()}>
{/* Logo + company name — always the most prominent element in the header */}
{/* Quick customer search — jump straight to a customer from anywhere, no menu digging */}
e.stopPropagation()}> {quickSearchOpen && (
setQuickQuery(e.target.value)} placeholder={t.quickSearchPh||"Search name, account, phone..."} style={{width:"100%", boxSizing:"border-box", padding:"9px 12px", borderRadius:"8px", border:"1px solid var(--line-strong)", background:"var(--paper)", color:"var(--ink)", fontSize:"13px", outline:"none"}} /> {quickQuery.trim() && (
{quickResults.length === 0 && (
{t.quickSearchEmpty||"No matches"}
)} {quickResults.map(c=>( ))}
)}
)}
{/* Account is represented ONLY by an avatar icon — clicking it reveals everything: photo, name, settings, logout */}
{userOpen && (
{user.photoUrl ? : initials(user.fullName)}
{user.fullName}
{t.settings.roles[user.role] || user.role} · {user.username}
{user.photoUrl && }
)}
{navGroups.map((g,gi)=>{ const isExpanded = mobileExpandedGroup === gi; const items = g.children ? g.children.flatMap(c => c.children ? c.children : [c]) : []; const hasOwnPage = !!g.page; return (
{isExpanded && (
{hasOwnPage && ( )} {items.map((c,i)=>( ))}
)}
); })}
); } /* ============ Dashboard ============ */ function MonthPicker({ value, onChange }){ const [open, setOpen] = useState(false); const ref = useRef(null); const name = jalaliMonthNamesFa[parseInt(value,10)-1]; useEffect(()=>{ if(!open) return; const handler = (e)=>{ if(ref.current && !ref.current.contains(e.target)) setOpen(false); }; document.addEventListener("pointerdown", handler, true); return ()=>document.removeEventListener("pointerdown", handler, true); }, [open]); return (
{open && (
{ if(el){ const btn = ref.current?.querySelector("button"); if(btn){ const rect = btn.getBoundingClientRect(); el.style.top = (rect.bottom+6)+"px"; el.style.right = (window.innerWidth-rect.right)+"px"; } } }}> {jalaliMonthNamesFa.map((mn,i)=>{ const mo = String(i+1).padStart(2,"0"); const active = mo===value; return ( ); })}
)}
); } function Dashboard({ customers, areas, employees, expenses, consumptionLists, setPage, onSelectArea, user, lang }){ const t = STR[lang]; const td = t.dash; const f = nd(lang); const isDari = lang === "dari"; const totalCustomers = customers.length; const totalReceipts = customers.reduce((s,c)=>s+c.receipts.length,0); const totalRevenue = customers.reduce((s,c)=>s+c.receipts.reduce((rs,r)=>rs+(r.total||0),0),0); const totalArrears = customers.reduce((s,c)=>s+c.receipts.reduce((rs,r)=>rs+(r.arrears||0),0),0); const totalEmployees = employees.length; const today = todayJalali(); const [selectedMonth, setSelectedMonthRaw] = useState(()=>{ try{ return localStorage.getItem("shvm_dashboard_month") || "02"; }catch(e){ return "02"; } }); const setSelectedMonth = (m) => { setSelectedMonthRaw(m); try{ localStorage.setItem("shvm_dashboard_month", m); }catch(e){} }; // Total expenses = employee salaries + other + purchases + all consumption lists, // filtered to the selected month — so months with nothing registered yet show 0, // and figures update automatically once data is entered for that month. const filterListByMonth = (items) => (items||[]).filter(x=>{ if(!x.date) return false; return String(x.date).split("-")[1] === selectedMonth; }); const cl = consumptionLists || {}; const ex = expenses || {}; const arbaabIncome = filterListByMonth(cl.arbaab).reduce((s,x)=>s+(Number(x.amount)||0),0); const barqTotal = filterListByMonth(cl.barq).reduce((s,x)=>s+(Number(x.amount)||0),0); const teelTotal = filterListByMonth(cl.teel).reduce((s,x)=>s+(Number(x.amount)||0),0); const arbaabResult = arbaabIncome - barqTotal - teelTotal; const officeMisc = filterListByMonth(cl.mataraffe).reduce((s,x)=>s+(Number(x.amount)||0),0); const officeFood = filterListByMonth(cl.khorak).reduce((s,x)=>s+(Number(x.amount)||0),0); const officeEmp = filterListByMonth(ex.employee).reduce((s,x)=>s+(Number(x.amount)||0),0); const officeTotal = officeEmp + officeMisc + officeFood; const totalExpenses = arbaabResult + officeTotal; const allReceipts = []; customers.forEach(c=>c.receipts.forEach(r=>allReceipts.push(r))); const monthReceipts = allReceipts.filter(r=>{ const mo = r.receiptMonth || (r.date ? r.date.split("-")[1] : ""); return mo === selectedMonth; }); const monthTotal = monthReceipts.reduce((s,r)=>s+(r.total||0),0); const monthUnpaid = monthReceipts.filter(r=>!isPaid(r)).reduce((s,r)=>s+(r.total||0),0); const allUnpaid = allReceipts.filter(r=>!isPaid(r)).reduce((s,r)=>s+(r.total||0),0); const allPaidIncome = allReceipts.filter(r=>isPaid(r)).reduce((s,r)=>s+(r.total||0),0); const totalDepositDue = allReceipts.reduce((s,r)=>s+(r.disconnectionDeposit||0),0); const totalDepositPaid = allReceipts.filter(r=>r.depositPaid).reduce((s,r)=>s+(r.disconnectionDeposit||0),0); const allTotalDue = allReceipts.reduce((s,r)=>s+(r.total||0),0); // Monthly billing breakdown (for selected month) const monthExpectedIncome = monthReceipts.reduce((s,r)=>s+(r.currentMonthAmount||0),0); const monthArrears = monthReceipts.reduce((s,r)=>s+(r.arrears||0),0); const monthPenalties = monthReceipts.reduce((s,r)=>s+(r.penalty||0),0); const monthTotalDue = monthReceipts.reduce((s,r)=>s+(r.total||0),0); const monthTotalPaid = monthReceipts.filter(r=>isPaid(r)).reduce((s,r)=>s+(r.total||0),0); const monthRemaining = monthTotalDue - monthTotalPaid; const netAfterExpenses = monthTotalDue - totalExpenses; const selectedMonthName = isDari ? jalaliMonthNamesFa[parseInt(selectedMonth,10)-1] : jalaliMonthNamesEn[parseInt(selectedMonth,10)-1]; const recentReceipts = []; customers.forEach(c=>c.receipts.forEach(r=>recentReceipts.push({ ...r, customerName:c.fullName }))); recentReceipts.sort((a,b)=> (b.date||"").localeCompare(a.date||"")); const areaCounts = areas.map(a => ({ ...a, count: customers.filter(c=>c.area===a.id).length })); // Monthly computed stats const monthPaid = monthReceipts.filter(r=>isPaid(r)); const monthUnpaidList = monthReceipts.filter(r=>!isPaid(r)); const monthWithPenalty = monthReceipts.filter(r=>(r.penalty||0)>0); const customersWithReceiptThisMonth = new Set( customers.filter(c=>c.receipts.some(r=>(r.receiptMonth || (r.date ? r.date.split("-")[1] : "")) === selectedMonth)).map(c=>c.id) ); // All receipts flat totals const allMonthlyAmt = allReceipts.reduce((s,r)=>s+(r.currentMonthAmount||0),0); const allArrearsAmt = allReceipts.reduce((s,r)=>s+(r.arrears||0),0); const allPenaltyAmt = allReceipts.reduce((s,r)=>s+(r.penalty||0),0); const allTotalPaid2 = allReceipts.filter(r=>isPaid(r)).reduce((s,r)=>s+(r.total||0),0); const allRemaining = allTotalDue - allTotalPaid2; const depositDue2 = allReceipts.reduce((s,r)=>s+(r.disconnectionDeposit||0),0); const depositReceived = allReceipts.filter(r=>r.depositPaid).reduce((s,r)=>s+(r.disconnectionDeposit||0),0); const monthDepositDue = monthReceipts.reduce((s,r)=>s+(r.disconnectionDeposit||0),0); const monthDepositReceived = monthReceipts.filter(r=>r.depositPaid).reduce((s,r)=>s+(r.disconnectionDeposit||0),0); // ── Selected-area summary (for the selected month) ── const [summaryArea, setSummaryAreaRaw] = useState(()=>{ try{ return localStorage.getItem("shvm_dashboard_area") || ""; }catch(e){ return ""; } }); const setSummaryArea = (id) => { setSummaryAreaRaw(id); try{ localStorage.setItem("shvm_dashboard_area", id); }catch(e){} }; const summaryAreaObj = areas.find(a=>a.id===summaryArea) || null; const areaStats = (()=>{ if(!summaryAreaObj) return null; const areaCustomers = customers.filter(c=>c.area===summaryAreaObj.id); const aReceipts = []; areaCustomers.forEach(c=>c.receipts.forEach(r=>{ const mo = r.receiptMonth || (r.date ? r.date.split("-")[1] : ""); if(mo === selectedMonth) aReceipts.push(r); })); const monthAmount = aReceipts.reduce((s,r)=>s+(r.currentMonthAmount||0),0); const arrears = aReceipts.reduce((s,r)=>s+(r.arrears||0),0); const penalty = aReceipts.reduce((s,r)=>s+(r.penalty||0),0); const totalDue = aReceipts.reduce((s,r)=>s+(r.total||0),0); const paid = aReceipts.filter(r=>isPaid(r)).reduce((s,r)=>s+(r.total||0),0); const unpaid = totalDue - paid; // Same rule as the customer list: read = شماره فعلی entered for this month const readCount = areaCustomers.filter(c=>c.receipts.some(r=>(((r.date||"").split("-")[1]===selectedMonth) || r.receiptMonth===selectedMonth) && r.currentReading !== undefined && r.currentReading !== null && String(r.currentReading).trim() !== "" && (Number(r.currentReading)||0) > 0)).length; return { monthAmount, arrears, penalty, paid, unpaid, readCount, unreadCount: areaCustomers.length - readCount, customerCount: areaCustomers.length }; })(); return (

{td.greeting} {user.fullName}

{td.sub}

{isDari?`خلاصه مالی — برج ${selectedMonthName}`:`Financial Summary — ${selectedMonthName}`}
{/* Top row — 4 cards */}
{[ { label: isDari?"مجموع مصارف ثبت شده":"Total Expenses", value: totalExpenses, color:"#b45309", sub: isDari?"معاشات + ارباب + متفرقه + خوراک + برق + تیل":"" }, { label: isDari?"باقیداری انشعاب":"Connection Deposit Due", value: monthDepositDue, color:"#7c3aed", sub: isDari?`دریافت شده: ${f(fmtMoney(monthDepositReceived))}`:"" }, { label: isDari?"دریافت شد انشعاب":"Deposit Received", value: monthDepositReceived, color:"#0FA4AF", sub: isDari?`از مجموع ${f(fmtMoney(monthDepositDue))}`:"" }, { label: isDari?"تعداد کل مشتریان":"Total Customers", value: totalCustomers, color:"var(--navy)", sub: isDari?"مشتری فعال در سیستم":"", isCount: true }, ].map((c,i)=>(
{c.label}
{c.isCount ? f(c.value) : ((c.value<0)?"-":"")+f(fmtMoney(Math.abs(c.value)))}
{c.sub &&
{c.sub}
}
))}
{/* Bottom row — 6 cards */}
{[ { label: isDari?"مبلغ ماه جاری":"Monthly Billing", value: monthExpectedIncome, color:"#0FA4AF", sub: isDari?`${f(customersWithReceiptThisMonth.size)} مشتری میترخوانی شده`:"" }, { label: isDari?"باقیمانده قبلی":"Previous Arrears", value: monthArrears, color:"#b45309", sub: isDari?"از ماه‌های قبل":"" }, { label: isDari?"جریمه ماه جاری":"Penalties", value: monthPenalties, color:"#7c3aed", sub: isDari?"مجموع جرایم":"" }, { label: isDari?"مجموع کل پرداختی‌ها":"Total Due", value: monthTotalDue, color:"var(--navy)", sub: isDari?"مبلغ + باقی + جریمه":"Monthly + arrears + penalty" }, { label: isDari?"مجموع پرداخت شده":"Total Paid", value: monthTotalPaid, color:"#15803d", sub: isDari?`${f(monthPaid.length)} قبض پرداخت شده`:"" }, { label: isDari?"مجموع پرداخت نشده":"Total Unpaid", value: monthRemaining, color: monthRemaining>0?"#C0392B":"#15803d", sub: isDari?"کار به پرداخت":"Remaining to collect" }, ].map((c,i)=>(
{c.label}
{f(fmtMoney(Math.abs(c.value)))}
{c.sub &&
{c.sub}
}
))}
{/* ── Income cards row ── */}
{/* درآمد خالص پس از همه هزینه‌ها */}
=0?"#15803d":"#C0392B"}`}}>
💰{isDari?"درآمد خالص پس از همه هزینه‌ها":"Net Income After All Expenses"}
{isDari?"مجموع کل مبلغ قابل وصول منهای همه مصارف":"Total amount due minus all expenses"}
=0?"#15803d":"#C0392B", fontFamily:"var(--font-mono)", letterSpacing:"-0.5px"}}> {netAfterExpenses<0?"-":""}{f(fmtMoney(Math.abs(netAfterExpenses)))}
{isDari?"مجموع مبلغ قابل وصول:":"Total due:"}{f(fmtMoney(monthTotalDue))}
{isDari?"منهای مجموع مصارف:":"Minus total expenses:"}{f(fmtMoney(totalExpenses))}
=0?"#15803d":"#C0392B"}}> {isDari?"نتیجه:":"Result:"} {f(fmtMoney(Math.abs(netAfterExpenses)))} {netAfterExpenses>=0?"✓":"↓"}
{/* درآمد خالص */} {(()=>{ const val = monthTotalPaid - totalExpenses; return (
=0?"#15803d":"#C0392B"}`}}>
📊{isDari?"درآمد خالص":"Net Profit"}
{isDari?"آنچه واقعاً نقد دریافت شده منهای همه مصارف":"Cash actually received minus all expenses"}
=0?"#15803d":"#C0392B", fontFamily:"var(--font-mono)", letterSpacing:"-0.5px"}}> {val<0?"-":""}{f(fmtMoney(Math.abs(val)))}
{isDari?"مجموع دریافت شده:":"Total received:"}{f(fmtMoney(monthTotalPaid))}
{isDari?"منهای مجموع مصارف:":"Minus total expenses:"}{f(fmtMoney(totalExpenses))}
=0?"#15803d":"#C0392B"}}> {isDari?"نتیجه:":"Result:"} {f(fmtMoney(Math.abs(val)))} {val>=0?"✓":"↓"}
); })()} {/* درآمد ناخالص */} {(()=>{ const val = monthExpectedIncome - totalExpenses; return (
=0?"#0FA4AF":"#C0392B"}`}}>
📈{isDari?"درآمد ناخالص":"Gross Profit"}
{isDari?"مبلغ محاسبه شده ماه جاری منهای همه مصارف":"This month's billed amount minus all expenses"}
=0?"#0FA4AF":"#C0392B", fontFamily:"var(--font-mono)", letterSpacing:"-0.5px"}}> {val<0?"-":""}{f(fmtMoney(Math.abs(val)))}
{isDari?"مبلغ ماه جاری:":"Current month billed:"}{f(fmtMoney(monthExpectedIncome))}
{isDari?"منهای مجموع مصارف:":"Minus total expenses:"}{f(fmtMoney(totalExpenses))}
=0?"#0FA4AF":"#C0392B"}}> {isDari?"نتیجه:":"Result:"} {f(fmtMoney(Math.abs(val)))} {val>=0?"✓":"↓"}
); })()}
{/* ── Selected-area summary ── */} {areas.length > 0 && (
📍 {isDari?`خلاصه منطقه — برج ${selectedMonthName}`:`Area Summary — ${selectedMonthName}`}
{!areaStats ? (
{isDari?"یک منطقه را انتخاب کنید تا معلومات آن نمایش داده شود":"Select an area to see its information"}
) : (
{[ { label: isDari?"مبلغ ماه جاری":"Monthly Billing", value: areaStats.monthAmount, color:"#0FA4AF" }, { label: isDari?"باقیمانده قبلی":"Previous Arrears", value: areaStats.arrears, color:"#b45309" }, { label: isDari?"مجموع پرداخت شده":"Total Paid", value: areaStats.paid, color:"#15803d" }, { label: isDari?"مجموع پرداخت نشده":"Total Unpaid", value: areaStats.unpaid, color: areaStats.unpaid>0?"#C0392B":"#15803d" }, { label: isDari?"متر خوانده شد":"Meter Read", value: areaStats.readCount, color:"#15803d", isCount:true, sub: isDari?`از ${f(areaStats.customerCount)} مشتری`:`of ${areaStats.customerCount} customers` }, { label: isDari?"متر خوانده نشد":"Meter Not Read", value: areaStats.unreadCount, color:"#b45309", isCount:true, sub: isDari?`از ${f(areaStats.customerCount)} مشتری`:`of ${areaStats.customerCount} customers` }, { label: isDari?"جبران خسارت":"Compensation", value: areaStats.penalty, color:"#7c3aed" }, ].map((c,i)=>(
{c.label}
{c.isCount ? f(c.value) : f(fmtMoney(Math.abs(c.value)))}
{c.sub || (c.isCount ? "" : td.currency)}
))}
)}
)} {areaCounts.length > 0 && (

{td.areasTitle}

{td.areasSub}

{areaCounts.map(a=>( ))}
)}

{td.recent}

{recentReceipts.length === 0 ? (

{td.emptyTitle}

{td.emptySub}

) : (
{recentReceipts.slice(0,6).map(r=>( ))}
{td.colSn}{td.colCustomer}{td.colDate}{td.colConsumption}{td.colAmount}
{f(r.sn)} {r.customerName} {f(r.date)} {f(r.consumption)} {f(fmtMoney(r.total))} {td.currency}
)}
); } /* ============ A4 New Customer Form ============ */ const emptyCustomer = () => ({ fullName:"", fatherName:"", accountNo:"", prevAccountNo:"", meterNo:"", nationalId:"", phone:"", address:"", subscriptionType:"residential", pipeSize:"", issueDate:"", notes:"", area:"", });