UserGroupDetailPage.tsx 16 KB

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