/
merge.js
371 lines (329 loc) · 11.1 KB
/
merge.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
/*
* Copyright (C) 2019 Nicolas Pelletier
*
* 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.
*/
// @flow
import * as auth from '../helpers/auth';
import * as commonUtils from '../../common/helpers/utils';
import * as entityRoutes from './entity/entity';
import * as middleware from '../helpers/middleware';
import {BadRequestError, ConflictError, NotFoundError} from '../../common/helpers/error';
import {basicRelations,
getEntityFetchPropertiesByType,
getEntitySectionByType} from '../helpers/merge';
import {
entityMergeMarkup,
generateEntityMergeProps
} from '../helpers/entityRouteUtils';
import _ from 'lodash';
import {escapeProps} from '../helpers/props';
import express from 'express';
import renderRelationship from '../helpers/render';
import targetTemplate from '../templates/target';
const router = express.Router();
function entitiesToFormState(entities) {
const [targetEntity, ...otherEntities] = entities;
const aliases = entities.reduce((returnValue, entity) => {
if (Array.isArray(_.get(entity, 'aliasSet.aliases'))) {
return returnValue.concat(
entity.aliasSet.aliases.map(({language, ...rest}) => ({
language: language.id,
...rest
}))
);
}
return returnValue;
}, []);
let defaultAliasIndex;
if (_.get(targetEntity, 'aliasSet.defaultAliasId')) {
defaultAliasIndex = _.findIndex(aliases, alias => alias.id === targetEntity.aliasSet.defaultAliasId);
}
else {
defaultAliasIndex = entityRoutes.getDefaultAliasIndex(aliases);
}
const aliasEditor = {};
aliases.forEach((alias) => {
aliasEditor[alias.id] = alias;
});
const nameSection = aliases[defaultAliasIndex] ||
{
disambiguation: null,
language: null,
name: '',
sortName: ''
};
const hasDisambiguation = _.find(entities, 'disambiguation');
nameSection.disambiguation = hasDisambiguation &&
hasDisambiguation.disambiguation &&
hasDisambiguation.disambiguation.comment;
const identifiers = entities.reduce((returnValue, entity) => {
if (entity.identifierSet) {
const mappedIdentifiers = entity.identifierSet.identifiers.map(
({type, ...rest}) => ({
type: type.id,
...rest
})
);
return returnValue.concat(mappedIdentifiers);
}
return returnValue;
}, []);
const identifierEditor = {};
const uniqueIdentifiers = _.uniqWith(identifiers, (identifierA, identifierB) =>
identifierA.type === identifierB.type && identifierA.value === identifierB.value);
uniqueIdentifiers.forEach((identifier) => {
identifierEditor[identifier.id] = identifier;
});
const type = _.camelCase(targetEntity.type);
const entityTypeSection = getEntitySectionByType(type, entities);
const relationshipSection = {
canEdit: false,
lastRelationships: null,
relationshipEditorProps: null,
relationshipEditorVisible: false,
relationships: {}
};
const relationships = entities.reduce((returnValue, entity) => {
if (entity.relationships) {
return returnValue.concat(entity.relationships);
}
return returnValue;
}, []);
const otherEntitiesBBIDs = otherEntities.map(entity => entity.bbid);
relationships.forEach((relationship) => {
relationshipSection.relationships[relationship.id] = {
relationshipType: relationship.type,
rendered: relationship.rendered,
rowID: relationship.id,
// Change the source and/or target BBIDs of the relationship accordingly
// to the bbid of the entity we're merging into
sourceEntity: otherEntitiesBBIDs.includes(relationship.sourceBbid) ? targetEntity : relationship.source,
targetEntity: otherEntitiesBBIDs.includes(relationship.targetBbid) ? targetEntity : relationship.target
};
});
const props = {
aliasEditor,
identifierEditor,
nameSection,
relationshipSection
};
props[`${type}Section`] = entityTypeSection;
return props;
}
function loadEntityRelationships(entity, orm, transacting): Promise<any> {
const {RelationshipSet} = orm;
if (!entity.relationshipSetId) {
return null;
}
return RelationshipSet.forge({id: entity.relationshipSetId})
.fetch({
transacting,
withRelated: [
'relationships.source',
'relationships.target',
'relationships.type'
]
})
.then((relationshipSet) => {
entity.relationships = relationshipSet ?
relationshipSet.related('relationships').toJSON() : [];
function getEntityWithAlias(relEntity) {
const model = commonUtils.getEntityModelByType(orm, relEntity.type);
return model.forge({bbid: relEntity.bbid})
.fetch({withRelated: 'defaultAlias'});
}
/**
* Source and target are generic Entity objects, so until we have
* a good way of polymorphically fetching the right specific entity,
* we need to fetch default alias in a somewhat sketchier way.
*/
return Promise.all(entity.relationships.map(
(relationship) => Promise.all(
[getEntityWithAlias(relationship.source),
getEntityWithAlias(relationship.target)]
)
.then(([relationshipSource, relationshipTarget]) => {
relationship.source = relationshipSource.toJSON();
relationship.target = relationshipTarget.toJSON();
return relationship;
})
));
})
.then((relationships) => {
// Set rendered relationships on relationship objects
relationships.forEach((relationship) => {
relationship.rendered = renderRelationship(relationship);
});
return entity;
});
}
async function getEntityByBBID(orm, transacting, bbid) {
const redirectBbid = await orm.func.entity.recursivelyGetRedirectBBID(orm, bbid, transacting);
const entityHeader = await orm.Entity.forge({bbid: redirectBbid}).fetch({transacting});
const entityType = entityHeader.get('type');
const model = commonUtils.getEntityModelByType(orm, entityType);
return model.forge({bbid: redirectBbid})
.fetch({
require: true,
transacting,
withRelated: basicRelations.concat(getEntityFetchPropertiesByType(entityType))
})
.then(async (entity) => {
const entityJSON = entity.toJSON();
try {
await loadEntityRelationships(entityJSON, orm, transacting);
}
catch (error) {
// eslint-disable-next-line no-console
console.error(error);
}
return entityJSON;
})
.catch(error => {
throw error;
});
}
router.get('/add/:bbid', auth.isAuthenticated,
async (req, res, next) => {
const {orm}: {orm: any} = req.app.locals;
let {mergeQueue} = req.session;
if (_.isNil(req.params.bbid) ||
!commonUtils.isValidBBID(req.params.bbid)) {
return next(new BadRequestError(`Invalid bbid: ${req.params.bbid}`, req));
}
if (!mergeQueue) {
mergeQueue = {
entityType: '',
mergingEntities: {}
};
req.session.mergeQueue = mergeQueue;
}
if (_.has(mergeQueue.mergingEntities, req.params.bbid)) {
// Do nothing, redirect to referer.
return res.redirect(req.headers.referer);
}
let fetchedEntity;
try {
await orm.bookshelf.transaction(async (transacting) => {
fetchedEntity = await getEntityByBBID(orm, transacting, req.params.bbid);
});
}
catch (error) {
return next(new NotFoundError('Entity not found', req));
}
/* If there is no fetchedEntity or no dataId, the entity has been deleted */
if (!_.get(fetchedEntity, 'dataId')) {
const conflictError = new ConflictError('You cannot merge an entity that has been deleted');
return next(conflictError);
}
const {bbid, type} = fetchedEntity;
if (type !== mergeQueue.entityType) {
mergeQueue.mergingEntities = {};
mergeQueue.entityType = _.upperFirst(type);
}
mergeQueue.mergingEntities[bbid] = fetchedEntity;
return res.redirect(req.headers.referer);
});
router.get('/remove/:bbid', auth.isAuthenticated,
(req, res) => {
const {mergeQueue} = req.session;
if (!mergeQueue || _.isNil(req.params.bbid)) {
res.redirect(req.headers.referer);
return;
}
const {mergingEntities} = mergeQueue;
delete mergingEntities[req.params.bbid];
/* If there's only one item in the queue, delete the queue entirely */
const mergingBBIDs = Object.keys(mergingEntities);
if (mergingBBIDs.length === 0) {
req.session.mergeQueue = null;
}
res.redirect(req.headers.referer);
});
router.get('/cancel', auth.isAuthenticated,
(req, res) => {
req.session.mergeQueue = null;
res.redirect(req.headers.referer);
});
router.get('/submit/:targetBBID?', auth.isAuthenticated,
middleware.loadIdentifierTypes, middleware.loadLanguages,
middleware.loadRelationshipTypes,
async (req, res, next) => {
const {orm}: {orm: any} = req.app.locals;
const {bookshelf} = orm;
const {mergeQueue} = req.session;
if (!mergeQueue) {
return next(new ConflictError('No entities selected for merge'));
}
const {mergingEntities, entityType} = mergeQueue;
const bbids = Object.keys(mergingEntities);
if (bbids.length < 2) {
return next(new ConflictError('You must have at least 2 entities selected to merge'));
}
const invalidBBIDs = bbids.filter(bbid => !commonUtils.isValidBBID(bbid));
if (invalidBBIDs.length) {
return next(new ConflictError(`Invalid bbids: ${invalidBBIDs.join(', ')}`));
}
let mergingFetchedEntities = _.values(mergingEntities);
let {targetBBID} = req.params;
if (_.isNil(targetBBID)) {
targetBBID = bbids[0];
}
if (!_.uniqBy(mergingFetchedEntities, 'type').length === 1) {
const conflictError = new ConflictError('You can only merge entities of the same type');
return next(conflictError);
}
try {
await bookshelf.transaction(async (transacting) => {
const refreshedMergingEntities = await Promise.all(bbids.map(
(bbid) =>
getEntityByBBID(orm, transacting, bbid)
));
refreshedMergingEntities.forEach(entity => {
mergeQueue.mergingEntities[entity.bbid] = entity;
});
mergingFetchedEntities = refreshedMergingEntities;
});
}
catch (error) {
return next(error);
}
if (_.uniqBy(mergingFetchedEntities, 'bbid').length !== mergingFetchedEntities.length) {
const conflictError = new ConflictError('You cannot merge an entity that has already been merged');
return next(conflictError);
}
mergingFetchedEntities.sort((first, second) => {
if (first.bbid === targetBBID) { return -1; }
else if (second.bbid === targetBBID) { return 1; }
return 0;
});
res.locals.entity = mergingFetchedEntities[0];
const {markup, props} = entityMergeMarkup(generateEntityMergeProps(
req, res, {
entityType: _.camelCase(entityType),
mergingEntities: mergingFetchedEntities,
title: 'Merge Page'
}
, entitiesToFormState
));
return res.send(targetTemplate({
markup,
props: escapeProps(props),
script: '/js/entity-editor.js',
title: `Merge ${mergingFetchedEntities.length} ${_.startCase(entityType)}s`
}));
});
export default router;