server/routes/entity/publisher.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.iterator.js");
require("core-js/modules/es.string.iterator.js");
require("core-js/modules/es.weak-map.js");
require("core-js/modules/web.dom-collections.iterator.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.publisherToFormState = publisherToFormState;
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.date.to-json.js");
require("core-js/modules/web.url.to-json.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 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"];
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 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 additionalPublisherProps = ['typeId', 'areaId', 'beginDate', 'endDate', 'ended'];
function transformNewForm(data) {
  var aliases = entityRoutes.constructAliases(data.aliasEditor, data.nameSection);
  var identifiers = entityRoutes.constructIdentifiers(data.identifierEditor);
  var relationships = entityRoutes.constructRelationships(data.relationshipSection);
  return {
    aliases: aliases,
    annotation: data.annotationSection.content,
    areaId: data.publisherSection.area && data.publisherSection.area.id,
    beginDate: data.publisherSection.beginDate,
    disambiguation: data.nameSection.disambiguation,
    endDate: data.publisherSection.endDate ? data.publisherSection.endDate : null,
    ended: data.publisherSection.ended,
    identifiers: identifiers,
    note: data.submissionSection.note,
    relationships: relationships,
    typeId: data.publisherSection.type
  };
}
var createOrEditHandler = (0, _entityRouteUtils.makeEntityCreateOrEditHandler)('publisher', transformNewForm, additionalPublisherProps);
var mergeHandler = (0, _entityRouteUtils.makeEntityCreateOrEditHandler)('publisher', transformNewForm, additionalPublisherProps, 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.loadPublisherTypes, 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)('publisher', 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, 'Publisher');
          case 6:
            nameSection.searchResults = _context.sent;
            _context.next = 9;
            return search.checkIfExists(req.app.locals.orm, nameSection.name, 'Publisher');
          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.loadPublisherTypes, middleware.loadRelationshipTypes, /*#__PURE__*/function () {
  var _ref2 = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee2(req, res) {
    var orm, PublisherType, entity, markupProps, _entityEditorMarkup2, markup, props;
    return _regenerator.default.wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            orm = req.app.locals.orm;
            PublisherType = orm.PublisherType;
            _context2.next = 4;
            return utils.parseInitialState(req, 'publisher');
          case 4:
            entity = _context2.sent;
            if (!entity.publisherSection) {
              _context2.next = 15;
              break;
            }
            if (!entity.publisherSection.type) {
              _context2.next = 10;
              break;
            }
            _context2.next = 9;
            return utils.getIdByField(PublisherType, 'label', entity.publisherSection.type);
          case 9:
            entity.publisherSection.type = _context2.sent;
          case 10:
            if (entity.publisherSection.endDate) {
              entity.publisherSection.ended = true;
            }
            if (!entity.publisherSection.area) {
              _context2.next = 15;
              break;
            }
            _context2.next = 14;
            return utils.searchOption(orm, 'area', entity.publisherSection.area);
          case 14:
            entity.publisherSection.area = _context2.sent;
          case 15:
            markupProps = (0, _entityRouteUtils.generateEntityProps)('publisher', 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 18:
          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('Publisher', ['publisherType', 'area'], 'Publisher not found'));
function _setPublisherTitle(res) {
  res.locals.title = utils.createEntityPageTitle(res.locals.entity, 'Publisher', utils.template(_templateObject || (_templateObject = (0, _taggedTemplateLiteral2.default)(["Publisher \u201C", "\u201D"])), 'name'));
}
router.get('/:bbid', middleware.loadEntityRelationships, middleware.loadWikipediaExtract, function (req, res, next) {
  // Fetch editions
  var Publisher = req.app.locals.orm.Publisher;
  var editionRelationsToFetch = ['defaultAlias', 'disambiguation', 'releaseEventSet.releaseEvents', 'identifierSet.identifiers.type', 'editionFormat', 'authorCredit.names'];
  var editionsPromise = Publisher.forge({
    bbid: res.locals.entity.bbid
  }).editions({
    withRelated: editionRelationsToFetch
  });
  return editionsPromise.then(function (editions) {
    res.locals.entity.editions = editions.toJSON();
    _setPublisherTitle(res);
    res.locals.entity.editions.sort(entityRoutes.compareEntitiesByDate);
    return entityRoutes.displayEntity(req, res);
  }).catch(next);
});
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'));
  }
  _setPublisherTitle(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 PublisherHeader = orm.PublisherHeader,
    PublisherRevision = orm.PublisherRevision;
  return entityRoutes.handleDelete(orm, req, res, PublisherHeader, PublisherRevision);
});
router.get('/:bbid/revisions', function (req, res, next) {
  var PublisherRevision = req.app.locals.orm.PublisherRevision;
  _setPublisherTitle(res);
  entityRoutes.displayRevisions(req, res, next, PublisherRevision);
});
router.get('/:bbid/revisions/revisions', function (req, res, next) {
  var PublisherRevision = req.app.locals.orm.PublisherRevision;
  _setPublisherTitle(res);
  entityRoutes.updateDisplayedRevisions(req, res, next, PublisherRevision);
});
function publisherToFormState(publisher) {
  /** The front-end expects a language id rather than the language object. */
  var aliases = publisher.aliasSet ? publisher.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(publisher.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 = publisher.disambiguation && publisher.disambiguation.comment;
  var identifiers = publisher.identifierSet ? publisher.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 publisherSection = {
    area: entityRoutes.areaToOption(publisher.area),
    beginDate: publisher.beginDate,
    endDate: publisher.endDate,
    ended: publisher.ended,
    type: publisher.publisherType && publisher.publisherType.id
  };
  var relationshipSection = {
    canEdit: true,
    lastRelationships: null,
    relationshipEditorProps: null,
    relationshipEditorVisible: false,
    relationships: {}
  };
  publisher.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 (publisher.annotation) {
    optionalSections.annotationSection = publisher.annotation;
  }
  return _objectSpread({
    aliasEditor: aliasEditor,
    buttonBar: buttonBar,
    identifierEditor: identifierEditor,
    nameSection: nameSection,
    publisherSection: publisherSection,
    relationshipSection: relationshipSection
  }, optionalSections);
}
router.get('/:bbid/edit', auth.isAuthenticated, auth.isAuthorized(ENTITY_EDITOR), middleware.loadIdentifierTypes, middleware.loadPublisherTypes, middleware.loadLanguages, middleware.loadEntityRelationships, middleware.loadRelationshipTypes, function (req, res) {
  var _entityEditorMarkup3 = (0, _entityRouteUtils.entityEditorMarkup)((0, _entityRouteUtils.generateEntityProps)('publisher', req, res, {}, publisherToFormState)),
    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=publisher.js.map