From bf41292b28941180a06fd530bff03f991227af9f Mon Sep 17 00:00:00 2001 From: Sianida26 Date: Sat, 27 Jan 2024 22:23:41 +0700 Subject: [PATCH] Added upsert role action --- .../roles/_modals/FormModal/FormModal.tsx | 64 ++++++++++------- src/app/dashboard/(auth)/roles/page.tsx | 4 -- .../dashboard/roles/actions/upsertRole.ts | 68 +++++++++++++++++++ 3 files changed, 109 insertions(+), 27 deletions(-) create mode 100644 src/features/dashboard/roles/actions/upsertRole.ts diff --git a/src/app/dashboard/(auth)/roles/_modals/FormModal/FormModal.tsx b/src/app/dashboard/(auth)/roles/_modals/FormModal/FormModal.tsx index 93e2eb1..d2f7471 100644 --- a/src/app/dashboard/(auth)/roles/_modals/FormModal/FormModal.tsx +++ b/src/app/dashboard/(auth)/roles/_modals/FormModal/FormModal.tsx @@ -1,7 +1,9 @@ -"use client" +"use client"; +import upsertRole from "@/features/dashboard/roles/actions/upsertRole"; import roleFormDataSchema, { RoleFormData, } from "@/features/dashboard/roles/formSchemas/RoleFormData"; +import { showNotification } from "@/utils/notifications"; import { Flex, Modal, @@ -14,6 +16,7 @@ import { Checkbox, } from "@mantine/core"; import { useForm, zodResolver } from "@mantine/form"; +import { notifications } from "@mantine/notifications"; import { useRouter } from "next/navigation"; import React, { useState } from "react"; import { TbDeviceFloppy } from "react-icons/tb"; @@ -23,27 +26,48 @@ interface Props { readonly?: boolean; data: RoleFormData; opened: boolean; - onClose?: () => void + onClose?: () => void; } export default function FormModal(props: Props) { const router = useRouter(); const [isSubmitting, setSubmitting] = useState(false); - const [value, setValue] = useState("") + const [value, setValue] = useState(""); const form = useForm({ initialValues: props.data, validate: zodResolver(roleFormDataSchema), validateInputOnChange: false, - onValuesChange: (values) => {console.log(values)} + onValuesChange: (values) => { + console.log(values); + }, }); const closeModal = () => { - form.reset() + form.reset(); props.onClose ? props.onClose() : router.replace("?"); }; + const handleSubmit = (values: RoleFormData) => { + upsertRole(values) + .then((response) => { + if (response.success){ + showNotification(response.message,"success"); + return closeModal() + } else { + form.setErrors(response.errors ?? {}); + if (!response.errors){ + showNotification(response.message, "error") + } + } + }) + .catch(e =>{ + //TODO: Handle Error + console.log(e) + }) + } + return ( +
{/* ID */} {props.data.id ? ( @@ -60,7 +85,9 @@ export default function FormModal(props: Props) { variant="filled" {...form.getInputProps("id")} /> - ) :
} + ) : ( +
+ )} {/* Code */} {/* Description */} @@ -84,25 +111,15 @@ export default function FormModal(props: Props) { label="Description" readOnly={props.readonly} disabled={isSubmitting} - // {...form.getInputProps("description")} + {...form.getInputProps("description")} /> - - - - - {/* Buttons */} @@ -126,6 +143,7 @@ export default function FormModal(props: Props) { )}
+
); } diff --git a/src/app/dashboard/(auth)/roles/page.tsx b/src/app/dashboard/(auth)/roles/page.tsx index 6da690f..f4ba1dc 100644 --- a/src/app/dashboard/(auth)/roles/page.tsx +++ b/src/app/dashboard/(auth)/roles/page.tsx @@ -19,10 +19,6 @@ interface Props { } } -export const metadata: Metadata = { - title: "Roles", -}; - export default async function RolesPage({searchParams}: Props) { if (!(await checkPermission("role.readAll"))) { return unauthorized(); diff --git a/src/features/dashboard/roles/actions/upsertRole.ts b/src/features/dashboard/roles/actions/upsertRole.ts new file mode 100644 index 0000000..ce94a64 --- /dev/null +++ b/src/features/dashboard/roles/actions/upsertRole.ts @@ -0,0 +1,68 @@ +"use server" +import checkPermission from "@/features/auth/tools/checkPermission"; +import roleFormDataSchema, { RoleFormData } from "../formSchemas/RoleFormData"; +import { unauthorized } from "@/BaseError"; +import mapObjectToFirstValue from "@/utils/mapObjectToFirstValue"; +import prisma from "@/db"; +import { revalidatePath } from "next/cache"; + +export default async function upsertRole(data: RoleFormData){ + + const isInsert = !!data.id; + + if (isInsert && !await checkPermission("role.create")){ + return unauthorized(); + } + + if (!isInsert && !await checkPermission("role.update")){ + return unauthorized(); + } + + const validatedFields = roleFormDataSchema.safeParse(data); + if (!validatedFields.success){ + return { + success: false, + message: "Invalid Form Data", + errors: mapObjectToFirstValue(validatedFields.error.flatten().fieldErrors) + } as const + } + + // Update user data in the database + try { + if (isInsert){ + await prisma.role.update({ + where: { id: validatedFields.data.id!}, + data: { + code: validatedFields.data.code, + description: validatedFields.data.description, + isActive: validatedFields.data.isActive, + name: validatedFields.data.name + }, + }) + } else { + await prisma.role.create({ + data: { + code: validatedFields.data.code, + description: validatedFields.data.description, + name: validatedFields.data.name, + isActive: validatedFields.data.isActive + } + }) + } + + // Revalidate the cache + revalidatePath("."); + + return { + success: true, + message: `Role ${validatedFields.data.name} has been successfully ${isInsert ? "Updated" : "Created"}` + }; + } catch (error) { + // Consider handling specific database errors here + console.error('Error updating user data', error); + return { + success: false, + message: "Error updating user data" + }; + } +} \ No newline at end of file