UserGroupDetailPage.tsx 16 KB

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