UserGroupDetailPage.tsx 18 KB

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