UserGroupDetailPage.tsx 14 KB

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