81 lines
2.6 KiB
TypeScript
81 lines
2.6 KiB
TypeScript
'use server';
|
|
|
|
import { revalidatePath } from 'next/cache';
|
|
import { redirect } from 'next/navigation';
|
|
import clientPromise, { getDbClient } from '../dbClient';
|
|
import { ObjectId } from 'mongodb';
|
|
import { BillingLocation } from '../db-types';
|
|
import { AuthenticatedUser } from '../types/next-auth';
|
|
import { withUser } from '../auth';
|
|
|
|
/**
|
|
* Server-side action which adds a new month to the database
|
|
* @param locationId location of the bill
|
|
* @param billId ID of the bill
|
|
* @param prevState previous state of the form
|
|
* @param formData form data
|
|
* @returns
|
|
*/
|
|
export const addMonth = withUser(async (user:AuthenticatedUser, yearString: string, monthString: string) => {
|
|
const { id: userId } = user;
|
|
|
|
// update the bill in the mongodb
|
|
const dbClient = await getDbClient();
|
|
|
|
const year = parseInt(yearString);
|
|
const month = parseInt(monthString);
|
|
|
|
const prevYear = month === 1 ? year - 1 : year;
|
|
const prevMonth = month === 1 ? 12 : month - 1;
|
|
|
|
// find all locations for the previous month
|
|
const prevMonthLocations = await dbClient.collection<BillingLocation>("lokacije").find({
|
|
userId, // make sure that the locations belongs to the user
|
|
year: prevYear,
|
|
month: prevMonth,
|
|
});
|
|
|
|
const newMonthLocationsCursor = prevMonthLocations.map((prevLocation) => {
|
|
return({
|
|
// copy all the properties from the previous location
|
|
...prevLocation,
|
|
// assign a new ID
|
|
_id: (new ObjectId()).toHexString(),
|
|
year: year,
|
|
month: month,
|
|
// copy bill array, but set all bills to unpaid and remove attachments and notes
|
|
bills: prevLocation.bills.map((bill) => {
|
|
return {
|
|
...bill,
|
|
paid: false,
|
|
attachment: null,
|
|
notes: null,
|
|
}
|
|
})
|
|
} as BillingLocation);
|
|
});
|
|
|
|
const newMonthLocations = await newMonthLocationsCursor.toArray()
|
|
await dbClient.collection<BillingLocation>("lokacije").insertMany(newMonthLocations);
|
|
|
|
// clear the cache for the path
|
|
revalidatePath('/');
|
|
// go to the bill list
|
|
redirect('/');
|
|
});
|
|
|
|
export async function gotoHome() {
|
|
redirect('/');
|
|
}
|
|
|
|
export const fetchAvailableYears = withUser(async (user:AuthenticatedUser) => {
|
|
const { id: userId } = user;
|
|
|
|
const dbClient = await getDbClient();
|
|
|
|
// query mnogodb for all `yearMonth` values
|
|
const yearMonths = await dbClient.collection<BillingLocation>("lokacije").distinct("year", { userId });
|
|
|
|
return(yearMonths);
|
|
})
|