'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 addYearMonth = withUser(async (user:AuthenticatedUser, yearMonthString: string) => { const { id: userId } = user; // update the bill in the mongodb const dbClient = await getDbClient(); const yearMonth = parseInt(yearMonthString); const prevYearMonth = (yearMonth - 1) % 100 === 0 ? yearMonth - 89 : yearMonth - 1; // find all locations for the previous month const prevMonthLocations = await dbClient.collection("lokacije").find({ userId, // make sure that the locations belongs to the user yearMonth: prevYearMonth }); const newMonthLocationsCursor = prevMonthLocations.map((prevLocation) => { return({ // copy all the properties from the previous location ...prevLocation, // assign a new ID _id: (new ObjectId()).toHexString(), yearMonth, // 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("lokacije").insertMany(newMonthLocations); // clear the cache for the path revalidatePath('/'); // go to the bill list redirect('/'); }); export async function gotoHome() { redirect('/'); } export const fetchBillById = withUser(async (user:AuthenticatedUser, locationID:string, billID:string) => { const { id: userId } = user; const dbClient = await getDbClient(); // find a location with the given locationID const billLocation = await dbClient.collection("lokacije").findOne({ _id: locationID, userId // make sure that the location belongs to the user }) 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("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); });