UserGroupDetailPage.tsx 18 KB

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