Bläddra i källkod

Merge pull request #1563 from weseek/reactify-admin/update-existing-notification-data

Reactify admin/update existing notification data
itizawa 6 år sedan
förälder
incheckning
223acd480f

+ 29 - 26
src/client/js/components/Admin/Notification/ManageGlobalNotification.jsx

@@ -1,6 +1,7 @@
 import React from 'react';
 import PropTypes from 'prop-types';
 import { withTranslation } from 'react-i18next';
+import urljoin from 'url-join';
 
 import loggerFactory from '@alias/logger';
 
@@ -18,31 +19,25 @@ class ManageGlobalNotification extends React.Component {
   constructor() {
     super();
 
-    this.state = {
-      retrieveError: null,
-      triggerPath: '',
-      notifyToType: 'mail',
-      emailToSend: '',
-      slackChannelToSend: '',
-      triggerEvents: new Set([]),
-    };
-
-    this.submitHandler = this.submitHandler.bind(this);
-  }
-
-  componentDidMount() {
-    this.retrieveTriggerEvent();
-  }
-
-  async retrieveTriggerEvent() {
+    let globalNotification;
     try {
-      // TODO GW-913 create apiV3
+      globalNotification = JSON.parse(document.getElementById('admin-global-notification-setting').getAttribute('data-global-notification'));
     }
     catch (err) {
       toastError(err);
       logger.error(err);
-      this.setState({ retrieveError: err });
     }
+
+    this.state = {
+      globalNotificationId: globalNotification._id || null,
+      triggerPath: globalNotification.triggerPath || '',
+      notifyToType: globalNotification.__t || 'mail',
+      emailToSend: globalNotification.toEmail || '',
+      slackChannelToSend: globalNotification.slackChannels || '',
+      triggerEvents: new Set(globalNotification.triggerEvents),
+    };
+
+    this.submitHandler = this.submitHandler.bind(this);
   }
 
   onChangeTriggerPath(inputValue) {
@@ -76,14 +71,22 @@ class ManageGlobalNotification extends React.Component {
 
   async submitHandler() {
 
+    const requestParams = {
+      triggerPath: this.state.triggerPath,
+      notifyToType: this.state.notifyToType,
+      toEmail: this.state.emailToSend,
+      slackChannels: this.state.slackChannelToSend,
+      triggerEvents: [...this.state.triggerEvents],
+    };
+
     try {
-      await this.props.appContainer.apiv3.post('/notification-setting/global-notification', {
-        triggerPath: this.state.triggerPath,
-        notifyToType: this.state.notifyToType,
-        toEmail: this.state.emailToSend,
-        slackChannels: this.state.slackChannelToSend,
-        triggerEvents: [...this.state.triggerEvents],
-      });
+      if (this.state.globalNotificationId != null) {
+        await this.props.appContainer.apiv3.put(`/notification-setting/global-notification/${this.state.globalNotificationId}`, requestParams);
+      }
+      else {
+        await this.props.appContainer.apiv3.post('/notification-setting/global-notification', requestParams);
+      }
+      window.location.href = urljoin(window.location.origin, '/admin/notification#global-notification');
     }
     catch (err) {
       toastError(err);

+ 3 - 3
src/server/routes/admin.js

@@ -267,18 +267,18 @@ module.exports = function(crowi, app) {
   actions.globalNotification = {};
   actions.globalNotification.detail = async(req, res) => {
     const notificationSettingId = req.params.id;
-    const renderVars = {};
+    let globalNotification;
 
     if (notificationSettingId) {
       try {
-        renderVars.setting = await GlobalNotificationSetting.findOne({ _id: notificationSettingId });
+        globalNotification = await GlobalNotificationSetting.findOne({ _id: notificationSettingId });
       }
       catch (err) {
         logger.error(`Error in finding a global notification setting with {_id: ${notificationSettingId}}`);
       }
     }
 
-    return res.render('admin/global-notification-detail', renderVars);
+    return res.render('admin/global-notification-detail', { globalNotification });
   };
 
   actions.globalNotification.create = (req, res) => {

+ 86 - 6
src/server/routes/apiv3/notification-setting.js

@@ -105,7 +105,7 @@ module.exports = (crowi) => {
    *
    *    /_api/v3/notification-setting/:
    *      get:
-   *        tags: [NotificationSetting]
+   *        tags: [NotificationSetting, apiv3]
    *        description: Get notification paramators
    *        responses:
    *          200:
@@ -135,7 +135,7 @@ module.exports = (crowi) => {
    *
    *    /_api/v3/notification-setting/slack-configuration:
    *      put:
-   *        tags: [NotificationSetting]
+   *        tags: [NotificationSetting, apiv3]
    *        description: Update slack configuration setting
    *        requestBody:
    *          required: true
@@ -182,7 +182,7 @@ module.exports = (crowi) => {
   *
   *    /_api/v3/notification-setting/user-notification:
   *      post:
-  *        tags: [NotificationSetting]
+  *        tags: [NotificationSetting, apiv3]
   *        description: add user notification setting
   *        requestBody:
   *          required: true
@@ -229,7 +229,7 @@ module.exports = (crowi) => {
    *
    *    /_api/v3/notification-setting/global-notification:
    *      post:
-   *        tags: [NotificationSetting]
+   *        tags: [NotificationSetting, apiv3]
    *        description: add global notification
    *        requestBody:
    *          required: true
@@ -280,12 +280,92 @@ module.exports = (crowi) => {
 
   });
 
+  /**
+   * @swagger
+   *
+   *    /_api/v3/notification-setting/global-notification/{id}:
+   *      put:
+   *        tags: [NotificationSetting, apiv3]
+   *        description: update global notification
+   *        parameters:
+   *          - name: id
+   *            in: path
+   *            required: true
+   *            description: global notification id for updated
+   *            schema:
+   *              type: string
+   *        requestBody:
+   *          required: true
+   *          content:
+   *            application/json:
+   *              schema:
+   *                $ref: '#/components/schemas/GlobalNotificationParams'
+   *        responses:
+   *          200:
+   *            description: Succeeded to update global notification
+   *            content:
+   *              application/json:
+   *                schema:
+   *                  properties:
+   *                    createdNotification:
+   *                      type: object
+   *                      description: notification param updated
+   */
+  router.put('/global-notification/:id', loginRequiredStrictly, adminRequired, csrf, validator.globalNotification, ApiV3FormValidator, async(req, res) => {
+    const { id } = req.params;
+    const {
+      notifyToType, toEmail, slackChannels, triggerPath, triggerEvents,
+    } = req.body;
+
+    const models = {
+      [GlobalNotificationSetting.TYPE.MAIL]: GlobalNotificationMailSetting,
+      [GlobalNotificationSetting.TYPE.SLACK]: GlobalNotificationSlackSetting,
+    };
+
+    try {
+      let setting = await GlobalNotificationSetting.findOne({ _id: id });
+      setting = setting.toObject();
+
+      // when switching from one type to another,
+      // remove toEmail from slack setting and slackChannels from mail setting
+      if (setting.__t !== notifyToType) {
+        setting = models[setting.__t].hydrate(setting);
+        setting.toEmail = undefined;
+        setting.slackChannels = undefined;
+        await setting.save();
+        setting = setting.toObject();
+      }
+
+      if (notifyToType === GlobalNotificationSetting.TYPE.MAIL) {
+        setting = GlobalNotificationMailSetting.hydrate(setting);
+        setting.toEmail = toEmail;
+      }
+      if (notifyToType === GlobalNotificationSetting.TYPE.SLACK) {
+        setting = GlobalNotificationSlackSetting.hydrate(setting);
+        setting.slackChannels = slackChannels;
+      }
+
+      setting.__t = notifyToType;
+      setting.triggerPath = triggerPath;
+      setting.triggerEvents = triggerEvents || [];
+
+      const createdNotification = await setting.save();
+      return res.apiv3({ createdNotification });
+    }
+    catch (err) {
+      const msg = 'Error occurred in updating global notification';
+      logger.error('Error', err);
+      return res.apiv3Err(new ErrorV3(msg, 'post-globalNotification-failed'));
+    }
+
+  });
+
   /**
    * @swagger
    *
    *    /_api/v3/notification-setting/global-notification/{id}/enabled:
    *      put:
-   *        tags: [NotificationSetting]
+   *        tags: [NotificationSetting, apiv3]
    *        description: toggle enabled global notification
    *        parameters:
    *          - name: id
@@ -342,7 +422,7 @@ module.exports = (crowi) => {
   *
   *    /_api/v3/notification-setting/global-notification/{id}:
   *      delete:
-  *        tags: [NotificationSetting]
+  *        tags: [NotificationSetting, apiv3]
   *        description: delete global notification pattern
   *        parameters:
   *          - name: id

+ 3 - 1
src/server/views/admin/global-notification-detail.html

@@ -31,7 +31,9 @@
       {% include './widget/menu.html' with {current: 'notification'} %}
     </div>
 
-    <div class="col-md-9" id="admin-global-notification-setting" />
+    <div class="col-md-9" id="admin-global-notification-setting"
+      data-global-notification="{{ globalNotification|json }}">
+    </div>
     <!-- <a href="/admin/notification#global-notification" class="btn btn-default">
         <i class="icon-fw ti-arrow-left" aria-hidden="true"></i>
         {{ t('notification_setting.back_to_list') }}