server/routes/entity/series.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.seriesToFormState = seriesToFormState;
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.array.concat.js");
require("core-js/modules/es.function.name.js");
require("core-js/modules/es.array.includes.js");
require("core-js/modules/es.array.index-of.js");
require("core-js/modules/es.string.includes.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) 2021  Akash Gupta
 *
 * 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 additionalSeriesProps = ['entityType', 'orderingTypeId'];
function transformNewForm(data) {
  var aliases = entityRoutes.constructAliases(data.aliasEditor, data.nameSection);
  var identifiers = entityRoutes.constructIdentifiers(data.identifierEditor);
  var seriesItems = entityRoutes.constructRelationships(data.seriesSection, 'seriesItems');
  var relationshipsItems = entityRoutes.constructRelationships(data.relationshipSection, 'relationships');
  var relationships = seriesItems.concat(relationshipsItems);
  return {
    aliases: aliases,
    annotation: data.annotationSection.content,
    disambiguation: data.nameSection.disambiguation,
    entityType: data.seriesSection.seriesType,
    identifiers: identifiers,
    note: data.submissionSection.note,
    orderingTypeId: data.seriesSection.orderType,
    relationships: relationships
  };
}
var createOrEditHandler = (0, _entityRouteUtils.makeEntityCreateOrEditHandler)('series', transformNewForm, additionalSeriesProps);
var mergeHandler = (0, _entityRouteUtils.makeEntityCreateOrEditHandler)('series', transformNewForm, additionalSeriesProps, 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.loadRelationshipTypes, middleware.loadSeriesOrderingTypes, /*#__PURE__*/function () {
  var _ref = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee(req, res) {
    var _req$query$name, _req$query;
    var _entityEditorMarkup, markup, props, nameSection;
    return _regenerator.default.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _entityEditorMarkup = (0, _entityRouteUtils.entityEditorMarkup)((0, _entityRouteUtils.generateEntityProps)('series', req, res, {})), markup = _entityEditorMarkup.markup, props = _entityEditorMarkup.props;
            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, 'Series');
          case 6:
            nameSection.searchResults = _context.sent;
            _context.next = 9;
            return search.checkIfExists(req.app.locals.orm, nameSection.name, 'Series');
          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:
            props.initialState.nameSection = nameSection;
            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 17:
          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.loadRelationshipTypes, middleware.loadSeriesOrderingTypes, /*#__PURE__*/function () {
  var _ref2 = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee2(req, res) {
    var entity, orderingTypes, seriesTypes, _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, 'series');
          case 2:
            entity = _context2.sent;
            if (entity.seriesSection) {
              orderingTypes = ['Automatic', 'Manual'];
              seriesTypes = ['Author', 'Work', 'EditionGroup', 'Edition', 'Publisher'];
              if (entity.seriesSection.orderType) {
                if (!orderingTypes.includes(entity.seriesSection.orderType)) {
                  delete entity.seriesSection.orderType;
                } else {
                  entity.seriesSection.orderType = orderingTypes.indexOf(entity.seriesSection.orderType) + 1;
                }
              }
              if (entity.seriesSection.seriesType && !seriesTypes.includes(entity.seriesSection.seriesType)) {
                delete entity.seriesSection.seriesType;
              }
            }
            if ((0, _isEmpty2.default)(entity.seriesSection)) {
              delete entity.seriesSection;
            } else {
              entity.seriesSection.seriesItems = {};
            }
            _entityEditorMarkup2 = (0, _entityRouteUtils.entityEditorMarkup)((0, _entityRouteUtils.generateEntityProps)('series', req, res, {}, function () {
              return entity;
            })), 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 7:
          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);
router.post('/:bbid/merge/handler', auth.isAuthenticatedForHandler, auth.isAuthorized(ENTITY_EDITOR), mergeHandler);

/* 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('Series', ['defaultAlias', 'disambiguation', 'seriesOrderingType', 'identifierSet.identifiers.type'], 'Series not found'));
function _setSeriesTitle(res) {
  res.locals.title = utils.createEntityPageTitle(res.locals.entity, 'Series', utils.template(_templateObject || (_templateObject = (0, _taggedTemplateLiteral2.default)(["Series \u201C", "\u201D"])), 'name'));
}
router.get('/:bbid', middleware.loadEntityRelationships, middleware.loadSeriesItems, middleware.loadGenders, middleware.loadWikipediaExtract, function (req, res) {
  _setSeriesTitle(res);
  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'));
  }
  _setSeriesTitle(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 SeriesHeader = orm.SeriesHeader,
    SeriesRevision = orm.SeriesRevision;
  return entityRoutes.handleDelete(orm, req, res, SeriesHeader, SeriesRevision);
});
router.get('/:bbid/revisions', function (req, res, next) {
  var SeriesRevision = req.app.locals.orm.SeriesRevision;
  _setSeriesTitle(res);
  entityRoutes.displayRevisions(req, res, next, SeriesRevision);
});
router.get('/:bbid/revisions/revisions', function (req, res, next) {
  var SeriesRevision = req.app.locals.orm.SeriesRevision;
  _setSeriesTitle(res);
  entityRoutes.updateDisplayedRevisions(req, res, next, SeriesRevision);
});
function seriesToFormState(series) {
  var aliases = series.aliasSet ? series.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(series.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 = series.disambiguation && series.disambiguation.comment;
  var identifiers = series.identifierSet ? series.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 seriesSection = {
    orderType: series.seriesOrderingType && series.seriesOrderingType.id,
    seriesItems: {},
    seriesType: series.entityType
  };
  var relationshipSection = {
    canEdit: true,
    lastRelationships: null,
    relationshipEditorProps: null,
    relationshipEditorVisible: false,
    relationships: {}
  };
  series.relationships.forEach(function (relationship) {
    var formattedRelationship = {
      attributeSetId: relationship.attributeSetId,
      attributes: relationship.attributeSet ? relationship.attributeSet.relationshipAttributes : [],
      relationshipType: relationship.type,
      rowID: "n".concat(relationship.id),
      sourceEntity: relationship.source,
      targetEntity: relationship.target
    };
    // separate series items from relationships
    if (relationship.typeId > 69 && relationship.typeId < 75) {
      seriesSection.seriesItems["n".concat(relationship.id)] = formattedRelationship;
    } else {
      relationshipSection.relationships["n".concat(relationship.id)] = formattedRelationship;
    }
  });
  var optionalSections = {};
  if (series.annotation) {
    optionalSections.annotationSection = series.annotation;
  }
  return _objectSpread({
    aliasEditor: aliasEditor,
    buttonBar: buttonBar,
    identifierEditor: identifierEditor,
    nameSection: nameSection,
    relationshipSection: relationshipSection,
    seriesSection: seriesSection
  }, optionalSections);
}
router.get('/:bbid/edit', auth.isAuthenticated, auth.isAuthorized(ENTITY_EDITOR), middleware.loadIdentifierTypes, middleware.loadSeriesOrderingTypes, middleware.loadLanguages, middleware.loadEntityRelationships, middleware.loadRelationshipTypes, function (req, res) {
  var _entityEditorMarkup3 = (0, _entityRouteUtils.entityEditorMarkup)((0, _entityRouteUtils.generateEntityProps)('series', req, res, {}, seriesToFormState)),
    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);
var _default = router;
exports.default = _default;
//# sourceMappingURL=series.js.map