import { fetchAllLocations } from '@/app/lib/actions/locationActions'; import { fetchAvailableYears } from '@/app/lib/actions/monthActions'; import { BillingLocation, YearMonth } from '@/app/lib/db-types'; import { FC } from 'react'; import { MonthLocationList } from '@/app/ui/MonthLocationList'; export interface HomePageProps { searchParams?: { year?: string; month?: string; }; } export const HomePage:FC = async ({ searchParams }) => { let availableYears: number[]; // const asyncTimout = (ms:number) => new Promise(resolve => setTimeout(resolve, ms)); // await asyncTimout(5000); try { availableYears = await fetchAvailableYears(); } catch (error:any) { return (

{error.message}

); } // if the database is in it's initial state, show the add location button for the current month if(availableYears.length === 0) { return (); } const currentYear = Number(searchParams?.year) || new Date().getFullYear(); const locations = await fetchAllLocations(currentYear); // group locations by month const months = locations.reduce((acc, location) => { const {year, month} = location.yearMonth; const key = `${year}-${month}`; const locationsInMonth = acc[key]; if(locationsInMonth) { return({ ...acc, [key]: { yearMonth: location.yearMonth, locations: [...locationsInMonth.locations, location], monthlyExpense: locationsInMonth.monthlyExpense + location.bills.reduce((acc, bill) => (bill.paid && (bill.billedToTenant ?? true)) ? acc + (bill.payedAmount ?? 0) : acc, 0) } }) } return({ ...acc, [key]: { yearMonth: location.yearMonth, locations: [location], monthlyExpense: location.bills.reduce((acc, bill) => (bill.paid && (bill.billedToTenant ?? true)) ? acc + (bill.payedAmount ?? 0) : acc, 0) } }); }, {} as {[key:string]:{ yearMonth: YearMonth, locations: BillingLocation[], monthlyExpense: number } }); return ( ); } export default HomePage;