You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

110 lines
3.4 KiB

import React, { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { Button } from '@/components/ui/button';
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form';
import { Checkbox } from '@/components/ui/checkbox';
import { roleService } from '@/services/roleService';
import { Role } from '@/services/roleService';
import { User } from '@/services/userService';
interface UserRolesFormProps {
user: User;
onSubmit: (roles: string[]) => void;
}
export default function UserRolesForm({ user, onSubmit }: UserRolesFormProps) {
const [roles, setRoles] = useState<Role[]>([]);
const [loading, setLoading] = useState(false);
const form = useForm({
defaultValues: {
roles: user.roles || [],
},
});
useEffect(() => {
const fetchRoles = async () => {
setLoading(true);
const result = await roleService.getAllRoles();
if (result.success && result.data) {
setRoles(result.data.roles || []);
}
setLoading(false);
};
fetchRoles();
}, []);
const handleSubmit = (data: { roles: string[] }) => {
onSubmit(data.roles);
form.reset();
};
if (loading) {
return <div className="text-center text-muted-foreground">...</div>;
}
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-4">
<FormField
control={form.control}
name="roles"
render={() => (
<FormItem>
<FormLabel className="text-foreground"></FormLabel>
<div className="grid grid-cols-2 gap-4">
{roles.map((role) => (
<FormField
key={role.id}
control={form.control}
name="roles"
render={({ field }) => {
return (
<FormItem
key={role.id}
className="flex flex-row items-start space-x-3 space-y-0"
>
<FormControl>
<Checkbox
checked={field.value?.includes(role.name)}
onCheckedChange={(checked: boolean) => {
const currentRoles = field.value || [];
if (checked) {
field.onChange([...currentRoles, role.name]);
} else {
field.onChange(
currentRoles.filter((r) => r !== role.name)
);
}
}}
/>
</FormControl>
<FormLabel className="font-normal">
{role.name}
</FormLabel>
</FormItem>
);
}}
/>
))}
</div>
<FormMessage className="text-destructive" />
</FormItem>
)}
/>
<div className="flex justify-end">
<Button type="submit" className="bg-primary text-primary-foreground hover:bg-primary/90">
</Button>
</div>
</form>
</Form>
);
}