'use server'; import { z } from 'zod'; import { revalidatePath } from 'next/cache'; import { redirect } from 'next/navigation'; import clientPromise from './mongodb'; import { ObjectId } from 'mongodb'; export type State = { errors?: { billName?: string[]; billAttachment?: string[], billNotes?: string[], }; message?:string | null; } const FormSchema = z.object({ _id: z.string(), billName: z.coerce.string().min(1, "Bill Name is required."), billAttachment: z.object({ }), billNotes: z.string(), }); const UpdateBill = FormSchema.omit({ _id: true }); export async function updateBill(locationId: string, billId:string, prevState:State, formData: FormData) { const validatedFields = UpdateBill.safeParse({ billName: formData.get('billName'), billAttachment: formData.get('billAttachment'), billNotes: formData.get('billNotes'), }); // If form validation fails, return errors early. Otherwise, continue... if(!validatedFields.success) { console.log("updateBill.validation-error"); return({ errors: validatedFields.error.flatten().fieldErrors, message: "Missing Fields. Field to Update Bill.", }); } const { billName, billAttachment, billNotes, } = validatedFields.data; const billPaid = formData.get('billPaid') === 'on'; // update the bill in the mongodb const client = await clientPromise; const db = client.db("rezije"); // find a location with the given locationID const post = await db.collection("lokacije").updateOne( { _id: locationId // find a location with the given locationID }, { $set: { "bills.$[elem].name": billName, "bills.$[elem].paid": billPaid, "bills.$[elem].attachment": billAttachment, "bills.$[elem].notes": billNotes, } }, { arrayFilters: [ { "elem._id": { $eq: new ObjectId(billId) } } // find a bill with the given billID ] }); // clear the cache for the path revalidatePath('/'); // go to the bill list redirect('/'); }