server/routes/entity/edition-group.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/es.object.get-own-property-descriptors.js");
require("core-js/modules/es.array.slice.js");
require("core-js/modules/es.array.from.js");
require("core-js/modules/es.string.iterator.js");
require("core-js/modules/es.regexp.exec.js");
require("core-js/modules/es.symbol.description.js");
require("core-js/modules/es.symbol.iterator.js");
require("core-js/modules/es.array.iterator.js");
require("core-js/modules/web.dom-collections.iterator.js");
require("core-js/modules/es.weak-map.js");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = require("@babel/runtime/helpers/typeof");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
exports.editionGroupToFormState = editionGroupToFormState;
exports.transformNewForm = transformNewForm;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var _taggedTemplateLiteral2 = _interopRequireDefault(require("@babel/runtime/helpers/taggedTemplateLiteral"));
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
require("core-js/modules/es.function.name.js");
require("core-js/modules/es.array.sort.js");
require("core-js/modules/es.array.map.js");
require("core-js/modules/es.array.splice.js");
require("core-js/modules/es.object.to-string.js");
require("core-js/modules/web.dom-collections.for-each.js");
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _isEmpty2 = _interopRequireDefault(require("lodash/isEmpty"));
var _isNil2 = _interopRequireDefault(require("lodash/isNil"));
var _get2 = _interopRequireDefault(require("lodash/get"));
var auth = _interopRequireWildcard(require("../../helpers/auth"));
var entityRoutes = _interopRequireWildcard(require("./entity"));
var middleware = _interopRequireWildcard(require("../../helpers/middleware"));
var search = _interopRequireWildcard(require("../../../common/helpers/search"));
var utils = _interopRequireWildcard(require("../../helpers/utils"));
var _entityRouteUtils = require("../../helpers/entityRouteUtils");
var _error = require("../../../common/helpers/error");
var _privilegesUtils = require("../../../common/helpers/privileges-utils");
var _props = require("../../helpers/props");
var _express = _interopRequireDefault(require("express"));
var _log = _interopRequireDefault(require("log"));
var _target = _interopRequireDefault(require("../../templates/target"));
var _excluded = ["languageId"],
  _excluded2 = ["type"],
  _excluded3 = ["author"];
var _templateObject;
/*
 * Copyright (C) 2015       Ben Ockmore
 *               2015-2016  Sean Burke
 *
 * 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.
 */
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
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; }
/** ****************************
*********** Helpers ************
*******************************/

function transformNewForm(data) {
  var aliases = entityRoutes.constructAliases(data.aliasEditor, data.nameSection);
  var identifiers = entityRoutes.constructIdentifiers(data.identifierEditor);
  var relationships = entityRoutes.constructRelationships(data.relationshipSection);
  var authorCreditEnable = (0, _get2.default)(data, ['editionGroupSection', 'authorCreditEnable'], true);
  var authorCredit = {};
  if (!authorCreditEnable) {
    authorCredit = null;
  } else if (!(0, _isNil2.default)(data.authorCredit)) {
    // When merging entities, we use a separate reducer "authorCredit"
    authorCredit = data.authorCredit.names;
  } else if (!(0, _isNil2.default)(data.authorCreditEditor)) {
    authorCredit = entityRoutes.constructAuthorCredit(data.authorCreditEditor);
  }
  return {
    aliases: aliases,
    annotation: data.annotationSection.content,
    authorCredit: authorCredit,
    creditSection: authorCreditEnable,
    disambiguation: data.nameSection.disambiguation,
    identifiers: identifiers,
    note: data.submissionSection.note,
    relationships: relationships,
    typeId: data.editionGroupSection.type
  };
}
var createOrEditHandler = (0, _entityRouteUtils.makeEntityCreateOrEditHandler)('editionGroup', transformNewForm, ['typeId', 'creditSection']);
var mergeHandler = (0, _entityRouteUtils.makeEntityCreateOrEditHandler)('editionGroup', transformNewForm, 'typeId', true);
var ENTITY_EDITOR = _privilegesUtils.PrivilegeType.ENTITY_EDITOR;

/** ****************************
*********** Routes ************
*******************************/

var router = _express.default.Router();

// Creation
router.get('/create', auth.isAuthenticated, auth.isAuthorized(ENTITY_EDITOR), middleware.loadIdentifierTypes, middleware.loadLanguages, middleware.loadEditionGroupTypes, middleware.loadRelationshipTypes, /*#__PURE__*/function () {
  var _ref = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee(req, res) {
    var _req$query$name, _req$query;
    var markupProps, nameSection, _entityEditorMarkup, markup, props;
    return _regenerator.default.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            markupProps = (0, _entityRouteUtils.generateEntityProps)('editionGroup', req, res, {});
            nameSection = {
              disambiguation: '',
              exactMatches: null,
              language: null,
              name: (_req$query$name = (_req$query = req.query) === null || _req$query === void 0 ? void 0 : _req$query.name) !== null && _req$query$name !== void 0 ? _req$query$name : '',
              searchResults: null,
              sortName: ''
            };
            if (!nameSection.name) {
              _context.next = 15;
              break;
            }
            _context.prev = 3;
            _context.next = 6;
            return search.autocomplete(req.app.locals.orm, nameSection.name, 'EditionGroup');
          case 6:
            nameSection.searchResults = _context.sent;
            _context.next = 9;
            return search.checkIfExists(req.app.locals.orm, nameSection.name, 'EditionGroup');
          case 9:
            nameSection.exactMatches = _context.sent;
            _context.next = 15;
            break;
          case 12:
            _context.prev = 12;
            _context.t0 = _context["catch"](3);
            _log.default.debug(_context.t0);
          case 15:
            markupProps.initialState.nameSection = nameSection;
            _entityEditorMarkup = (0, _entityRouteUtils.entityEditorMarkup)(markupProps), markup = _entityEditorMarkup.markup, props = _entityEditorMarkup.props;
            return _context.abrupt("return", res.send((0, _target.default)({
              markup: markup,
              props: (0, _props.escapeProps)(props),
              script: '/js/entity-editor.js',
              title: props.heading
            })));
          case 18:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[3, 12]]);
  }));
  return function (_x, _x2) {
    return _ref.apply(this, arguments);
  };
}());
router.post('/create', entityRoutes.displayPreview, auth.isAuthenticatedForHandler, auth.isAuthorized(ENTITY_EDITOR), middleware.loadIdentifierTypes, middleware.loadLanguages, middleware.loadEditionGroupTypes, middleware.loadRelationshipTypes, /*#__PURE__*/function () {
  var _ref2 = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee2(req, res) {
    var _entity$editionGroupS;
    var entity, orm, EditionGroupType, markupProps, _entityEditorMarkup2, markup, props;
    return _regenerator.default.wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            _context2.next = 2;
            return utils.parseInitialState(req, 'editionGroup');
          case 2:
            entity = _context2.sent;
            orm = req.app.locals.orm;
            EditionGroupType = orm.EditionGroupType;
            if (!((_entity$editionGroupS = entity.editionGroupSection) !== null && _entity$editionGroupS !== void 0 && _entity$editionGroupS.type)) {
              _context2.next = 10;
              break;
            }
            _context2.next = 8;
            return utils.getIdByField(EditionGroupType, 'label', entity.editionGroupSection.type);
          case 8:
            _context2.t0 = _context2.sent;
            entity.editionGroupSection = {
              type: _context2.t0
            };
          case 10:
            markupProps = (0, _entityRouteUtils.generateEntityProps)('editionGroup', req, res, {}, function () {
              return entity;
            });
            _entityEditorMarkup2 = (0, _entityRouteUtils.entityEditorMarkup)(markupProps), markup = _entityEditorMarkup2.markup, props = _entityEditorMarkup2.props;
            return _context2.abrupt("return", res.send((0, _target.default)({
              markup: markup,
              props: (0, _props.escapeProps)(props),
              script: '/js/entity-editor.js',
              title: props.heading
            })));
          case 13:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2);
  }));
  return function (_x3, _x4) {
    return _ref2.apply(this, arguments);
  };
}());
router.post('/create/handler', auth.isAuthenticatedForHandler, auth.isAuthorized(ENTITY_EDITOR), createOrEditHandler);

/* If the route specifies a BBID, make sure it does not redirect to another bbid then load the corresponding entity */
router.param('bbid', middleware.redirectedBbid);
router.param('bbid', middleware.makeEntityLoader('EditionGroup', ['authorCredit.names.author.defaultAlias', 'editionGroupType', 'editions.defaultAlias', 'editions.disambiguation', 'editions.releaseEventSet.releaseEvents', 'editions.identifierSet.identifiers.type', 'editions.editionFormat'], 'Edition Group not found'));
function _setEditionGroupTitle(res) {
  res.locals.title = utils.createEntityPageTitle(res.locals.entity, 'EditionGroup', utils.template(_templateObject || (_templateObject = (0, _taggedTemplateLiteral2.default)(["Edition Group \u201C", "\u201D"])), 'name'));
}
router.get('/:bbid', middleware.loadEntityRelationships, middleware.loadWikipediaExtract, function (req, res) {
  _setEditionGroupTitle(res);
  res.locals.entity.editions.sort(entityRoutes.compareEntitiesByDate);
  entityRoutes.displayEntity(req, res);
});
router.get('/:bbid/delete', auth.isAuthenticated, auth.isAuthorized(ENTITY_EDITOR), function (req, res, next) {
  if (!res.locals.entity.dataId) {
    return next(new _error.ConflictError('This entity has already been deleted'));
  }
  _setEditionGroupTitle(res);
  return entityRoutes.displayDeleteEntity(req, res);
});
router.post('/:bbid/delete/handler', auth.isAuthenticatedForHandler, auth.isAuthorized(ENTITY_EDITOR), function (req, res) {
  var orm = req.app.locals.orm;
  var EditionGroupHeader = orm.EditionGroupHeader,
    EditionGroupRevision = orm.EditionGroupRevision;
  return entityRoutes.handleDelete(orm, req, res, EditionGroupHeader, EditionGroupRevision);
});
router.get('/:bbid/revisions', function (req, res, next) {
  var EditionGroupRevision = req.app.locals.orm.EditionGroupRevision;
  _setEditionGroupTitle(res);
  entityRoutes.displayRevisions(req, res, next, EditionGroupRevision);
});
router.get('/:bbid/revisions/revisions', function (req, res, next) {
  var EditionGroupRevision = req.app.locals.orm.EditionGroupRevision;
  _setEditionGroupTitle(res);
  entityRoutes.updateDisplayedRevisions(req, res, next, EditionGroupRevision);
});
function editionGroupToFormState(editionGroup) {
  /** The front-end expects a language id rather than the language object. */
  var aliases = editionGroup.aliasSet ? editionGroup.aliasSet.aliases.map(function (_ref3) {
    var languageId = _ref3.languageId,
      rest = (0, _objectWithoutProperties2.default)(_ref3, _excluded);
    return _objectSpread(_objectSpread({}, rest), {}, {
      language: languageId
    });
  }) : [];
  var defaultAliasIndex = entityRoutes.getDefaultAliasIndex(editionGroup.aliasSet);
  var defaultAliasList = aliases.splice(defaultAliasIndex, 1);
  var aliasEditor = {};
  aliases.forEach(function (alias) {
    aliasEditor[alias.id] = alias;
  });
  var buttonBar = {
    aliasEditorVisible: false,
    identifierEditorVisible: false
  };
  var nameSection = (0, _isEmpty2.default)(defaultAliasList) ? {
    language: null,
    name: '',
    sortName: ''
  } : defaultAliasList[0];
  nameSection.disambiguation = editionGroup.disambiguation && editionGroup.disambiguation.comment;
  var identifiers = editionGroup.identifierSet ? editionGroup.identifierSet.identifiers.map(function (_ref4) {
    var type = _ref4.type,
      rest = (0, _objectWithoutProperties2.default)(_ref4, _excluded2);
    return _objectSpread({
      type: type.id
    }, rest);
  }) : [];
  var identifierEditor = {};
  identifiers.forEach(function (identifier) {
    identifierEditor[identifier.id] = identifier;
  });
  var editionGroupSection = {
    authorCreditEnable: editionGroup.creditSection,
    type: editionGroup.editionGroupType && editionGroup.editionGroupType.id
  };
  var relationshipSection = {
    canEdit: true,
    lastRelationships: null,
    relationshipEditorProps: null,
    relationshipEditorVisible: false,
    relationships: {}
  };
  editionGroup.relationships.forEach(function (relationship) {
    return relationshipSection.relationships["n".concat(relationship.id)] = {
      attributeSetId: relationship.attributeSetId,
      attributes: relationship.attributeSet ? relationship.attributeSet.relationshipAttributes : [],
      relationshipType: relationship.type,
      rowID: "n".concat(relationship.id),
      sourceEntity: relationship.source,
      targetEntity: relationship.target
    };
  });
  var optionalSections = {};
  if (editionGroup.annotation) {
    optionalSections.annotationSection = editionGroup.annotation;
  }
  var credits = editionGroup.authorCredit ? editionGroup.authorCredit.names.map(function (_ref5) {
    var author = _ref5.author,
      rest = (0, _objectWithoutProperties2.default)(_ref5, _excluded3);
    return _objectSpread({
      author: utils.entityToOption(author)
    }, rest);
  }) : [];
  var authorCreditEditor = {};
  var _iterator = _createForOfIteratorHelper(credits),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var credit = _step.value;
      authorCreditEditor[credit.position] = credit;
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  if (!editionGroup.creditSection) {
    authorCreditEditor = {};
  }
  if ((0, _isEmpty2.default)(authorCreditEditor) && editionGroup.creditSection) {
    authorCreditEditor.n0 = {
      author: null,
      joinPhrase: '',
      name: ''
    };
  }
  return _objectSpread({
    aliasEditor: aliasEditor,
    authorCreditEditor: authorCreditEditor,
    buttonBar: buttonBar,
    editionGroupSection: editionGroupSection,
    identifierEditor: identifierEditor,
    nameSection: nameSection,
    relationshipSection: relationshipSection
  }, optionalSections);
}
router.get('/:bbid/edit', auth.isAuthenticated, auth.isAuthorized(ENTITY_EDITOR), middleware.loadIdentifierTypes, middleware.loadEditionGroupTypes, middleware.loadLanguages, middleware.loadEntityRelationships, middleware.loadRelationshipTypes, function (req, res) {
  var _entityEditorMarkup3 = (0, _entityRouteUtils.entityEditorMarkup)((0, _entityRouteUtils.generateEntityProps)('editionGroup', req, res, {}, editionGroupToFormState)),
    markup = _entityEditorMarkup3.markup,
    props = _entityEditorMarkup3.props;
  return res.send((0, _target.default)({
    markup: markup,
    props: (0, _props.escapeProps)(props),
    script: '/js/entity-editor.js',
    title: props.heading
  }));
});
router.post('/:bbid/edit/handler', auth.isAuthenticatedForHandler, auth.isAuthorized(ENTITY_EDITOR), createOrEditHandler);
router.post('/:bbid/merge/handler', auth.isAuthenticatedForHandler, auth.isAuthorized(ENTITY_EDITOR), mergeHandler);
var _default = router;
exports.default = _default;
//# sourceMappingURL=edition-group.js.map