Merge branch 'feat/users' into 'main'

Connected users with Kratos

Closes #19

See merge request stackspin/dashboard!14
This commit is contained in:
Maarten de Waard 2021-12-21 14:55:46 +00:00
commit 0352f21789
22 changed files with 479 additions and 228 deletions

View file

@ -24,7 +24,7 @@
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-helmet": "^6.1.0",
"react-hook-form": "^7.12.1",
"react-hook-form": "^7.22.0",
"react-hot-toast": "^2.0.0",
"react-markdown": "^7.0.1",
"react-redux": "^7.2.4",

View file

@ -0,0 +1,45 @@
import React from 'react';
import { useController } from 'react-hook-form';
/* eslint-disable react/react-in-jsx-scope */
export const Input = ({ control, name, type = 'text', label, ...props }: InputProps) => {
const {
field,
// fieldState: { invalid, isTouched, isDirty },
// formState: { touchedFields, dirtyFields },
} = useController({
name,
control,
rules: { required: true },
defaultValue: '',
});
return (
<>
{label && (
<label htmlFor={name} className="block text-sm font-medium text-gray-700 mb-1">
{label}
</label>
)}
<input
type={type}
id={name}
onChange={field.onChange} // send value to hook form
onBlur={field.onBlur} // notify when input is touched/blur
value={field.value ? field.value.toString() : ''} // input value
name={name} // send down the input name
ref={field.ref} // send input ref, so we can focus on input when error appear
autoComplete="given-name"
className="shadow-sm focus:ring-primary-500 focus:border-primary-500 block w-full sm:text-sm border-gray-300 rounded-md"
{...props}
/>
</>
);
};
type InputProps = {
control: any;
name: string;
type?: string;
label?: string;
} & React.HTMLProps<HTMLInputElement>;

View file

@ -0,0 +1 @@
export { Input } from './Input';

View file

@ -0,0 +1,48 @@
import React from 'react';
import { useController } from 'react-hook-form';
/* eslint-disable react/react-in-jsx-scope */
export const Select = ({ control, name, label, options }: SelectProps) => {
const {
field,
// fieldState: { invalid, isTouched, isDirty },
// formState: { touchedFields, dirtyFields },
} = useController({
name,
control,
rules: { required: true },
defaultValue: '',
});
return (
<>
{label && (
<label htmlFor={name} className="block text-sm font-medium text-gray-700 mb-1">
{label}
</label>
)}
<select
id={name}
onChange={field.onChange} // send value to hook form
onBlur={field.onBlur} // notify when input is touched/blur
value={field.value ? field.value.toString() : ''} // input value
name={name} // send down the input name
ref={field.ref} // send input ref, so we can focus on input when error appear
className="shadow-sm focus:ring-primary-500 focus:border-primary-500 block w-full sm:text-sm border-gray-300 rounded-md"
>
{options?.map((value) => (
<option key={value} value={value}>
{value}
</option>
))}
</select>
</>
);
};
type SelectProps = {
control: any;
name: string;
label?: string;
options?: any[];
};

View file

@ -0,0 +1 @@
export { Select } from './Select';

View file

@ -0,0 +1,2 @@
export { Input } from './Input';
export { Select } from './Select';

View file

@ -10,8 +10,11 @@ export const Modal: React.FC<ModalProps> = ({
children,
title = '',
useCancelButton = false,
isLoading = false,
leftActions = <></>,
}) => {
const cancelButtonRef = useRef(null);
const saveButtonRef = useRef(null);
return (
<Transition.Root show={open} as={Fragment}>
@ -42,7 +45,25 @@ export const Modal: React.FC<ModalProps> = ({
leaveFrom="opacity-100 translate-y-0 sm:scale-100"
leaveTo="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
>
<div className="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-2xl sm:w-full">
<div className="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-2xl sm:w-full relative">
{isLoading && (
<Dialog.Overlay className="inset-0 bg-gray-400 bg-opacity-75 transition-opacity absolute flex justify-center items-center">
<svg
className="animate-spin -ml-1 mr-3 h-5 w-5 text-white"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
/>
</svg>
</Dialog.Overlay>
)}
{!useCancelButton && (
<div className="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:items-center sm:justify-between">
<div>{title}</div>
@ -60,24 +81,28 @@ export const Modal: React.FC<ModalProps> = ({
<div className="bg-white px-4 p-6">{children}</div>
{onSave && (
<div className="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
<button
type="button"
className="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-primary-600 text-base font-medium text-white hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 sm:ml-3 sm:w-auto sm:text-sm"
onClick={onSave}
>
Save Changes
</button>
{useCancelButton && (
<div className="bg-gray-50 px-4 py-3 sm:px-6 sm:flex">
{leftActions}
<div className="ml-auto sm:flex sm:flex-row-reverse">
<button
type="button"
className="mt-3 w-full inline-flex justify-center rounded-md border border-gray-200 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm"
onClick={onClose}
ref={cancelButtonRef}
className="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-primary-600 text-base font-medium text-white hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 sm:ml-3 sm:w-auto sm:text-sm"
onClick={onSave}
ref={saveButtonRef}
>
Cancel
Save Changes
</button>
)}
{useCancelButton && (
<button
type="button"
className="mt-3 w-full inline-flex justify-center rounded-md border border-gray-200 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm"
onClick={onClose}
ref={cancelButtonRef}
>
Cancel
</button>
)}
</div>
</div>
)}
</div>

View file

@ -1,7 +1,11 @@
import React from 'react';
export type ModalProps = {
open: boolean;
onClose: () => void;
title?: string;
onSave?: () => void;
useCancelButton?: boolean;
isLoading?: boolean;
leftActions?: React.ReactNode;
};

View file

@ -6,6 +6,7 @@ import { CogIcon, TrashIcon } from '@heroicons/react/outline';
import { useUsers } from 'src/services/users';
import { Table } from 'src/components';
import { ConfirmationModal } from 'src/components/Modal';
import { debounce } from 'lodash';
import { UserModal } from './components/UserModal';
const pages = [{ name: 'Users', href: '#', current: true }];
@ -14,37 +15,35 @@ export const Users: React.FC<RouteComponentProps> = () => {
const [selectedRowsIds, setSelectedRowsIds] = useState({});
const [deleteModal, setDeleteModal] = useState(false);
const [configureModal, setConfigureModal] = useState(false);
const [userId, setUserId] = useState(null);
const [search, setSearch] = useState('');
const { loadUsers, users } = useUsers();
const { users, loadUsers } = useUsers();
const handleSearch = useCallback((event: any) => {
const handleSearch = (event: any) => {
setSearch(event.target.value);
}, []);
};
// TODO: Check why it needs any
const allUsers: any = users.items;
const debouncedSearch = useCallback(debounce(handleSearch, 250), []);
useEffect(() => {
const asyncFc = async () => {
try {
await loadUsers();
} catch {
// continue
}
};
loadUsers();
asyncFc();
/* eslint-disable-next-line react-hooks/exhaustive-deps */
return () => {
debouncedSearch.cancel();
};
}, []);
const filterSearch = useMemo(() => {
return allUsers.filter((item: any) => item.name?.toLowerCase().includes(search.toLowerCase()));
}, [search, allUsers]);
return users.filter((item: any) => item.email?.toLowerCase().includes(search.toLowerCase()));
}, [search, users]);
const deleteModalOpen = () => setDeleteModal(true);
const deleteModalClose = () => setDeleteModal(false);
const configureModalOpen = () => setConfigureModal(true);
const configureModalOpen = (id: any) => {
setUserId(id);
setConfigureModal(true);
};
const configureModalClose = () => setConfigureModal(false);
const columns: any = React.useMemo(
@ -64,18 +63,15 @@ export const Users: React.FC<RouteComponentProps> = () => {
accessor: 'status',
width: 'auto',
},
{
Header: 'Last Sign-In',
accessor: 'last_login',
width: 'auto',
},
{
Header: ' ',
Cell: () => {
Cell: (props: any) => {
const { row } = props;
return (
<div className="text-right opacity-0 group-hover:opacity-100 transition-opacity">
<button
onClick={configureModalOpen}
onClick={() => configureModalOpen(row.original.id)}
type="button"
className="inline-flex items-center px-4 py-2 border border-gray-200 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500"
>
@ -127,7 +123,7 @@ export const Users: React.FC<RouteComponentProps> = () => {
<h1 className="text-3xl leading-6 font-bold text-gray-900">Users</h1>
<div className="mt-3 sm:mt-0 sm:ml-4">
<button
onClick={configureModalOpen}
onClick={() => configureModalOpen(null)}
type="button"
className="inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-primary-700 hover:bg-primary-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-800"
>
@ -139,23 +135,6 @@ export const Users: React.FC<RouteComponentProps> = () => {
<div className="flex justify-between w-100 my-3 items-center mb-5 ">
<div className="flex items-center">
{/* <div className="mr-3 inline-block shadow-sm">
<label htmlFor="location" className="block text-sm font-medium text-gray-700 sr-only">
Location
</label>
<select
id="location"
name="location"
className="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-200 focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm rounded-md"
defaultValue="All users"
>
<option>All users</option>
<option>Owner</option>
<option>Admins</option>
<option>Members</option>
</select>
</div> */}
<div className="inline-block">
<label htmlFor="email" className="block text-sm font-medium text-gray-700 sr-only">
Search candidates
@ -171,7 +150,7 @@ export const Users: React.FC<RouteComponentProps> = () => {
id="email"
className="focus:ring-primary-500 focus:border-primary-500 block w-full rounded-md pl-10 sm:text-sm border-gray-200"
placeholder="Search Users"
onChange={handleSearch}
onChange={debouncedSearch}
/>
</div>
</div>
@ -196,7 +175,7 @@ export const Users: React.FC<RouteComponentProps> = () => {
<div className="-my-2 sm:-mx-6 lg:-mx-8">
<div className="py-2 align-middle inline-block min-w-full sm:px-6 lg:px-8">
<div className="shadow border-b border-gray-200 sm:rounded-lg">
<Table data={filterSearch} columns={columns} getSelectedRowIds={selectedRows} selectable />
<Table data={filterSearch as any} columns={columns} getSelectedRowIds={selectedRows} selectable />
</div>
</div>
</div>
@ -209,7 +188,7 @@ export const Users: React.FC<RouteComponentProps> = () => {
body="Are you sure you want to delete this user? All of your data will be permanently removed. This action cannot be undone."
/>
<UserModal open={configureModal} onClose={configureModalClose} onSave={configureModalClose} />
<UserModal open={configureModal} onClose={configureModalClose} userId={userId} />
</div>
);
};

View file

@ -1,11 +1,96 @@
import React from 'react';
import React, { useEffect } from 'react';
import { TrashIcon } from '@heroicons/react/outline';
import { useForm } from 'react-hook-form';
import { Modal } from 'src/components';
import { Input } from 'src/components/Form';
import { useUsers } from 'src/services/users';
import { CurrentUserState } from 'src/services/users/redux';
import { appAccessList } from './consts';
import { UserModalProps } from './types';
export const UserModal = ({ open, onClose, onSave = () => {} }: UserModalProps) => {
export const UserModal = ({ open, onClose, userId }: UserModalProps) => {
const { user, loadUser, editUserById, createNewUser, userModalLoading, deleteUserById } = useUsers();
const { control, reset, handleSubmit } = useForm<CurrentUserState>({
defaultValues: {
name: null,
email: null,
id: null,
status: null,
},
});
useEffect(() => {
if (userId) {
loadUser(userId);
}
reset({ name: null, email: null, id: null, status: null });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [userId]);
useEffect(() => {
if (user) {
reset(user);
}
return () => {
reset({ name: null, email: null, id: null, status: null });
};
}, [user, reset]);
const handleSave = async () => {
try {
if (userId) {
await handleSubmit((data) => editUserById(data))();
} else {
await handleSubmit((data) => createNewUser(data))();
reset({ name: null, email: null, id: null, status: null });
}
onClose();
} catch (e: any) {
// Continue
}
};
const handleKeyPress = (e: any) => {
if (e.key === 'Enter' || e.key === 'NumpadEnter') {
handleSave();
}
};
const handleClose = () => {
onClose();
};
const handleDelete = () => {
if (userId) {
deleteUserById(userId);
}
handleClose();
};
return (
<Modal onClose={onClose} open={open} onSave={onSave} useCancelButton>
<Modal
onClose={handleClose}
open={open}
onSave={handleSave}
isLoading={userModalLoading}
leftActions={
userId && (
<button
onClick={handleDelete}
type="button"
className="inline-flex items-center px-4 py-2 text-sm font-medium rounded-md text-red-700 bg-red-50 hover:bg-red-100 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500"
>
<TrashIcon className="-ml-0.5 mr-2 h-4 w-4" aria-hidden="true" />
Delete
</button>
)
}
useCancelButton
>
<div className="bg-white px-4">
<div className="space-y-4 divide-y divide-gray-200">
<div>
@ -15,36 +100,15 @@ export const UserModal = ({ open, onClose, onSave = () => {} }: UserModalProps)
<div className="mt-6 grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-6">
<div className="sm:col-span-3">
<label htmlFor="name" className="block text-sm font-medium text-gray-700">
Name
</label>
<div className="mt-1">
<input
type="text"
name="name"
id="name"
autoComplete="given-name"
className="shadow-sm focus:ring-primary-500 focus:border-primary-500 block w-full sm:text-sm border-gray-300 rounded-md"
/>
</div>
<Input control={control} name="name" label="Name" onKeyPress={handleKeyPress} />
</div>
<div className="sm:col-span-3">
<label htmlFor="email" className="block text-sm font-medium text-gray-700">
Email
</label>
<div className="mt-1">
<input
type="email"
name="email"
id="email"
autoComplete="family-name"
className="shadow-sm focus:ring-primary-500 focus:border-primary-500 block w-full sm:text-sm border-gray-300 rounded-md"
/>
</div>
<Input control={control} name="email" label="Email" type="email" onKeyPress={handleKeyPress} />
</div>
<div className="sm:col-span-3">
{/* <Select control={control} name="status" label="Status" options={['Active', 'Inactive']} /> */}
<label htmlFor="status" className="block text-sm font-medium text-gray-700">
Status
</label>

View file

@ -1,5 +1,5 @@
export type UserModalProps = {
open: boolean;
onClose: () => void;
onSave?: () => void;
userId: string | null;
};

View file

@ -4,8 +4,8 @@ import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import { reducer as authReducer } from 'src/services/auth';
import { reducer as usersReducer } from 'src/services/users';
import usersReducer from 'src/services/users/redux/reducers';
import { State } from './types';
const persistConfig = {

View file

@ -1,16 +1,41 @@
import { useDispatch, useSelector } from 'react-redux';
import { getUsers, fetchUsers } from '../redux';
import { getUsers, fetchUsers, fetchUserById, updateUserById, createUser, deleteUser } from '../redux';
import { getUserById, getUserModalLoading } from '../redux/selectors';
export function useUsers() {
const dispatch = useDispatch();
const users = useSelector(getUsers);
const user = useSelector(getUserById);
const userModalLoading = useSelector(getUserModalLoading);
function loadUsers() {
return dispatch(fetchUsers());
}
function loadUser(id: string) {
return dispatch(fetchUserById(id));
}
function editUserById(data: any) {
return dispatch(updateUserById(data));
}
function createNewUser(data: any) {
return dispatch(createUser(data));
}
function deleteUserById(id: string) {
return dispatch(deleteUser(id));
}
return {
users,
user,
loadUser,
loadUsers,
editUserById,
userModalLoading,
createNewUser,
deleteUserById,
};
}

View file

@ -1,6 +1,6 @@
export * from './types';
export { reducer, fetchCurrentUser, getCurrentUser } from './redux';
export { reducer } from './redux';
export { useUsers } from './hooks';

View file

@ -1,64 +1,132 @@
import { createApiAction, createCrudApiActions } from 'src/services/api';
import { transformUserForApi } from '../transformations';
import { User } from '../types';
import { CurrentUserUpdateAPI } from './types';
import { Dispatch } from 'redux';
import { showToast, ToastType } from 'src/common/util/show-toast';
import { performApiCall } from 'src/services/api';
import { transformRequestUser, transformResponseUser } from '../transformations';
export enum UserActionTypes {
CHANGE_CURRENT_USER_START = 'users/fetch_current_user_start',
CHANGE_CURRENT_USER_FAILURE = 'users/fetch_current_user_failure',
FETCH_CURRENT_USER_SUCCESS = 'users/fetch_current_user_success',
UPDATE_CURRENT_USER_SUCCESS = 'users/update_current_user_success',
CHANGE_USERS_START = 'users/change_users_start',
CHANGE_USERS_FAILURE = 'users/change_users_failure',
FETCH_USERS_SUCCESS = 'users/fetch_users_success',
ADD_ACCOUNT_USER_SUCCESS = 'users/add_account_user_success',
UPDATE_ACCOUNT_USER_SUCCESS = 'users/update_account_user_success',
DELETE_ACCOUNT_USER_SUCCESS = 'users/delete_account_user_success',
CHANGE_USER_ROLES_START = 'users/change_user_roles_start',
CHANGE_USER_ROLES_FAILURE = 'users/change_user_roles_failure',
FETCH_USER_ROLES_SUCCESS = 'users/fetch_user_roles_success',
ADD_USER_ROLE_SUCCESS = 'users/add_user_role_success',
UPDATE_USER_ROLE_SUCCESS = 'users/update_user_role_success',
DELETE_USER_ROLE_SUCCESS = 'users/delete_user_role_success',
FETCH_USERS = 'users/fetch_users',
FETCH_USER = 'users/fetch_user',
UPDATE_USER = 'users/update_user',
CREATE_USER = 'users/create_user',
DELETE_USER = 'users/delete_user',
SET_USER_MODAL_LOADING = 'users/user_modal_loading',
}
export const fetchCurrentUser = () =>
createApiAction(
{
path: '/users/me',
export const fetchUsers = () => async (dispatch: Dispatch<any>) => {
try {
const { data } = await performApiCall({
path: '/users',
method: 'GET',
},
[
UserActionTypes.CHANGE_CURRENT_USER_START,
UserActionTypes.FETCH_CURRENT_USER_SUCCESS,
UserActionTypes.CHANGE_CURRENT_USER_FAILURE,
],
);
});
export const updateCurrentUser = (data: CurrentUserUpdateAPI) =>
createApiAction(
{
path: '/users/me',
method: 'PATCH',
body: data,
},
[
UserActionTypes.CHANGE_CURRENT_USER_START,
UserActionTypes.UPDATE_CURRENT_USER_SUCCESS,
UserActionTypes.CHANGE_CURRENT_USER_FAILURE,
],
);
dispatch({
type: UserActionTypes.FETCH_USERS,
payload: data.map(transformResponseUser),
});
} catch (err) {
console.error(err);
}
};
export const [fetchUsers, addUser, updateUser, deleteUser] = createCrudApiActions<User>(
'/users',
UserActionTypes.CHANGE_USERS_START,
UserActionTypes.CHANGE_USERS_FAILURE,
UserActionTypes.FETCH_USERS_SUCCESS,
UserActionTypes.ADD_ACCOUNT_USER_SUCCESS,
UserActionTypes.UPDATE_ACCOUNT_USER_SUCCESS,
UserActionTypes.DELETE_ACCOUNT_USER_SUCCESS,
transformUserForApi,
);
export const setUserModalLoading = (isLoading: boolean) => (dispatch: Dispatch<any>) => {
dispatch({
type: UserActionTypes.SET_USER_MODAL_LOADING,
payload: isLoading,
});
};
export const fetchUserById = (id: string) => async (dispatch: Dispatch<any>) => {
dispatch(setUserModalLoading(true));
try {
const { data } = await performApiCall({
path: `/users/${id}`,
method: 'GET',
});
dispatch({
type: UserActionTypes.FETCH_USER,
payload: transformResponseUser(data),
});
} catch (err) {
console.error(err);
}
dispatch(setUserModalLoading(false));
};
export const updateUserById = (user: any) => async (dispatch: Dispatch<any>) => {
dispatch(setUserModalLoading(true));
try {
const { data } = await performApiCall({
path: `/users/${user.id}`,
method: 'PUT',
body: transformRequestUser(user),
});
dispatch({
type: UserActionTypes.UPDATE_USER,
payload: transformResponseUser(data),
});
showToast('User updated sucessfully.', ToastType.Success);
dispatch(fetchUsers());
} catch (err) {
console.error(err);
}
dispatch(setUserModalLoading(false));
};
export const createUser = (user: any) => async (dispatch: Dispatch<any>) => {
dispatch(setUserModalLoading(true));
try {
const { data } = await performApiCall({
path: '/users',
method: 'POST',
body: transformRequestUser(user),
});
dispatch({
type: UserActionTypes.CREATE_USER,
payload: transformResponseUser(data),
});
showToast('User created sucessfully.', ToastType.Success);
dispatch(fetchUsers());
} catch (err: any) {
dispatch(setUserModalLoading(false));
showToast(`${err}`, ToastType.Error);
throw err;
}
dispatch(setUserModalLoading(false));
};
export const deleteUser = (id: string) => async (dispatch: Dispatch<any>) => {
dispatch(setUserModalLoading(true));
try {
await performApiCall({
path: `/users/${id}`,
method: 'DELETE',
});
dispatch({
type: UserActionTypes.DELETE_USER,
payload: {},
});
showToast('User deleted sucessfully.', ToastType.Success);
dispatch(fetchUsers());
} catch (err) {
console.error(err);
}
dispatch(setUserModalLoading(false));
};

View file

@ -1,4 +1,4 @@
export * from './actions';
export { default as reducer } from './reducers';
export { getCurrentUser, getUsers } from './selectors';
export { getUsers } from './selectors';
export * from './types';

View file

@ -1,61 +1,39 @@
import { combineReducers } from 'redux';
import { createApiReducer, chainReducers, INITIAL_API_STATE, createCrudApiReducer } from 'src/services/api';
import { AuthActionTypes } from 'src/services/auth/redux/actions';
import { transformUser } from '../transformations';
import { User } from '../types';
import { UserActionTypes } from './actions';
const signInReducer = createApiReducer(
[AuthActionTypes.SIGN_IN_START, AuthActionTypes.SIGN_IN_SUCCESS, AuthActionTypes.SIGN_IN_FAILURE],
transformUser,
(data) => data,
);
const initialUsersState: any = {
users: [],
user: {},
userModalLoading: false,
};
const fetchCurrentUserReducer = createApiReducer(
[
UserActionTypes.CHANGE_CURRENT_USER_START,
UserActionTypes.FETCH_CURRENT_USER_SUCCESS,
UserActionTypes.CHANGE_CURRENT_USER_FAILURE,
],
transformUser,
(data) => data,
);
const usersReducer = (state: any = initialUsersState, action: any) => {
switch (action.type) {
case UserActionTypes.FETCH_USERS:
return {
...state,
users: action.payload,
};
case UserActionTypes.SET_USER_MODAL_LOADING:
return {
...state,
userModalLoading: action.payload,
};
case UserActionTypes.FETCH_USER:
case UserActionTypes.UPDATE_USER:
case UserActionTypes.CREATE_USER:
return {
...state,
isModalVisible: false,
user: action.payload,
};
case UserActionTypes.DELETE_USER:
return {
...state,
user: {},
};
default:
return state;
}
};
const updateCurrentUserReducer = createApiReducer(
[
UserActionTypes.CHANGE_CURRENT_USER_START,
UserActionTypes.UPDATE_CURRENT_USER_SUCCESS,
UserActionTypes.CHANGE_CURRENT_USER_FAILURE,
],
transformUser,
(data) => data,
);
const signOutReducer = createApiReducer(
['', AuthActionTypes.SIGN_OUT, ''],
() => INITIAL_API_STATE,
() => INITIAL_API_STATE,
);
const usersReducer = createCrudApiReducer<User>(
UserActionTypes.CHANGE_USERS_START,
UserActionTypes.CHANGE_USERS_FAILURE,
UserActionTypes.FETCH_USERS_SUCCESS,
UserActionTypes.ADD_ACCOUNT_USER_SUCCESS,
UserActionTypes.UPDATE_ACCOUNT_USER_SUCCESS,
UserActionTypes.DELETE_ACCOUNT_USER_SUCCESS,
transformUser,
);
export default combineReducers({
currentUser: chainReducers(
INITIAL_API_STATE,
signInReducer,
fetchCurrentUserReducer,
updateCurrentUserReducer,
signOutReducer,
),
users: usersReducer,
});
export default usersReducer;

View file

@ -1,4 +1,5 @@
import { State } from 'src/redux';
export const getCurrentUser = (state: State) => state.users.currentUser;
export const getUsers = (state: State) => state.users.users;
export const getUserById = (state: State) => state.users.user;
export const getUserModalLoading = (state: State) => state.users.userModalLoading;

View file

@ -1,4 +1,4 @@
import { ApiState, ApiStatus } from 'src/services/api/redux';
import { ApiStatus } from 'src/services/api/redux';
import { User } from '../types';
@ -8,10 +8,13 @@ export interface CurrentUserState extends User {
export interface UsersState {
currentUser: CurrentUserState;
users: ApiState<User>;
users: User[];
user: User;
userModalLoading: boolean;
}
export interface CurrentUserUpdateAPI {
id: number;
phoneNumber?: string;
email?: string;
language?: string;

View file

@ -1,14 +1,17 @@
import _ from 'lodash';
import { FormUser, User, UserApiRequest } from './types';
import { User } from './types';
export const transformUserForApi = (user: FormUser): UserApiRequest => ({
id: user.id,
email: user.email,
name: user.name,
status: user.status,
last_login: user.last_login,
});
export const transformResponseUser = (response: any): User => {
const userResponse = _.get(response, 'user', response);
return {
id: userResponse.id,
email: userResponse.traits.email,
name: userResponse.traits.name ?? null,
status: userResponse.state,
};
};
export const transformUser = (response: any): User => {
const userResponse = _.get(response, 'user', response);
@ -17,7 +20,13 @@ export const transformUser = (response: any): User => {
id: userResponse.id,
email: userResponse.email,
name: userResponse.name,
last_login: userResponse.last_login,
status: userResponse.status,
};
};
export const transformRequestUser = (data: any) => {
return {
email: data.email,
name: data.name,
};
};

View file

@ -1,9 +1,8 @@
export interface User {
id: number | null;
email: string;
name: string;
last_login: string;
status: string;
email: string | null;
name: string | null;
status: string | null;
}
export interface FormUser extends User {
@ -21,6 +20,5 @@ export interface UserApiRequest {
id: number | null;
email: string;
name: string;
last_login: string;
status: string;
}

View file

@ -10331,10 +10331,10 @@ react-helmet@^6.1.0:
react-fast-compare "^3.1.1"
react-side-effect "^2.1.0"
react-hook-form@^7.12.1:
version "7.12.1"
resolved "https://registry.yarnpkg.com/react-hook-form/-/react-hook-form-7.12.1.tgz#dc6adbbd78a3c8817129672a6367d45479e9ca3e"
integrity sha512-JBu5TZK3IXzDKw9SuNFwyQFdIx5uGZSmN9QTDsNsDSYdccU/O+43jBUh0zKG4jDc4hiNYYgDw34lLt7qLSeusA==
react-hook-form@^7.22.0:
version "7.22.0"
resolved "https://registry.yarnpkg.com/react-hook-form/-/react-hook-form-7.22.0.tgz#391f0827d487d133333789b60ad7a00e70ad1bdf"
integrity sha512-0gPE29N0wdd/5ZMD+TaAq5LF4NTguLnPaTqdSiWyu1QiSkB6jmWY1q0550JYu2BSgfOHecA7pxky9q+zWAwMqg==
react-hot-toast@^2.0.0:
version "2.0.0"