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/actions/locationActions'; import { formatCurrency } from './lib/formatStrings'; import { fetchAvailableYears } from './lib/actions/monthActions'; import { YearMonth } from './lib/db-types'; import { formatYearMonth } from './lib/format'; const getNextYearMonth = (yearMonth:YearMonth) => { const {year, month} = yearMonth; return({ year: month===12 ? year+1 : year, month: month===12 ? 1 : month+1 } as YearMonth); } export const Page = async () => { const locations = await fetchAllLocations(); const availableYears = await fetchAvailableYears(); 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:YearMonth = { year: new Date().getFullYear(), month: new Date().getMonth() + 1 }; return ( ); } let monthlyExpense = 0; return ( { locations.map((location, ix, array) => { const { year, month } = location.yearMonth const { year: prevYear, month: prevMonth } = array[ix-1]?.yearMonth ?? { year: undefined, month: undefined }; const { year: nextYear, month: nextMonth } = array[ix+1]?.yearMonth ?? { year: undefined, month: undefined }; const isFirstLocationInMonth = ix === 0 || year !== prevYear || month !== prevMonth; const isLastLocationInMonth = year !== nextYear || month !== nextMonth; const isLastLocationOfFirstMonth = isLastLocationInMonth && year === array[0].yearMonth.year && month === array[0].yearMonth.month 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) } : null } > ) }) } { availableYears.map(ym => {ym}) } ); } export default Page;
{locations.message}
Total monthly expenditure: { formatCurrency(monthlyExpense) }
{ym}