UserGroupDetailPage.tsx 16 KB

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