mirror of
https://github.com/prowler-cloud/prowler.git
synced 2026-07-22 03:51:53 +00:00
feat: edit role feature
This commit is contained in:
+107
-116
@@ -4,7 +4,7 @@ import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
import { auth } from "@/auth.config";
|
||||
import { parseStringify } from "@/lib";
|
||||
import { getErrorMessage, parseStringify } from "@/lib";
|
||||
|
||||
export const getRoles = async ({
|
||||
page = 1,
|
||||
@@ -48,127 +48,118 @@ export const getRoles = async ({
|
||||
}
|
||||
};
|
||||
|
||||
// export const sendInvite = async (formData: FormData) => {
|
||||
// const session = await auth();
|
||||
// const keyServer = process.env.API_BASE_URL;
|
||||
export const addRole = async (formData: FormData) => {
|
||||
const session = await auth();
|
||||
const keyServer = process.env.API_BASE_URL;
|
||||
|
||||
// const email = formData.get("email");
|
||||
// const url = new URL(`${keyServer}/tenants/invitations`);
|
||||
const url = new URL(`${keyServer}/roles`);
|
||||
const body = JSON.stringify({
|
||||
data: {
|
||||
type: "role",
|
||||
attributes: {
|
||||
name: formData.get("name"),
|
||||
manage_users: formData.get("manage_users") === "true",
|
||||
manage_account: formData.get("manage_account") === "true",
|
||||
manage_billing: formData.get("manage_billing") === "true",
|
||||
manage_providers: formData.get("manage_providers") === "true",
|
||||
manage_integrations: formData.get("manage_integrations") === "true",
|
||||
manage_scans: formData.get("manage_scans") === "true",
|
||||
unlimited_visibility: formData.get("unlimited_visibility") === "true",
|
||||
},
|
||||
relationships: {
|
||||
provider_groups: {
|
||||
data: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// const body = JSON.stringify({
|
||||
// data: {
|
||||
// type: "invitations",
|
||||
// attributes: {
|
||||
// email,
|
||||
// },
|
||||
// relationships: {},
|
||||
// },
|
||||
// });
|
||||
try {
|
||||
const response = await fetch(url.toString(), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/vnd.api+json",
|
||||
Accept: "application/vnd.api+json",
|
||||
Authorization: `Bearer ${session?.accessToken}`,
|
||||
},
|
||||
body,
|
||||
});
|
||||
const data = await response.json();
|
||||
revalidatePath("/roles");
|
||||
return data;
|
||||
} catch (error) {
|
||||
return {
|
||||
error: getErrorMessage(error),
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
// try {
|
||||
// const response = await fetch(url.toString(), {
|
||||
// method: "POST",
|
||||
// headers: {
|
||||
// "Content-Type": "application/vnd.api+json",
|
||||
// Accept: "application/vnd.api+json",
|
||||
// Authorization: `Bearer ${session?.accessToken}`,
|
||||
// },
|
||||
// body,
|
||||
// });
|
||||
// const data = await response.json();
|
||||
export const updateRole = async (formData: FormData, roleId: string) => {
|
||||
const session = await auth();
|
||||
const keyServer = process.env.API_BASE_URL;
|
||||
|
||||
// return parseStringify(data);
|
||||
// } catch (error) {
|
||||
// return {
|
||||
// error: getErrorMessage(error),
|
||||
// };
|
||||
// }
|
||||
// };
|
||||
const url = new URL(`${keyServer}/roles/${roleId}`);
|
||||
const body = JSON.stringify({
|
||||
data: {
|
||||
type: "role",
|
||||
id: roleId,
|
||||
attributes: {
|
||||
name: formData.get("name"),
|
||||
manage_users: formData.get("manage_users") === "true",
|
||||
manage_account: formData.get("manage_account") === "true",
|
||||
manage_billing: formData.get("manage_billing") === "true",
|
||||
manage_providers: formData.get("manage_providers") === "true",
|
||||
manage_integrations: formData.get("manage_integrations") === "true",
|
||||
manage_scans: formData.get("manage_scans") === "true",
|
||||
unlimited_visibility: formData.get("unlimited_visibility") === "true",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// export const updateInvite = async (formData: FormData) => {
|
||||
// const session = await auth();
|
||||
// const keyServer = process.env.API_BASE_URL;
|
||||
try {
|
||||
const response = await fetch(url.toString(), {
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
"Content-Type": "application/vnd.api+json",
|
||||
Accept: "application/vnd.api+json",
|
||||
Authorization: `Bearer ${session?.accessToken}`,
|
||||
},
|
||||
body,
|
||||
});
|
||||
const data = await response.json();
|
||||
revalidatePath("/roles");
|
||||
return data;
|
||||
} catch (error) {
|
||||
return {
|
||||
error: getErrorMessage(error),
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
// const invitationId = formData.get("invitationId");
|
||||
// const invitationEmail = formData.get("invitationEmail");
|
||||
// const expiresAt = formData.get("expires_at");
|
||||
export const deleteRole = async (roleId: string) => {
|
||||
const session = await auth();
|
||||
const keyServer = process.env.API_BASE_URL;
|
||||
|
||||
// const url = new URL(`${keyServer}/tenants/invitations/${invitationId}`);
|
||||
const url = new URL(`${keyServer}/roles/${roleId}`);
|
||||
try {
|
||||
const response = await fetch(url.toString(), {
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
Authorization: `Bearer ${session?.accessToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
// try {
|
||||
// const response = await fetch(url.toString(), {
|
||||
// method: "PATCH",
|
||||
// headers: {
|
||||
// "Content-Type": "application/vnd.api+json",
|
||||
// Accept: "application/vnd.api+json",
|
||||
// Authorization: `Bearer ${session?.accessToken}`,
|
||||
// },
|
||||
// body: JSON.stringify({
|
||||
// data: {
|
||||
// type: "invitations",
|
||||
// id: invitationId,
|
||||
// attributes: {
|
||||
// email: invitationEmail,
|
||||
// ...(expiresAt && { expires_at: expiresAt }),
|
||||
// },
|
||||
// },
|
||||
// }),
|
||||
// });
|
||||
// const data = await response.json();
|
||||
// revalidatePath("/invitations");
|
||||
// return parseStringify(data);
|
||||
// } catch (error) {
|
||||
// // eslint-disable-next-line no-console
|
||||
// console.error("Error updating invitation:", error);
|
||||
// return {
|
||||
// error: getErrorMessage(error),
|
||||
// };
|
||||
// }
|
||||
// };
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData?.message || "Failed to delete the role");
|
||||
}
|
||||
|
||||
// export const getInvitationInfoById = async (invitationId: string) => {
|
||||
// const session = await auth();
|
||||
// const keyServer = process.env.API_BASE_URL;
|
||||
// const url = new URL(`${keyServer}/tenants/invitations/${invitationId}`);
|
||||
|
||||
// try {
|
||||
// const response = await fetch(url.toString(), {
|
||||
// method: "GET",
|
||||
// headers: {
|
||||
// Accept: "application/vnd.api+json",
|
||||
// Authorization: `Bearer ${session?.accessToken}`,
|
||||
// },
|
||||
// });
|
||||
|
||||
// const data = await response.json();
|
||||
// return parseStringify(data);
|
||||
// } catch (error) {
|
||||
// return {
|
||||
// error: getErrorMessage(error),
|
||||
// };
|
||||
// }
|
||||
// };
|
||||
|
||||
// export const revokeInvite = async (formData: FormData) => {
|
||||
// const session = await auth();
|
||||
// const keyServer = process.env.API_BASE_URL;
|
||||
|
||||
// const invitationId = formData.get("invitationId");
|
||||
// const url = new URL(`${keyServer}/tenants/invitations/${invitationId}`);
|
||||
// try {
|
||||
// const response = await fetch(url.toString(), {
|
||||
// method: "DELETE",
|
||||
// headers: {
|
||||
// Authorization: `Bearer ${session?.accessToken}`,
|
||||
// },
|
||||
// });
|
||||
// const data = await response.json();
|
||||
// await wait(1000);
|
||||
// revalidatePath("/invitations");
|
||||
// return parseStringify(data);
|
||||
// } catch (error) {
|
||||
// return {
|
||||
// error: getErrorMessage(error),
|
||||
// };
|
||||
// }
|
||||
// };
|
||||
const data = await response.json();
|
||||
revalidatePath("/roles");
|
||||
return data;
|
||||
} catch (error) {
|
||||
return {
|
||||
error: getErrorMessage(error),
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import React from "react";
|
||||
|
||||
import { EditRoleForm } from "@/components/roles/workflow/forms/edit-role-form";
|
||||
import { SearchParamsProps } from "@/types";
|
||||
|
||||
export default function EditRolePage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: SearchParamsProps;
|
||||
}) {
|
||||
if (!searchParams.roleId || Array.isArray(searchParams.roleId)) {
|
||||
redirect("/roles");
|
||||
}
|
||||
|
||||
return <EditRoleForm roleId={searchParams.roleId} />;
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import { DateWithTime } from "@/components/ui/entities";
|
||||
import { DataTableColumnHeader } from "@/components/ui/table";
|
||||
import { RolesProps } from "@/types";
|
||||
|
||||
import { DataTableRowActions } from "./data-table-row-actions";
|
||||
|
||||
const getRoleAttributes = (row: { original: RolesProps["data"][number] }) => {
|
||||
return row.original.attributes;
|
||||
};
|
||||
@@ -100,4 +102,12 @@ export const ColumnsRoles: ColumnDef<RolesProps["data"][number]>[] = [
|
||||
return <DateWithTime dateTime={inserted_at} showTime={false} />;
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "actions",
|
||||
header: () => <div className="text-right">Actions</div>,
|
||||
id: "actions",
|
||||
cell: ({ row }) => {
|
||||
return <DataTableRowActions row={row} />;
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
@@ -9,52 +9,38 @@ import {
|
||||
DropdownTrigger,
|
||||
} from "@nextui-org/react";
|
||||
import {
|
||||
AddNoteBulkIcon,
|
||||
DeleteDocumentBulkIcon,
|
||||
EditDocumentBulkIcon,
|
||||
} from "@nextui-org/shared-icons";
|
||||
import { Row } from "@tanstack/react-table";
|
||||
import clsx from "clsx";
|
||||
import { useState } from "react";
|
||||
|
||||
import { VerticalDotsIcon } from "@/components/icons";
|
||||
import { CustomAlertModal } from "@/components/ui/custom/custom-alert-modal";
|
||||
|
||||
// import { DeleteForm, EditForm } from "../forms";
|
||||
|
||||
interface DataTableRowActionsProps<InvitationProps> {
|
||||
row: Row<InvitationProps>;
|
||||
import { DeleteRoleForm } from "../workflow/forms";
|
||||
interface DataTableRowActionsProps<RoleProps> {
|
||||
row: Row<RoleProps>;
|
||||
}
|
||||
const iconClasses =
|
||||
"text-2xl text-default-500 pointer-events-none flex-shrink-0";
|
||||
|
||||
export function DataTableRowActions<InvitationProps>({
|
||||
export function DataTableRowActions<RoleProps>({
|
||||
row,
|
||||
}: DataTableRowActionsProps<InvitationProps>) {
|
||||
// const [isEditOpen, setIsEditOpen] = useState(false);
|
||||
// const [isDeleteOpen, setIsDeleteOpen] = useState(false);
|
||||
const invitationId = (row.original as { id: string }).id;
|
||||
}: DataTableRowActionsProps<RoleProps>) {
|
||||
const [isDeleteOpen, setIsDeleteOpen] = useState(false);
|
||||
const roleId = (row.original as { id: string }).id;
|
||||
return (
|
||||
<>
|
||||
{/* <CustomAlertModal
|
||||
isOpen={isEditOpen}
|
||||
onOpenChange={setIsEditOpen}
|
||||
title="Edit Invitation"
|
||||
description={"Edit the invitation details"}
|
||||
>
|
||||
<EditForm
|
||||
invitationId={invitationId}
|
||||
invitationEmail={invitationEmail}
|
||||
setIsOpen={setIsEditOpen}
|
||||
/>
|
||||
</CustomAlertModal> */}
|
||||
{/* <CustomAlertModal
|
||||
<CustomAlertModal
|
||||
isOpen={isDeleteOpen}
|
||||
onOpenChange={setIsDeleteOpen}
|
||||
title="Are you absolutely sure?"
|
||||
description="This action cannot be undone. This will permanently revoke your invitation."
|
||||
description="This action cannot be undone. This will permanently delete your role and remove your data from the server."
|
||||
>
|
||||
<DeleteForm invitationId={invitationId} setIsOpen={setIsDeleteOpen} />
|
||||
</CustomAlertModal> */}
|
||||
|
||||
<DeleteRoleForm roleId={roleId} setIsOpen={setIsDeleteOpen} />
|
||||
</CustomAlertModal>
|
||||
<div className="relative flex items-center justify-end gap-2">
|
||||
<Dropdown
|
||||
className="shadow-xl dark:bg-prowler-blue-800"
|
||||
@@ -73,23 +59,13 @@ export function DataTableRowActions<InvitationProps>({
|
||||
>
|
||||
<DropdownSection title="Actions">
|
||||
<DropdownItem
|
||||
href={`/invitations/check-details?id=${invitationId}`}
|
||||
href={`/roles/edit?roleId=${roleId}`}
|
||||
key="check-details"
|
||||
description="View invitation details"
|
||||
textValue="Check Details"
|
||||
startContent={<AddNoteBulkIcon className={iconClasses} />}
|
||||
>
|
||||
Check Details
|
||||
</DropdownItem>
|
||||
|
||||
<DropdownItem
|
||||
key="edit"
|
||||
description="Allows you to edit the invitation"
|
||||
textValue="Edit Invitation"
|
||||
description="Edit the role details"
|
||||
textValue="Edit Role"
|
||||
startContent={<EditDocumentBulkIcon className={iconClasses} />}
|
||||
// onClick={() => setIsEditOpen(true)}
|
||||
>
|
||||
Edit Invitation
|
||||
Edit Role
|
||||
</DropdownItem>
|
||||
</DropdownSection>
|
||||
<DropdownSection title="Danger zone">
|
||||
@@ -97,16 +73,16 @@ export function DataTableRowActions<InvitationProps>({
|
||||
key="delete"
|
||||
className="text-danger"
|
||||
color="danger"
|
||||
description="Delete the invitation permanently"
|
||||
textValue="Delete Invitation"
|
||||
description="Delete the role permanently"
|
||||
textValue="Delete Role"
|
||||
startContent={
|
||||
<DeleteDocumentBulkIcon
|
||||
className={clsx(iconClasses, "!text-danger")}
|
||||
/>
|
||||
}
|
||||
// onClick={() => setIsDeleteOpen(true)}
|
||||
onClick={() => setIsDeleteOpen(true)}
|
||||
>
|
||||
Revoke Invitation
|
||||
Delete Role
|
||||
</DropdownItem>
|
||||
</DropdownSection>
|
||||
</DropdownMenu>
|
||||
|
||||
@@ -4,6 +4,7 @@ import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { Checkbox } from "@nextui-org/react";
|
||||
import { SaveIcon } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
|
||||
@@ -33,8 +34,39 @@ export const AddRoleForm = () => {
|
||||
},
|
||||
});
|
||||
|
||||
const manageProviders = form.watch("manage_providers");
|
||||
|
||||
useEffect(() => {
|
||||
if (manageProviders) {
|
||||
form.setValue("unlimited_visibility", true, {
|
||||
shouldValidate: true,
|
||||
shouldDirty: true,
|
||||
shouldTouch: true,
|
||||
});
|
||||
}
|
||||
}, [manageProviders, form]);
|
||||
|
||||
const isLoading = form.formState.isSubmitting;
|
||||
|
||||
const onSelectAllChange = (checked: boolean) => {
|
||||
const permissions = [
|
||||
"manage_users",
|
||||
"manage_account",
|
||||
"manage_billing",
|
||||
"manage_providers",
|
||||
"manage_integrations",
|
||||
"manage_scans",
|
||||
"unlimited_visibility",
|
||||
];
|
||||
permissions.forEach((permission) => {
|
||||
form.setValue(permission as keyof FormValues, checked, {
|
||||
shouldValidate: true,
|
||||
shouldDirty: true,
|
||||
shouldTouch: true,
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const onSubmitClient = async (values: FormValues) => {
|
||||
const formData = new FormData();
|
||||
formData.append("name", values.name);
|
||||
@@ -72,7 +104,6 @@ export const AddRoleForm = () => {
|
||||
});
|
||||
} else {
|
||||
toast({
|
||||
variant: "success",
|
||||
title: "Role Added",
|
||||
description: "The role was added successfully.",
|
||||
});
|
||||
@@ -87,11 +118,21 @@ export const AddRoleForm = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const permissions = [
|
||||
{ field: "manage_users", label: "Invite and Manage Users" },
|
||||
{ field: "manage_account", label: "Manage SaaS Account" },
|
||||
{ field: "manage_billing", label: "Manage Billing" },
|
||||
{ field: "manage_providers", label: "Manage Cloud Accounts" },
|
||||
{ field: "manage_integrations", label: "Manage Integrations" },
|
||||
{ field: "manage_scans", label: "Manage Scans" },
|
||||
{ field: "unlimited_visibility", label: "Unlimited Visibility" },
|
||||
];
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form
|
||||
onSubmit={form.handleSubmit(onSubmitClient)}
|
||||
className="flex flex-col space-y-4"
|
||||
className="flex flex-col space-y-6"
|
||||
>
|
||||
<CustomInput
|
||||
control={form.control}
|
||||
@@ -105,19 +146,38 @@ export const AddRoleForm = () => {
|
||||
isInvalid={!!form.formState.errors.name}
|
||||
/>
|
||||
|
||||
{[
|
||||
"manage_users",
|
||||
"manage_account",
|
||||
"manage_billing",
|
||||
"manage_providers",
|
||||
"manage_integrations",
|
||||
"manage_scans",
|
||||
"unlimited_visibility",
|
||||
].map((field) => (
|
||||
<Checkbox key={field} {...form.register(field as keyof FormValues)}>
|
||||
{field.replace("_", " ")}
|
||||
<div className="flex flex-col space-y-4">
|
||||
<span className="text-lg font-semibold">Admin Permissions</span>
|
||||
|
||||
{/* Select All Checkbox */}
|
||||
<Checkbox
|
||||
isSelected={permissions.every((perm) =>
|
||||
form.watch(perm.field as keyof FormValues),
|
||||
)}
|
||||
onChange={(e) => onSelectAllChange(e.target.checked)}
|
||||
classNames={{
|
||||
label: "text-small",
|
||||
}}
|
||||
>
|
||||
Grant all admin permissions
|
||||
</Checkbox>
|
||||
))}
|
||||
|
||||
{/* Permissions Grid */}
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
{permissions.map(({ field, label }) => (
|
||||
<Checkbox
|
||||
key={field}
|
||||
{...form.register(field as keyof FormValues)}
|
||||
isSelected={!!form.watch(field as keyof FormValues)}
|
||||
classNames={{
|
||||
label: "text-small",
|
||||
}}
|
||||
>
|
||||
{label}
|
||||
</Checkbox>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex w-full justify-end sm:space-x-6">
|
||||
<CustomButton
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
"use client";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import React, { Dispatch, SetStateAction } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import * as z from "zod";
|
||||
|
||||
import { deleteRole } from "@/actions/roles";
|
||||
import { DeleteIcon } from "@/components/icons";
|
||||
import { useToast } from "@/components/ui";
|
||||
import { CustomButton } from "@/components/ui/custom";
|
||||
import { Form } from "@/components/ui/form";
|
||||
|
||||
const formSchema = z.object({
|
||||
roleId: z.string(),
|
||||
});
|
||||
|
||||
export const DeleteRoleForm = ({
|
||||
roleId,
|
||||
setIsOpen,
|
||||
}: {
|
||||
roleId: string;
|
||||
setIsOpen: Dispatch<SetStateAction<boolean>>;
|
||||
}) => {
|
||||
const form = useForm<z.infer<typeof formSchema>>({
|
||||
resolver: zodResolver(formSchema),
|
||||
});
|
||||
const { toast } = useToast();
|
||||
const isLoading = form.formState.isSubmitting;
|
||||
|
||||
async function onSubmitClient(formData: FormData) {
|
||||
const roleId = formData.get("id") as string;
|
||||
const data = await deleteRole(roleId);
|
||||
|
||||
if (data?.errors && data.errors.length > 0) {
|
||||
const error = data.errors[0];
|
||||
const errorMessage = `${error.detail}`;
|
||||
// show error
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Oops! Something went wrong",
|
||||
description: errorMessage,
|
||||
});
|
||||
} else {
|
||||
toast({
|
||||
title: "Success!",
|
||||
description: "The role was removed successfully.",
|
||||
});
|
||||
}
|
||||
setIsOpen(false); // Close the modal on success
|
||||
}
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form action={onSubmitClient}>
|
||||
<input type="hidden" name="id" value={roleId} />
|
||||
<div className="flex w-full justify-center sm:space-x-6">
|
||||
<CustomButton
|
||||
type="button"
|
||||
ariaLabel="Cancel"
|
||||
className="w-full bg-transparent"
|
||||
variant="faded"
|
||||
size="lg"
|
||||
radius="lg"
|
||||
onPress={() => setIsOpen(false)}
|
||||
isDisabled={isLoading}
|
||||
>
|
||||
<span>Cancel</span>
|
||||
</CustomButton>
|
||||
|
||||
<CustomButton
|
||||
type="submit"
|
||||
ariaLabel="Delete"
|
||||
className="w-full"
|
||||
variant="solid"
|
||||
color="danger"
|
||||
size="lg"
|
||||
isLoading={isLoading}
|
||||
startContent={!isLoading && <DeleteIcon size={24} />}
|
||||
>
|
||||
{isLoading ? <>Loading</> : <span>Delete</span>}
|
||||
</CustomButton>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,206 @@
|
||||
"use client";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { Checkbox } from "@nextui-org/react";
|
||||
import { SaveIcon } from "lucide-react";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { useEffect } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
|
||||
import { updateRole } from "@/actions/roles/roles";
|
||||
import { useToast } from "@/components/ui";
|
||||
import { CustomButton, CustomInput } from "@/components/ui/custom";
|
||||
import { Form } from "@/components/ui/form";
|
||||
import { ApiError, editRoleFormSchema } from "@/types";
|
||||
|
||||
export type FormValues = z.infer<typeof editRoleFormSchema>;
|
||||
|
||||
export const EditRoleForm = ({ roleId }: { roleId: string }) => {
|
||||
const { toast } = useToast();
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const searchRoleId = searchParams.get("roleId") || roleId;
|
||||
|
||||
const form = useForm<FormValues>({
|
||||
resolver: zodResolver(editRoleFormSchema),
|
||||
defaultValues: {
|
||||
roleId: roleId,
|
||||
},
|
||||
});
|
||||
|
||||
const { watch, setValue } = form;
|
||||
|
||||
const manageProviders = watch("manage_providers");
|
||||
const unlimitedVisibility = watch("unlimited_visibility");
|
||||
|
||||
useEffect(() => {
|
||||
if (manageProviders && !unlimitedVisibility) {
|
||||
setValue("unlimited_visibility", true, {
|
||||
shouldValidate: true,
|
||||
shouldDirty: true,
|
||||
shouldTouch: true,
|
||||
});
|
||||
}
|
||||
}, [manageProviders, unlimitedVisibility, setValue]);
|
||||
|
||||
const isLoading = form.formState.isSubmitting;
|
||||
|
||||
const onSelectAllChange = (checked: boolean) => {
|
||||
const permissions = [
|
||||
"manage_users",
|
||||
"manage_account",
|
||||
"manage_billing",
|
||||
"manage_providers",
|
||||
"manage_integrations",
|
||||
"manage_scans",
|
||||
"unlimited_visibility",
|
||||
];
|
||||
permissions.forEach((permission) => {
|
||||
form.setValue(permission as keyof FormValues, checked, {
|
||||
shouldValidate: true,
|
||||
shouldDirty: true,
|
||||
shouldTouch: true,
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const onSubmitClient = async (values: FormValues) => {
|
||||
if (!searchRoleId) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description: "Role ID is missing.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append("name", values.name);
|
||||
formData.append("manage_users", String(values.manage_users));
|
||||
formData.append("manage_account", String(values.manage_account));
|
||||
formData.append("manage_billing", String(values.manage_billing));
|
||||
formData.append("manage_providers", String(values.manage_providers));
|
||||
formData.append("manage_integrations", String(values.manage_integrations));
|
||||
formData.append("manage_scans", String(values.manage_scans));
|
||||
formData.append(
|
||||
"unlimited_visibility",
|
||||
String(values.unlimited_visibility),
|
||||
);
|
||||
|
||||
try {
|
||||
const data = await updateRole(formData, searchRoleId);
|
||||
|
||||
if (data?.errors && data.errors.length > 0) {
|
||||
data.errors.forEach((error: ApiError) => {
|
||||
const errorMessage = error.detail;
|
||||
switch (error.source.pointer) {
|
||||
case "/data/attributes/name":
|
||||
form.setError("name", {
|
||||
type: "server",
|
||||
message: errorMessage,
|
||||
});
|
||||
break;
|
||||
default:
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description: errorMessage,
|
||||
});
|
||||
}
|
||||
});
|
||||
} else {
|
||||
toast({
|
||||
title: "Role Updated",
|
||||
description: "The role was updated successfully.",
|
||||
});
|
||||
router.push("/roles");
|
||||
}
|
||||
} catch (error) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description: "An unexpected error occurred. Please try again.",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const permissions = [
|
||||
{ field: "manage_users", label: "Invite and Manage Users" },
|
||||
{ field: "manage_account", label: "Manage SaaS Account" },
|
||||
{ field: "manage_billing", label: "Manage Billing" },
|
||||
{ field: "manage_providers", label: "Manage Cloud Accounts" },
|
||||
{ field: "manage_integrations", label: "Manage Integrations" },
|
||||
{ field: "manage_scans", label: "Manage Scans" },
|
||||
{ field: "unlimited_visibility", label: "Unlimited Visibility" },
|
||||
];
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form
|
||||
onSubmit={form.handleSubmit(onSubmitClient)}
|
||||
className="flex flex-col space-y-6"
|
||||
>
|
||||
<CustomInput
|
||||
control={form.control}
|
||||
name="name"
|
||||
type="text"
|
||||
label="Role Name"
|
||||
labelPlacement="inside"
|
||||
placeholder="Enter role name"
|
||||
variant="bordered"
|
||||
isRequired
|
||||
isInvalid={!!form.formState.errors.name}
|
||||
/>
|
||||
|
||||
<div className="flex flex-col space-y-4">
|
||||
<span className="text-lg font-semibold">Admin Permissions</span>
|
||||
|
||||
{/* Select All Checkbox */}
|
||||
<Checkbox
|
||||
isSelected={permissions.every((perm) =>
|
||||
form.watch(perm.field as keyof FormValues),
|
||||
)}
|
||||
onChange={(e) => onSelectAllChange(e.target.checked)}
|
||||
classNames={{
|
||||
label: "text-small",
|
||||
}}
|
||||
>
|
||||
Grant all admin permissions
|
||||
</Checkbox>
|
||||
|
||||
{/* Permissions Grid */}
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
{permissions.map(({ field, label }) => (
|
||||
<Checkbox
|
||||
key={field}
|
||||
{...form.register(field as keyof FormValues)}
|
||||
isSelected={!!form.watch(field as keyof FormValues)}
|
||||
classNames={{
|
||||
label: "text-small",
|
||||
}}
|
||||
>
|
||||
{label}
|
||||
</Checkbox>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex w-full justify-end sm:space-x-6">
|
||||
<CustomButton
|
||||
type="submit"
|
||||
ariaLabel="Update Role"
|
||||
className="w-1/2"
|
||||
variant="solid"
|
||||
color="action"
|
||||
size="lg"
|
||||
isLoading={isLoading}
|
||||
startContent={!isLoading && <SaveIcon size={24} />}
|
||||
>
|
||||
{isLoading ? <>Loading</> : <span>Update Role</span>}
|
||||
</CustomButton>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
};
|
||||
@@ -1 +1,3 @@
|
||||
export * from "./add-role-form";
|
||||
export * from "./delete-role-form";
|
||||
export * from "./edit-role-form";
|
||||
|
||||
@@ -15,7 +15,7 @@ const steps = [
|
||||
{
|
||||
title: "Edit a existing role",
|
||||
description:
|
||||
"Review the role details and share the information required for the role.",
|
||||
"Update the role's details, including its name and permissions.",
|
||||
href: "/roles/edit",
|
||||
},
|
||||
];
|
||||
|
||||
@@ -11,6 +11,18 @@ export const addRoleFormSchema = z.object({
|
||||
unlimited_visibility: z.boolean().default(false),
|
||||
});
|
||||
|
||||
export const editRoleFormSchema = z.object({
|
||||
roleId: z.string().uuid(),
|
||||
name: z.string().min(1, "Name is required"),
|
||||
manage_users: z.boolean().default(false),
|
||||
manage_account: z.boolean().default(false),
|
||||
manage_billing: z.boolean().default(false),
|
||||
manage_providers: z.boolean().default(false),
|
||||
manage_integrations: z.boolean().default(false),
|
||||
manage_scans: z.boolean().default(false),
|
||||
unlimited_visibility: z.boolean().default(false),
|
||||
});
|
||||
|
||||
export const editScanFormSchema = (currentName: string) =>
|
||||
z.object({
|
||||
scanName: z
|
||||
|
||||
Reference in New Issue
Block a user