yearMonth split into year + month
This commit is contained in:
@@ -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, yearMonth?: string, prevState:State, formData: FormData) => {
|
export const updateOrAddLocation = withUser(async (user:AuthenticatedUser, locationId?: string, year?: string, month?: string, prevState:State, formData: FormData) => {
|
||||||
|
|
||||||
const validatedFields = UpdateLocation.safeParse({
|
const validatedFields = UpdateLocation.safeParse({
|
||||||
locationName: formData.get('locationName'),
|
locationName: formData.get('locationName'),
|
||||||
@@ -70,14 +70,15 @@ export const updateOrAddLocation = withUser(async (user:AuthenticatedUser, locat
|
|||||||
notes: locationNotes,
|
notes: locationNotes,
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
} else if(yearMonth) {
|
} else if(year && month) {
|
||||||
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,
|
||||||
yearMonth: parseInt(yearMonth), // ToDo: get the current year and month
|
year: parseInt(year), // ToDo: get the current year and month
|
||||||
|
month: parseInt(month), // ToDo: get the current year and month
|
||||||
bills: [],
|
bills: [],
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -98,7 +99,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({ yearMonth: -1, name: 1 })
|
.sort({ year: -1, month: -1, name: 1 })
|
||||||
.skip(pageIx * pageSize)
|
.skip(pageIx * pageSize)
|
||||||
.limit(pageSize)
|
.limit(pageSize)
|
||||||
.toArray();
|
.toArray();
|
||||||
|
|||||||
@@ -16,20 +16,23 @@ import { withUser } from '../auth';
|
|||||||
* @param formData form data
|
* @param formData form data
|
||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
export const addYearMonth = withUser(async (user:AuthenticatedUser, yearMonthString: string) => {
|
export const addMonth = withUser(async (user:AuthenticatedUser, yearString: string, monthString: string) => {
|
||||||
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 yearMonth = parseInt(yearMonthString);
|
const year = parseInt(yearString);
|
||||||
|
const month = parseInt(monthString);
|
||||||
|
|
||||||
const prevYearMonth = (yearMonth - 1) % 100 === 0 ? yearMonth - 89 : yearMonth - 1;
|
const prevYear = month === 1 ? year - 1 : year;
|
||||||
|
const prevMonth = month === 1 ? 12 : month - 1;
|
||||||
|
|
||||||
// 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: prevYearMonth
|
year: prevYear,
|
||||||
|
month: prevMonth,
|
||||||
});
|
});
|
||||||
|
|
||||||
const newMonthLocationsCursor = prevMonthLocations.map((prevLocation) => {
|
const newMonthLocationsCursor = prevMonthLocations.map((prevLocation) => {
|
||||||
@@ -38,7 +41,8 @@ export const addYearMonth = withUser(async (user:AuthenticatedUser, yearMonthStr
|
|||||||
...prevLocation,
|
...prevLocation,
|
||||||
// assign a new ID
|
// assign a new ID
|
||||||
_id: (new ObjectId()).toHexString(),
|
_id: (new ObjectId()).toHexString(),
|
||||||
yearMonth,
|
year: year,
|
||||||
|
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 {
|
||||||
@@ -64,52 +68,13 @@ export async function gotoHome() {
|
|||||||
redirect('/');
|
redirect('/');
|
||||||
}
|
}
|
||||||
|
|
||||||
export const fetchBillById = withUser(async (user:AuthenticatedUser, locationID:string, billID:string) => {
|
export const fetchAvailableYears = withUser(async (user:AuthenticatedUser) => {
|
||||||
const { id: userId } = user;
|
const { id: userId } = user;
|
||||||
|
|
||||||
const dbClient = await getDbClient();
|
const dbClient = await getDbClient();
|
||||||
|
|
||||||
// find a location with the given locationID
|
// query mnogodb for all `yearMonth` values
|
||||||
const billLocation = await dbClient.collection<BillingLocation>("lokacije").findOne({
|
const yearMonths = await dbClient.collection<BillingLocation>("lokacije").distinct("year", { userId });
|
||||||
_id: locationID,
|
|
||||||
userId // make sure that the location belongs to the user
|
return(yearMonths);
|
||||||
})
|
})
|
||||||
|
|
||||||
if(!billLocation) {
|
|
||||||
console.log(`Location ${locationID} not found`);
|
|
||||||
return(null);
|
|
||||||
}
|
|
||||||
|
|
||||||
// find a bill with the given billID
|
|
||||||
const bill = billLocation?.bills.find(({ _id }) => _id.toString() === billID);
|
|
||||||
|
|
||||||
if(!bill) {
|
|
||||||
console.log('Bill not found');
|
|
||||||
return(null);
|
|
||||||
}
|
|
||||||
|
|
||||||
return(bill);
|
|
||||||
})
|
|
||||||
|
|
||||||
export const deleteBillById = withUser(async (user:AuthenticatedUser, locationID:string, billID:string) => {
|
|
||||||
const { id: userId } = user;
|
|
||||||
|
|
||||||
const dbClient = await getDbClient();
|
|
||||||
|
|
||||||
// find a location with the given locationID
|
|
||||||
const post = await dbClient.collection<BillingLocation>("lokacije").updateOne(
|
|
||||||
{
|
|
||||||
_id: locationID, // find a location with the given locationID
|
|
||||||
userId // make sure that the location belongs to the user
|
|
||||||
},
|
|
||||||
{
|
|
||||||
// remove the bill with the given billID
|
|
||||||
$pull: {
|
|
||||||
bills: {
|
|
||||||
_id: billID
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
return(post.modifiedCount);
|
|
||||||
});
|
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { ObjectId } from "mongodb";
|
import { ObjectId } from "mongodb";
|
||||||
|
import { inter } from "../ui/fonts";
|
||||||
|
|
||||||
export interface BillAttachment {
|
export interface BillAttachment {
|
||||||
fileName: string;
|
fileName: string;
|
||||||
@@ -17,8 +18,10 @@ export interface BillingLocation {
|
|||||||
userEmail?: string | null;
|
userEmail?: string | null;
|
||||||
/** name of the location */
|
/** name of the location */
|
||||||
name: string;
|
name: string;
|
||||||
/** the value is encoded as yyyymm (i.e. 202301) */
|
/** billing period year */
|
||||||
yearMonth: number;
|
year: number;
|
||||||
|
/** billing period month */
|
||||||
|
month: number;
|
||||||
/** array of bills */
|
/** array of bills */
|
||||||
bills: Bill[];
|
bills: Bill[];
|
||||||
/** (optional) notes */
|
/** (optional) notes */
|
||||||
|
|||||||
@@ -1,6 +1,4 @@
|
|||||||
|
|
||||||
export const formatYearMonth = (yearMonth: number): string => {
|
export const formatYearMonth = (year: number, month:number): string => {
|
||||||
const year = Math.floor(yearMonth / 100);
|
|
||||||
const month = yearMonth % 100;
|
|
||||||
return `${year}-${month<10?"0":""}${month}`;
|
return `${year}-${month<10?"0":""}${month}`;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { LocationEditForm } from '@/app/ui/LocationEditForm';
|
import { LocationEditForm } from '@/app/ui/LocationEditForm';
|
||||||
|
|
||||||
export default async function Page({ params:{ id:yearMonth } }: { params: { id:string } }) {
|
export default async function Page({ params:{ id } }: { params: { id:string } }) {
|
||||||
|
|
||||||
return (<LocationEditForm yearMonth={yearMonth} />);
|
const [year, month] = id.split("-");
|
||||||
|
return (<LocationEditForm year={year} month={month} />);
|
||||||
}
|
}
|
||||||
31
app/page.tsx
31
app/page.tsx
@@ -6,14 +6,19 @@ import { PageFooter } from './ui/PageFooter';
|
|||||||
import { isAuthErrorMessage } from '@/app/lib/auth';
|
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';
|
||||||
|
|
||||||
const getNextYearMonth = (yearMonth:number) => {
|
const getNextYearMonth = (year:number, month:number) => {
|
||||||
return(yearMonth % 100 === 12 ? yearMonth + 89 : yearMonth + 1);
|
return({
|
||||||
|
year: month<12 ? year+1 : year,
|
||||||
|
month: month<12 ? month+1 : 1
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export const Page = async () => {
|
export const Page = async () => {
|
||||||
|
|
||||||
const locations = await fetchAllLocations();
|
const locations = await fetchAllLocations();
|
||||||
|
const availableYearMonths = await fetchAvailableYears();
|
||||||
|
|
||||||
if(isAuthErrorMessage(locations)) {
|
if(isAuthErrorMessage(locations)) {
|
||||||
return (
|
return (
|
||||||
@@ -24,11 +29,14 @@ 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 currentYearMonth = new Date().getFullYear() * 100 + new Date().getMonth() + 1;
|
|
||||||
|
const currentYear = new Date().getFullYear();
|
||||||
|
const currentMonth = 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 yearMonth={currentYearMonth} />
|
<MonthTitle year={currentYear} month={currentMonth} />
|
||||||
<AddLocationButton yyyymm={currentYearMonth} />
|
<AddLocationButton year={currentYear} month={currentMonth} />
|
||||||
<PageFooter />
|
<PageFooter />
|
||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
@@ -38,13 +46,13 @@ 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 nextYearMonth={getNextYearMonth(locations[0].yearMonth)} />
|
<AddMonthButton {...getNextYearMonth(locations[0].year, locations[0].month)} />
|
||||||
{
|
{
|
||||||
locations.map((location, ix, array) => {
|
locations.map((location, ix, array) => {
|
||||||
|
|
||||||
const isFirstLocationInMonth = ix === 0 || location.yearMonth !== array[ix-1].yearMonth;
|
const isFirstLocationInMonth = ix === 0 || location.year !== array[ix-1].year || location.month !== array[ix-1].month;
|
||||||
const isLastLocationInMonth = location.yearMonth !== array[ix+1]?.yearMonth;
|
const isLastLocationInMonth = location.year !== array[ix+1]?.year || location.month !== array[ix+1]?.month;
|
||||||
const isLastLocationOfFirstMonth = isLastLocationInMonth && location.yearMonth === array[0].yearMonth;
|
const isLastLocationOfFirstMonth = isLastLocationInMonth && location.year === array[0].year && location.month === array[0].month;
|
||||||
|
|
||||||
if(isFirstLocationInMonth) {
|
if(isFirstLocationInMonth) {
|
||||||
monthlyExpense = 0;
|
monthlyExpense = 0;
|
||||||
@@ -57,13 +65,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.yearMonth} yearMonth={location.yearMonth} /> : null
|
<MonthTitle key={`${location.year}-${location.month}`} year={location.year} month={location.month} /> : 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.yearMonth}`} yyyymm={location.yearMonth} /> : null
|
<AddLocationButton key={`add-loc-${location.year}-${location.month}`} year={location.year} month={location.month} /> : null
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
isLastLocationInMonth && monthlyExpense>0 ?
|
isLastLocationInMonth && monthlyExpense>0 ?
|
||||||
@@ -80,6 +88,7 @@ export const Page = async () => {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
<PageFooter />
|
<PageFooter />
|
||||||
|
{ availableYearMonths.map(ym => <p key={`year-month-${ym}`}>{ym}</p>) }
|
||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,13 +2,15 @@ import { PlusCircleIcon } from "@heroicons/react/24/outline";
|
|||||||
|
|
||||||
|
|
||||||
export interface AddLocationButtonProps {
|
export interface AddLocationButtonProps {
|
||||||
/** year month at which the new billing location should be addes */
|
/** year at which the new billing location should be addes */
|
||||||
yyyymm: number
|
year: number
|
||||||
|
/** month at which the new billing location should be addes */
|
||||||
|
month: number
|
||||||
}
|
}
|
||||||
|
|
||||||
export const AddLocationButton:React.FC<AddLocationButtonProps> = ({yyyymm}) =>
|
export const AddLocationButton:React.FC<AddLocationButtonProps> = ({year,month}) =>
|
||||||
<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/${yyyymm}/add`} className="card-body tooltip self-center" data-tip="Add a new billing location">
|
<a href={`/location/${year}-${month<10?"0":""}${month}/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>
|
||||||
|
|||||||
@@ -2,10 +2,11 @@ import { PlusCircleIcon } from "@heroicons/react/24/outline";
|
|||||||
import React from "react";
|
import React from "react";
|
||||||
|
|
||||||
export interface AddMonthButtonProps {
|
export interface AddMonthButtonProps {
|
||||||
nextYearMonth: number;
|
year: number;
|
||||||
|
month: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const AddMonthButton:React.FC<AddMonthButtonProps> = ({ nextYearMonth }) =>
|
export const AddMonthButton:React.FC<AddMonthButtonProps> = ({ year, month }) =>
|
||||||
<a href={`/year-month/${nextYearMonth}/add`} className='grid self-center tooltip' data-tip="Dodaj novi mjesec">
|
<a href={`/year-month/${year}-${month<10?"0":""}${month}/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>
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ export interface LocationCardProps {
|
|||||||
location: BillingLocation
|
location: BillingLocation
|
||||||
}
|
}
|
||||||
|
|
||||||
export const LocationCard:FC<LocationCardProps> = ({location: { _id, name, yearMonth, bills }}) => {
|
export const LocationCard:FC<LocationCardProps> = ({location: { _id, name, year, month, 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, yearM
|
|||||||
<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(yearMonth)} {name}</h2>
|
<h2 className="card-title">{formatYearMonth(year, month)} {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} />)
|
||||||
|
|||||||
@@ -10,14 +10,16 @@ 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 month at a new billing location should be assigned */
|
/** year at a new billing location should be assigned */
|
||||||
yearMonth?: string
|
year?: string
|
||||||
|
/** month at a new billing location should be assigned */
|
||||||
|
month?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export const LocationEditForm:FC<LocationEditFormProps> = ({ location, yearMonth }) =>
|
export const LocationEditForm:FC<LocationEditFormProps> = ({ location, year, month }) =>
|
||||||
{
|
{
|
||||||
const initialState = { message: null, errors: {} };
|
const initialState = { message: null, errors: {} };
|
||||||
const handleAction = updateOrAddLocation.bind(null, location?._id, yearMonth);
|
const handleAction = updateOrAddLocation.bind(null, location?._id, year, month);
|
||||||
const [ state, dispatch ] = useFormState(handleAction, initialState);
|
const [ state, dispatch ] = useFormState(handleAction, initialState);
|
||||||
|
|
||||||
// redirect to the main page
|
// redirect to the main page
|
||||||
|
|||||||
@@ -2,8 +2,9 @@ import { FC } from "react";
|
|||||||
import { formatYearMonth } from "../lib/format";
|
import { formatYearMonth } from "../lib/format";
|
||||||
|
|
||||||
export interface MonthTitleProps {
|
export interface MonthTitleProps {
|
||||||
yearMonth: number;
|
year: number;
|
||||||
|
month: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const MonthTitle:FC<MonthTitleProps> = ({yearMonth}) =>
|
export const MonthTitle:FC<MonthTitleProps> = ({year, month}) =>
|
||||||
<div className="divider text-2xl">{`${formatYearMonth(yearMonth)}`}</div>
|
<div className="divider text-2xl">{`${formatYearMonth(year, month)}`}</div>
|
||||||
@@ -1,10 +1,12 @@
|
|||||||
import { addYearMonth } from '@/app/lib/actions/yearMonthActions';
|
import { addMonth } from '@/app/lib/actions/monthActions';
|
||||||
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 } }) {
|
||||||
|
|
||||||
await addYearMonth(id);
|
const [year, month] = id.split("-");
|
||||||
|
|
||||||
|
await addMonth(year, month);
|
||||||
|
|
||||||
revalidatePath('/');
|
revalidatePath('/');
|
||||||
redirect(`/`);
|
redirect(`/`);
|
||||||
|
|||||||
Reference in New Issue
Block a user