refactor(admin): refactor admin roles and users management
This commit is contained in:
99
src/app/(modules)/users/hooks/useUserForm.ts
Normal file
99
src/app/(modules)/users/hooks/useUserForm.ts
Normal file
@@ -0,0 +1,99 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback } from 'react';
|
||||
import { useForm, useWatch } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
import type { AdministrationUser } from '@/types';
|
||||
import { useSaveUserMutation } from './useUserMutations';
|
||||
|
||||
export interface UserFormValues {
|
||||
id?: number;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
email: string;
|
||||
phone_number: string;
|
||||
role_id: string;
|
||||
}
|
||||
|
||||
const defaultValues: UserFormValues = {
|
||||
first_name: '',
|
||||
last_name: '',
|
||||
email: '',
|
||||
phone_number: '',
|
||||
role_id: '',
|
||||
};
|
||||
|
||||
export function useUserForm({ onSaved }: { onSaved: () => void }) {
|
||||
const {
|
||||
control,
|
||||
register,
|
||||
handleSubmit: submitForm,
|
||||
reset,
|
||||
setValue,
|
||||
formState: { isSubmitting, errors },
|
||||
} = useForm<UserFormValues>({
|
||||
defaultValues,
|
||||
});
|
||||
const saveMutation = useSaveUserMutation({
|
||||
onSaved: () => {
|
||||
reset(defaultValues);
|
||||
onSaved();
|
||||
},
|
||||
});
|
||||
|
||||
const userId = useWatch({ control, name: 'id' });
|
||||
const roleId = useWatch({ control, name: 'role_id' }) || '';
|
||||
|
||||
const handleSubmit = submitForm(
|
||||
(values) => saveMutation.mutate(values),
|
||||
(formErrors) => {
|
||||
if (formErrors.first_name || formErrors.last_name || formErrors.email) {
|
||||
toast.error('First name, last name and email are required');
|
||||
return;
|
||||
}
|
||||
if (formErrors.role_id) {
|
||||
toast.error('Select a role');
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const openCreate = useCallback(() => {
|
||||
reset(defaultValues);
|
||||
}, [reset]);
|
||||
|
||||
const openEdit = useCallback(
|
||||
(user: AdministrationUser) => {
|
||||
const selectedRoleId = user.role_ids?.[0] ?? user.roles?.[0]?.id;
|
||||
reset({
|
||||
id: user.id,
|
||||
first_name: user.first_name || '',
|
||||
last_name: user.last_name || '',
|
||||
email: user.email || '',
|
||||
phone_number: user.phone_number || '',
|
||||
role_id: selectedRoleId ? String(selectedRoleId) : '',
|
||||
});
|
||||
},
|
||||
[reset],
|
||||
);
|
||||
|
||||
const setRoleId = useCallback(
|
||||
(value: string) => {
|
||||
setValue('role_id', value, { shouldDirty: true, shouldValidate: true });
|
||||
},
|
||||
[setValue],
|
||||
);
|
||||
|
||||
return {
|
||||
register,
|
||||
handleSubmit,
|
||||
reset,
|
||||
openCreate,
|
||||
openEdit,
|
||||
setRoleId,
|
||||
roleId,
|
||||
userId,
|
||||
errors,
|
||||
isSaving: isSubmitting || saveMutation.isPending,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user