import type { IRole, IRoom } from '@rocket.chat/core-typings'; import { Box, Field, FieldLabel, FieldRow, Margins, ButtonGroup, Button, Callout, FieldError } from '@rocket.chat/fuselage'; import { useStableCallback } from '@rocket.chat/fuselage-hooks'; import { usePagination, Page, PageHeader, PageContent } from '@rocket.chat/ui-client'; import { useToastMessageDispatch, useEndpoint, useRouter } from '@rocket.chat/ui-contexts'; import { useQuery, useQueryClient } from '@tanstack/react-query'; import { useId, useMemo } from 'react'; import { useForm, Controller } from 'react-hook-form'; import { useTranslation } from 'react-i18next'; import UsersInRoleTable from './UsersInRoleTable'; import { useRemoveUserFromRole } from './hooks/useRemoveUserFromRole'; import RoomAutoComplete from '../../../../components/RoomAutoComplete'; import UserAutoCompleteMultiple from '../../../../components/UserAutoCompleteMultiple'; type UsersInRolePayload = { rid?: IRoom['_id']; users: string[]; }; export type UsersInRolePageProps = { role: IRole }; const UsersInRolePage = ({ role }: UsersInRolePageProps) => { const { t } = useTranslation(); const dispatchToastMessage = useToastMessageDispatch(); const queryClient = useQueryClient(); const { control, handleSubmit, formState: { errors, isDirty }, watch, } = useForm({ defaultValues: { users: [] } }); const { _id, name, description } = role; const router = useRouter(); const addUserToRoleEndpoint = useEndpoint('POST', '/v1/roles.addUserToRole'); const { rid } = watch(); const roomFieldId = useId(); const usersFieldId = useId(); const handleAdd = useStableCallback(async ({ users, rid }: UsersInRolePayload) => { try { await Promise.all( users.map(async (user) => { if (user) { await addUserToRoleEndpoint({ roleId: _id, username: user, roomId: rid }); } }), ); dispatchToastMessage({ type: 'success', message: t('Users_added') }); queryClient.invalidateQueries({ queryKey: ['getUsersInRole'], }); } catch (error) { dispatchToastMessage({ type: 'error', message: error }); } }); const getUsersInRoleEndpoint = useEndpoint('GET', '/v1/roles.getUsersInRole'); const paginationData = usePagination(); const { itemsPerPage, current } = paginationData; const query = useMemo( () => ({ role: _id, ...(rid && { roomId: rid }), ...(itemsPerPage && { count: itemsPerPage }), ...(current && { offset: current }), }), [itemsPerPage, current, rid, _id], ); const { data, isLoading, isSuccess, refetch, isError } = useQuery({ queryKey: ['getUsersInRole', _id, query], queryFn: async () => getUsersInRoleEndpoint(query), }); const handleRemove = useRemoveUserFromRole({ rid, roleId: _id, roleName: name, roleDescription: description }); return ( {role.scope !== 'Users' && ( {t('Choose_a_room')} ( )} /> {errors.rid && ( {errors.rid.message} )} )} {t('Add_users')} ( )} /> {errors.users && ( {errors.users.message} )} {(role.scope === 'Users' || rid) && ( )} {role.scope !== 'Users' && !rid && {t('Select_a_room')}} ); }; export default UsersInRolePage;