server/routes/entity/edition.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/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.editionToFormState = editionToFormState;
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.parse-int.js");
require("core-js/modules/es.array.map.js");
require("core-js/modules/es.object.values.js");
require("core-js/modules/es.function.name.js");
require("core-js/modules/es.date.to-json.js");
require("core-js/modules/web.url.to-json.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");
require("core-js/modules/es.array.iterator.js");
require("core-js/modules/es.object.from-entries.js");
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _isNull2 = _interopRequireDefault(require("lodash/isNull"));
var _isEmpty2 = _interopRequireDefault(require("lodash/isEmpty"));
var _omit2 = _interopRequireDefault(require("lodash/omit"));
var _isNil2 = _interopRequireDefault(require("lodash/isNil"));
var _get2 = _interopRequireDefault(require("lodash/get"));
var _map2 = _interopRequireDefault(require("lodash/map"));
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 _types = require("../../../client/entity-editor/relationship-editor/types");
var _props = require("../../helpers/props");
var _express = _interopRequireDefault(require("express"));
var _log = _interopRequireDefault(require("log"));
var _utils2 = require("../../../common/helpers/utils");
var _target = _interopRequireDefault(require("../../templates/target"));
var _excluded = ["languageId"],
  _excluded2 = ["author"],
  _excluded3 = ["type"];
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 ************
*******************************/

var additionalEditionProps = ['editionGroupBbid', 'width', 'height', 'depth', 'weight', 'pages', 'formatId', 'statusId'];
function transformNewForm(data) {
  var aliases = entityRoutes.constructAliases(data.aliasEditor, data.nameSection);
  var identifiers = entityRoutes.constructIdentifiers(data.identifierEditor);
  var relationships = entityRoutes.constructRelationships(data.relationshipSection);
  var releaseEvents = [];
  if (data.editionSection.releaseDate) {
    releaseEvents = [{
      date: data.editionSection.releaseDate
    }];
  }
  var languages = (0, _map2.default)(data.editionSection.languages, function (language) {
    return language.value;
  });
  var authorCredit = {};
  if (!(0, _get2.default)(data, ['editionSection', 'authorCreditEnable'], true)) {
    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,
    depth: data.editionSection.depth && parseInt(data.editionSection.depth, 10),
    disambiguation: data.nameSection.disambiguation,
    editionGroupBbid: data.editionSection.editionGroup && data.editionSection.editionGroup.id,
    formatId: data.editionSection.format && parseInt(data.editionSection.format, 10),
    height: data.editionSection.height && parseInt(data.editionSection.height, 10),
    identifiers: identifiers,
    languages: languages,
    note: data.submissionSection.note,
    pages: data.editionSection.pages && parseInt(data.editionSection.pages, 10),
    publishers: data.editionSection.publisher && Object.values(data.editionSection.publisher).map(function (pub) {
      return pub.id;
    }),
    relationships: relationships,
    releaseEvents: releaseEvents,
    statusId: data.editionSection.status && parseInt(data.editionSection.status, 10),
    weight: data.editionSection.weight && parseInt(data.editionSection.weight, 10),
    width: data.editionSection.width && parseInt(data.editionSection.width, 10)
  };
}
function getInitialNameSection(entity) {
  return {
    disambiguation: entity.disambiguation,
    language: entity.defaultAlias.languageId,
    languageId: entity.defaultAlias.languageId,
    name: entity.defaultAlias.name,
    primary: entity.defaultAlias.primary,
    sortName: entity.defaultAlias.sortName
  };
}
var createOrEditHandler = (0, _entityRouteUtils.makeEntityCreateOrEditHandler)('edition', transformNewForm, additionalEditionProps);
var mergeHandler = (0, _entityRouteUtils.makeEntityCreateOrEditHandler)('edition', transformNewForm, additionalEditionProps, 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.loadEditionStatuses, middleware.loadEditionFormats, middleware.loadLanguages, middleware.loadRelationshipTypes, function (req, res, next) {
  var _req$app$locals$orm = req.app.locals.orm,
    EditionGroup = _req$app$locals$orm.EditionGroup,
    Publisher = _req$app$locals$orm.Publisher,
    Work = _req$app$locals$orm.Work,
    Author = _req$app$locals$orm.Author;
  var propsPromise = (0, _entityRouteUtils.generateEntityProps)('edition', req, res, {});
  if (req.query.author) {
    propsPromise.author = Author.forge({
      bbid: req.query.author
    }).fetch({
      require: false,
      withRelated: 'defaultAlias'
    }).then(function (data) {
      return data && utils.entityToOption(data.toJSON());
    });
  }

  // Access edition-group property: can't write req.query.edition-group as the dash makes it invalid Javascript
  if (req.query['edition-group']) {
    propsPromise.editionGroup = EditionGroup.forge({
      bbid: req.query['edition-group']
    }).fetch({
      require: false,
      withRelated: 'defaultAlias'
    }).then(function (data) {
      return data && utils.entityToOption(data.toJSON());
    });
  }
  if (req.query.publisher) {
    propsPromise.publisher = Publisher.forge({
      bbid: req.query.publisher
    }).fetch({
      require: false,
      withRelated: 'defaultAlias'
    }).then(function (data) {
      return data && utils.entityToOption(data.toJSON());
    });
  }
  if (req.query.work) {
    propsPromise.work = Work.forge({
      bbid: req.query.work
    }).fetch({
      require: false,
      withRelated: 'defaultAlias'
    }).then(function (data) {
      return data && utils.entityToOption(data.toJSON());
    });
  }
  function render(_x) {
    return _render.apply(this, arguments);
  }
  function _render() {
    _render = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee(props) {
      var _req$query$name, _req$query, _initialState$edition, _initialState$nameSec;
      var initialState, relationshipTypeId, initialRelationshipIndex, name, _initialState$edition2, editorMarkup, markup, updatedProps;
      return _regenerator.default.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              initialState = props.initialState;
              initialState.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: ''
              };
              initialRelationshipIndex = 0;
              initialState.editionSection = (_initialState$edition = initialState.editionSection) !== null && _initialState$edition !== void 0 ? _initialState$edition : {};
              if (props.author) {
                initialState.authorCreditEditor = {
                  a0: {
                    author: {
                      id: props.author.id,
                      rowId: 'a0',
                      text: props.author.text,
                      type: 'Author'
                    },
                    automaticJoinPhrase: true,
                    joinPhrase: '',
                    name: props.author.text
                  }
                };
              }
              if (props.publisher) {
                initialState.editionSection.publisher = props.publisher;
                // add initial relationship with relationshipTypeId = 4 (<Publisher> published < New Edition>)
                relationshipTypeId = _types.RelationshipTypes.PublisherPublishedEdition;
                (0, _entityRouteUtils.addInitialRelationship)(props, relationshipTypeId, initialRelationshipIndex++, props.publisher);
              }
              if (props.editionGroup) {
                if (!initialState.nameSection.name) {
                  // If a name hasn't been passed in query parameters, default to same name as the Edition Group
                  initialState.nameSection = getInitialNameSection(props.editionGroup);
                }
                initialState.editionSection.editionGroup = props.editionGroup;
                // add initial raltionship with relationshipTypeId = 3 (<New Edition> is an edition of <EditionGroup>)
                relationshipTypeId = _types.RelationshipTypes.EditionIsAnEditionOfEditionGroup;
                (0, _entityRouteUtils.addInitialRelationship)(props, relationshipTypeId, initialRelationshipIndex++, props.editionGroup);
              }
              if (props.work) {
                if (!initialState.nameSection.name) {
                  // If a name hasn't been passed in query parameters, default to same name as the Work
                  initialState.nameSection = getInitialNameSection(props.work);
                }
                // add initial raltionship with relationshipTypeId = 10 (<New Edition> Contains <Work>)
                relationshipTypeId = _types.RelationshipTypes.EditionContainsWork;
                (0, _entityRouteUtils.addInitialRelationship)(props, relationshipTypeId, initialRelationshipIndex++, props.work);
              }
              if (!((_initialState$nameSec = initialState.nameSection) !== null && _initialState$nameSec !== void 0 && _initialState$nameSec.name)) {
                _context.next = 30;
                break;
              }
              name = initialState.nameSection.name;
              _context.prev = 10;
              _context.next = 13;
              return search.autocomplete(req.app.locals.orm, name, 'Edition');
            case 13:
              initialState.nameSection.searchResults = _context.sent;
              _context.next = 16;
              return search.checkIfExists(req.app.locals.orm, name, 'Edition');
            case 16:
              initialState.nameSection.exactMatches = _context.sent;
              if (!((_initialState$edition2 = initialState.editionSection.editionGroup) !== null && _initialState$edition2 !== void 0)) {
                _context.next = 21;
                break;
              }
              _context.t0 = _initialState$edition2;
              _context.next = 24;
              break;
            case 21:
              _context.next = 23;
              return search.autocomplete(req.app.locals.orm, name, 'EditionGroup');
            case 23:
              _context.t0 = _context.sent;
            case 24:
              initialState.editionSection.matchingNameEditionGroups = _context.t0;
              _context.next = 30;
              break;
            case 27:
              _context.prev = 27;
              _context.t1 = _context["catch"](10);
              _log.default.debug(_context.t1);
            case 30:
              editorMarkup = (0, _entityRouteUtils.entityEditorMarkup)(props);
              markup = editorMarkup.markup;
              updatedProps = editorMarkup.props;
              return _context.abrupt("return", res.send((0, _target.default)({
                markup: markup,
                props: (0, _props.escapeProps)(updatedProps),
                script: '/js/entity-editor.js',
                title: props.heading
              })));
            case 34:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, null, [[10, 27]]);
    }));
    return _render.apply(this, arguments);
  }
  (0, _utils2.makePromiseFromObject)(propsPromise).then(render).catch(next);
});
router.post('/create', entityRoutes.displayPreview, auth.isAuthenticatedForHandler, auth.isAuthorized(ENTITY_EDITOR), middleware.loadIdentifierTypes, middleware.loadEditionStatuses, middleware.loadEditionFormats, middleware.loadLanguages, middleware.loadRelationshipTypes, /*#__PURE__*/function () {
  var _ref = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee2(req, res, next) {
    var entity, orm, EditionFormat, keysToInt, physicalEnable, _i, _keysToInt, key, foundOption, propsPromise, render;
    return _regenerator.default.wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            render = function _render2(props) {
              var editorMarkup = (0, _entityRouteUtils.entityEditorMarkup)(props);
              var markup = editorMarkup.markup;
              var updatedProps = editorMarkup.props;
              return res.send((0, _target.default)({
                markup: markup,
                props: (0, _props.escapeProps)(updatedProps),
                script: '/js/entity-editor.js',
                title: props.heading
              }));
            };
            _context2.next = 3;
            return utils.parseInitialState(req, 'edition');
          case 3:
            entity = _context2.sent;
            if (!entity.editionSection) {
              _context2.next = 23;
              break;
            }
            orm = req.app.locals.orm;
            EditionFormat = orm.EditionFormat;
            _context2.next = 9;
            return utils.parseLanguages(entity.editionSection, orm);
          case 9:
            entity.editionSection = _context2.sent;
            if (!entity.editionSection.format) {
              _context2.next = 14;
              break;
            }
            _context2.next = 13;
            return utils.getIdByField(EditionFormat, 'label', entity.editionSection.format);
          case 13:
            entity.editionSection.format = _context2.sent;
          case 14:
            keysToInt = ['height', 'width', 'depth', 'weight', 'pages'];
            physicalEnable = false;
            for (_i = 0, _keysToInt = keysToInt; _i < _keysToInt.length; _i++) {
              key = _keysToInt[_i];
              entity.editionSection[key] = parseInt(entity.editionSection[key], 10) || null;
              if (entity.editionSection[key]) {
                physicalEnable = true;
              }
            }
            entity.editionSection.physicalEnable = physicalEnable;
            // adding publisher
            if (!entity.editionSection.publisher) {
              _context2.next = 23;
              break;
            }
            _context2.next = 21;
            return utils.searchOption(orm, 'publisher', entity.editionSection.publisher, 'bbid', true);
          case 21:
            foundOption = _context2.sent;
            entity.editionSection.publisher = foundOption ? (0, _omit2.default)(foundOption, ['disambiguation']) : null;
          case 23:
            propsPromise = (0, _entityRouteUtils.generateEntityProps)('edition', req, res, {}, function () {
              return entity;
            });
            (0, _utils2.makePromiseFromObject)(propsPromise).then(render).catch(next);
          case 25:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2);
  }));
  return function (_x2, _x3, _x4) {
    return _ref.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('Edition', ['authorCredit.names.author.defaultAlias', 'editionGroup.defaultAlias', 'languageSet.languages', 'editionFormat', 'editionStatus', 'releaseEventSet.releaseEvents', 'publisherSet.publishers.defaultAlias'], 'Edition not found'));
function _setEditionTitle(res) {
  res.locals.title = utils.createEntityPageTitle(res.locals.entity, 'Edition', utils.template(_templateObject || (_templateObject = (0, _taggedTemplateLiteral2.default)(["Edition \u201C", "\u201D"])), 'name'));
}
router.get('/:bbid', middleware.loadEntityRelationships, middleware.loadWorkTableAuthors, middleware.loadWikipediaExtract, function (req, res) {
  _setEditionTitle(res);
  entityRoutes.displayEntity(req, res);
});
router.get('/:bbid/revisions', function (req, res, next) {
  var EditionRevision = req.app.locals.orm.EditionRevision;
  _setEditionTitle(res);
  entityRoutes.displayRevisions(req, res, next, EditionRevision);
});
router.get('/:bbid/revisions/revisions', function (req, res, next) {
  var EditionRevision = req.app.locals.orm.EditionRevision;
  _setEditionTitle(res);
  entityRoutes.updateDisplayedRevisions(req, res, next, EditionRevision);
});
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'));
  }
  _setEditionTitle(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 EditionHeader = orm.EditionHeader,
    EditionRevision = orm.EditionRevision;
  return entityRoutes.handleDelete(orm, req, res, EditionHeader, EditionRevision);
});
function editionToFormState(edition) {
  /** The front-end expects a language id rather than the language object. */
  var aliases = edition.aliasSet ? edition.aliasSet.aliases.map(function (_ref2) {
    var languageId = _ref2.languageId,
      rest = (0, _objectWithoutProperties2.default)(_ref2, _excluded);
    return _objectSpread(_objectSpread({}, rest), {}, {
      language: languageId
    });
  }) : [];
  var defaultAliasIndex = entityRoutes.getDefaultAliasIndex(edition.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 = edition.disambiguation && edition.disambiguation.comment;
  var credits = edition.authorCredit ? edition.authorCredit.names.map(function (_ref3) {
    var author = _ref3.author,
      rest = (0, _objectWithoutProperties2.default)(_ref3, _excluded2);
    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 ((0, _isEmpty2.default)(authorCreditEditor)) {
    authorCreditEditor.n0 = {
      author: null,
      joinPhrase: '',
      name: ''
    };
  }
  var identifiers = edition.identifierSet ? edition.identifierSet.identifiers.map(function (_ref4) {
    var type = _ref4.type,
      rest = (0, _objectWithoutProperties2.default)(_ref4, _excluded3);
    return _objectSpread({
      type: type.id
    }, rest);
  }) : [];
  var identifierEditor = {};
  identifiers.forEach(function (identifier) {
    identifierEditor[identifier.id] = identifier;
  });
  var physicalEnable = !((0, _isNull2.default)(edition.depth) && (0, _isNull2.default)(edition.height) && (0, _isNull2.default)(edition.pages) && (0, _isNull2.default)(edition.weight) && (0, _isNull2.default)(edition.width));
  var releaseDate = edition.releaseEventSetId ? edition.releaseEventSet.releaseEvents[0].date : null;
  var publisher = edition.publisherSet && ((0, _isEmpty2.default)(edition.publisherSet.publishers) ? null : Object.fromEntries(edition.publisherSet.publishers.map(utils.entityToOption).map(function (op, index) {
    return [index, op];
  })));
  var editionGroup = utils.entityToOption(edition.editionGroup);
  var editionSection = {
    authorCreditEnable: true,
    depth: edition.depth,
    editionGroup: editionGroup,
    // Determines whether the EG can be left blank (an EG will be auto-created) for existing Editions
    editionGroupRequired: false,
    editionGroupVisible: true,
    format: edition.editionFormat && edition.editionFormat.id,
    height: edition.height,
    languages: edition.languageSet ? edition.languageSet.languages.map(function (_ref5) {
      var id = _ref5.id,
        name = _ref5.name;
      return {
        label: name,
        value: id
      };
    }) : [],
    pages: edition.pages,
    physicalEnable: physicalEnable,
    publisher: publisher,
    releaseDate: releaseDate,
    status: edition.editionStatus && edition.editionStatus.id,
    weight: edition.weight,
    width: edition.width
  };
  var relationshipSection = {
    canEdit: true,
    lastRelationships: null,
    relationshipEditorProps: null,
    relationshipEditorVisible: false,
    relationships: {}
  };
  edition.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 (edition.annotation) {
    optionalSections.annotationSection = edition.annotation;
  }
  return _objectSpread({
    aliasEditor: aliasEditor,
    authorCreditEditor: authorCreditEditor,
    buttonBar: buttonBar,
    editionSection: editionSection,
    identifierEditor: identifierEditor,
    nameSection: nameSection,
    relationshipSection: relationshipSection
  }, optionalSections);
}
router.get('/:bbid/edit', auth.isAuthenticated, auth.isAuthorized(ENTITY_EDITOR), middleware.loadIdentifierTypes, middleware.loadEditionStatuses, middleware.loadEditionFormats, middleware.loadLanguages, middleware.loadEntityRelationships, middleware.loadRelationshipTypes, function (req, res) {
  var _entityEditorMarkup = (0, _entityRouteUtils.entityEditorMarkup)((0, _entityRouteUtils.generateEntityProps)('edition', req, res, {}, editionToFormState)),
    markup = _entityEditorMarkup.markup,
    props = _entityEditorMarkup.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.js.map