Просмотр исходного кода

Merge pull request #1169 from weseek/imprv/reactify-admin-user-groups-detail-2

Imprv/reactify admin user groups detail 2
Yuki Takei 6 лет назад
Родитель
Сommit
31937b86f6

+ 0 - 2
resource/locales/en-US/translation.json

@@ -719,8 +719,6 @@
     "select_group": "Select a group",
     "no_groups": "No groups to select",
     "no_pages": "There are no pages the group has view permission",
-    "how_to_add1": "Enter a username to add",
-    "how_to_add2": "Select a user from user list",
     "remove_from_group": "Remove this user"
   },
 

+ 0 - 2
resource/locales/ja/translation.json

@@ -703,8 +703,6 @@
     "select_group": "グループを選択してください",
     "no_groups": "グループがありません",
     "no_pages": "グループが閲覧権限を保有するページはありません",
-    "how_to_add1": "ユーザー名を入力して追加",
-    "how_to_add2": "ユーザーを下のリストから選択",
     "remove_from_group": "グループから外す"
   },
 

+ 3 - 1
src/client/js/app.jsx

@@ -47,6 +47,7 @@ import PageContainer from './services/PageContainer';
 import CommentContainer from './services/CommentContainer';
 import EditorContainer from './services/EditorContainer';
 import TagContainer from './services/TagContainer';
+import UserGroupDetailContainer from './services/UserGroupDetailContainer';
 import WebsocketContainer from './services/WebsocketContainer';
 
 const logger = loggerFactory('growi:app');
@@ -151,8 +152,9 @@ Object.keys(componentMappings).forEach((key) => {
 // render for admin
 const adminUserGroupDetailElem = document.getElementById('admin-user-group-detail');
 if (adminUserGroupDetailElem != null) {
+  const userGroupDetailContainer = new UserGroupDetailContainer(appContainer);
   ReactDOM.render(
-    <Provider inject={[]}>
+    <Provider inject={[userGroupDetailContainer]}>
       <I18nextProvider i18n={i18n}>
         <UserGroupDetailPage />
       </I18nextProvider>

+ 1 - 1
src/client/js/components/Admin/UserGroup/UserGroupTable.jsx

@@ -73,7 +73,7 @@ class UserGroupTable extends React.Component {
                       })}
                     </ul>
                   </td>
-                  <td>{dateFnsFormat(new Date(group.createdAt), 'yyyy-MM-dd')}</td>
+                  <td>{dateFnsFormat(new Date(group.createdAt), 'YYYY-MM-DD')}</td>
                   {this.props.isAclEnabled
                     ? (
                       <td>

+ 26 - 16
src/client/js/components/Admin/UserGroupDetail/UserGroupDetailPage.jsx

@@ -1,24 +1,18 @@
 import React from 'react';
+import PropTypes from 'prop-types';
+import { withTranslation } from 'react-i18next';
 
 import UserGroupEditForm from './UserGroupEditForm';
 import UserGroupUserTable from './UserGroupUserTable';
 import UserGroupUserModal from './UserGroupUserModal';
 import UserGroupPageList from './UserGroupPageList';
+import { createSubscribedElement } from '../../UnstatedUtils';
+import AppContainer from '../../../services/AppContainer';
 
 class UserGroupDetailPage extends React.Component {
 
-  constructor(props) {
-    super(props);
-
-    const elem = document.getElementById('admin-user-group-detail');
-    const userGroup = JSON.parse(elem.getAttribute('data-user-group'));
-
-    this.state = {
-      userGroup,
-    };
-  }
-
   render() {
+    const { t } = this.props;
 
     return (
       <div>
@@ -26,16 +20,32 @@ class UserGroupDetailPage extends React.Component {
           <i className="icon-fw ti-arrow-left" aria-hidden="true"></i>
         グループ一覧に戻る
         </a>
-        <UserGroupEditForm
-          userGroup={this.state.userGroup}
-        />
+        <div className="m-t-20 form-box">
+          <UserGroupEditForm />
+        </div>
+        <legend className="m-t-20">{ t('User List') }</legend>
         <UserGroupUserTable />
         <UserGroupUserModal />
-        <UserGroupPageList />
+        <legend className="m-t-20">{ t('Page') }</legend>
+        <div className="page-list">
+          <UserGroupPageList />
+        </div>
       </div>
     );
   }
 
 }
 
-export default UserGroupDetailPage;
+UserGroupDetailPage.propTypes = {
+  t: PropTypes.func.isRequired, // i18next
+  appContainer: PropTypes.instanceOf(AppContainer).isRequired,
+};
+
+/**
+ * Wrapper component for using unstated
+ */
+const UserGroupDetailPageWrapper = (props) => {
+  return createSubscribedElement(UserGroupDetailPage, props, [AppContainer]);
+};
+
+export default withTranslation()(UserGroupDetailPageWrapper);

+ 38 - 29
src/client/js/components/Admin/UserGroupDetail/UserGroupEditForm.jsx

@@ -5,6 +5,7 @@ import dateFnsFormat from 'date-fns/format';
 
 import { createSubscribedElement } from '../../UnstatedUtils';
 import AppContainer from '../../../services/AppContainer';
+import UserGroupDetailContainer from '../../../services/UserGroupDetailContainer';
 import { toastSuccess, toastError } from '../../../util/apiNotification';
 
 class UserGroupEditForm extends React.Component {
@@ -13,17 +14,18 @@ class UserGroupEditForm extends React.Component {
     super(props);
 
     this.state = {
-      name: props.userGroup.name,
+      name: props.userGroupDetailContainer.state.userGroup.name,
+      nameCache: props.userGroupDetailContainer.state.userGroup.name, // cache for name. update every submit
     };
 
     this.xss = window.xss;
 
-    this.handleChange = this.handleChange.bind(this);
+    this.changeUserGroupName = this.changeUserGroupName.bind(this);
     this.handleSubmit = this.handleSubmit.bind(this);
     this.validateForm = this.validateForm.bind(this);
   }
 
-  handleChange(event) {
+  changeUserGroupName(event) {
     this.setState({
       name: event.target.value,
     });
@@ -33,11 +35,12 @@ class UserGroupEditForm extends React.Component {
     e.preventDefault();
 
     try {
-      const res = await this.props.appContainer.apiv3.put(`/user-groups/${this.props.userGroup._id}`, {
+      const res = await this.props.userGroupDetailContainer.updateUserGroup({
         name: this.state.name,
       });
 
       toastSuccess(`Updated the group name to "${this.xss.process(res.data.userGroup.name)}"`);
+      this.setState({ nameCache: this.state.name });
     }
     catch (err) {
       toastError(new Error('Unable to update the group name'));
@@ -45,37 +48,43 @@ class UserGroupEditForm extends React.Component {
   }
 
   validateForm() {
-    return this.state.name !== '';
+    return (
+      this.state.name !== this.state.nameCache
+      && this.state.name !== ''
+    );
   }
 
   render() {
-    const { t } = this.props;
+    const { t, userGroupDetailContainer } = this.props;
 
     return (
-      <div className="m-t-20 form-box">
-        <form className="form-horizontal" onSubmit={this.handleSubmit}>
-          <fieldset>
-            <legend>基本情報</legend>
-            <div className="form-group">
-              <label htmlFor="name" className="col-sm-2 control-label">{ t('Name') }</label>
-              <div className="col-sm-4">
-                <input className="form-control" type="text" name="name" value={this.state.name} onChange={this.handleChange} disabled={!this.validateForm()} />
-              </div>
+      <form className="form-horizontal" onSubmit={this.handleSubmit}>
+        <fieldset>
+          <legend>基本情報</legend>
+          <div className="form-group">
+            <label htmlFor="name" className="col-sm-2 control-label">{ t('Name') }</label>
+            <div className="col-sm-4">
+              <input className="form-control" type="text" name="name" value={this.state.name} onChange={this.changeUserGroupName} />
             </div>
-            <div className="form-group">
-              <label className="col-sm-2 control-label">{ t('Created') }</label>
-              <div className="col-sm-4">
-                <input className="form-control" type="text" disabled value={dateFnsFormat(new Date(this.props.userGroup.createdAt), 'yyyy-MM-dd')} />
-              </div>
+          </div>
+          <div className="form-group">
+            <label className="col-sm-2 control-label">{ t('Created') }</label>
+            <div className="col-sm-4">
+              <input
+                type="text"
+                className="form-control"
+                value={dateFnsFormat(new Date(userGroupDetailContainer.state.userGroup.createdAt), 'YYYY-MM-DD')}
+                disabled
+              />
             </div>
-            <div className="form-group">
-              <div className="col-sm-offset-2 col-sm-10">
-                <button type="submit" className="btn btn-primary">{ t('Update') }</button>
-              </div>
+          </div>
+          <div className="form-group">
+            <div className="col-sm-offset-2 col-sm-10">
+              <button type="submit" className="btn btn-primary" disabled={!this.validateForm()}>{ t('Update') }</button>
             </div>
-          </fieldset>
-        </form>
-      </div>
+          </div>
+        </fieldset>
+      </form>
     );
   }
 
@@ -84,14 +93,14 @@ class UserGroupEditForm extends React.Component {
 UserGroupEditForm.propTypes = {
   t: PropTypes.func.isRequired, // i18next
   appContainer: PropTypes.instanceOf(AppContainer).isRequired,
-  userGroup: PropTypes.object.isRequired,
+  userGroupDetailContainer: PropTypes.instanceOf(UserGroupDetailContainer).isRequired,
 };
 
 /**
  * Wrapper component for using unstated
  */
 const UserGroupEditFormWrapper = (props) => {
-  return createSubscribedElement(UserGroupEditForm, props, [AppContainer]);
+  return createSubscribedElement(UserGroupEditForm, props, [AppContainer, UserGroupDetailContainer]);
 };
 
 export default withTranslation()(UserGroupEditFormWrapper);

+ 26 - 6
src/client/js/components/Admin/UserGroupDetail/UserGroupPageList.jsx

@@ -1,20 +1,40 @@
-import React from 'react';
-// import PropTypes from 'prop-types';
+import React, { Fragment } from 'react';
+import PropTypes from 'prop-types';
+import { withTranslation } from 'react-i18next';
+
+import Page from '../../PageList/Page';
+import { createSubscribedElement } from '../../UnstatedUtils';
+import AppContainer from '../../../services/AppContainer';
+import UserGroupDetailContainer from '../../../services/UserGroupDetailContainer';
 
 class UserGroupPageList extends React.Component {
 
   render() {
+    const { t, userGroupDetailContainer } = this.props;
 
     return (
-      <div>
-        UserGroupPageList
-      </div>
+      <Fragment>
+        <ul className="page-list-ul page-list-ul-flat">
+          {userGroupDetailContainer.state.relatedPages.map((page) => { return <Page key={page._id} page={page} /> })}
+        </ul>
+        {userGroupDetailContainer.state.relatedPages.length === 0 ? <p>{ t('user_group_management.no_pages') }</p> : null}
+      </Fragment>
     );
   }
 
 }
 
 UserGroupPageList.propTypes = {
+  t: PropTypes.func.isRequired, // i18next
+  appContainer: PropTypes.instanceOf(AppContainer).isRequired,
+  userGroupDetailContainer: PropTypes.instanceOf(UserGroupDetailContainer).isRequired,
+};
+
+/**
+ * Wrapper component for using unstated
+ */
+const UserGroupPageListWrapper = (props) => {
+  return createSubscribedElement(UserGroupPageList, props, [AppContainer, UserGroupDetailContainer]);
 };
 
-export default UserGroupPageList;
+export default withTranslation()(UserGroupPageListWrapper);

+ 83 - 0
src/client/js/components/Admin/UserGroupDetail/UserGroupUserFormByInput.jsx

@@ -0,0 +1,83 @@
+import React from 'react';
+import PropTypes from 'prop-types';
+import { withTranslation } from 'react-i18next';
+
+import { createSubscribedElement } from '../../UnstatedUtils';
+import AppContainer from '../../../services/AppContainer';
+import UserGroupDetailContainer from '../../../services/UserGroupDetailContainer';
+import { toastSuccess, toastError } from '../../../util/apiNotification';
+
+class UserGroupUserFormByInput extends React.Component {
+
+  constructor(props) {
+    super(props);
+
+    this.state = {
+      username: '',
+    };
+
+    this.xss = window.xss;
+
+    this.changeUsername = this.changeUsername.bind(this);
+    this.addUserBySubmit = this.addUserBySubmit.bind(this);
+    this.validateForm = this.validateForm.bind(this);
+  }
+
+  changeUsername(e) {
+    this.setState({ username: e.target.value });
+  }
+
+  async addUserBySubmit(e) {
+    e.preventDefault();
+    const { username } = this.state;
+
+    try {
+      await this.props.userGroupDetailContainer.addUserByUsername(username);
+      toastSuccess(`Added "${this.xss.process(username)}" to "${this.xss.process(this.props.userGroupDetailContainer.state.userGroup.name)}"`);
+      this.setState({ username: '' });
+    }
+    catch (err) {
+      toastError(new Error(`Unable to add "${this.xss.process(username)}" to "${this.xss.process(this.props.userGroupDetailContainer.state.userGroup.name)}"`));
+    }
+  }
+
+  validateForm() {
+    return this.state.username !== '';
+  }
+
+  render() {
+    const { t } = this.props;
+
+    return (
+      <form className="form-inline" onSubmit={this.addUserBySubmit}>
+        <div className="form-group">
+          <input
+            type="text"
+            name="username"
+            className="form-control input-sm"
+            placeholder={t('User Name')}
+            value={this.state.username}
+            onChange={this.changeUsername}
+          />
+        </div>
+        <button type="submit" className="btn btn-sm btn-success" disabled={!this.validateForm()}>{ t('Add') }</button>
+      </form>
+    );
+  }
+
+}
+
+UserGroupUserFormByInput.propTypes = {
+  t: PropTypes.func.isRequired, // i18next
+  appContainer: PropTypes.instanceOf(AppContainer).isRequired,
+  userGroupDetailContainer: PropTypes.instanceOf(UserGroupDetailContainer).isRequired,
+};
+
+/**
+ * Wrapper component for using unstated
+ */
+const UserGroupUserFormByInputWrapper = (props) => {
+  return createSubscribedElement(UserGroupUserFormByInput, props, [AppContainer, UserGroupDetailContainer]);
+};
+
+export default withTranslation()(UserGroupUserFormByInputWrapper);

+ 28 - 5
src/client/js/components/Admin/UserGroupDetail/UserGroupUserModal.jsx

@@ -1,20 +1,43 @@
 import React from 'react';
-// import PropTypes from 'prop-types';
+import PropTypes from 'prop-types';
+import { withTranslation } from 'react-i18next';
+import Modal from 'react-bootstrap/es/Modal';
+
+import UserGroupUserFormByInput from './UserGroupUserFormByInput';
+import { createSubscribedElement } from '../../UnstatedUtils';
+import AppContainer from '../../../services/AppContainer';
+import UserGroupDetailContainer from '../../../services/UserGroupDetailContainer';
 
 class UserGroupUserModal extends React.Component {
 
   render() {
+    const { t, userGroupDetailContainer } = this.props;
 
     return (
-      <div>
-        UserGroupUserModal
-      </div>
+      <Modal show={userGroupDetailContainer.state.isUserGroupUserModalOpen} onHide={userGroupDetailContainer.closeUserGroupUserModal}>
+        <Modal.Header closeButton>
+          <Modal.Title>{ t('user_group_management.add_user') }</Modal.Title>
+        </Modal.Header>
+        <Modal.Body>
+          <UserGroupUserFormByInput />
+        </Modal.Body>
+      </Modal>
     );
   }
 
 }
 
 UserGroupUserModal.propTypes = {
+  t: PropTypes.func.isRequired, // i18next
+  appContainer: PropTypes.instanceOf(AppContainer).isRequired,
+  userGroupDetailContainer: PropTypes.instanceOf(UserGroupDetailContainer).isRequired,
+};
+
+/**
+ * Wrapper component for using unstated
+ */
+const UserGroupUserModalWrapper = (props) => {
+  return createSubscribedElement(UserGroupUserModal, props, [AppContainer, UserGroupDetailContainer]);
 };
 
-export default UserGroupUserModal;
+export default withTranslation()(UserGroupUserModalWrapper);

+ 101 - 5
src/client/js/components/Admin/UserGroupDetail/UserGroupUserTable.jsx

@@ -1,20 +1,116 @@
 import React from 'react';
-// import PropTypes from 'prop-types';
+import PropTypes from 'prop-types';
+import { withTranslation } from 'react-i18next';
+import dateFnsFormat from 'date-fns/format';
+
+import UserPicture from '../../User/UserPicture';
+import { createSubscribedElement } from '../../UnstatedUtils';
+import AppContainer from '../../../services/AppContainer';
+import UserGroupDetailContainer from '../../../services/UserGroupDetailContainer';
+import { toastSuccess, toastError } from '../../../util/apiNotification';
 
 class UserGroupUserTable extends React.Component {
 
+  constructor(props) {
+    super(props);
+
+    this.xss = window.xss;
+
+    this.removeUser = this.removeUser.bind(this);
+  }
+
+  async removeUser(username) {
+    try {
+      await this.props.userGroupDetailContainer.removeUserByUsername(username);
+      toastSuccess(`Removed "${this.xss.process(username)}" from "${this.xss.process(this.props.userGroupDetailContainer.state.userGroup.name)}"`);
+    }
+    catch (err) {
+      // eslint-disable-next-line max-len
+      toastError(new Error(`Unable to remove "${this.xss.process(username)}" from "${this.xss.process(this.props.userGroupDetailContainer.state.userGroup.name)}"`));
+    }
+  }
+
   render() {
+    const { t, userGroupDetailContainer } = this.props;
 
     return (
-      <div>
-        UserGroupUserTable
-      </div>
+      <table className="table table-bordered table-user-list">
+        <thead>
+          <tr>
+            <th width="100px">#</th>
+            <th>
+              { t('User') }
+            </th>
+            <th>{ t('Name') }</th>
+            <th width="100px">{ t('Created') }</th>
+            <th width="160px">{ t('Last Login')}</th>
+            <th width="70px"></th>
+          </tr>
+        </thead>
+        <tbody>
+          {userGroupDetailContainer.state.userGroupRelations.map((sRelation) => {
+              const { relatedUser } = sRelation;
+
+              return (
+                <tr key={sRelation._id}>
+                  <td>
+                    <UserPicture user={relatedUser} className="picture img-circle" />
+                  </td>
+                  <td>
+                    <strong>{relatedUser.username}</strong>
+                  </td>
+                  <td>{relatedUser.name}</td>
+                  <td>{relatedUser.createdAt ? dateFnsFormat(new Date(relatedUser.createdAt), 'YYYY-MM-DD') : ''}</td>
+                  <td>{relatedUser.lastLoginAt ? dateFnsFormat(new Date(relatedUser.lastLoginAt), 'YYYY-MM-DD HH:mm:ss') : ''}</td>
+                  <td>
+                    <div className="btn-group admin-user-menu">
+                      <button type="button" className="btn btn-default btn-sm dropdown-toggle" data-toggle="dropdown">
+                        <i className="icon-settings"></i> <span className="caret"></span>
+                      </button>
+                      <ul className="dropdown-menu" role="menu">
+                        <li>
+                          <a onClick={() => { return this.removeUser(relatedUser.username) }}>
+                            <i className="icon-fw icon-user-unfollow"></i> { t('user_group_management.remove_from_group')}
+                          </a>
+                        </li>
+                      </ul>
+                    </div>
+                  </td>
+                </tr>
+              );
+            })}
+
+          <tr>
+            <td></td>
+            <td className="text-center">
+              <button className="btn btn-default" type="button" onClick={userGroupDetailContainer.openUserGroupUserModal}>
+                <i className="ti-plus"></i>
+              </button>
+            </td>
+            <td></td>
+            <td></td>
+            <td></td>
+            <td></td>
+          </tr>
+
+        </tbody>
+      </table>
     );
   }
 
 }
 
 UserGroupUserTable.propTypes = {
+  t: PropTypes.func.isRequired, // i18next
+  appContainer: PropTypes.instanceOf(AppContainer).isRequired,
+  userGroupDetailContainer: PropTypes.instanceOf(UserGroupDetailContainer).isRequired,
+};
+
+/**
+ * Wrapper component for using unstated
+ */
+const UserGroupUserTableWrapper = (props) => {
+  return createSubscribedElement(UserGroupUserTable, props, [AppContainer, UserGroupDetailContainer]);
 };
 
-export default UserGroupUserTable;
+export default withTranslation()(UserGroupUserTableWrapper);

+ 0 - 8
src/client/js/legacy/crowi-admin.js

@@ -61,14 +61,6 @@ $(() => {
     return false;
   });
 
-  $('form#user-group-relation-create').on('submit', function(e) {
-    $.post('/admin/user-group-relation/create', $(this).serialize(), (res) => {
-      $('#admin-add-user-group-relation-modal').modal('hide');
-      return;
-    });
-  });
-
-
   $('#pictureUploadForm input[name=userGroupPicture]').on('change', function() {
     const $form = $('#pictureUploadForm');
     const fd = new FormData($form[0]);

+ 3 - 3
src/client/js/services/AppContainer.js

@@ -332,7 +332,7 @@ export default class AppContainer extends Container {
     return this.apiv3Request('get', path, { params });
   }
 
-  async apiv3Post(path, params) {
+  async apiv3Post(path, params = {}) {
     if (!params._csrf) {
       params._csrf = this.csrfToken;
     }
@@ -340,7 +340,7 @@ export default class AppContainer extends Container {
     return this.apiv3Request('post', path, params);
   }
 
-  async apiv3Put(path, params) {
+  async apiv3Put(path, params = {}) {
     if (!params._csrf) {
       params._csrf = this.csrfToken;
     }
@@ -348,7 +348,7 @@ export default class AppContainer extends Container {
     return this.apiv3Request('put', path, params);
   }
 
-  async apiv3Delete(path, params) {
+  async apiv3Delete(path, params = {}) {
     if (!params._csrf) {
       params._csrf = this.csrfToken;
     }

+ 135 - 0
src/client/js/services/UserGroupDetailContainer.js

@@ -0,0 +1,135 @@
+import { Container } from 'unstated';
+
+import loggerFactory from '@alias/logger';
+
+import { toastError } from '../util/apiNotification';
+
+// eslint-disable-next-line no-unused-vars
+const logger = loggerFactory('growi:services:UserGroupDetailContainer');
+
+/**
+ * Service container for admin user group detail page (UserGroupDetailPage.jsx)
+ * @extends {Container} unstated Container
+ */
+export default class UserGroupDetailContainer extends Container {
+
+  constructor(appContainer) {
+    super();
+
+    this.appContainer = appContainer;
+
+    this.state = {
+      // TODO: [SPA] get userGroup from props
+      userGroup: JSON.parse(document.getElementById('admin-user-group-detail').getAttribute('data-user-group')),
+      userGroupRelations: [],
+      relatedPages: [],
+      isUserGroupUserModalOpen: false,
+    };
+
+    this.init();
+
+    this.openUserGroupUserModal = this.openUserGroupUserModal.bind(this);
+    this.closeUserGroupUserModal = this.closeUserGroupUserModal.bind(this);
+    this.addUserByUsername = this.addUserByUsername.bind(this);
+    this.removeUserByUsername = this.removeUserByUsername.bind(this);
+  }
+
+  /**
+   * Workaround for the mangling in production build to break constructor.name
+   */
+  static getClassName() {
+    return 'UserGroupDetailContainer';
+  }
+
+  /**
+   * retrieve user group data
+   */
+  async init() {
+    try {
+      const [
+        userGroupRelations,
+        relatedPages,
+      ] = await Promise.all([
+        this.appContainer.apiv3.get(`/user-groups/${this.state.userGroup._id}/user-group-relations`).then((res) => { return res.data.userGroupRelations }),
+        this.appContainer.apiv3.get(`/user-groups/${this.state.userGroup._id}/pages`).then((res) => { return res.data.pages }),
+      ]);
+
+      await this.setState({
+        userGroupRelations,
+        relatedPages,
+      });
+    }
+    catch (err) {
+      logger.error(err);
+      toastError(new Error('Failed to fetch data'));
+    }
+  }
+
+  /**
+   * update user group
+   *
+   * @memberOf UserGroupDetailContainer
+   * @param {object} param update param for user group
+   * @return {object} response object
+   */
+  async updateUserGroup(param) {
+    const res = await this.appContainer.apiv3.put(`/user-groups/${this.state.userGroup._id}`, param);
+    const { userGroup } = res.data;
+
+    await this.setState({ userGroup });
+
+    return res;
+  }
+
+  /**
+   * open a modal
+   *
+   * @memberOf UserGroupDetailContainer
+   */
+  async openUserGroupUserModal() {
+    await this.setState({ isUserGroupUserModalOpen: true });
+  }
+
+  /**
+   * close a modal
+   *
+   * @memberOf UserGroupDetailContainer
+   */
+  async closeUserGroupUserModal() {
+    await this.setState({ isUserGroupUserModalOpen: false });
+  }
+
+  /**
+   * update user group
+   *
+   * @memberOf UserGroupDetailContainer
+   * @param {string} username username of the user to be added to the group
+   */
+  async addUserByUsername(username) {
+    const res = await this.appContainer.apiv3.post(`/user-groups/${this.state.userGroup._id}/users/${username}`);
+    const { userGroupRelation } = res.data;
+
+    this.setState((prevState) => {
+      return {
+        userGroupRelations: [...prevState.userGroupRelations, userGroupRelation],
+      };
+    });
+  }
+
+  /**
+   * update user group
+   *
+   * @memberOf UserGroupDetailContainer
+   * @param {string} username username of the user to be removed from the group
+   */
+  async removeUserByUsername(username) {
+    const res = await this.appContainer.apiv3.delete(`/user-groups/${this.state.userGroup._id}/users/${username}`);
+
+    this.setState((prevState) => {
+      return {
+        userGroupRelations: prevState.userGroupRelations.filter((u) => { return u._id !== res.data.userGroupRelation._id }),
+      };
+    });
+  }
+
+}

+ 5 - 1
src/server/middlewares/ApiV3FormValidator.js

@@ -7,13 +7,17 @@ class ApiV3FormValidator {
     const { ErrorV3 } = crowi.models;
 
     return (req, res, next) => {
+      logger.debug('req.query', req.query);
+      logger.debug('req.params', req.params);
+      logger.debug('req.body', req.body);
+
       const errObjArray = validationResult(req);
       if (errObjArray.isEmpty()) {
         return next();
       }
 
       const errs = errObjArray.array().map((err) => {
-        logger.error(`${err.param} in ${err.location}: ${err.msg}`);
+        logger.error(`${err.location}.${err.param}: ${err.value} - ${err.msg}`);
         return new ErrorV3(`${err.param}: ${err.msg}`, 'validation_failed');
       });
 

+ 1 - 76
src/server/routes/admin.js

@@ -685,89 +685,14 @@ module.exports = function(crowi, app) {
   // グループ詳細
   actions.userGroup.detail = async function(req, res) {
     const userGroupId = req.params.id;
-    const renderVar = {
-      userGroup: null,
-      userGroupRelations: [],
-      notRelatedusers: [],
-      relatedPages: [],
-    };
-
     const userGroup = await UserGroup.findOne({ _id: userGroupId });
 
     if (userGroup == null) {
       logger.error('no userGroup is exists. ', userGroupId);
-      req.flash('errorMessage', 'グループがありません');
       return res.redirect('/admin/user-groups');
     }
-    renderVar.userGroup = userGroup;
-
-    const resolves = await Promise.all([
-      // get all user and group relations
-      UserGroupRelation.findAllRelationForUserGroup(userGroup),
-      // get all not related users for group
-      UserGroupRelation.findUserByNotRelatedGroup(userGroup),
-      // get all related pages
-      Page.find({ grant: Page.GRANT_USER_GROUP, grantedGroup: { $in: [userGroup] } }),
-    ]);
-    renderVar.userGroupRelations = resolves[0];
-    renderVar.notRelatedusers = resolves[1];
-    renderVar.relatedPages = resolves[2];
-
-    return res.render('admin/user-group-detail', renderVar);
-  };
-
-  actions.userGroupRelation = {};
-  actions.userGroupRelation.index = function(req, res) {
 
-  };
-
-  actions.userGroupRelation.create = function(req, res) {
-    const User = crowi.model('User');
-    const UserGroup = crowi.model('UserGroup');
-    const UserGroupRelation = crowi.model('UserGroupRelation');
-
-    // req params
-    const userName = req.body.user_name;
-    const userGroupId = req.body.user_group_id;
-
-    let user = null;
-    let userGroup = null;
-
-    Promise.all([
-      // ユーザグループをIDで検索
-      UserGroup.findById(userGroupId),
-      // ユーザを名前で検索
-      User.findUserByUsername(userName),
-    ])
-      .then((resolves) => {
-        userGroup = resolves[0];
-        user = resolves[1];
-        // Relation を作成
-        UserGroupRelation.createRelation(userGroup, user);
-      })
-      .then((result) => {
-        return res.redirect(`/admin/user-group-detail/${userGroup.id}`);
-      })
-      .catch((err) => {
-        debug('Error on create user-group relation', err);
-        req.flash('errorMessage', 'Error on create user-group relation');
-        return res.redirect(`/admin/user-group-detail/${userGroup.id}`);
-      });
-  };
-
-  actions.userGroupRelation.remove = function(req, res) {
-    const UserGroupRelation = crowi.model('UserGroupRelation');
-    const userGroupId = req.params.id;
-    const relationId = req.params.relationId;
-
-    UserGroupRelation.removeById(relationId)
-      .then(() => {
-        return res.redirect(`/admin/user-group-detail/${userGroupId}`);
-      })
-      .catch((err) => {
-        debug('Error on remove user-group-relation', err);
-        req.flash('errorMessage', 'グループのユーザ削除に失敗しました。');
-      });
+    return res.render('admin/user-group-detail', { userGroup });
   };
 
   // Importer management

+ 296 - 10
src/server/routes/apiv3/user-group.js

@@ -10,6 +10,8 @@ const { body, param, query } = require('express-validator/check');
 
 const validator = {};
 
+const { ObjectId } = require('mongoose').Types;
+
 /**
  * @swagger
  *  tags:
@@ -17,7 +19,13 @@ const validator = {};
  */
 
 module.exports = (crowi) => {
-  const { ErrorV3, UserGroup, UserGroupRelation } = crowi.models;
+  const {
+    ErrorV3,
+    UserGroup,
+    UserGroupRelation,
+    User,
+    Page,
+  } = crowi.models;
   const { ApiV3FormValidator } = crowi.middlewares;
 
   const {
@@ -33,7 +41,7 @@ module.exports = (crowi) => {
    *    /_api/v3/user-groups:
    *      get:
    *        tags: [UserGroup]
-   *        description: Gets usergroups
+   *        description: Get usergroups
    *        produces:
    *          - application/json
    *        responses:
@@ -63,7 +71,7 @@ module.exports = (crowi) => {
   });
 
   validator.create = [
-    body('name', 'Group name is required').trim().exists(),
+    body('name', 'Group name is required').trim().exists({ checkFalsy: true }),
   ];
 
   /**
@@ -113,8 +121,8 @@ module.exports = (crowi) => {
   });
 
   validator.delete = [
-    param('id').trim().exists(),
-    query('actionName').trim().exists(),
+    param('id').trim().exists({ checkFalsy: true }),
+    query('actionName').trim().exists({ checkFalsy: true }),
     query('transferToUserGroupId').trim(),
   ];
 
@@ -176,7 +184,7 @@ module.exports = (crowi) => {
   // });
 
   validator.update = [
-    body('name', 'Group name is required').trim().exists(),
+    body('name', 'Group name is required').trim().exists({ checkFalsy: true }),
   ];
 
   /**
@@ -186,7 +194,7 @@ module.exports = (crowi) => {
    *    /_api/v3/user-groups/{:id}:
    *      put:
    *        tags: [UserGroup]
-   *        description: Updates userGroup
+   *        description: Update userGroup
    *        produces:
    *          - application/json
    *        parameters:
@@ -234,14 +242,16 @@ module.exports = (crowi) => {
     }
   });
 
+  validator.users = {};
+
   /**
    * @swagger
    *
    *  paths:
-   *    /_api/v3/user-groups/{:id/users}:
+   *    /_api/v3/user-groups/{:id}/users:
    *      get:
    *        tags: [UserGroup]
-   *        description: Gets the users related to the userGroup
+   *        description: Get users related to the userGroup
    *        produces:
    *          - application/json
    *        parameters:
@@ -279,7 +289,283 @@ module.exports = (crowi) => {
     catch (err) {
       const msg = `Error occurred in fetching users for group: ${id}`;
       logger.error(msg, err);
-      return res.apiv3Err(new ErrorV3(msg, 'user-group-fetch-failed'));
+      return res.apiv3Err(new ErrorV3(msg, 'user-group-user-list-fetch-failed'));
+    }
+  });
+
+  /**
+   * @swagger
+   *
+   *  paths:
+   *    /_api/v3/user-groups/{:id}/unrelated-users:
+   *      get:
+   *        tags: [UserGroup]
+   *        description: Get users unrelated to the userGroup
+   *        produces:
+   *          - application/json
+   *        parameters:
+   *          - name: id
+   *            in: path
+   *            description: id of userGroup
+   *            schema:
+   *              type: ObjectId
+   *        responses:
+   *          200:
+   *            description: users are fetched
+   *            content:
+   *              application/json:
+   *                schema:
+   *                  properties:
+   *                    users:
+   *                      type: array
+   *                      items:
+   *                        type: object
+   *                      description: user objects
+   */
+  router.get('/:id/unrelated-users', loginRequired(), adminRequired, async(req, res) => {
+    const { id } = req.params;
+
+    try {
+      const userGroup = await UserGroup.findById(id);
+      const users = await UserGroupRelation.findUserByNotRelatedGroup(userGroup);
+
+      return res.apiv3({ users });
+    }
+    catch (err) {
+      const msg = `Error occurred in fetching unrelated users for group: ${id}`;
+      logger.error(msg, err);
+      return res.apiv3Err(new ErrorV3(msg, 'user-group-unrelated-user-list-fetch-failed'));
+    }
+  });
+
+  validator.users.post = [
+    param('id').trim().exists({ checkFalsy: true }),
+    param('username').trim().exists({ checkFalsy: true }),
+  ];
+
+  /**
+   * @swagger
+   *
+   *  paths:
+   *    /_api/v3/user-groups/{:id}/users:
+   *      post:
+   *        tags: [UserGroup]
+   *        description: Add a user to the userGroup
+   *        produces:
+   *          - application/json
+   *        parameters:
+   *          - name: id
+   *            in: path
+   *            description: id of userGroup
+   *            schema:
+   *              type: ObjectId
+   *          - name: username
+   *            in: path
+   *            description: id of user
+   *            schema:
+   *              type: string
+   *        responses:
+   *          200:
+   *            description: a user is added
+   *            content:
+   *              application/json:
+   *                schema:
+   *                  type: object
+   *                  properties:
+   *                    user:
+   *                      type: object
+   *                      description: the user added to the group
+   *                    userGroup:
+   *                      type: object
+   *                      description: the group to which a user was added
+   *                    userGroupRelation:
+   *                      type: object
+   *                      description: the associative entity between user and userGroup
+   */
+  router.post('/:id/users/:username', loginRequired(), adminRequired, validator.users.post, ApiV3FormValidator, async(req, res) => {
+    const { id, username } = req.params;
+
+    try {
+      const [userGroup, user] = await Promise.all([
+        UserGroup.findById(id),
+        User.findUserByUsername(username),
+      ]);
+
+      const userGroupRelation = await UserGroupRelation.createRelation(userGroup, user);
+      await userGroupRelation.populate('relatedUser', User.USER_PUBLIC_FIELDS).execPopulate();
+
+      return res.apiv3({ user, userGroup, userGroupRelation });
+    }
+    catch (err) {
+      const msg = `Error occurred in adding the user "${username}" to group "${id}"`;
+      logger.error(msg, err);
+      return res.apiv3Err(new ErrorV3(msg, 'user-group-add-user-failed'));
+    }
+  });
+
+  validator.users.delete = [
+    param('id').trim().exists({ checkFalsy: true }),
+    param('username').trim().exists({ checkFalsy: true }),
+  ];
+
+  /**
+   * @swagger
+   *
+   *  paths:
+   *    /_api/v3/user-groups/{:id}/users:
+   *      delete:
+   *        tags: [UserGroup]
+   *        description: remove a user from the userGroup
+   *        produces:
+   *          - application/json
+   *        parameters:
+   *          - name: id
+   *            in: path
+   *            description: id of userGroup
+   *            schema:
+   *              type: ObjectId
+   *          - name: username
+   *            in: path
+   *            description: id of user
+   *            schema:
+   *              type: string
+   *        responses:
+   *          200:
+   *            description: a user was removed
+   *            content:
+   *              application/json:
+   *                schema:
+   *                  type: object
+   *                  properties:
+   *                    user:
+   *                      type: object
+   *                      description: the user removed from the group
+   *                    userGroup:
+   *                      type: object
+   *                      description: the group from which a user was removed
+   *                    userGroupRelation:
+   *                      type: object
+   *                      description: the associative entity between user and userGroup
+   */
+  router.delete('/:id/users/:username', loginRequired(), adminRequired, validator.users.delete, ApiV3FormValidator, async(req, res) => {
+    const { id, username } = req.params;
+
+    try {
+      const [userGroup, user] = await Promise.all([
+        UserGroup.findById(id),
+        User.findUserByUsername(username),
+      ]);
+
+      const userGroupRelation = await UserGroupRelation.findOne({ relatedUser: new ObjectId(user._id), relatedGroup: new ObjectId(userGroup._id) });
+      if (userGroupRelation == null) {
+        throw new Error(`Group "${id}" does not exist or user "${username}" does not belong to group "${id}"`);
+      }
+
+      await userGroupRelation.remove();
+
+      return res.apiv3({ user, userGroup, userGroupRelation });
+    }
+    catch (err) {
+      const msg = `Error occurred in removing the user "${username}" from group "${id}"`;
+      logger.error(msg, err);
+      return res.apiv3Err(new ErrorV3(msg, 'user-group-remove-user-failed'));
+    }
+  });
+
+  validator.userGroupRelations = {};
+
+  /**
+   * @swagger
+   *
+   *  paths:
+   *    /_api/v3/user-groups/{:id}/user-group-relations:
+   *      get:
+   *        tags: [UserGroup]
+   *        description: Get the user group relations for the userGroup
+   *        produces:
+   *          - application/json
+   *        parameters:
+   *          - name: id
+   *            in: path
+   *            description: id of userGroup
+   *            schema:
+   *              type: ObjectId
+   *        responses:
+   *          200:
+   *            description: user group relations are fetched
+   *            content:
+   *              application/json:
+   *                schema:
+   *                  properties:
+   *                    userGroupRelations:
+   *                      type: array
+   *                      items:
+   *                        type: object
+   *                      description: userGroupRelation objects
+   */
+  router.get('/:id/user-group-relations', loginRequired(), adminRequired, async(req, res) => {
+    const { id } = req.params;
+
+    try {
+      const userGroup = await UserGroup.findById(id);
+      const userGroupRelations = await UserGroupRelation.findAllRelationForUserGroup(userGroup);
+
+      return res.apiv3({ userGroupRelations });
+    }
+    catch (err) {
+      const msg = `Error occurred in fetching user group relations for group: ${id}`;
+      logger.error(msg, err);
+      return res.apiv3Err(new ErrorV3(msg, 'user-group-user-group-relation-list-fetch-failed'));
+    }
+  });
+
+  validator.userGroupRelations = {};
+
+  /**
+   * @swagger
+   *
+   *  paths:
+   *    /_api/v3/user-groups/{:id}/pages:
+   *      get:
+   *        tags: [UserGroup]
+   *        description: Get closed pages for the userGroup
+   *        produces:
+   *          - application/json
+   *        parameters:
+   *          - name: id
+   *            in: path
+   *            description: id of userGroup
+   *            schema:
+   *              type: ObjectId
+   *        responses:
+   *          200:
+   *            description: pages are fetched
+   *            content:
+   *              application/json:
+   *                schema:
+   *                  properties:
+   *                    pages:
+   *                      type: array
+   *                      items:
+   *                        type: object
+   *                      description: page objects
+   */
+  router.get('/:id/pages', loginRequired(), adminRequired, async(req, res) => {
+    const { id } = req.params;
+
+    try {
+      const userGroup = await UserGroup.findById(id);
+      const pages = await Page
+        .find({ grant: Page.GRANT_USER_GROUP, grantedGroup: { $in: [userGroup] } })
+        .populate('lastUpdateUser', User.USER_PUBLIC_FIELDS)
+        .exec();
+
+      return res.apiv3({ pages });
+    }
+    catch (err) {
+      const msg = `Error occurred in fetching pages for group: ${id}`;
+      logger.error(msg, err);
+      return res.apiv3Err(new ErrorV3(msg, 'user-group-page-list-fetch-failed'));
     }
   });
 

+ 0 - 4
src/server/routes/index.js

@@ -135,10 +135,6 @@ module.exports = function(crowi, app) {
   app.get('/admin/user-groups'                    , loginRequired(), adminRequired, admin.userGroup.index);
   app.get('/admin/user-group-detail/:id'          , loginRequired(), adminRequired, admin.userGroup.detail);
 
-  // user-group-relations admin
-  app.post('/admin/user-group-relation/create', loginRequired(), adminRequired, csrf, admin.userGroupRelation.create);
-  app.post('/admin/user-group-relation/:id/remove-relation/:relationId', loginRequired(), adminRequired, csrf, admin.userGroupRelation.remove);
-
   // importer management for admin
   app.get('/admin/importer'                , loginRequired() , adminRequired , admin.importer.index);
   app.post('/_api/admin/settings/importerEsa' , loginRequired() , adminRequired , csrf , form.admin.importerEsa , admin.api.importerSettingEsa);