client/entity-editor/submission-section/actions.js

"use strict";

require("core-js/modules/es.object.keys.js");
require("core-js/modules/es.symbol.js");
require("core-js/modules/es.array.filter.js");
require("core-js/modules/es.object.get-own-property-descriptor.js");
require("core-js/modules/web.dom-collections.for-each.js");
require("core-js/modules/es.object.get-own-property-descriptors.js");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.UPDATE_REVISION_NOTE = exports.SET_SUBMIT_ERROR = exports.SET_SUBMITTED = void 0;
exports.debounceUpdateRevisionNote = debounceUpdateRevisionNote;
exports.setSubmitError = setSubmitError;
exports.setSubmitted = setSubmitted;
exports.submit = submit;
exports.submitSingleEntity = submitSingleEntity;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
require("core-js/modules/es.regexp.exec.js");
require("core-js/modules/es.string.split.js");
require("core-js/modules/es.array.iterator.js");
require("core-js/modules/es.object.from-entries.js");
require("core-js/modules/es.string.replace.js");
require("core-js/modules/es.array.concat.js");
require("core-js/modules/es.object.to-string.js");
require("core-js/modules/es.set.js");
require("core-js/modules/es.string.iterator.js");
require("core-js/modules/web.dom-collections.iterator.js");
require("core-js/modules/es.array.find.js");
require("core-js/modules/es.function.name.js");
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _get2 = _interopRequireDefault(require("lodash/get"));
var _mapValues2 = _interopRequireDefault(require("lodash/mapValues"));
var _size2 = _interopRequireDefault(require("lodash/size"));
var _set2 = _interopRequireDefault(require("lodash/set"));
var _forEach2 = _interopRequireDefault(require("lodash/forEach"));
var _utils = require("../../../common/helpers/utils");
var _superagent = _interopRequireDefault(require("superagent"));
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2.default)(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } /*
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          * Copyright (C) 2016  Ben Ockmore
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          * This program is free software; you can redistribute it and/or modify
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          * it under the terms of the GNU General Public License as published by
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          * the Free Software Foundation; either version 2 of the License, or
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          * (at your option) any later version.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          * This program is distributed in the hope that it will be useful,
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          * but WITHOUT ANY WARRANTY; without even the implied warranty of
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          * GNU General Public License for more details.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          * You should have received a copy of the GNU General Public License along
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          * with this program; if not, write to the Free Software Foundation, Inc.,
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          */
var SET_SUBMIT_ERROR = 'SET_SUBMIT_ERROR';
exports.SET_SUBMIT_ERROR = SET_SUBMIT_ERROR;
var UPDATE_REVISION_NOTE = 'UPDATE_REVISION_NOTE';
exports.UPDATE_REVISION_NOTE = UPDATE_REVISION_NOTE;
var SET_SUBMITTED = 'SET_SUBMITTED';
exports.SET_SUBMITTED = SET_SUBMITTED;
/**
 * Produces an action indicating that the submit error for the editing form
 * should be updated with the provided value. This error is displayed in an
 * Alert if set, to indicate to the user what went wrong.
 *
 * @param {string} error - The error message to be set for the form.
 * @returns {Action} The resulting SET_SUBMIT_ERROR action.
 */
function setSubmitError(error) {
  return {
    error: error,
    type: SET_SUBMIT_ERROR
  };
}

/**
 * Produces an action indicating whether the form  has been submitted or not.
 * This consequently enables or disables the submit button to prevent double submissions
 *
 * @param {boolean} submitted - Boolean indicating if the form has been submitted
 * @returns {Action} The resulting SET_SUBMITTED action.
 */
function setSubmitted(submitted) {
  return {
    submitted: submitted,
    type: SET_SUBMITTED
  };
}

/**
 * Produces an action indicating that the revision note for the editing form
 * should be updated with the provided value. The action is marked to be
 * debounced by the keystroke debouncer defined for redux-debounce.
 *
 * @param {string} value - The new value to be used for the revision note.
 * @returns {Action} The resulting UPDATE_REVISION_NOTE action.
 */
function debounceUpdateRevisionNote(value) {
  return {
    meta: {
      debounce: 'keystroke'
    },
    type: UPDATE_REVISION_NOTE,
    value: value
  };
}
function postSubmission(url, data) {
  /*
   * TODO: Not the best way to do this, but once we unify the
   * /<entity>/create/handler and /<entity>/edit/handler URLs, we can simply
   * pass the entity type and generate both URLs from that.
   */

  var _url$split = url.split('/'),
    _url$split2 = (0, _slicedToArray2.default)(_url$split, 2),
    submissionEntity = _url$split2[1];
  return _superagent.default.post(url).send(Object.fromEntries(data)).then(function (response) {
    if (!response.body) {
      window.location.replace('/login');
    }
    var redirectUrl = "/".concat(submissionEntity, "/").concat(response.body.bbid);
    if (response.body.alert) {
      var alertParam = "?alert=".concat(response.body.alert);
      window.location.href = "".concat(redirectUrl).concat(alertParam);
    } else {
      window.location.href = redirectUrl;
    }
  });
}
function transformFormData(data) {
  var newData = {};
  var nextId = 0;
  // add new series
  (0, _forEach2.default)(data.Series, function (series, sid) {
    // sync local series section with global series section
    series.seriesSection = data.seriesSection;
    // might be possible for series items to not have target id
    (0, _forEach2.default)(series.seriesSection.seriesItems, function (item) {
      (0, _set2.default)(item, 'targetEntity.bbid', series.id);
    });
    series.seriesSection.seriesItems = (0, _utils.filterObject)(series.seriesSection.seriesItems, function (rel) {
      return !rel.attributeSetId;
    });
    // if new items have been added to series, then add series to the post data
    if ((0, _size2.default)(series.seriesSection.seriesItems) > 0) {
      series.__isNew__ = false;
      series.submissionSection = {
        note: 'added more series items'
      };
      newData[sid] = series;
    }
  });
  // add new works
  var authorWorkRelationshipTypeId = 8;
  (0, _forEach2.default)(data.Works, function (work, wid) {
    // if authors have been added to the work, then add work to the post data
    if (!work.checked) {
      return;
    }
    var relationshipCount = 0;
    // hashset in order to avoid duplicate relationships
    var authorBBIDSet = new Set();
    if (work.relationshipSet) {
      (0, _forEach2.default)(work.relationshipSet.relationships, function (rel) {
        if (rel.typeId === authorWorkRelationshipTypeId) {
          authorBBIDSet.add(rel.sourceBbid);
        }
      });
    }
    var flag = false;
    (0, _forEach2.default)(data.authorCreditEditor, function (authorCredit) {
      if (authorBBIDSet.has(authorCredit.author.bbid)) {
        return;
      }
      var relationship = {
        attributeSetId: null,
        attributes: [],
        isAdded: true,
        relationshipType: {
          id: authorWorkRelationshipTypeId
        },
        rowId: "a".concat(relationshipCount),
        sourceEntity: {
          bbid: authorCredit.author.id
        },
        targetEntity: {
          bbid: work.id
        }
      };
      (0, _set2.default)(work, ['relationshipSection', 'relationships', "a".concat(relationshipCount)], relationship);
      relationshipCount++;
      flag = true;
    });
    if (flag) {
      work.submissionSection = {
        note: 'added authors from parent edition'
      };
      work.__isNew__ = false;
      newData[wid] = work;
    }
  });
  // add edition at last
  if (data.ISBN.type) {
    data.identifierEditor.m0 = data.ISBN;
  }
  data.relationshipSection.relationships = (0, _mapValues2.default)(data.Works, function (work, key) {
    var relationship = {
      attributeSetId: null,
      attributes: [],
      isAdded: true,
      relationshipType: {
        id: 10
      },
      rowID: key,
      sourceEntity: {},
      targetEntity: {
        bbid: work.id
      }
    };
    return relationship;
  });
  newData["e".concat(nextId)] = _objectSpread(_objectSpread({}, data), {}, {
    type: 'Edition'
  });
  return newData;
}
function postUFSubmission(url, data) {
  // transform data
  var jsonData = data.toJS();
  var postData = transformFormData(jsonData);
  return _superagent.default.post(url).send(postData).then(function (response) {
    if (!response.body) {
      window.location.replace('/login');
    }
    var editionEntity = response.body.find(function (entity) {
      return entity.type === 'Edition';
    });
    var redirectUrl = "/edition/".concat(editionEntity.bbid);
    if (response.body.alert) {
      var alertParam = "?alert=".concat(response.body.alert);
      window.location.href = "".concat(redirectUrl).concat(alertParam);
    } else {
      window.location.href = redirectUrl;
    }
  });
}
function submit(submissionUrl) {
  var isUnifiedForm = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  return function (dispatch, getState) {
    var rootState = getState();
    dispatch(setSubmitted(true));
    if (isUnifiedForm) {
      return postUFSubmission(submissionUrl, rootState).catch(function (error) {
        var message = (0, _get2.default)(error, ['response', 'body', 'error'], null) || error.message;
        dispatch(setSubmitted(false));
        return dispatch(setSubmitError(message));
      });
    }
    return postSubmission(submissionUrl, rootState).catch(function (error) {
      /*
       * Use server-set message first, otherwise internal
       * superagent message
       */
      var message = (0, _get2.default)(error, ['response', 'body', 'error'], null) || error.message;
      // If there was an error submitting the form, make the submit button clickable again
      dispatch(setSubmitted(false));
      return dispatch(setSubmitError(message));
    });
  };
}

/**
 *
 * @param {string} submissionUrl - The URL to post the submission to
 * @param {string} entityType - The type of entity being submitted
 * @param {Function} callback - A function that adds the entity to the store
 * @param {Object} initialState - The initial state of the entity being submitted, this include some fields which are required by the server
 * @returns {function} - A thunk that posts the submission to the server
 */
function submitSingleEntity(submissionUrl, entityType, callback) {
  var initialState = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  return /*#__PURE__*/function () {
    var _ref = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee(dispatch, getState) {
      var rootState, JSONState, entity, postData, response, mainEntity, entityObject, message;
      return _regenerator.default.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              rootState = getState();
              dispatch(setSubmitted(true));
              JSONState = rootState.toJS();
              entity = _objectSpread(_objectSpread({}, JSONState), {}, {
                type: entityType
              });
              postData = {
                0: entity
              };
              _context.prev = 5;
              _context.next = 8;
              return _superagent.default.post(submissionUrl).send(postData);
            case 8:
              response = _context.sent;
              mainEntity = response.body[0];
              entityObject = _objectSpread(_objectSpread({}, initialState), {}, {
                __isNew__: true,
                id: mainEntity.bbid,
                text: mainEntity.name
              }, mainEntity);
              return _context.abrupt("return", dispatch(callback(entityObject)) && dispatch(setSubmitted(false)));
            case 14:
              _context.prev = 14;
              _context.t0 = _context["catch"](5);
              message = (0, _get2.default)(_context.t0, ['response', 'body', 'error'], null) || _context.t0.message;
              dispatch(setSubmitted(false));
              return _context.abrupt("return", dispatch(setSubmitError(message)));
            case 19:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, null, [[5, 14]]);
    }));
    return function (_x, _x2) {
      return _ref.apply(this, arguments);
    };
  }();
}
//# sourceMappingURL=actions.js.map