import { LocationCard } from './ui/LocationCard'; import { MonthTitle } from './ui/MonthTitle'; import { AddMonthButton } from './ui/AddMonthButton'; import { AddLocationButton } from './ui/AddLocationButton'; import { PageFooter } from './ui/PageFooter'; import { isAuthErrorMessage } from '@/app/lib/auth'; import { fetchAllLocations } from './lib/locationActions'; const getNextYearMonth = (yearMonth:number) => { return(yearMonth % 100 === 12 ? yearMonth + 89 : yearMonth + 1); } const formatCurrency = (amount:number) => { // format number wirh 2 decimal places and a thousand separator const formattedAmount = amount.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'); return(formattedAmount); } export const Page = async () => { const locations = await fetchAllLocations(); if(isAuthErrorMessage(locations)) { return (

{locations.message}

); } // if the database is in it's initial state, show the add location button for the current month if(locations.length === 0) { const currentYearMonth = new Date().getFullYear() * 100 + new Date().getMonth() + 1; return (
); } let monthlyExpense = 0; return (
{ locations.map((location, ix, array) => { const isFirstLocationInMonth = ix === 0 || location.yearMonth !== array[ix-1].yearMonth; const isLastLocationInMonth = location.yearMonth !== array[ix+1]?.yearMonth; const isLastLocationOfFirstMonth = isLastLocationInMonth && location.yearMonth === array[0].yearMonth; if(isFirstLocationInMonth) { monthlyExpense = 0; } monthlyExpense += location.bills.reduce((acc, bill) => acc + (bill.payedAmount ?? 0), 0); return ( <> { // show month title above the first LocationCard in the month isFirstLocationInMonth ? : null } { // show AddLocationButton as a last item in the firts month isLastLocationOfFirstMonth ? : null } { isLastLocationInMonth && monthlyExpense>0 ?

Total monthly expenditure: { formatCurrency(monthlyExpense/100) }

: null } ) }) }
); } export default Page;