feat: add new role feature

This commit is contained in:
Pablo Lara
2024-12-10 07:24:01 +01:00
parent 010de4b415
commit e80704d6f0
10 changed files with 636 additions and 15 deletions
@@ -0,0 +1,32 @@
import "@/styles/globals.css";
import { Spacer } from "@nextui-org/react";
import React from "react";
import { WorkflowAddEditRole } from "@/components/roles/workflow";
import { NavigationHeader } from "@/components/ui";
interface RoleLayoutProps {
children: React.ReactNode;
}
export default function RoleLayout({ children }: RoleLayoutProps) {
return (
<>
<NavigationHeader
title="Role Management"
icon="icon-park-outline:close-small"
href="/roles"
/>
<Spacer y={16} />
<div className="grid grid-cols-1 gap-8 lg:grid-cols-12">
<div className="order-1 my-auto hidden h-full lg:col-span-4 lg:col-start-2 lg:block">
<WorkflowAddEditRole />
</div>
<div className="order-2 my-auto lg:col-span-5 lg:col-start-6">
{children}
</div>
</div>
</>
);
}
@@ -0,0 +1,7 @@
import React from "react";
import { AddRoleForm } from "@/components/roles/workflow/forms/add-role-form";
export default function AddRolePage() {
return <AddRoleForm />;
}
+23 -15
View File
@@ -60,24 +60,32 @@ export const ColumnsRoles: ColumnDef<RolesProps["data"][number]>[] = [
cell: ({ row }) => {
const relationships = getRoleRelationships(row);
return (
<p className="font-semibold">{relationships.invitations.meta.count}</p>
<p className="font-semibold">
{relationships.invitations.meta.count === 0
? "No Invitations"
: `${relationships.invitations.meta.count} ${
relationships.invitations.meta.count === 1
? "Invitation"
: "Invitations"
}`}
</p>
);
},
},
{
accessorKey: "updated_at",
header: ({ column }) => (
<DataTableColumnHeader
column={column}
title={"Updated At"}
param="updated_at"
/>
),
cell: ({ row }) => {
const { updated_at } = getRoleAttributes(row);
return <DateWithTime dateTime={updated_at} showTime={false} />;
},
},
// {
// accessorKey: "updated_at",
// header: ({ column }) => (
// <DataTableColumnHeader
// column={column}
// title={"Updated At"}
// param="updated_at"
// />
// ),
// cell: ({ row }) => {
// const { updated_at } = getRoleAttributes(row);
// return <DateWithTime dateTime={updated_at} showTime={false} />;
// },
// },
{
accessorKey: "inserted_at",
header: ({ column }) => (
@@ -0,0 +1,139 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import { Checkbox } from "@nextui-org/react";
import { SaveIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { addRole } from "@/actions/roles/roles";
import { useToast } from "@/components/ui";
import { CustomButton, CustomInput } from "@/components/ui/custom";
import { Form } from "@/components/ui/form";
import { addRoleFormSchema, ApiError } from "@/types";
export type FormValues = z.infer<typeof addRoleFormSchema>;
export const AddRoleForm = () => {
const { toast } = useToast();
const router = useRouter();
const form = useForm<FormValues>({
resolver: zodResolver(addRoleFormSchema),
defaultValues: {
name: "",
manage_users: false,
manage_account: false,
manage_billing: false,
manage_providers: false,
manage_integrations: false,
manage_scans: false,
unlimited_visibility: false,
},
});
const isLoading = form.formState.isSubmitting;
const onSubmitClient = async (values: FormValues) => {
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 addRole(formData);
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({
variant: "success",
title: "Role Added",
description: "The role was added successfully.",
});
router.push("/roles");
}
} catch (error) {
toast({
variant: "destructive",
title: "Error",
description: "An unexpected error occurred. Please try again.",
});
}
};
return (
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmitClient)}
className="flex flex-col space-y-4"
>
<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}
/>
{[
"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("_", " ")}
</Checkbox>
))}
<div className="flex w-full justify-end sm:space-x-6">
<CustomButton
type="submit"
ariaLabel="Add Role"
className="w-1/2"
variant="solid"
color="action"
size="lg"
isLoading={isLoading}
startContent={!isLoading && <SaveIcon size={24} />}
>
{isLoading ? <>Loading</> : <span>Add Role</span>}
</CustomButton>
</div>
</form>
</Form>
);
};
@@ -0,0 +1 @@
export * from "./add-role-form";
+3
View File
@@ -0,0 +1,3 @@
export * from "./skeleton-role-form";
export * from "./vertical-steps";
export * from "./workflow-add-edit-role";
@@ -0,0 +1,65 @@
import { Card, Skeleton } from "@nextui-org/react";
import React from "react";
export const SkeletonRoleForm = () => {
return (
<Card className="h-full w-full space-y-5 p-4" radius="sm">
{/* Table headers */}
<div className="hidden justify-between md:flex">
<Skeleton className="w-1/12 rounded-lg">
<div className="h-8 bg-default-200"></div>
</Skeleton>
<Skeleton className="w-2/12 rounded-lg">
<div className="h-8 bg-default-200"></div>
</Skeleton>
<Skeleton className="w-2/12 rounded-lg">
<div className="h-8 bg-default-200"></div>
</Skeleton>
<Skeleton className="w-2/12 rounded-lg">
<div className="h-8 bg-default-200"></div>
</Skeleton>
<Skeleton className="w-2/12 rounded-lg">
<div className="h-8 bg-default-200"></div>
</Skeleton>
<Skeleton className="w-1/12 rounded-lg">
<div className="h-8 bg-default-200"></div>
</Skeleton>
<Skeleton className="w-1/12 rounded-lg">
<div className="h-8 bg-default-200"></div>
</Skeleton>
</div>
{/* Table body */}
<div className="space-y-3">
{[...Array(3)].map((_, index) => (
<div
key={index}
className="flex flex-col items-center justify-between space-x-0 md:flex-row md:space-x-4"
>
<Skeleton className="mb-2 w-full rounded-lg md:mb-0 md:w-1/12">
<div className="h-12 bg-default-300"></div>
</Skeleton>
<Skeleton className="mb-2 w-full rounded-lg md:mb-0 md:w-2/12">
<div className="h-12 bg-default-300"></div>
</Skeleton>
<Skeleton className="mb-2 hidden rounded-lg sm:flex md:mb-0 md:w-2/12">
<div className="h-12 bg-default-300"></div>
</Skeleton>
<Skeleton className="mb-2 hidden rounded-lg sm:flex md:mb-0 md:w-2/12">
<div className="h-12 bg-default-300"></div>
</Skeleton>
<Skeleton className="mb-2 hidden rounded-lg sm:flex md:mb-0 md:w-2/12">
<div className="h-12 bg-default-300"></div>
</Skeleton>
<Skeleton className="mb-2 hidden rounded-lg sm:flex md:mb-0 md:w-1/12">
<div className="h-12 bg-default-300"></div>
</Skeleton>
<Skeleton className="mb-2 hidden rounded-lg sm:flex md:mb-0 md:w-1/12">
<div className="h-12 bg-default-300"></div>
</Skeleton>
</div>
))}
</div>
</Card>
);
};
@@ -0,0 +1,291 @@
"use client";
import type { ButtonProps } from "@nextui-org/react";
import { cn } from "@nextui-org/react";
import { useControlledState } from "@react-stately/utils";
import { domAnimation, LazyMotion, m } from "framer-motion";
import type { ComponentProps } from "react";
import React from "react";
export type VerticalStepProps = {
className?: string;
description?: React.ReactNode;
title?: React.ReactNode;
};
export interface VerticalStepsProps
extends React.HTMLAttributes<HTMLButtonElement> {
/**
* An array of steps.
*
* @default []
*/
steps?: VerticalStepProps[];
/**
* The color of the steps.
*
* @default "primary"
*/
color?: ButtonProps["color"];
/**
* The current step index.
*/
currentStep?: number;
/**
* The default step index.
*
* @default 0
*/
defaultStep?: number;
/**
* Whether to hide the progress bars.
*
* @default false
*/
hideProgressBars?: boolean;
/**
* The custom class for the steps wrapper.
*/
className?: string;
/**
* The custom class for the step.
*/
stepClassName?: string;
/**
* Callback function when the step index changes.
*/
onStepChange?: (stepIndex: number) => void;
}
function CheckIcon(props: ComponentProps<"svg">) {
return (
<svg
{...props}
fill="none"
stroke="currentColor"
strokeWidth={2}
viewBox="0 0 24 24"
>
<m.path
animate={{ pathLength: 1 }}
d="M5 13l4 4L19 7"
initial={{ pathLength: 0 }}
strokeLinecap="round"
strokeLinejoin="round"
transition={{
delay: 0.2,
type: "tween",
ease: "easeOut",
duration: 0.3,
}}
/>
</svg>
);
}
export const VerticalSteps = React.forwardRef<
HTMLButtonElement,
VerticalStepsProps
>(
(
{
color = "primary",
steps = [],
defaultStep = 0,
onStepChange,
currentStep: currentStepProp,
hideProgressBars = false,
stepClassName,
className,
...props
},
ref,
) => {
const [currentStep, setCurrentStep] = useControlledState(
currentStepProp,
defaultStep,
onStepChange,
);
const colors = React.useMemo(() => {
let userColor;
let fgColor;
const colorsVars = [
"[--active-fg-color:var(--step-fg-color)]",
"[--active-border-color:var(--step-color)]",
"[--active-color:var(--step-color)]",
"[--complete-background-color:var(--step-color)]",
"[--complete-border-color:var(--step-color)]",
"[--inactive-border-color:hsl(var(--nextui-default-300))]",
"[--inactive-color:hsl(var(--nextui-default-300))]",
];
switch (color) {
case "primary":
userColor = "[--step-color:hsl(var(--nextui-primary))]";
fgColor = "[--step-fg-color:hsl(var(--nextui-primary-foreground))]";
break;
case "secondary":
userColor = "[--step-color:hsl(var(--nextui-secondary))]";
fgColor = "[--step-fg-color:hsl(var(--nextui-secondary-foreground))]";
break;
case "success":
userColor = "[--step-color:hsl(var(--nextui-success))]";
fgColor = "[--step-fg-color:hsl(var(--nextui-success-foreground))]";
break;
case "warning":
userColor = "[--step-color:hsl(var(--nextui-warning))]";
fgColor = "[--step-fg-color:hsl(var(--nextui-warning-foreground))]";
break;
case "danger":
userColor = "[--step-color:hsl(var(--nextui-error))]";
fgColor = "[--step-fg-color:hsl(var(--nextui-error-foreground))]";
break;
case "default":
userColor = "[--step-color:hsl(var(--nextui-default))]";
fgColor = "[--step-fg-color:hsl(var(--nextui-default-foreground))]";
break;
default:
userColor = "[--step-color:hsl(var(--nextui-primary))]";
fgColor = "[--step-fg-color:hsl(var(--nextui-primary-foreground))]";
break;
}
if (!className?.includes("--step-fg-color")) colorsVars.unshift(fgColor);
if (!className?.includes("--step-color")) colorsVars.unshift(userColor);
if (!className?.includes("--inactive-bar-color"))
colorsVars.push(
"[--inactive-bar-color:hsl(var(--nextui-default-300))]",
);
return colorsVars;
}, [color, className]);
return (
<nav aria-label="Progress" className="max-w-fit">
<ol className={cn("flex flex-col gap-y-3", colors, className)}>
{steps?.map((step, stepIdx) => {
const status =
currentStep === stepIdx
? "active"
: currentStep < stepIdx
? "inactive"
: "complete";
return (
<li key={stepIdx} className="relative">
<div className="flex w-full max-w-full items-center">
<button
key={stepIdx}
ref={ref}
aria-current={status === "active" ? "step" : undefined}
className={cn(
"group flex w-full cursor-pointer items-center justify-center gap-4 rounded-large px-3 py-2.5",
stepClassName,
)}
onClick={() => setCurrentStep(stepIdx)}
{...props}
>
<div className="flex h-full items-center">
<LazyMotion features={domAnimation}>
<div className="relative">
<m.div
animate={status}
className={cn(
"relative flex h-[34px] w-[34px] items-center justify-center rounded-full border-medium text-large font-semibold text-default-foreground",
{
"shadow-lg": status === "complete",
},
)}
data-status={status}
initial={false}
transition={{ duration: 0.25 }}
variants={{
inactive: {
backgroundColor: "transparent",
borderColor: "var(--inactive-border-color)",
color: "var(--inactive-color)",
},
active: {
backgroundColor: "transparent",
borderColor: "var(--active-border-color)",
color: "var(--active-color)",
},
complete: {
backgroundColor:
"var(--complete-background-color)",
borderColor: "var(--complete-border-color)",
},
}}
>
<div className="flex items-center justify-center">
{status === "complete" ? (
<CheckIcon className="h-6 w-6 text-[var(--active-fg-color)]" />
) : (
<span>{stepIdx + 1}</span>
)}
</div>
</m.div>
</div>
</LazyMotion>
</div>
<div className="flex-1 text-left">
<div>
<div
className={cn(
"text-medium font-medium text-default-foreground transition-[color,opacity] duration-300 group-active:opacity-70",
{
"text-default-500": status === "inactive",
},
)}
>
{step.title}
</div>
<div
className={cn(
"text-tiny text-default-600 transition-[color,opacity] duration-300 group-active:opacity-70 lg:text-small",
{
"text-default-500": status === "inactive",
},
)}
>
{step.description}
</div>
</div>
</div>
</button>
</div>
{stepIdx < steps.length - 1 && !hideProgressBars && (
<div
aria-hidden="true"
className={cn(
"pointer-events-none absolute left-3 top-[calc(64px_*_var(--idx)_+_1)] flex h-1/2 -translate-y-1/3 items-center px-4",
)}
style={{
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
"--idx": stepIdx,
}}
>
<div
className={cn(
"relative h-full w-0.5 bg-[var(--inactive-bar-color)] transition-colors duration-300",
"after:absolute after:block after:h-0 after:w-full after:bg-[var(--active-border-color)] after:transition-[height] after:duration-300 after:content-['']",
{
"after:h-full": stepIdx < currentStep,
},
)}
/>
</div>
)}
</li>
);
})}
</ol>
</nav>
);
},
);
VerticalSteps.displayName = "VerticalSteps";
@@ -0,0 +1,64 @@
"use client";
import { Progress, Spacer } from "@nextui-org/react";
import { usePathname } from "next/navigation";
import React from "react";
import { VerticalSteps } from "./vertical-steps";
const steps = [
{
title: "Create a new role",
description: "Enter the name of the role you want to add.",
href: "/roles/new",
},
{
title: "Edit a existing role",
description:
"Review the role details and share the information required for the role.",
href: "/roles/edit",
},
];
export const WorkflowAddEditRole = () => {
const pathname = usePathname();
// Calculate current step based on pathname
const currentStepIndex = steps.findIndex((step) =>
pathname.endsWith(step.href),
);
const currentStep = currentStepIndex === -1 ? 0 : currentStepIndex;
return (
<section className="max-w-sm">
<h1 className="mb-2 text-xl font-medium" id="getting-started">
Manage Role Permissions
</h1>
<p className="mb-5 text-small text-default-500">
Define a new role with customized permissions or modify an existing one
to meet your needs.
</p>
<Progress
classNames={{
base: "px-0.5 mb-5",
label: "text-small",
value: "text-small text-default-400",
}}
label="Steps"
maxValue={steps.length - 1}
minValue={0}
showValueLabel={true}
size="md"
value={currentStep}
valueLabel={`${currentStep + 1} of ${steps.length}`}
/>
<VerticalSteps
hideProgressBars
currentStep={currentStep}
stepClassName="border border-default-200 dark:border-default-50 aria-[current]:bg-default-100 dark:aria-[current]:bg-prowler-blue-800 cursor-default"
steps={steps}
/>
<Spacer y={4} />
</section>
);
};
+11
View File
@@ -1,5 +1,16 @@
import { z } from "zod";
export const addRoleFormSchema = z.object({
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