UserGroupDetailPage.tsx 18 KB

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