implemented location edit
This commit is contained in:
@@ -15,6 +15,7 @@ export interface BillingLocation {
|
||||
/** the value is encoded as yyyymm (i.e. 202301) */
|
||||
yearMonth: number;
|
||||
bills: Bill[];
|
||||
notes: string|null;
|
||||
};
|
||||
|
||||
/** Bill basic data */
|
||||
|
||||
107
app/lib/locationActions.ts
Normal file
107
app/lib/locationActions.ts
Normal file
@@ -0,0 +1,107 @@
|
||||
'use server';
|
||||
|
||||
import { z } from 'zod';
|
||||
import { revalidatePath } from 'next/cache';
|
||||
import { redirect } from 'next/navigation';
|
||||
import clientPromise from './mongodb';
|
||||
import { BillingLocation } from './db-types';
|
||||
import { ObjectId } from 'mongodb';
|
||||
|
||||
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 async function updateOrAddLocation(locationId?: 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 client = await clientPromise;
|
||||
const db = client.db("rezije");
|
||||
|
||||
if(locationId) {
|
||||
await db.collection<BillingLocation>("lokacije").updateOne(
|
||||
{
|
||||
_id: locationId // find a location with the given locationID
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
name: locationName,
|
||||
notes: locationNotes,
|
||||
}
|
||||
});
|
||||
} else {
|
||||
await db.collection<BillingLocation>("lokacije").insertOne({
|
||||
_id: (new ObjectId()).toHexString(),
|
||||
name: locationName,
|
||||
notes: locationNotes,
|
||||
yearMonth: 202101, // ToDo: get the current year and month
|
||||
bills: [],
|
||||
});
|
||||
}
|
||||
|
||||
// clear the cache for the path
|
||||
revalidatePath('/');
|
||||
// go to the bill list
|
||||
redirect('/');
|
||||
}
|
||||
|
||||
export const fetchLocationById = async (locationID:string) => {
|
||||
const client = await clientPromise;
|
||||
const db = client.db("rezije");
|
||||
|
||||
// find a location with the given locationID
|
||||
const billLocation = await db.collection<BillingLocation>("lokacije").findOne({ _id: locationID });
|
||||
|
||||
if(!billLocation) {
|
||||
console.log(`Location ${locationID} not found`);
|
||||
return(null);
|
||||
}
|
||||
|
||||
return(billLocation);
|
||||
}
|
||||
|
||||
export const deleteLocationById = async (locationID:string) => {
|
||||
const client = await clientPromise;
|
||||
const db = client.db("rezije");
|
||||
|
||||
// find a location with the given locationID
|
||||
const post = await db.collection<BillingLocation>("lokacije").deleteOne({ _id: locationID });
|
||||
|
||||
return(post.deletedCount);
|
||||
}
|
||||
4
app/location/[id]/edit/not-found.tsx
Normal file
4
app/location/[id]/edit/not-found.tsx
Normal file
@@ -0,0 +1,4 @@
|
||||
import { NotFoundPage } from '@/app/ui/NotFoundPage';
|
||||
|
||||
export default () =>
|
||||
<NotFoundPage title="404 Location Not Found" description="Could not find the requested Location." />;
|
||||
18
app/location/[id]/edit/page.tsx
Normal file
18
app/location/[id]/edit/page.tsx
Normal file
@@ -0,0 +1,18 @@
|
||||
import { BillingLocation, Bill } from '@/app/lib/db-types';
|
||||
import { fetchBillById } from '@/app/lib/billActions';
|
||||
import clientPromise from '@/app/lib/mongodb';
|
||||
import { BillEditForm } from '@/app/ui/BillEditForm';
|
||||
import { ObjectId } from 'mongodb';
|
||||
import { notFound } from 'next/navigation';
|
||||
import { LocationEditForm } from '@/app/ui/LocationEditForm';
|
||||
import { fetchLocationById } from '@/app/lib/locationActions';
|
||||
|
||||
export default async function Page({ params:{ id } }: { params: { id:string } }) {
|
||||
|
||||
const location = await fetchLocationById(id);
|
||||
|
||||
if (!location) {
|
||||
return(notFound());
|
||||
}
|
||||
return (<LocationEditForm location={location} />);
|
||||
}
|
||||
@@ -1,18 +1,76 @@
|
||||
"use client";
|
||||
|
||||
import { TrashIcon } from "@heroicons/react/24/outline";
|
||||
import { FC } from "react";
|
||||
import { BillingLocation } from "../lib/db-types";
|
||||
import { updateOrAddLocation } from "../lib/locationActions";
|
||||
import { useFormState } from "react-dom";
|
||||
import { gotoHome } from "../lib/billActions";
|
||||
|
||||
export interface LocationEditFormProps {
|
||||
|
||||
/** location which should be edited */
|
||||
location?: BillingLocation
|
||||
}
|
||||
|
||||
export const LocationEditForm:FC<LocationEditFormProps> = () =>
|
||||
<div className="card card-compact card-bordered max-w-sm bg-base-100 shadow-s my-1">
|
||||
<div className="card-body">
|
||||
<form>
|
||||
<TrashIcon className="h-[1em] w-[1em] absolute cursor-pointer text-error bottom-5 right-4 text-2xl" />
|
||||
<input type="text" placeholder="Naziv lokacije" className="input input-bordered w-full" defaultValue="Budakova" />
|
||||
<textarea className="textarea textarea-bordered my-1 w-full max-w-sm block" placeholder="Opis" value="Stan u Budakovoj"></textarea>
|
||||
<button className="btn btn-primary">Spremi</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
export const LocationEditForm:FC<LocationEditFormProps> = ({ location }) =>
|
||||
{
|
||||
const initialState = { message: null, errors: {} };
|
||||
const handleAction = updateOrAddLocation.bind(null, location?._id);
|
||||
const [ state, dispatch ] = useFormState(handleAction, initialState);
|
||||
|
||||
// redirect to the main page
|
||||
const handleCancel = () => {
|
||||
console.log('handleCancel');
|
||||
gotoHome();
|
||||
};
|
||||
|
||||
return(
|
||||
<main>
|
||||
<div className="card card-compact card-bordered max-w-sm bg-base-100 shadow-s my-1">
|
||||
<div className="card-body">
|
||||
<form action={dispatch}>
|
||||
{
|
||||
// show delete button only if location is set (otherwise it's a add operation)
|
||||
location ?
|
||||
<a href={`/location/${location._id}/delete`} className="card-subtitle tooltip" data-tip="Delete Location">
|
||||
<TrashIcon className="h-[1em] w-[1em] absolute cursor-pointer text-error bottom-5 right-4 text-2xl" />
|
||||
</a> : null
|
||||
}
|
||||
|
||||
<input id="locationName" name="locationName" type="text" placeholder="Naziv lokacije" className="input input-bordered w-full" defaultValue={location?.name ?? ""} />
|
||||
<div id="status-error" aria-live="polite" aria-atomic="true">
|
||||
{state.errors?.locationName &&
|
||||
state.errors.locationName.map((error: string) => (
|
||||
<p className="mt-2 text-sm text-red-500" key={error}>
|
||||
{error}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<textarea id="locationNotes" name="locationNotes" className="textarea textarea-bordered my-1 w-full max-w-sm block" placeholder="Opis" defaultValue={location?.notes ?? ""}></textarea>
|
||||
<div id="status-error" aria-live="polite" aria-atomic="true">
|
||||
{state.errors?.locationNotes &&
|
||||
state.errors.locationNotes.map((error: string) => (
|
||||
<p className="mt-2 text-sm text-red-500" key={error}>
|
||||
{error}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div id="status-error" aria-live="polite" aria-atomic="true">
|
||||
{
|
||||
state.message &&
|
||||
<p className="mt-2 text-sm text-red-500">
|
||||
{state.message}
|
||||
</p>
|
||||
}
|
||||
</div>
|
||||
|
||||
<button className="btn btn-primary">Save</button>
|
||||
<button type="button" className="btn btn-neutral ml-3" onClick={handleCancel}>Cancel</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user