refactoring: actions moved to seprate dir

This commit is contained in:
2024-01-09 15:00:26 +01:00
parent af7d42891c
commit 8112c9765d
13 changed files with 56 additions and 58 deletions

View File

@@ -0,0 +1,256 @@
'use server';
import { z } from 'zod';
import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
import clientPromise, { getDbClient } from '../dbClient';
import { BillAttachment, BillingLocation } from '../db-types';
import { ObjectId } from 'mongodb';
import { withUser } from '@/app/lib/auth';
import { AuthenticatedUser } from '../types/next-auth';
export type State = {
errors?: {
billName?: string[];
billAttachment?: string[],
billNotes?: string[],
payedAmount?: string[],
};
message?:string | null;
}
const FormSchema = z.object({
_id: z.string(),
billName: z.coerce.string().min(1, "Bill Name is required."),
billNotes: z.string(),
payedAmount: z.string().nullable().transform((val, ctx) => {
if(!val || val === '') {
return null;
}
const parsed = parseFloat(val.replace(',', '.'));
if (isNaN(parsed)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Not a number",
});
// This is a special symbol you can use to
// return early from the transform function.
// It has type `never` so it does not affect the
// inferred return type.
return z.NEVER;
}
if (parsed < 0) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Value must be a positive number",
});
// This is a special symbol you can use to
// return early from the transform function.
// It has type `never` so it does not affect the
// inferred return type.
return z.NEVER;
}
return Math.floor(parsed * 100); // value is stored in cents
}),
});
parseFloat
const UpdateBill = FormSchema.omit({ _id: true });
/**
* converts the file to a format stored in the database
* @param billAttachment
* @returns
*/
const serializeAttachment = async (billAttachment: File | null) => {
if (!billAttachment) {
return null;
}
const {
name: fileName,
size: fileSize,
type: fileType,
lastModified: fileLastModified,
} = billAttachment;
if(!fileName || fileName === 'undefined') {
return null;
}
// convert the billAttachment file contents to format that can be stored in the database
const fileContents = await billAttachment.arrayBuffer();
const fileContentsBase64 = Buffer.from(fileContents).toString('base64');
// create an object to store the file in the database
return({
fileName,
fileSize,
fileType,
fileLastModified,
fileContentsBase64,
} as BillAttachment);
}
/**
* 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 const updateOrAddBill = withUser(async (user:AuthenticatedUser, locationId: string, billId?:string, prevState:State, formData: FormData) => {
const { id: userId } = user;
const x = formData.get('payedAmount');
const validatedFields = UpdateBill.safeParse({
billName: formData.get('billName'),
billNotes: formData.get('billNotes'),
payedAmount: formData.get('payedAmount'),
});
// 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,
billNotes,
payedAmount,
} = validatedFields.data;
const billPaid = formData.get('billPaid') === 'on';
// update the bill in the mongodb
const dbClient = await getDbClient();
const billAttachment = await serializeAttachment(formData.get('billAttachment') as File);
if(billId) {
// if there is an attachment, update the attachment field
// otherwise, do not update the attachment field
const mongoDbSet = billAttachment ? {
"bills.$[elem].name": billName,
"bills.$[elem].paid": billPaid,
"bills.$[elem].attachment": billAttachment,
"bills.$[elem].notes": billNotes,
"bills.$[elem].payedAmount": payedAmount,
}: {
"bills.$[elem].name": billName,
"bills.$[elem].paid": billPaid,
"bills.$[elem].notes": billNotes,
"bills.$[elem].payedAmount": payedAmount,
};
// 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
},
{
$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 dbClient.collection<BillingLocation>("lokacije").updateOne(
{
_id: locationId, // find a location with the given locationID
userId // make sure that the location belongs to the user
},
{
$push: {
bills: {
_id: (new ObjectId()).toHexString(),
name: billName,
paid: billPaid,
attachment: billAttachment,
notes: billNotes,
payedAmount
}
}
});
}
// clear the cache for the path
revalidatePath('/');
// go to the bill list
redirect('/');
})
export async function gotoHome() {
revalidatePath('/');
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<BillingLocation>("lokacije").findOne({ _id: locationID, userId })
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);
});

View File

@@ -0,0 +1,136 @@
'use server';
import { z } from 'zod';
import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
import clientPromise, { getDbClient } from '../dbClient';
import { BillingLocation } from '../db-types';
import { ObjectId } from 'mongodb';
import { auth, withUser } from '@/app/lib/auth';
import { AuthenticatedUser } from '../types/next-auth';
import { NormalizedRouteManifest } from 'next/dist/server/base-server';
export type State = {
errors?: {
locationName?: string[];
locationNotes?: string[],
};
message?:string | null;
}
const FormSchema = z.object({
_id: z.string(),
locationName: z.coerce.string().min(1, "Location Name is required."),
locationNotes: z.string(),
});
const UpdateLocation = FormSchema.omit({ _id: true });
/**
* Server-side action which adds or updates a bill
* @param locationId location of the bill
* @param prevState previous state of the form
* @param formData form data
* @returns
*/
export const updateOrAddLocation = withUser(async (user:AuthenticatedUser, locationId?: string, yearMonth?: string, prevState:State, formData: FormData) => {
const validatedFields = UpdateLocation.safeParse({
locationName: formData.get('locationName'),
locationNotes: formData.get('locationNotes'),
});
// If form validation fails, return errors early. Otherwise, continue...
if(!validatedFields.success) {
return({
errors: validatedFields.error.flatten().fieldErrors,
message: "Missing Fields",
});
}
const {
locationName,
locationNotes,
} = validatedFields.data;
// update the bill in the mongodb
const dbClient = await getDbClient();
const { id: userId, email: userEmail } = user;
if(locationId) {
await dbClient.collection<BillingLocation>("lokacije").updateOne(
{
_id: locationId, // find a location with the given locationID
userId // make sure the location belongs to the user
},
{
$set: {
name: locationName,
notes: locationNotes,
}
});
} else if(yearMonth) {
await dbClient.collection<BillingLocation>("lokacije").insertOne({
_id: (new ObjectId()).toHexString(),
userId,
userEmail,
name: locationName,
notes: locationNotes,
yearMonth: parseInt(yearMonth), // ToDo: get the current year and month
bills: [],
});
}
// clear the cache for the path
revalidatePath('/');
// go to the bill list
redirect('/');
});
export const fetchAllLocations = withUser(async (user:AuthenticatedUser, pageIx:number=0, pageSize:number=2000) => {
const dbClient = await getDbClient();
const { id: userId } = user;
// fetch `pageSize` locations for the given page index
const locations = await dbClient.collection<BillingLocation>("lokacije")
.find({ userId })
.sort({ yearMonth: -1, name: 1 })
.skip(pageIx * pageSize)
.limit(pageSize)
.toArray();
return(locations);
})
export const fetchLocationById = withUser(async (user:AuthenticatedUser, locationID:string) => {
const dbClient = await getDbClient();
const { id: userId } = user;
// find a location with the given locationID
const billLocation = await dbClient.collection<BillingLocation>("lokacije").findOne({ _id: locationID, userId});
if(!billLocation) {
console.log(`Location ${locationID} not found`);
return(null);
}
return(billLocation);
})
export const deleteLocationById = withUser(async (user:AuthenticatedUser, locationID:string) => {
const dbClient = await getDbClient();
const { id: userId } = user;
// find a location with the given locationID
const post = await dbClient.collection<BillingLocation>("lokacije").deleteOne({ _id: locationID, userId });
return(post.deletedCount);
})

View File

@@ -0,0 +1,115 @@
'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<BillingLocation>("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<BillingLocation>("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<BillingLocation>("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<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);
});