UserGroupDetailPage.tsx 17 KB

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