UserGroupDetailPage.tsx 16 KB

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