Files
evidencija-rezija/app/ui/MonthLocationList.tsx

80 lines
2.8 KiB
TypeScript

"use client";
import React from "react";
import { AddLocationButton } from "./AddLocationButton";
import { AddMonthButton } from "./AddMonthButton";
import { MonthCard } from "./MonthCard";
import Pagination from "./Pagination";
import { LocationCard } from "./LocationCard";
import { BillingLocation, YearMonth } from "../lib/db-types";
import { useParams, useRouter } from "next/navigation";
const getNextYearMonth = (yearMonth:YearMonth) => {
const {year, month} = yearMonth;
return({
year: month===12 ? year+1 : year,
month: month===12 ? 1 : month+1
} as YearMonth);
}
export interface MonthLocationListProps {
availableYears: number[];
months: {
[key: string]: {
yearMonth: YearMonth;
locations: BillingLocation[];
monthlyExpense: number;
};
};
}
export const MonthLocationList:React.FC<MonthLocationListProps > = ({
availableYears,
months,
}) => {
const router = useRouter();
const params = useParams();
const { month: initialMonth } = params;
const [expandedMonth, setExpandedMonth] = React.useState<number>(
initialMonth ? parseInt(initialMonth as string) : new Date().getMonth() + 1
);
const monthsArray = Object.entries(months);
// when the month is toggled, update the URL
// and set the the new expandedMonth
const handleMonthToggle = (yearMonth:YearMonth) => {
// if the month is already expanded, collapse it
if(expandedMonth === yearMonth.month) {
router.push(`/?year=${yearMonth.year}`);
setExpandedMonth(-1); // no month is expanded
} else {
router.push(`/?year=${yearMonth.year}&month=${yearMonth.month}`);
setExpandedMonth(yearMonth.month);
}
}
return(<>
<AddMonthButton yearMonth={getNextYearMonth(monthsArray[0][1].locations[0].yearMonth)} />
{
monthsArray.map(([monthKey, { yearMonth, locations, monthlyExpense }], monthIx) =>
<MonthCard yearMonth={yearMonth} key={`month-${monthKey}`} monthlyExpense={monthlyExpense} expanded={ yearMonth.month === expandedMonth } onToggle={handleMonthToggle} >
{
locations.map((location, ix) => <LocationCard key={`location-${location._id}`} location={location} />)
}
{
// show AddLocationButton as a last item in the first month
monthIx === 0 ? <AddLocationButton yearMonth={yearMonth} /> : null
}
</MonthCard>
)
}
<div className="mt-5 flex w-full justify-center">
<Pagination availableYears={availableYears} />
</div>
</>)
}