year & month replaced by yearMonth object

This commit is contained in:
2024-01-09 16:20:49 +01:00
parent 46b65711a8
commit d627ad757d
12 changed files with 82 additions and 64 deletions

View File

@@ -4,7 +4,7 @@ import { z } from 'zod';
import { revalidatePath } from 'next/cache'; import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation'; import { redirect } from 'next/navigation';
import clientPromise, { getDbClient } from '../dbClient'; import clientPromise, { getDbClient } from '../dbClient';
import { BillingLocation } from '../db-types'; import { BillingLocation, YearMonth } from '../db-types';
import { ObjectId } from 'mongodb'; import { ObjectId } from 'mongodb';
import { auth, withUser } from '@/app/lib/auth'; import { auth, withUser } from '@/app/lib/auth';
import { AuthenticatedUser } from '../types/next-auth'; import { AuthenticatedUser } from '../types/next-auth';
@@ -33,7 +33,7 @@ const UpdateLocation = FormSchema.omit({ _id: true });
* @param formData form data * @param formData form data
* @returns * @returns
*/ */
export const updateOrAddLocation = withUser(async (user:AuthenticatedUser, locationId?: string, year?: string, month?: string, prevState:State, formData: FormData) => { export const updateOrAddLocation = withUser(async (user:AuthenticatedUser, locationId?: string, yearMonth?: YearMonth, prevState:State, formData: FormData) => {
const validatedFields = UpdateLocation.safeParse({ const validatedFields = UpdateLocation.safeParse({
locationName: formData.get('locationName'), locationName: formData.get('locationName'),
@@ -70,15 +70,14 @@ export const updateOrAddLocation = withUser(async (user:AuthenticatedUser, locat
notes: locationNotes, notes: locationNotes,
} }
}); });
} else if(year && month) { } else if(yearMonth) {
await dbClient.collection<BillingLocation>("lokacije").insertOne({ await dbClient.collection<BillingLocation>("lokacije").insertOne({
_id: (new ObjectId()).toHexString(), _id: (new ObjectId()).toHexString(),
userId, userId,
userEmail, userEmail,
name: locationName, name: locationName,
notes: locationNotes, notes: locationNotes,
year: parseInt(year), // ToDo: get the current year and month yearMonth: yearMonth,
month: parseInt(month), // ToDo: get the current year and month
bills: [], bills: [],
}); });
} }
@@ -99,7 +98,7 @@ export const fetchAllLocations = withUser(async (user:AuthenticatedUser, pageIx:
// fetch `pageSize` locations for the given page index // fetch `pageSize` locations for the given page index
const locations = await dbClient.collection<BillingLocation>("lokacije") const locations = await dbClient.collection<BillingLocation>("lokacije")
.find({ userId }) .find({ userId })
.sort({ year: -1, month: -1, name: 1 }) .sort({ yearMonth: -1, name: 1 })
.skip(pageIx * pageSize) .skip(pageIx * pageSize)
.limit(pageSize) .limit(pageSize)
.toArray(); .toArray();

View File

@@ -4,7 +4,7 @@ import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation'; import { redirect } from 'next/navigation';
import clientPromise, { getDbClient } from '../dbClient'; import clientPromise, { getDbClient } from '../dbClient';
import { ObjectId } from 'mongodb'; import { ObjectId } from 'mongodb';
import { BillingLocation } from '../db-types'; import { BillingLocation, YearMonth } from '../db-types';
import { AuthenticatedUser } from '../types/next-auth'; import { AuthenticatedUser } from '../types/next-auth';
import { withUser } from '../auth'; import { withUser } from '../auth';
@@ -16,14 +16,12 @@ import { withUser } from '../auth';
* @param formData form data * @param formData form data
* @returns * @returns
*/ */
export const addMonth = withUser(async (user:AuthenticatedUser, yearString: string, monthString: string) => { export const addMonth = withUser(async (user:AuthenticatedUser, { year, month }: YearMonth) => {
const { id: userId } = user; const { id: userId } = user;
// update the bill in the mongodb // update the bill in the mongodb
const dbClient = await getDbClient(); const dbClient = await getDbClient();
const year = parseInt(yearString);
const month = parseInt(monthString);
const prevYear = month === 1 ? year - 1 : year; const prevYear = month === 1 ? year - 1 : year;
const prevMonth = month === 1 ? 12 : month - 1; const prevMonth = month === 1 ? 12 : month - 1;
@@ -31,8 +29,10 @@ export const addMonth = withUser(async (user:AuthenticatedUser, yearString: stri
// find all locations for the previous month // find all locations for the previous month
const prevMonthLocations = await dbClient.collection<BillingLocation>("lokacije").find({ const prevMonthLocations = await dbClient.collection<BillingLocation>("lokacije").find({
userId, // make sure that the locations belongs to the user userId, // make sure that the locations belongs to the user
yearMonth: {
year: prevYear, year: prevYear,
month: prevMonth, month: prevMonth,
}
}); });
const newMonthLocationsCursor = prevMonthLocations.map((prevLocation) => { const newMonthLocationsCursor = prevMonthLocations.map((prevLocation) => {
@@ -41,8 +41,10 @@ export const addMonth = withUser(async (user:AuthenticatedUser, yearString: stri
...prevLocation, ...prevLocation,
// assign a new ID // assign a new ID
_id: (new ObjectId()).toHexString(), _id: (new ObjectId()).toHexString(),
yearMonth: {
year: year, year: year,
month: month, month: month,
},
// copy bill array, but set all bills to unpaid and remove attachments and notes // copy bill array, but set all bills to unpaid and remove attachments and notes
bills: prevLocation.bills.map((bill) => { bills: prevLocation.bills.map((bill) => {
return { return {

View File

@@ -9,6 +9,11 @@ export interface BillAttachment {
fileContentsBase64: string; fileContentsBase64: string;
}; };
export interface YearMonth {
year: number;
month: number;
};
/** bill object in the form returned by MongoDB */ /** bill object in the form returned by MongoDB */
export interface BillingLocation { export interface BillingLocation {
_id: string; _id: string;
@@ -18,10 +23,8 @@ export interface BillingLocation {
userEmail?: string | null; userEmail?: string | null;
/** name of the location */ /** name of the location */
name: string; name: string;
/** billing period year */ /** billing period year and month */
year: number; yearMonth: YearMonth;
/** billing period month */
month: number;
/** array of bills */ /** array of bills */
bills: Bill[]; bills: Bill[];
/** (optional) notes */ /** (optional) notes */

View File

@@ -1,4 +1,12 @@
import { YearMonth } from "./db-types";
export const formatYearMonth = (year: number, month:number): string => { export const formatYearMonth = ({ year, month }: YearMonth): string => {
return `${year}-${month<10?"0":""}${month}`; return `${year}-${month<10?"0":""}${month}`;
} }
export const parseYearMonth = (yearMonthString: string): YearMonth => {
const [year, month] = yearMonthString.split("-").map((s) => parseInt(s, 10));
return({ year, month } as YearMonth);
}

View File

@@ -1,7 +1,6 @@
import { parseYearMonth } from '@/app/lib/format';
import { LocationEditForm } from '@/app/ui/LocationEditForm'; import { LocationEditForm } from '@/app/ui/LocationEditForm';
export default async function Page({ params:{ id } }: { params: { id:string } }) { export default async function Page({ params:{ id } }: { params: { id:string } }) {
return (<LocationEditForm yearMonth={ parseYearMonth(id) } />);
const [year, month] = id.split("-");
return (<LocationEditForm year={year} month={month} />);
} }

View File

@@ -7,18 +7,21 @@ import { isAuthErrorMessage } from '@/app/lib/auth';
import { fetchAllLocations } from './lib/actions/locationActions'; import { fetchAllLocations } from './lib/actions/locationActions';
import { formatCurrency } from './lib/formatStrings'; import { formatCurrency } from './lib/formatStrings';
import { fetchAvailableYears } from './lib/actions/monthActions'; import { fetchAvailableYears } from './lib/actions/monthActions';
import { YearMonth } from './lib/db-types';
import { formatYearMonth } from './lib/format';
const getNextYearMonth = (year:number, month:number) => { const getNextYearMonth = (yearMonth:YearMonth) => {
const {year, month} = yearMonth;
return({ return({
year: month<12 ? year+1 : year, year: month===12 ? year+1 : year,
month: month<12 ? month+1 : 1 month: month===12 ? 1 : month+1
}); } as YearMonth);
} }
export const Page = async () => { export const Page = async () => {
const locations = await fetchAllLocations(); const locations = await fetchAllLocations();
const availableYearMonths = await fetchAvailableYears(); const availableYears = await fetchAvailableYears();
if(isAuthErrorMessage(locations)) { if(isAuthErrorMessage(locations)) {
return ( return (
@@ -30,13 +33,15 @@ export const Page = async () => {
// if the database is in it's initial state, show the add location button for the current month // if the database is in it's initial state, show the add location button for the current month
if(locations.length === 0) { if(locations.length === 0) {
const currentYear = new Date().getFullYear(); const currentYearMonth:YearMonth = {
const currentMonth = new Date().getMonth() + 1; year: new Date().getFullYear(),
month: new Date().getMonth() + 1
};
return ( return (
<main className="flex min-h-screen flex-col p-6 bg-base-300"> <main className="flex min-h-screen flex-col p-6 bg-base-300">
<MonthTitle year={currentYear} month={currentMonth} /> <MonthTitle yearMonth={currentYearMonth} />
<AddLocationButton year={currentYear} month={currentMonth} /> <AddLocationButton yearMonth={currentYearMonth} />
<PageFooter /> <PageFooter />
</main> </main>
); );
@@ -46,13 +51,17 @@ export const Page = async () => {
return ( return (
<main className="flex min-h-screen flex-col p-6 bg-base-300"> <main className="flex min-h-screen flex-col p-6 bg-base-300">
<AddMonthButton {...getNextYearMonth(locations[0].year, locations[0].month)} /> <AddMonthButton yearMonth={getNextYearMonth(locations[0].yearMonth)} />
{ {
locations.map((location, ix, array) => { locations.map((location, ix, array) => {
const isFirstLocationInMonth = ix === 0 || location.year !== array[ix-1].year || location.month !== array[ix-1].month; const { year, month } = location.yearMonth
const isLastLocationInMonth = location.year !== array[ix+1]?.year || location.month !== array[ix+1]?.month; const { year: prevYear, month: prevMonth } = array[ix-1]?.yearMonth ?? { year: undefined, month: undefined };
const isLastLocationOfFirstMonth = isLastLocationInMonth && location.year === array[0].year && location.month === array[0].month; 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) { if(isFirstLocationInMonth) {
monthlyExpense = 0; monthlyExpense = 0;
@@ -65,13 +74,13 @@ export const Page = async () => {
{ {
// show month title above the first LocationCard in the month // show month title above the first LocationCard in the month
isFirstLocationInMonth ? isFirstLocationInMonth ?
<MonthTitle key={`${location.year}-${location.month}`} year={location.year} month={location.month} /> : null <MonthTitle key={`${year}-${month}`} yearMonth={location.yearMonth} /> : null
} }
<LocationCard key={`${location._id}`} location={location} /> <LocationCard key={`${location._id}`} location={location} />
{ {
// show AddLocationButton as a last item in the firts month // show AddLocationButton as a last item in the firts month
isLastLocationOfFirstMonth ? isLastLocationOfFirstMonth ?
<AddLocationButton key={`add-loc-${location.year}-${location.month}`} year={location.year} month={location.month} /> : null <AddLocationButton key={`add-loc-${formatYearMonth(location.yearMonth)}`} yearMonth={location.yearMonth} /> : null
} }
{ {
isLastLocationInMonth && monthlyExpense>0 ? isLastLocationInMonth && monthlyExpense>0 ?
@@ -88,7 +97,7 @@ export const Page = async () => {
}) })
} }
<PageFooter /> <PageFooter />
{ availableYearMonths.map(ym => <p key={`year-month-${ym}`}>{ym}</p>) } { availableYears.map(ym => <p key={`year-month-${ym}`}>{ym}</p>) }
</main> </main>
); );
} }

View File

@@ -1,16 +1,16 @@
import { PlusCircleIcon } from "@heroicons/react/24/outline"; import { PlusCircleIcon } from "@heroicons/react/24/outline";
import { YearMonth } from "../lib/db-types";
import { formatYearMonth } from "../lib/format";
export interface AddLocationButtonProps { export interface AddLocationButtonProps {
/** year at which the new billing location should be addes */ /** year and month at which the new billing location should be addes */
year: number yearMonth: YearMonth
/** month at which the new billing location should be addes */
month: number
} }
export const AddLocationButton:React.FC<AddLocationButtonProps> = ({year,month}) => export const AddLocationButton:React.FC<AddLocationButtonProps> = ({yearMonth}) =>
<div className="card card-compact card-bordered max-w-[36em] bg-base-100 shadow-s my-1"> <div className="card card-compact card-bordered max-w-[36em] bg-base-100 shadow-s my-1">
<a href={`/location/${year}-${month<10?"0":""}${month}/add`} className="card-body tooltip self-center" data-tip="Add a new billing location"> <a href={`/location/${ formatYearMonth(yearMonth) }/add`} className="card-body tooltip self-center" data-tip="Add a new billing location">
<span className='grid self-center' data-tip="Add a new billing location"> <span className='grid self-center' data-tip="Add a new billing location">
<PlusCircleIcon className="h-[1em] w-[1em] cursor-pointer text-4xl" /> <PlusCircleIcon className="h-[1em] w-[1em] cursor-pointer text-4xl" />
</span> </span>

View File

@@ -1,12 +1,13 @@
import { PlusCircleIcon } from "@heroicons/react/24/outline"; import { PlusCircleIcon } from "@heroicons/react/24/outline";
import React from "react"; import React from "react";
import { formatYearMonth } from "../lib/format";
import { YearMonth } from "../lib/db-types";
export interface AddMonthButtonProps { export interface AddMonthButtonProps {
year: number; yearMonth: YearMonth;
month: number;
} }
export const AddMonthButton:React.FC<AddMonthButtonProps> = ({ year, month }) => export const AddMonthButton:React.FC<AddMonthButtonProps> = ({ yearMonth }) =>
<a href={`/year-month/${year}-${month<10?"0":""}${month}/add`} className='grid self-center tooltip' data-tip="Dodaj novi mjesec"> <a href={`/year-month/${formatYearMonth(yearMonth)}/add`} className='grid self-center tooltip' data-tip="Dodaj novi mjesec">
<PlusCircleIcon className="h-[1em] w-[1em] cursor-pointer text-4xl" /> <PlusCircleIcon className="h-[1em] w-[1em] cursor-pointer text-4xl" />
</a> </a>

View File

@@ -11,7 +11,7 @@ export interface LocationCardProps {
location: BillingLocation location: BillingLocation
} }
export const LocationCard:FC<LocationCardProps> = ({location: { _id, name, year, month, bills }}) => { export const LocationCard:FC<LocationCardProps> = ({location: { _id, name, yearMonth, bills }}) => {
// sum all the billAmounts // sum all the billAmounts
const monthlyExpense = bills.reduce((acc, bill) => acc + (bill.payedAmount ?? 0), 0); const monthlyExpense = bills.reduce((acc, bill) => acc + (bill.payedAmount ?? 0), 0);
@@ -22,7 +22,7 @@ export const LocationCard:FC<LocationCardProps> = ({location: { _id, name, year,
<a href={`/location/${_id}/edit`} className="card-subtitle tooltip" data-tip="Edit Location"> <a href={`/location/${_id}/edit`} className="card-subtitle tooltip" data-tip="Edit Location">
<Cog8ToothIcon className="h-[1em] w-[1em] absolute cursor-pointer top-3 right-3 text-2xl" /> <Cog8ToothIcon className="h-[1em] w-[1em] absolute cursor-pointer top-3 right-3 text-2xl" />
</a> </a>
<h2 className="card-title">{formatYearMonth(year, month)} {name}</h2> <h2 className="card-title">{formatYearMonth(yearMonth)} {name}</h2>
<div className="card-actions"> <div className="card-actions">
{ {
bills.map(bill => <BillBadge key={`${bill._id}`} locationId={_id} bill={bill} />) bills.map(bill => <BillBadge key={`${bill._id}`} locationId={_id} bill={bill} />)

View File

@@ -2,7 +2,7 @@
import { TrashIcon } from "@heroicons/react/24/outline"; import { TrashIcon } from "@heroicons/react/24/outline";
import { FC } from "react"; import { FC } from "react";
import { BillingLocation } from "../lib/db-types"; import { BillingLocation, YearMonth } from "../lib/db-types";
import { updateOrAddLocation } from "../lib/actions/locationActions"; import { updateOrAddLocation } from "../lib/actions/locationActions";
import { useFormState } from "react-dom"; import { useFormState } from "react-dom";
import { gotoHome } from "../lib/actions/billActions"; import { gotoHome } from "../lib/actions/billActions";
@@ -10,16 +10,14 @@ import { gotoHome } from "../lib/actions/billActions";
export interface LocationEditFormProps { export interface LocationEditFormProps {
/** location which should be edited */ /** location which should be edited */
location?: BillingLocation, location?: BillingLocation,
/** year at a new billing location should be assigned */ /** year adn month at a new billing location should be assigned */
year?: string yearMonth?: YearMonth
/** month at a new billing location should be assigned */
month?: string
} }
export const LocationEditForm:FC<LocationEditFormProps> = ({ location, year, month }) => export const LocationEditForm:FC<LocationEditFormProps> = ({ location, yearMonth }) =>
{ {
const initialState = { message: null, errors: {} }; const initialState = { message: null, errors: {} };
const handleAction = updateOrAddLocation.bind(null, location?._id, year, month); const handleAction = updateOrAddLocation.bind(null, location?._id, yearMonth);
const [ state, dispatch ] = useFormState(handleAction, initialState); const [ state, dispatch ] = useFormState(handleAction, initialState);
// redirect to the main page // redirect to the main page

View File

@@ -1,10 +1,10 @@
import { FC } from "react"; import { FC } from "react";
import { formatYearMonth } from "../lib/format"; import { formatYearMonth } from "../lib/format";
import { YearMonth } from "../lib/db-types";
export interface MonthTitleProps { export interface MonthTitleProps {
year: number; yearMonth: YearMonth
month: number;
} }
export const MonthTitle:FC<MonthTitleProps> = ({year, month}) => export const MonthTitle:FC<MonthTitleProps> = ({ yearMonth }) =>
<div className="divider text-2xl">{`${formatYearMonth(year, month)}`}</div> <div className="divider text-2xl">{`${formatYearMonth(yearMonth)}`}</div>

View File

@@ -1,12 +1,11 @@
import { addMonth } from '@/app/lib/actions/monthActions'; import { addMonth } from '@/app/lib/actions/monthActions';
import { parseYearMonth } from '@/app/lib/format';
import { revalidatePath } from 'next/cache'; import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation'; import { redirect } from 'next/navigation';
export default async function Page({ params:{ id } }: { params: { id:string } }) { export default async function Page({ params:{ id } }: { params: { id:string } }) {
const [year, month] = id.split("-"); await addMonth(parseYearMonth(id));
await addMonth(year, month);
revalidatePath('/'); revalidatePath('/');
redirect(`/`); redirect(`/`);