UserGroupDetailPage.tsx 15 KB

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