implemente bill add

This commit is contained in:
2024-01-05 14:20:00 +01:00
parent 73029fb28a
commit 245cc38717
9 changed files with 69 additions and 46 deletions

View File

@@ -4,7 +4,8 @@ import { z } from 'zod';
import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
import clientPromise from './mongodb';
import { BillAttachment, Bill } from './db-types';
import { BillAttachment, Bill, BillingLocation } from './db-types';
import { ObjectId } from 'mongodb';
export type State = {
errors?: {
@@ -61,14 +62,14 @@ const serializeAttachment = async (billAttachment: File | null) => {
}
/**
* Server-side action which creates a new bill
* Server-side action which adds or updates a bill
* @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 async function updateBill(locationId: string, billId:string, prevState:State, formData: FormData) {
export async function updateOrAddBill(locationId: string, billId?:string, prevState:State, formData: FormData) {
const validatedFields = UpdateBill.safeParse({
billName: formData.get('billName'),
@@ -110,19 +111,37 @@ export async function updateBill(locationId: string, billId:string, prevState:St
"bills.$[elem].notes": billNotes,
};
// find a location with the given locationID
const post = await db.collection<BillingLocation>("lokacije").updateOne(
{
_id: locationId // find a location with the given locationID
},
{
$set: mongoDbSet
}, {
arrayFilters: [
{ "elem._id": { $eq: billId } } // find a bill with the given billID
]
});
if(billId) {
// find a location with the given locationID
const post = await db.collection<BillingLocation>("lokacije").updateOne(
{
_id: locationId // find a location with the given locationID
},
{
$set: mongoDbSet
}, {
arrayFilters: [
{ "elem._id": { $eq: billId } } // find a bill with the given billID
]
});
} else {
// find a location with the given locationID
const post = await db.collection<BillingLocation>("lokacije").updateOne(
{
_id: locationId // find a location with the given locationID
},
{
$push: {
bills: {
_id: (new ObjectId()).toHexString(),
name: billName,
paid: billPaid,
attachment: billAttachment,
notes: billNotes,
}
}
});
}
// clear the cache for the path
revalidatePath('/');
@@ -147,20 +166,14 @@ export const fetchBillById = async (locationID:string, billID:string) => {
}
// find a bill with the given billID
const Bill = billLocation?.bills.find(({ _id }) => _id.toString() === billID);
const bill = billLocation?.bills.find(({ _id }) => _id.toString() === billID);
if(!Bill) {
if(!bill) {
console.log('Bill not found');
return(null);
}
const { _id, ...billBase } = Bill;
return({
id: _id.toString(),
...billBase
} as Bill);
return(bill);
}
export const deleteBillById = async (locationID:string, billID:string) => {