UserGroupDetailPage.tsx 18 KB

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