UserGroupDetailPage.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. import React, {
  2. FC, useState, useCallback,
  3. } from 'react';
  4. import { useTranslation } from 'react-i18next';
  5. import UserGroupForm from '../UserGroup/UserGroupForm';
  6. import UserGroupTable from '../UserGroup/UserGroupTable';
  7. import UserGroupModal from '../UserGroup/UserGroupModal';
  8. import UserGroupDeleteModal from '../UserGroup/UserGroupDeleteModal';
  9. import UpdateParentConfirmModal from './UpdateParentConfirmModal';
  10. import UserGroupDropdown from '../UserGroup/UserGroupDropdown';
  11. import UserGroupUserTable from './UserGroupUserTable';
  12. import UserGroupUserModal from './UserGroupUserModal';
  13. import UserGroupPageList from './UserGroupPageList';
  14. import {
  15. apiv3Get, apiv3Put, apiv3Delete, apiv3Post,
  16. } from '~/client/util/apiv3-client';
  17. import { toastSuccess, toastError } from '~/client/util/apiNotification';
  18. import { IPageHasId } from '~/interfaces/page';
  19. import {
  20. IUserGroup, IUserGroupHasId,
  21. } from '~/interfaces/user';
  22. import {
  23. useSWRxUserGroupPages, useSWRxUserGroupRelationList, useSWRxChildUserGroupList,
  24. useSWRxSelectableParentUserGroups, useSWRxSelectableChildUserGroups, useSWRxAncestorUserGroups,
  25. } from '~/stores/user-group';
  26. import { useIsAclEnabled } from '~/stores/context';
  27. import { useUpdateUserGroupConfirmModal } from '~/stores/modal';
  28. const UserGroupDetailPage: FC = () => {
  29. const { t } = useTranslation();
  30. const adminUserGroupDetailElem = document.getElementById('admin-user-group-detail');
  31. /*
  32. * State (from AdminUserGroupDetailContainer)
  33. */
  34. const [currentUserGroup, setUserGroup] = useState<IUserGroupHasId>(JSON.parse(adminUserGroupDetailElem?.getAttribute('data-user-group') || 'null'));
  35. const [relatedPages, setRelatedPages] = useState<IPageHasId[]>([]); // For page list
  36. const [searchType, setSearchType] = useState<string>('partial');
  37. const [isAlsoMailSearched, setAlsoMailSearched] = useState<boolean>(false);
  38. const [isAlsoNameSearched, setAlsoNameSearched] = useState<boolean>(false);
  39. const [selectedUserGroup, setSelectedUserGroup] = useState<IUserGroupHasId | undefined>(undefined); // not null but undefined (to use defaultProps in UserGroupDeleteModal)
  40. const [isCreateModalShown, setCreateModalShown] = useState<boolean>(false);
  41. const [isUpdateModalShown, setUpdateModalShown] = useState<boolean>(false);
  42. const [isDeleteModalShown, setDeleteModalShown] = useState<boolean>(false);
  43. /*
  44. * Fetch
  45. */
  46. const { data: userGroupPages } = useSWRxUserGroupPages(currentUserGroup._id, 10, 0);
  47. const { data: childUserGroupsList, mutate: mutateChildUserGroups } = useSWRxChildUserGroupList([currentUserGroup._id], true);
  48. const childUserGroups = childUserGroupsList != null ? childUserGroupsList.childUserGroups : [];
  49. const grandChildUserGroups = childUserGroupsList != null ? childUserGroupsList.grandChildUserGroups : [];
  50. const childUserGroupIds = childUserGroups.map(group => group._id);
  51. const { data: userGroupRelationList, mutate: mutateUserGroupRelations } = useSWRxUserGroupRelationList(childUserGroupIds);
  52. const childUserGroupRelations = userGroupRelationList != null ? userGroupRelationList : [];
  53. const { data: selectableParentUserGroups, mutate: mutateSelectableParentUserGroups } = useSWRxSelectableParentUserGroups(currentUserGroup._id);
  54. const { data: selectableChildUserGroups, mutate: mutateSelectableChildUserGroups } = useSWRxSelectableChildUserGroups(currentUserGroup._id);
  55. const { data: ancestorUserGroups, mutate: mutateAncestorUserGroups } = useSWRxAncestorUserGroups(currentUserGroup._id);
  56. const { data: isAclEnabled } = useIsAclEnabled();
  57. const { open: openUpdateParentConfirmModal } = useUpdateUserGroupConfirmModal();
  58. /*
  59. * Function
  60. */
  61. // TODO 85062: old name: switchIsAlsoMailSearched
  62. const toggleIsAlsoMailSearched = useCallback(() => {
  63. setAlsoMailSearched(prev => !prev);
  64. }, []);
  65. // TODO 85062: old name: switchIsAlsoNameSearched
  66. const toggleAlsoNameSearched = useCallback(() => {
  67. setAlsoNameSearched(prev => !prev);
  68. }, []);
  69. const switchSearchType = useCallback((searchType) => {
  70. setSearchType(searchType);
  71. }, []);
  72. const updateUserGroup = useCallback(async(userGroup: IUserGroupHasId, update: Partial<IUserGroupHasId>, forceUpdateParents: boolean) => {
  73. if (update.parent == null) {
  74. throw Error('"parent" attr must not be null');
  75. }
  76. const parentId = typeof update.parent === 'string' ? update.parent : update.parent?._id;
  77. const res = await apiv3Put<{ userGroup: IUserGroupHasId }>(`/user-groups/${userGroup._id}`, {
  78. name: update.name,
  79. description: update.description,
  80. parentId,
  81. forceUpdateParents,
  82. });
  83. const { userGroup: updatedUserGroup } = res.data;
  84. setUserGroup(updatedUserGroup);
  85. // mutate
  86. mutateAncestorUserGroups();
  87. mutateSelectableChildUserGroups();
  88. mutateSelectableParentUserGroups();
  89. }, [setUserGroup, mutateAncestorUserGroups, mutateSelectableChildUserGroups, mutateSelectableParentUserGroups]);
  90. const onSubmitUpdateGroup = useCallback(
  91. async(targetGroup: IUserGroupHasId, userGroupData: Partial<IUserGroupHasId>, forceUpdateParents: boolean): Promise<void> => {
  92. try {
  93. await updateUserGroup(targetGroup, userGroupData, forceUpdateParents);
  94. toastSuccess(t('toaster.update_successed', { target: t('UserGroup') }));
  95. }
  96. catch {
  97. toastError(t('toaster.update_failed', { target: t('UserGroup') }));
  98. }
  99. },
  100. [t, updateUserGroup],
  101. );
  102. const onClickSubmitForm = useCallback(async(targetGroup: IUserGroupHasId, userGroupData: Partial<IUserGroupHasId>): Promise<void> => {
  103. if (userGroupData?.parent === undefined || typeof userGroupData?.parent === 'string') {
  104. toastError(t('Something went wrong. Please try again.'));
  105. return;
  106. }
  107. const prevParentId = typeof targetGroup.parent === 'string' ? targetGroup.parent : (targetGroup.parent?._id || null);
  108. const newParentId = typeof userGroupData.parent?._id === 'string' ? userGroupData.parent?._id : null;
  109. const shouldShowConfirmModal = prevParentId !== newParentId;
  110. if (shouldShowConfirmModal) { // show confirm modal before submiting
  111. await openUpdateParentConfirmModal(
  112. targetGroup,
  113. userGroupData,
  114. onSubmitUpdateGroup,
  115. );
  116. }
  117. else { // directly submit
  118. await onSubmitUpdateGroup(targetGroup, userGroupData, false);
  119. }
  120. }, [t, openUpdateParentConfirmModal, onSubmitUpdateGroup]);
  121. const fetchApplicableUsers = useCallback(async(searchWord) => {
  122. const res = await apiv3Get(`/user-groups/${currentUserGroup._id}/unrelated-users`, {
  123. searchWord,
  124. searchType,
  125. isAlsoMailSearched,
  126. isAlsoNameSearched,
  127. });
  128. const { users } = res.data;
  129. return users;
  130. }, [searchType, isAlsoMailSearched, isAlsoNameSearched]);
  131. // TODO 85062: will be used in UserGroupUserFormByInput
  132. const addUserByUsername = useCallback(async(username: string) => {
  133. await apiv3Post(`/user-groups/${currentUserGroup._id}/users/${username}`);
  134. mutateUserGroupRelations();
  135. }, [currentUserGroup, mutateUserGroupRelations]);
  136. const removeUserByUsername = useCallback(async(username: string) => {
  137. await apiv3Delete(`/user-groups/${currentUserGroup._id}/users/${username}`);
  138. mutateUserGroupRelations();
  139. }, [currentUserGroup, mutateUserGroupRelations]);
  140. const showUpdateModal = useCallback((group: IUserGroupHasId) => {
  141. setUpdateModalShown(true);
  142. setSelectedUserGroup(group);
  143. }, [setUpdateModalShown]);
  144. const hideUpdateModal = useCallback(() => {
  145. setUpdateModalShown(false);
  146. setSelectedUserGroup(undefined);
  147. }, [setUpdateModalShown]);
  148. const updateChildUserGroup = useCallback(async(userGroupData: IUserGroupHasId) => {
  149. try {
  150. await apiv3Put(`/user-groups/${userGroupData._id}`, {
  151. name: userGroupData.name,
  152. description: userGroupData.description,
  153. parentId: userGroupData.parent,
  154. });
  155. toastSuccess(t('toaster.update_successed', { target: t('UserGroup') }));
  156. // mutate
  157. mutateChildUserGroups();
  158. hideUpdateModal();
  159. }
  160. catch (err) {
  161. toastError(err);
  162. }
  163. }, [t, mutateChildUserGroups, hideUpdateModal]);
  164. const onClickAddExistingUserGroupButtonHandler = useCallback(async(selectedChild: IUserGroupHasId): Promise<void> => {
  165. // show confirm modal before submiting
  166. await openUpdateParentConfirmModal(
  167. selectedChild,
  168. {
  169. parent: currentUserGroup._id,
  170. },
  171. onSubmitUpdateGroup,
  172. );
  173. }, [openUpdateParentConfirmModal, onSubmitUpdateGroup, currentUserGroup]);
  174. const showCreateModal = useCallback(() => {
  175. setCreateModalShown(true);
  176. }, [setCreateModalShown]);
  177. const hideCreateModal = useCallback(() => {
  178. setCreateModalShown(false);
  179. }, [setCreateModalShown]);
  180. const createChildUserGroup = useCallback(async(userGroupData: IUserGroup) => {
  181. try {
  182. await apiv3Post('/user-groups', {
  183. name: userGroupData.name,
  184. description: userGroupData.description,
  185. parentId: currentUserGroup._id,
  186. });
  187. toastSuccess(t('toaster.update_successed', { target: t('UserGroup') }));
  188. // mutate
  189. mutateChildUserGroups();
  190. mutateSelectableChildUserGroups();
  191. mutateSelectableParentUserGroups();
  192. hideCreateModal();
  193. }
  194. catch (err) {
  195. toastError(err);
  196. }
  197. }, [t, currentUserGroup, mutateChildUserGroups, mutateSelectableChildUserGroups, mutateSelectableParentUserGroups, hideCreateModal]);
  198. const showDeleteModal = useCallback(async(group: IUserGroupHasId) => {
  199. setSelectedUserGroup(group);
  200. setDeleteModalShown(true);
  201. }, [setSelectedUserGroup, setDeleteModalShown]);
  202. const hideDeleteModal = useCallback(() => {
  203. setSelectedUserGroup(undefined);
  204. setDeleteModalShown(false);
  205. }, [setSelectedUserGroup, setDeleteModalShown]);
  206. const deleteChildUserGroupById = useCallback(async(deleteGroupId: string, actionName: string, transferToUserGroupId: string) => {
  207. try {
  208. const res = await apiv3Delete(`/user-groups/${deleteGroupId}`, {
  209. actionName,
  210. transferToUserGroupId,
  211. });
  212. // sync
  213. await mutateChildUserGroups();
  214. setSelectedUserGroup(undefined);
  215. setDeleteModalShown(false);
  216. toastSuccess(`Deleted ${res.data.userGroups.length} groups.`);
  217. }
  218. catch (err) {
  219. toastError(new Error('Unable to delete the groups'));
  220. }
  221. }, [mutateChildUserGroups, setSelectedUserGroup, setDeleteModalShown]);
  222. /*
  223. * Dependencies
  224. */
  225. if (currentUserGroup == null) {
  226. return <></>;
  227. }
  228. return (
  229. <div>
  230. <nav aria-label="breadcrumb">
  231. <ol className="breadcrumb">
  232. <li className="breadcrumb-item"><a href="/admin/user-groups">{t('admin:user_group_management.group_list')}</a></li>
  233. {
  234. ancestorUserGroups != null && ancestorUserGroups.length > 0 && (
  235. ancestorUserGroups.map((ancestorUserGroup: IUserGroupHasId) => (
  236. // eslint-disable-next-line max-len
  237. <li key={ancestorUserGroup._id} className={`breadcrumb-item ${ancestorUserGroup._id === currentUserGroup._id ? 'active' : ''}`} aria-current="page">
  238. { ancestorUserGroup._id === currentUserGroup._id ? (
  239. <>{ancestorUserGroup.name}</>
  240. ) : (
  241. <a href={`/admin/user-group-detail/${ancestorUserGroup._id}`}>{ancestorUserGroup.name}</a>
  242. )}
  243. </li>
  244. ))
  245. )
  246. }
  247. </ol>
  248. </nav>
  249. <div className="mt-4 form-box">
  250. <UserGroupForm
  251. userGroup={currentUserGroup}
  252. selectableParentUserGroups={selectableParentUserGroups}
  253. submitButtonLabel={t('Update')}
  254. onSubmit={onClickSubmitForm}
  255. />
  256. </div>
  257. <h2 className="admin-setting-header mt-4">{t('admin:user_group_management.user_list')}</h2>
  258. <UserGroupUserTable />
  259. <UserGroupUserModal />
  260. <h2 className="admin-setting-header mt-4">{t('admin:user_group_management.child_group_list')}</h2>
  261. <UserGroupDropdown
  262. selectableUserGroups={selectableChildUserGroups}
  263. onClickAddExistingUserGroupButton={onClickAddExistingUserGroupButtonHandler}
  264. onClickCreateUserGroupButton={showCreateModal}
  265. />
  266. <UserGroupModal
  267. userGroup={selectedUserGroup}
  268. buttonLabel={t('Update')}
  269. onClickSubmit={updateChildUserGroup}
  270. isShow={isUpdateModalShown}
  271. onHide={hideUpdateModal}
  272. />
  273. <UserGroupModal
  274. buttonLabel={t('Create')}
  275. onClickSubmit={createChildUserGroup}
  276. isShow={isCreateModalShown}
  277. onHide={hideCreateModal}
  278. />
  279. <UpdateParentConfirmModal />
  280. <UserGroupTable
  281. userGroups={childUserGroups}
  282. childUserGroups={grandChildUserGroups}
  283. isAclEnabled={isAclEnabled ?? false}
  284. onEdit={showUpdateModal}
  285. onDelete={showDeleteModal}
  286. userGroupRelations={childUserGroupRelations}
  287. />
  288. <UserGroupDeleteModal
  289. userGroups={childUserGroups}
  290. deleteUserGroup={selectedUserGroup}
  291. onDelete={deleteChildUserGroupById}
  292. isShow={isDeleteModalShown}
  293. onHide={hideDeleteModal}
  294. />
  295. <h2 className="admin-setting-header mt-4">{t('Page')}</h2>
  296. <div className="page-list">
  297. <UserGroupPageList />
  298. </div>
  299. </div>
  300. );
  301. };
  302. export default UserGroupDetailPage;