home page converted back to server-side component

This commit is contained in:
2024-02-09 09:40:43 +01:00
parent 960210cbc3
commit 27b696faab
5 changed files with 70 additions and 117 deletions

View File

@@ -1,118 +1,30 @@
"use client";
import { fetchAllLocations } from '@/app/lib/actions/locationActions';
import { fetchAvailableYears } from '@/app/lib/actions/monthActions';
import { BillingLocation, YearMonth } from '@/app/lib/db-types';
import { FC, useEffect, useState } from 'react';
import { FC } from 'react';
import { MonthLocationList } from '@/app/ui/MonthLocationList';
import { WithId } from 'mongodb';
import { MonthCardSkeleton } from './MonthCardSkeleton';
import { useSearchParams } from 'next/navigation';
export interface HomePageProps {
searchParams?: {
year?: string;
month?: string;
};
}
type MonthsLocations = {
[key:string]:{
yearMonth: YearMonth,
locations: BillingLocation[],
monthlyExpense: number
}
}
export const HomePage:FC<HomePageProps> = async ({ searchParams }) => {
const fetchAllLocations = async (year: number) => {
const response = await fetch(`/api/locations/in-year/?year=${year}`);
const { locations } : { locations: WithId<BillingLocation>[] } = await response.json();
return locations;
}
let availableYears: number[];
const fetchAvailableYears = async () => {
const response = await fetch(`/api/locations/available-years/`);
const { availableYears }: { availableYears: number[]} = await response.json();
return availableYears;
}
// const asyncTimout = (ms:number) => new Promise(resolve => setTimeout(resolve, ms));
// await asyncTimout(5000);
export const HomePage:FC<HomePageProps> = () => {
const searchParams = useSearchParams();
const year = searchParams.get('year');
const currentYear = year ? parseInt(year, 10) : new Date().getFullYear();
const [ homePageStatus, setHomePageStatus ] = useState<{
status: "loading" | "loaded" | "error",
availableYears: number[],
months?: MonthsLocations,
error?: string
}>({
status: "loading",
availableYears: [],
});
const {availableYears, months, status, error} = homePageStatus;
useEffect(() => {
const fetchData = async () => {
try {
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 ? acc + (bill.payedAmount ?? 0) : acc, 0)
}
})
}
return({
...acc,
[key]: {
yearMonth: location.yearMonth,
locations: [location],
monthlyExpense: location.bills.reduce((acc, bill) => bill.paid ? acc + (bill.payedAmount ?? 0) : acc, 0)
}
});
}, {} as MonthsLocations);
setHomePageStatus({
availableYears: await fetchAvailableYears(),
months,
status: "loaded",
});
} catch (error: any) {
setHomePageStatus({
status: "error",
availableYears: [],
error: error.message
});
}
}
fetchData();
}, [currentYear]);
if(status === "loading") {
try {
availableYears = await fetchAvailableYears();
} catch (error:any) {
return (
<>
<MonthCardSkeleton checked={true} />
<MonthCardSkeleton />
<MonthCardSkeleton />
</>
);
}
if(status === "error") {
return(<p className="text-center text-2xl text-red-500">{error}</p>);
<main className="flex min-h-screen flex-col p-6 bg-base-300">
<p className="text-center text-2xl text-red-500">{error.message}</p>
</main>);
}
// if the database is in it's initial state, show the add location button for the current month
@@ -120,6 +32,42 @@ export const HomePage:FC<HomePageProps> = () => {
return (<MonthLocationList />);
}
const currentYear = Number(searchParams?.year) || availableYears[0];
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 ? acc + (bill.payedAmount ?? 0) : acc, 0)
}
})
}
return({
...acc,
[key]: {
yearMonth: location.yearMonth,
locations: [location],
monthlyExpense: location.bills.reduce((acc, bill) => bill.paid ? acc + (bill.payedAmount ?? 0) : acc, 0)
}
});
}, {} as {[key:string]:{
yearMonth: YearMonth,
locations: BillingLocation[],
monthlyExpense: number
} });
return (
<MonthLocationList availableYears={availableYears} months={months} />
);