modify frontend for add multiple users

This commit is contained in:
Davor 2022-07-17 20:00:50 +02:00
parent f4a888ad26
commit 4431d72e09
13 changed files with 265 additions and 135 deletions

View file

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

View file

@ -0,0 +1,43 @@
import React from 'react';
import { useController } from 'react-hook-form';
/* eslint-disable react/react-in-jsx-scope */
export const TextArea = ({ control, name, label, required, ...props }: TextAreaProps) => {
const {
field,
// fieldState: { invalid, isTouched, isDirty },
// formState: { touchedFields, dirtyFields },
} = useController({
name,
control,
rules: { required },
defaultValue: '',
});
return (
<>
{label && (
<label htmlFor={name} className="block text-sm font-medium text-gray-700 mb-1">
{label}
</label>
)}
<textarea
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 TextAreaProps = {
control: any;
name: string;
label?: string;
} & React.HTMLProps<HTMLTextAreaElement>;

View file

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

View file

@ -23,26 +23,35 @@ export const appAccessList = [
}, },
]; ];
const initialAppRoles = [ export const allAppAccessList = [
...appAccessList,
{
name: 'dashboard',
image: '/assets/logo-small.svg',
label: 'Dashboard',
},
];
export const initialAppRoles = [
{ {
name: 'dashboard', name: 'dashboard',
role: UserRole.User, role: UserRole.User,
}, },
{ {
name: 'wekan', name: 'wekan',
role: UserRole.NoAccess, role: UserRole.User,
}, },
{ {
name: 'wordpress', name: 'wordpress',
role: UserRole.NoAccess, role: UserRole.User,
}, },
{ {
name: 'nextcloud', name: 'nextcloud',
role: UserRole.NoAccess, role: UserRole.User,
}, },
{ {
name: 'zulip', name: 'zulip',
role: UserRole.NoAccess, role: UserRole.User,
}, },
]; ];

View file

@ -1,10 +1,10 @@
/* eslint-disable react-hooks/exhaustive-deps */ /* eslint-disable react-hooks/exhaustive-deps */
import React, { useState, useCallback, useEffect, useMemo } from 'react'; import React, { useState, useCallback, useEffect, useMemo } from 'react';
import { SearchIcon, PlusIcon } from '@heroicons/react/solid'; import { SearchIcon, PlusIcon, ViewGridAddIcon } from '@heroicons/react/solid';
import { CogIcon, TrashIcon } from '@heroicons/react/outline'; import { CogIcon, TrashIcon } from '@heroicons/react/outline';
import { useUsers } from 'src/services/users'; import { useUsers } from 'src/services/users';
import { Table } from 'src/components'; import { Table } from 'src/components';
import _, { debounce } from 'lodash'; import { debounce } from 'lodash';
import { useAuth } from 'src/services/auth'; import { useAuth } from 'src/services/auth';
import { UserModal } from '../../components/UserModal'; import { UserModal } from '../../components/UserModal';
@ -41,8 +41,11 @@ export const Users: React.FC = () => {
setUserId(id); setUserId(id);
setConfigureModal(true); setConfigureModal(true);
}; };
const configureModalClose = () => setConfigureModal(false); const configureModalClose = () => setConfigureModal(false);
const multipleUsersModalClose = () => setMultipleUsersModal(false);
const columns: any = React.useMemo( const columns: any = React.useMemo(
() => [ () => [
{ {
@ -103,7 +106,7 @@ export const Users: React.FC = () => {
<button <button
onClick={() => configureModalOpen(null)} onClick={() => configureModalOpen(null)}
type="button" 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" 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 mx-5 "
> >
<PlusIcon className="-ml-0.5 mr-2 h-4 w-4" aria-hidden="true" /> <PlusIcon className="-ml-0.5 mr-2 h-4 w-4" aria-hidden="true" />
Add new user Add new user
@ -113,7 +116,7 @@ export const Users: React.FC = () => {
type="button" 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" 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"
> >
<PlusIcon className="-ml-0.5 mr-2 h-4 w-4" aria-hidden="true" /> <ViewGridAddIcon className="-ml-0.5 mr-2 h-4 w-4" aria-hidden="true" />
Add new users Add new users
</button> </button>
</div> </div>
@ -176,13 +179,7 @@ export const Users: React.FC = () => {
{configureModal && ( {configureModal && (
<UserModal open={configureModal} onClose={configureModalClose} userId={userId} setUserId={setUserId} /> <UserModal open={configureModal} onClose={configureModalClose} userId={userId} setUserId={setUserId} />
)} )}
{multipleUsersModal && ( {multipleUsersModal && <MultipleUsersModal open={multipleUsersModal} onClose={multipleUsersModalClose} />}
<MultipleUsersModal
open={multipleUsersModal}
onClose={() => setMultipleUsersModal(false)}
onUpload={_.noop}
/>
)}
</div> </div>
</div> </div>
); );

View file

@ -1,76 +1,31 @@
import React, { ChangeEvent, ChangeEventHandler, useEffect, useState } from 'react'; import React from 'react';
import _ from 'lodash'; import _ from 'lodash';
// import { TrashIcon } from '@heroicons/react/outline'; import { useFieldArray, useForm } from 'react-hook-form';
// import { useFieldArray, useForm, useWatch } from 'react-hook-form';
import { Modal, Tabs } from 'src/components'; import { Modal, Tabs } from 'src/components';
// import { Input, Select } from 'src/components/Form'; import { Select, TextArea } from 'src/components/Form';
import { useUsers } from 'src/services/users'; import { MultipleUsersData, UserRole, useUsers } from 'src/services/users';
import { useAuth } from 'src/services/auth'; import { allAppAccessList } from 'src/components/UserModal/consts';
import { MultipleUsersModalProps } from './types'; import { initialMultipleUsersForm, MultipleUsersModalProps } from './types';
import { csvFileToArray } from './utils';
export const MultipleUsersModal = ({ open, onClose, onUpload }: MultipleUsersModalProps) => { export const MultipleUsersModal = ({ open, onClose }: MultipleUsersModalProps) => {
const [file, setFile] = useState<File>(); const { createUsers, userModalLoading } = useUsers();
const { userModalLoading } = useUsers();
const { currentUser, isAdmin } = useAuth();
const handleOnChange = (e: ChangeEvent<HTMLInputElement>) => { const { control, handleSubmit } = useForm<MultipleUsersData>({
setFile(_.get(e.target, 'files[0]')); defaultValues: initialMultipleUsersForm,
console.log(_.get(e.target, 'files[0]')); });
};
const handleSubmit = () => { const { fields } = useFieldArray({
// e.preventDefault(); control,
name: 'appRoles',
if (file) { });
const formData = new FormData();
formData.append('image', file, file.name);
// console.log('csv to array', csvFileToArray(file));
console.log('submit', formData);
} else {
console.log('nothing in file?');
}
};
const renderUpload = () => {
return (
<div>
<div>Please upload CSV file using , as a delimiter</div>
<div>
<input type="file" id="csvFileInput" accept=".csv" onChange={handleOnChange} />
<button onClick={handleSubmit}>IMPORT CSV</button>
</div>
</div>
);
};
const renderMultilineInput = () => {
return (
<div>
<textarea
rows={5}
name="description"
className="w-full rounded-md border-gray-700 focus:border-gray-700 shadow-none focus:shadow-slate-800"
>
Enter details here...
</textarea>
</div>
);
};
const handleSave = async () => { const handleSave = async () => {
// try { try {
// if (userId) { await handleSubmit((data) => createUsers(data))();
// await handleSubmit((data) => editUserById(data))(); } catch (e: any) {
// } else { // Continue
// await handleSubmit((data) => createNewUser(data))(); }
// }
// } catch (e: any) {
// // Continue
// }
onUpload();
onClose(); onClose();
}; };
@ -79,28 +34,70 @@ export const MultipleUsersModal = ({ open, onClose, onUpload }: MultipleUsersMod
onClose(); onClose();
}; };
const renderUsersCsvDataInput = () => {
return ( return (
<> <div>
<Modal <TextArea
onClose={handleClose} control={control}
open={open} name="csvUserData"
onSave={handleSave} label="CSV user data"
isLoading={userModalLoading} placeholder="Please paste users in CSV format: email,name"
// leftActions={ rows={15}
// userId && required
// user.email !== currentUser?.email && ( />
// <button </div>
// onClick={deleteModalOpen} );
// type="button" };
// className="mb-4 sm:mb-0 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"
// > const renderAppAccess = () => {
// <TrashIcon className="-ml-0.5 mr-2 h-4 w-4" aria-hidden="true" /> return (
// Delete <div>
// </button> <div className="mt-8">
// ) <h3 className="text-lg leading-6 font-medium text-gray-900">App Access</h3>
// } </div>
useCancelButton
> <div>
<div className="flow-root mt-6">
<ul className="-my-5 divide-y divide-gray-200 ">
{fields.map((item, index) => {
return (
<li className="py-4" key={item.name}>
<div className="flex items-center space-x-4">
<div className="flex-shrink-0 flex-1 flex items-center">
<img
className="h-10 w-10 rounded-md overflow-hidden"
src={_.find(allAppAccessList, ['name', item.name!])?.image}
alt={item.name ?? 'Image'}
/>
<h3 className="ml-4 text-md leading-6 font-medium text-gray-900">
{_.find(allAppAccessList, ['name', item.name!])?.label}
</h3>
</div>
<div>
<Select
key={item.id}
control={control}
name={`appRoles.${index}.role`}
options={[
{ value: UserRole.NoAccess, name: 'No Access' },
{ value: UserRole.User, name: 'User' },
{ value: UserRole.Admin, name: 'Admin' },
]}
/>
</div>
</div>
</li>
);
})}
</ul>
</div>
</div>
</div>
);
};
return (
<Modal onClose={handleClose} open={open} onSave={handleSave} isLoading={userModalLoading} useCancelButton>
<div className="bg-white px-4"> <div className="bg-white px-4">
<div className="space-y-10 divide-y divide-gray-200"> <div className="space-y-10 divide-y divide-gray-200">
<div> <div>
@ -110,8 +107,8 @@ export const MultipleUsersModal = ({ open, onClose, onUpload }: MultipleUsersMod
<div className="sm:p-6"> <div className="sm:p-6">
<Tabs <Tabs
tabs={[ tabs={[
{ name: 'Add users', component: renderMultilineInput() }, { name: 'Add users', component: renderUsersCsvDataInput() },
{ name: 'Import from file', component: renderUpload() }, { name: 'App access roles', component: renderAppAccess() },
]} ]}
/> />
</div> </div>
@ -119,6 +116,5 @@ export const MultipleUsersModal = ({ open, onClose, onUpload }: MultipleUsersMod
</div> </div>
</div> </div>
</Modal> </Modal>
</>
); );
}; };

View file

@ -1,5 +1,10 @@
import { initialAppRoles } from 'src/components/UserModal/consts';
export type MultipleUsersModalProps = { export type MultipleUsersModalProps = {
open: boolean; open: boolean;
onClose: () => void; onClose: () => void;
onUpload: () => void; };
export const initialMultipleUsersForm = {
appRoles: initialAppRoles,
}; };

View file

@ -1,14 +0,0 @@
import { User } from 'src/services/users';
export const csvFileToArray = (csvData: string) => {
const csvRows = csvData.slice(csvData.indexOf('\n') + 1).split('\n');
const array = csvRows.map((i) => {
const values = i.split(',');
const email = values[0];
const name = values[1];
return { email, name, app_roles: [], preferredUsername: '', status: '', id: '' } as User;
});
return array;
};

View file

@ -7,6 +7,7 @@ import {
createUser, createUser,
deleteUser, deleteUser,
clearCurrentUser, clearCurrentUser,
createBatchUsers,
} from '../redux'; } from '../redux';
import { getUserById, getUserModalLoading, getUserslLoading } from '../redux/selectors'; import { getUserById, getUserModalLoading, getUserslLoading } from '../redux/selectors';
@ -37,6 +38,10 @@ export function useUsers() {
return dispatch(createUser(data)); return dispatch(createUser(data));
} }
function createUsers(data: any) {
return dispatch(createBatchUsers(data));
}
function deleteUserById(id: string) { function deleteUserById(id: string) {
return dispatch(deleteUser(id)); return dispatch(deleteUser(id));
} }
@ -52,5 +57,6 @@ export function useUsers() {
createNewUser, createNewUser,
deleteUserById, deleteUserById,
clearSelectedUser, clearSelectedUser,
createUsers,
}; };
} }

View file

@ -1,9 +1,15 @@
import _ from 'lodash';
import { Dispatch } from 'redux'; import { Dispatch } from 'redux';
import { showToast, ToastType } from 'src/common/util/show-toast'; import { showToast, ToastType } from 'src/common/util/show-toast';
import { State } from 'src/redux/types'; import { State } from 'src/redux/types';
import { performApiCall } from 'src/services/api'; import { performApiCall } from 'src/services/api';
import { AuthActionTypes } from 'src/services/auth'; import { AuthActionTypes } from 'src/services/auth';
import { transformRequestUser, transformUser } from '../transformations'; import {
transformBatchResponse,
transformRequestMultipleUsers,
transformRequestUser,
transformUser,
} from '../transformations';
export enum UserActionTypes { export enum UserActionTypes {
FETCH_USERS = 'users/fetch_users', FETCH_USERS = 'users/fetch_users',
@ -13,6 +19,7 @@ export enum UserActionTypes {
DELETE_USER = 'users/delete_user', DELETE_USER = 'users/delete_user',
SET_USER_MODAL_LOADING = 'users/user_modal_loading', SET_USER_MODAL_LOADING = 'users/user_modal_loading',
SET_USERS_LOADING = 'users/users_loading', SET_USERS_LOADING = 'users/users_loading',
CREATE_BATCH_USERS = 'users/create_batch_users',
} }
export const setUsersLoading = (isLoading: boolean) => (dispatch: Dispatch<any>) => { export const setUsersLoading = (isLoading: boolean) => (dispatch: Dispatch<any>) => {
@ -154,6 +161,51 @@ export const deleteUser = (id: string) => async (dispatch: Dispatch<any>) => {
dispatch(setUserModalLoading(false)); dispatch(setUserModalLoading(false));
}; };
export const createBatchUsers = (users: any) => async (dispatch: Dispatch<any>) => {
dispatch(setUserModalLoading(true));
try {
const { data } = await performApiCall({
path: '/users-batch',
method: 'POST',
body: transformRequestMultipleUsers(users),
});
const responseData = transformBatchResponse(data);
dispatch({
type: UserActionTypes.CREATE_BATCH_USERS,
payload: responseData,
});
// show information about created users
const createdUsersNumber = _.size(responseData.createdUsers);
if (createdUsersNumber > 0) {
showToast(
`${_.size(responseData.createdUsers)} ${createdUsersNumber > 1 ? 'users' : 'user'} created successfully.`,
ToastType.Success,
);
}
const notCreatedUsersNumber = _.size(responseData.notCreatedUsers);
if (notCreatedUsersNumber > 0) {
showToast(
`${_.size(responseData.notCreatedUsers)}
${notCreatedUsersNumber > 1 ? 'users' : 'user'} not created with
${notCreatedUsersNumber > 1 ? 'emails' : 'email'}: \n${responseData.notCreatedUsers.join(',\n')}`,
ToastType.Error,
);
}
dispatch(fetchUsers());
} catch (err: any) {
dispatch(setUserModalLoading(false));
showToast(`${err}`, ToastType.Error);
throw err;
}
dispatch(setUserModalLoading(false));
};
export const clearCurrentUser = () => (dispatch: Dispatch<any>) => { export const clearCurrentUser = () => (dispatch: Dispatch<any>) => {
dispatch({ dispatch({
type: UserActionTypes.DELETE_USER, type: UserActionTypes.DELETE_USER,

View file

@ -27,6 +27,7 @@ const usersReducer = (state: any = initialUsersState, action: any) => {
case UserActionTypes.FETCH_USER: case UserActionTypes.FETCH_USER:
case UserActionTypes.UPDATE_USER: case UserActionTypes.UPDATE_USER:
case UserActionTypes.CREATE_USER: case UserActionTypes.CREATE_USER:
case UserActionTypes.CREATE_BATCH_USERS:
return { return {
...state, ...state,
isModalVisible: false, isModalVisible: false,

View file

@ -1,4 +1,5 @@
import { AppRoles, User, UserRole } from './types'; import _ from 'lodash';
import { AppRoles, MultipleUsersData, User, UserRole } from './types';
const transformRoleById = (roleId: any): UserRole => { const transformRoleById = (roleId: any): UserRole => {
switch (roleId) { switch (roleId) {
@ -62,3 +63,30 @@ export const transformRequestUser = (data: Pick<User, 'app_roles' | 'name' | 'em
name: data.name ?? '', name: data.name ?? '',
}; };
}; };
const extractUsersFromCsv = (csvData: string) => {
const csvRows = csvData.split('\n');
return _.map(csvRows, (row) => {
const values = row.split(',');
const email = values[0].trim();
const name = !_.isNil(values[1]) ? values[1].trim() : '';
return { email, name, app_roles: [] };
});
};
export const transformRequestMultipleUsers = (data: MultipleUsersData) => {
const batchUsers = extractUsersFromCsv(data.csvUserData);
return {
users: _.map(batchUsers, (user) =>
transformRequestUser({ app_roles: data.appRoles, name: user.name, email: user.email } as User),
),
};
};
export const transformBatchResponse = (response: any): any => {
return {
createdUsers: response.created_users,
notCreatedUsers: response.not_created_users,
};
};

View file

@ -29,3 +29,8 @@ export interface UserApiRequest {
name: string; name: string;
status: string; status: string;
} }
export interface MultipleUsersData {
csvUserData: string;
appRoles: AppRoles[];
}