import { ArrowLeftOutlined, SaveOutlined } from '@ant-design/icons' import { Button, message, Spin } from 'antd' import dayjs from 'dayjs' import { FormComponents } from 'isp-ui-kit' import { useEffect } from 'react' import { useForm } from 'react-hook-form' import { useLocation, useNavigate } from 'react-router-dom' import { dateFormats } from '@constants/date.ts' import { ValidationRules } from '@constants/form/validationRules.ts' import { findExclusiveRole } from '@utils/roleUtils.ts' import useRole from '@hooks/useRole.tsx' import roleApi from '@services/roleService.ts' import userServiceApi from '@services/userService.ts' import { routePaths } from '@routes/routePaths.ts' import { PermissionKeysType, RoleType } from '@type/roles.type.ts' import { UserType } from '@type/user.type.ts' import { LabelItem } from 'isp-ui-kit/dist/FormComponents/formTypes' import './user-editor.scss' const UserEditor = () => { const location = useLocation() const navigate = useNavigate() const state = location.state as UserType const isNew = location.pathname.includes('new') const fromApp = location.state?.fromApp || false const { hasPermission } = useRole() const hasCreateUserPermission = hasPermission(PermissionKeysType.write) const hasUpdateUserPermission = hasPermission(PermissionKeysType.write) const [createUser] = userServiceApi.useCreateUserMutation() const { data: roles = [], isLoading } = roleApi.useGetAllRolesQuery() const [updateUser] = userServiceApi.useUpdateUserMutation() const isSaveBtnAvailable = isNew ? hasCreateUserPermission : hasUpdateUserPermission const { control, formState: { isDirty }, getValues, setValue, watch, setError } = useForm({ defaultValues: isNew ? { description: '', email: '', firstName: '', password: '', roles: [] } : state, mode: 'onChange' }) useEffect(() => { if (isNew && !fromApp) { navigate(routePaths.users) } }, [fromApp]) useEffect(() => { const subscription = watch((value, { name, type }) => { if (name === 'roles' && type === 'change') { const exclusiveRole = findExclusiveRole(roles, value.roles as number[]) if (exclusiveRole) { if (value.roles && value.roles.length > 1) { message.error( <> Роль: {exclusiveRole.name} несовместима с другими ролями ) } setValue('roles', [exclusiveRole.id]) } } }) return () => subscription.unsubscribe() }, [watch]) const sendForm = () => { if (isNew) { const newUser = { email: getValues().email, password: getValues().password, description: getValues().description, firstName: getValues().firstName, lastName: getValues().lastName, roles: getValues().roles } createUser(newUser) .unwrap() .then(() => { message.success('Пользователь успешно создан') navigate(routePaths.users) }) .catch((error) => { const { status } = error if (status === 409) { setError('email', { message: 'Пользователь с таким Email уже существует' }) } message.error('Произошла ошибка создания пользователя') }) } else { const formData = getValues() delete formData.lastSessionCreatedAt updateUser(formData) .unwrap() .then(() => { message.success('Пользователь успешно изменен') navigate(routePaths.users) }) .catch((error) => { const { status } = error if (status === 409) { setError('email', { message: 'Пользователь с таким Email уже существует' }) } message.error('Произошла ошибка обновления пользователя') }) } } const createSelectOptions = (role: RoleType[]) => { const options: LabelItem[] = role.map((r) => ({ value: r.id, label: r.name })) return options } if (isLoading) { return } return (
{isNew ? ( '' ) : ( {state.lastSessionCreatedAt && ( <> Последняя сессия   {dayjs(state.lastSessionCreatedAt).format( dateFormats.fullFormat )} )} )}
{isNew && (
)}
) } export default UserEditor