/
entity.tsx
1252 lines (1080 loc) · 37.5 KB
/
entity.tsx
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2016 Ben Ockmore
* 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.
*/
import * as React from 'react';
import * as achievement from '../../helpers/achievement';
import * as commonUtils from '../../../common/helpers/utils';
import * as error from '../../../common/helpers/error';
import * as handler from '../../helpers/handler';
import * as propHelpers from '../../../client/helpers/props';
import * as search from '../../../common/helpers/search';
import * as utils from '../../helpers/utils';
import type {Request as $Request, Response as $Response, NextFunction} from 'express';
import type {
EntityTypeString,
FormLanguageT as Language,
FormPublisherT as Publisher,
FormReleaseEventT as ReleaseEvent,
Transaction
} from 'bookbrainz-data/lib/func/types';
import {escapeProps, generateProps} from '../../helpers/props';
import AuthorPage from '../../../client/components/pages/entities/author';
import DeletionForm from '../../../client/components/forms/deletion';
import EditionGroupPage from '../../../client/components/pages/entities/edition-group';
import EditionPage from '../../../client/components/pages/entities/edition';
import EntityRevisions from '../../../client/components/pages/entity-revisions';
import Layout from '../../../client/containers/layout';
import PublisherPage from '../../../client/components/pages/entities/publisher';
import ReactDOMServer from 'react-dom/server';
import WorkPage from '../../../client/components/pages/entities/work';
import _ from 'lodash';
import {getEntityLabel} from '../../../client/helpers/entity';
import {getOrderedRevisionsForEntityPage} from '../../helpers/revisions';
import log from 'log';
import target from '../../templates/target';
type PassportRequest = $Request & {user: any, session: any};
const entityComponents = {
author: AuthorPage,
edition: EditionPage,
editionGroup: EditionGroupPage,
publisher: PublisherPage,
work: WorkPage
};
export function displayEntity(req: PassportRequest, res: $Response) {
const {orm}: {orm?: any} = req.app.locals;
const {AchievementUnlock, EditorEntityVisits} = orm;
const {locals: resLocals}: {locals: any} = res;
const {entity}: {entity: any} = resLocals;
// Get unique identifier types for display
// $FlowFixMe
let identifierTypes = [];
if (entity.identifierSet) {
identifierTypes = _.uniqBy(
_.map(entity.identifierSet.identifiers, 'type'),
'id'
);
}
let editorEntityVisitPromise;
if (resLocals.user) {
editorEntityVisitPromise = new EditorEntityVisits({
bbid: resLocals.entity.bbid,
editorId: resLocals.user.id
})
.save(null, {method: 'insert'})
.then(() => achievement.processPageVisit(orm, resLocals.user.id))
.catch(
// error caused by duplicates we do not want in database
() => new Promise(resolve => resolve(false))
);
}
else {
editorEntityVisitPromise = new Promise(resolve => resolve(false));
}
let alertPromise = editorEntityVisitPromise.then((visitAlert) => {
let alertIds = [];
if (visitAlert.alert) {
alertIds = alertIds.concat(visitAlert.alert.split(',').map(
(id) => parseInt(id, 10)
));
}
if (_.isString(req.query.alert)) {
// $FlowFixMe
alertIds = alertIds.concat(req.query.alert.split(',').map(
(id) => parseInt(id, 10)
));
}
if (alertIds.length > 0) {
const promiseList = alertIds.map(
(achievementAlert) =>
new AchievementUnlock(
{id: achievementAlert}
)
.fetch({
require: true,
withRelated: 'achievement'
})
.then((unlock) => unlock.toJSON())
.then((unlock) => {
let unlockName;
if (req.user.id === unlock.editorId) {
unlockName = {
name: unlock.achievement.name
};
}
return unlockName;
})
.catch((err) => {
log.debug(err);
})
);
alertPromise = Promise.all(promiseList);
}
else {
alertPromise = new Promise(resolve => resolve(false));
}
return alertPromise;
});
return alertPromise.then((alert) => {
const entityName = _.camelCase(entity.type);
const EntityComponent = entityComponents[entityName];
if (EntityComponent) {
const props = generateProps(req, res, {
alert,
identifierTypes
});
const markup = ReactDOMServer.renderToString(
<Layout {...propHelpers.extractLayoutProps(props)}>
<EntityComponent
{...propHelpers.extractEntityProps(props)}
/>
</Layout>
);
res.send(target({
markup,
page: entityName,
props: escapeProps(props),
script: '/js/entity/entity.js',
title: `${getEntityLabel(props.entity, false)} (${_.upperFirst(entityName)})`
}));
}
else {
throw new Error(
`Component was not found for the following entity:${entityName}`
);
}
});
}
export function displayDeleteEntity(req: PassportRequest, res: $Response) {
const props = generateProps(req, res);
const markup = ReactDOMServer.renderToString(
<Layout {...propHelpers.extractLayoutProps(props)}>
<DeletionForm entity={props.entity}/>
</Layout>
);
res.send(target({
markup,
props: escapeProps(props),
script: '/js/deletion.js'
}));
}
export async function displayRevisions(
req: PassportRequest, res: $Response, next: NextFunction, RevisionModel: any
) {
const size = _.isString(req.query.size) ? parseInt(req.query.size, 10) : 20;
const from = _.isString(req.query.from) ? parseInt(req.query.from, 10) : 0;
const {orm}: any = req.app.locals;
const {bbid} = req.params;
try {
// get 1 more revision than required to check nextEnabled
const orderedRevisions = await getOrderedRevisionsForEntityPage(orm, from, size + 1, RevisionModel, bbid);
const {newResultsArray, nextEnabled} = utils.getNextEnabledAndResultsArray(orderedRevisions, size);
const props = generateProps(req, res, {
from,
nextEnabled,
revisions: newResultsArray,
showRevisionEditor: true,
showRevisionNote: true,
size
});
const markup = ReactDOMServer.renderToString(
<Layout {...propHelpers.extractLayoutProps(props)}>
<EntityRevisions
entity={props.entity}
{...propHelpers.extractChildProps(props)}
/>
</Layout>
);
return res.send(target({
markup,
page: 'revisions',
props: escapeProps(props),
script: '/js/entity/entity.js'
}));
}
catch (err) {
return next(err);
}
}
// eslint-disable-next-line consistent-return
export async function updateDisplayedRevisions(
req: PassportRequest, res: $Response, next: NextFunction, RevisionModel: any
) {
const size = _.isString(req.query.size) ? parseInt(req.query.size, 10) : 20;
const from = _.isString(req.query.from) ? parseInt(req.query.from, 10) : 0;
const {orm}: any = req.app.locals;
const {bbid} = req.params;
try {
const orderedRevisions = await getOrderedRevisionsForEntityPage(orm, from, size, RevisionModel, bbid);
res.send(orderedRevisions);
}
catch (err) {
return next(err);
}
}
function _createNote(orm, content, editorID, revision, transacting) {
const {Note} = orm;
if (content) {
const revisionId = revision.get('id');
return new Note({
authorId: editorID,
content,
revisionId
})
.save(null, {transacting});
}
return null;
}
export function addNoteToRevision(req: PassportRequest, res: $Response) {
const {orm}: {orm?: any} = req.app.locals;
const {Revision, bookshelf} = orm;
const editorJSON = req.session.passport.user;
const revision = Revision.forge({id: req.params.id});
const {body}: {body: any} = req;
const revisionNotePromise = bookshelf.transaction(
(transacting) => _createNote(
orm, body.note, editorJSON.id, revision, transacting
)
);
return handler.sendPromiseResult(res, revisionNotePromise);
}
export async function getEntityByBBID(orm: any, transacting: Transaction, bbid: string) {
const redirectBbid = await orm.func.entity.recursivelyGetRedirectBBID(orm, bbid, transacting);
const entityHeader = await orm.Entity.forge({bbid: redirectBbid}).fetch({transacting});
const model = commonUtils.getEntityModelByType(orm, entityHeader.get('type'));
return model.forge({bbid: redirectBbid}).fetch({transacting});
}
async function setParentRevisions(transacting, newRevision, parentRevisionIDs) {
if (_.isEmpty(parentRevisionIDs)) {
return new Promise(resolve => resolve(null));
}
// Get the parents of the new revision
const parents =
await newRevision.related('parents').fetch({transacting});
// Add the previous revision as a parent of this revision.
return parents.attach(parentRevisionIDs, {transacting});
}
async function saveEntitiesAndFinishRevision(
orm, transacting, isNew: boolean, newRevision: any, mainEntity: any,
updatedEntities: any[], editorID: number, note: string
) {
const parentRevisionIDs = _.compact(_.uniq(updatedEntities.map(
(entityModel) => entityModel.get('revisionId')
)));
const entitiesSavedPromise = Promise.all(
_.map(updatedEntities, (entityModel) => {
entityModel.set('revisionId', newRevision.get('id'));
const shouldInsert =
entityModel.get('bbid') === mainEntity.get('bbid') && isNew;
const method = shouldInsert ? 'insert' : 'update';
return entityModel.save(null, {method, transacting});
})
);
const editorUpdatePromise =
utils.incrementEditorEditCountById(orm, editorID, transacting);
const notePromise = _createNote(
orm, note, editorID, newRevision, transacting
);
const parentsAddedPromise =
setParentRevisions(transacting, newRevision, parentRevisionIDs);
/** model.save returns a refreshed model */
// eslint-disable-next-line no-unused-vars
const [savedEntities, ...others] = await Promise.all([
entitiesSavedPromise,
editorUpdatePromise,
parentsAddedPromise,
notePromise
]);
return savedEntities.find(entityModel => entityModel.get('bbid') === mainEntity.get('bbid')) || mainEntity;
}
export async function deleteRelationships(orm: any, transacting: Transaction, mainEntity: any) {
const mainBBID = mainEntity.bbid;
const {relationshipSet} = mainEntity;
const otherBBIDs = [];
const otherEntities = [];
if (relationshipSet) {
// Create a list of BBID's that is related to the deleted entity
if (!relationshipSet.relationships) {
return [];
}
relationshipSet.relationships.forEach((relationship) => {
if (relationship.sourceBbid === mainBBID) {
otherBBIDs.push(relationship.targetBbid);
}
else if (relationship.targetBbid === mainBBID) {
otherBBIDs.push(relationship.sourceBbid);
}
});
// Loop over the BBID's of other entites related to deleted entity
if (otherBBIDs.length) {
if (otherBBIDs.length === 0) {
return [];
}
await Promise.all(otherBBIDs.map(async (entityBbid) => {
const otherEntity = await getEntityByBBID(orm, transacting, entityBbid);
const otherEntityRelationshipSet = await otherEntity.relationshipSet()
.fetch({require: false, transacting, withRelated: 'relationships'});
if (_.isNil(otherEntityRelationshipSet)) {
return;
}
// Fetch other entity relationships to remove relation with the deleted entity
let otherEntityRelationships = otherEntityRelationshipSet.related('relationships').toJSON();
// Filter out entites related to deleted entity
otherEntityRelationships = otherEntityRelationships.filter(({sourceBbid, targetBbid}) =>
mainBBID !== sourceBbid && mainBBID !== targetBbid);
const newRelationshipSet = await orm.func.relationship.updateRelationshipSets(
orm, transacting, otherEntityRelationshipSet, otherEntityRelationships
);
otherEntity.set(
'relationshipSetId',
newRelationshipSet[entityBbid] ? newRelationshipSet[entityBbid].get('id') : null
);
otherEntities.push(otherEntity);
}));
}
}
return otherEntities;
}
function fetchOrCreateMainEntity(
orm, transacting, isNew, bbid, entityType
) {
const model = commonUtils.getEntityModelByType(orm, entityType);
const entity = model.forge({bbid});
if (isNew) {
return new Promise(resolve => resolve(entity));
}
return entity.fetch({transacting});
}
export function handleDelete(
orm: any, req: PassportRequest, res: $Response, HeaderModel: any,
RevisionModel: any
) {
const {entity}: {entity?: any} = res.locals;
const {Revision, bookshelf} = orm;
const editorJSON = req.session.passport.user;
const {body}: {body: any} = req;
const entityDeletePromise = bookshelf.transaction(async (transacting) => {
if (!body.note || !body.note.length) {
throw new error.FormSubmissionError('A revision note is required when deleting an entity');
}
const otherEntities = await deleteRelationships(orm, transacting, entity);
const newRevision = await new Revision({
authorId: editorJSON.id
}).save(null, {transacting});
/*
* No trigger for deletions, so manually create the <Entity>Revision
* and update the entity header
*/
const entityRevision = await new RevisionModel({
bbid: entity.bbid,
dataId: null,
id: newRevision.get('id')
}).save(null, {
method: 'insert',
transacting
});
await new HeaderModel({
bbid: entity.bbid,
masterRevisionId: entityRevision.get('id')
}).save(null, {transacting});
const mainEntity = await fetchOrCreateMainEntity(
orm, transacting, false, entity.bbid, entity.type
);
const savedMainEntity =
await saveEntitiesAndFinishRevision(
orm,
transacting,
false,
newRevision,
mainEntity,
otherEntities,
editorJSON.id,
body.note
);
return savedMainEntity;
});
return handler.sendPromiseResult(res, entityDeletePromise, search.deleteEntity);
}
export async function processMergeOperation(orm, transacting, session, mainEntity, allEntities, relationshipSets) {
const {Edition, bookshelf} = orm;
const {mergingEntities} = session.mergeQueue;
if (!mergingEntities) {
throw new Error('Merge handler called with no merge queue, aborting');
}
const entityType = mainEntity.get('type');
const currentEntityBBID = mainEntity.get('bbid');
const mergingEntitiesBBIDs = Object.keys(mergingEntities);
if (!_.includes(mergingEntitiesBBIDs, currentEntityBBID)) {
throw new Error('Entity being merged into does not appear in merge queue, aborting');
}
const entitiesToMergeBBIDs = _.without(Object.keys(mergingEntities), currentEntityBBID);
let allEntitiesReturnArray = allEntities;
// fetch entities we're merging to add them to to the array of modified entities
const entitiesToMerge = _.values(mergingEntities).filter(({bbid}) => bbid !== currentEntityBBID);
const entitiesModelsToMerge = await Promise.all(entitiesToMergeBBIDs
.map(bbid => fetchOrCreateMainEntity(orm, transacting, false, bbid, entityType)));
/** Add entities to be merged to the array of modified entities */
allEntitiesReturnArray = _.unionBy(allEntitiesReturnArray, entitiesModelsToMerge, 'id');
/** Remove relationships that concern entities being merged from already modified relationshipSets */
await Promise.all(_.map(relationshipSets, async (relationshipSet) => {
/** Some items in this object may be null */
if (relationshipSet) {
/** Refresh RelationshipSet to fetch both existing and new relationships */
const refreshedrelationshipSet = await relationshipSet
.refresh({transacting, withRelated: 'relationships'});
/** Find relationships with entities being merge and remove them from set */
const relationshipsToRemove = refreshedrelationshipSet
.related('relationships').toJSON()
.filter(({sourceBbid, targetBbid}) => _.includes(entitiesToMergeBBIDs, sourceBbid) ||
_.includes(entitiesToMergeBBIDs, targetBbid))
.map(({id}) => id);
if (relationshipsToRemove.length) {
await refreshedrelationshipSet
.related('relationships')
.detach(relationshipsToRemove, {transacting});
}
}
}));
/**
* Fetch each merged entity, get its relationships, then fetch the related entity for each relationship.
* Then on the related entity's side, remove any relationship with merged entities from its relationship set
*/
await Promise.all(entitiesModelsToMerge.map(
async entity => {
const entityBBID = entity.get('bbid');
const relationshipSet = await entity.relationshipSet()
.fetch({require: false, transacting, withRelated: 'relationships'});
if (!relationshipSet) {
return;
}
const relationships = relationshipSet.related('relationships').toJSON();
const otherEntitiesToFetch = relationships
.reduce((accumulator, relationship) => {
if (relationship.sourceBbid === entityBBID) {
accumulator.push(relationship.targetBbid);
}
else if (relationship.targetBbid === entityBBID) {
accumulator.push(relationship.sourceBbid);
}
return accumulator;
}, [])
// Ignore entities that already have a modified relationshipSet (dealed with above)
.filter(bbid => !_.includes(_.keys(relationshipSets), bbid));
await Promise.all(otherEntitiesToFetch.map(
async (bbid) => {
const otherEntity = await getEntityByBBID(orm, transacting, bbid);
const otherEntityRelationshipSet = await entity.relationshipSet()
.fetch({require: false, transacting, withRelated: 'relationships'});
if (!otherEntityRelationshipSet) {
return;
}
const otherEntityRelationships = otherEntityRelationshipSet.related('relationships').toJSON();
// Remove relationships with entity being merged
const cleanedUpRelationships = otherEntityRelationships
.filter(({sourceBbid, targetBbid}) =>
entityBBID !== sourceBbid &&
entityBBID !== targetBbid);
// If there's a difference, apply the new relationships array without rels to merged entity
if (cleanedUpRelationships.length !== otherEntityRelationships.length) {
const updatedRelationshipSets = await orm.func.relationship.updateRelationshipSets(
orm, transacting, otherEntityRelationshipSet, cleanedUpRelationships
);
// Make sure the entity is later updated with its new relationshipSet id
allEntitiesReturnArray = _.unionBy(allEntitiesReturnArray, [otherEntity], 'id');
_.assign(relationshipSets, _.pick(updatedRelationshipSets, bbid));
}
}
));
}
));
/** Special cases per entity type*/
/**
* For EditionGroup entities, each merged EG may have editions associated to it.
* We need to set each Edition's edition_group_bbid to the target entity BBID
*/
if (entityType === 'EditionGroup') {
const editionsToSet = await Edition.query(
qb => qb
.whereIn('edition_group_bbid', entitiesToMergeBBIDs)
.andWhere('master', true)
)
.fetchAll({require: false, transacting});
if (editionsToSet.length) {
editionsToSet.forEach(editionModel => editionModel.set({editionGroupBbid: currentEntityBBID}));
// Add the modified Editions to the revision
allEntitiesReturnArray = _.unionBy(allEntitiesReturnArray, editionsToSet.toArray(), 'id');
}
}
/**
* For Publisher entities, each merged item may have editions associated to it.
* We need to set each Edition's publisher set to the target entity BBID
*/
if (entityType === 'Publisher') {
try {
const editionsToSetCollections = await Promise.all(entitiesModelsToMerge.map(entitiesModel => entitiesModel.editions()));
// eslint-disable-next-line consistent-return
let editionsToSet = _.flatMap(editionsToSetCollections, edition => {
if (edition.models && edition.models.length) {
return edition.models;
}
});
// Remove 'undefined' entries (no editions in those publishers)
editionsToSet = _.reject(editionsToSet, _.isNil);
await Promise.all(editionsToSet.map(async (edition) => {
// Fetch current PublisherSet
const oldPublisherSet = await edition.publisherSet();
// Create a new PublisherSet pointing to the main entity
const newPublisherSet = await orm.func.publisher.updatePublisherSet(orm, transacting, oldPublisherSet, [{bbid: currentEntityBBID}]);
// Set the new PublisherSet on the Edition
edition.set('publisherSetId', newPublisherSet.get('id'));
// Add the modified Edition to the revision (if it doesn't exist yet)
allEntitiesReturnArray = _.unionBy(allEntitiesReturnArray, [edition], 'id');
}));
}
catch (err) {
log.error(err);
throw err;
}
}
/**
* Some actions we only want to take once the main entity has been saved
*/
mainEntity.once('saved', async (model) => {
/**
* Set isMerge to true on the *entity*_revision models
* The *entity*_revision items are created by a postgres trigger instead of server code,
* so we need to wait until the entity is saved on the database.
* We only want to set isMerge to true on the entities we're merging,
* not the other entities potentially affected by the merge -> .where(…
*/
const newEntityRevision = await model.revision()
.fetch({transacting});
await newEntityRevision
.where('bbid', currentEntityBBID)
.save({isMerge: true}, {patch: true, transacting});
/* Also set dataID to null for slave entities to 'delete' them */
await newEntityRevision
.query(qb => qb.whereIn('bbid', entitiesToMergeBBIDs))
.save({dataId: null, isMerge: true}, {patch: true, transacting});
/** Clear the merge queue */
session.mergeQueue = null;
try {
/* Remove merged entities from search results */
await Promise.all(entitiesToMerge.map(search.deleteEntity));
}
catch (err) {
log.debug(err);
}
});
/** Update the redirection table to redirect merged entities' bbids
* to currentEntityBBID (the entity we're merging into)
*/
await bookshelf.knex('bookbrainz.entity_redirect')
.transacting(transacting)
.insert(entitiesToMergeBBIDs.map(bbid => (
// eslint-disable-next-line camelcase
{source_bbid: bbid, target_bbid: currentEntityBBID})));
return allEntitiesReturnArray;
}
type ProcessEditionSetsBody = {
languages: Array<Language>,
publishers: Array<Publisher>,
releaseEvents: Array<ReleaseEvent>
};
type ProcessEditionSetsResult = {languageSetId: number[], publisherSetId: number[], releaseEventSetId: number[]};
async function processEditionSets(
orm: any,
currentEntity: Record<string, unknown> | null | undefined,
body: ProcessEditionSetsBody,
transacting: Transaction
): Promise<ProcessEditionSetsResult> {
const languageSetID = _.get(currentEntity, ['languageSet', 'id']);
const oldLanguageSet = await (
languageSetID &&
orm.LanguageSet.forge({id: languageSetID})
.fetch({transacting, withRelated: ['languages']})
);
const languages = _.get(body, 'languages') || [];
const newLanguageSetIDPromise = orm.func.language.updateLanguageSet(
orm, transacting, oldLanguageSet,
languages.map((languageID) => ({id: languageID}))
)
.then((set) => set && set.get('id'));
const publisherSetID = _.get(currentEntity, ['publisherSet', 'id']);
const oldPublisherSet = await (
publisherSetID &&
orm.PublisherSet.forge({id: publisherSetID})
.fetch({transacting, withRelated: ['publishers']})
);
const publishers = _.get(body, 'publishers') || [];
const newPublisherSetIDPromise = orm.func.publisher.updatePublisherSet(
orm, transacting, oldPublisherSet,
publishers.map((publisherBBID) => ({bbid: publisherBBID}))
)
.then((set) => set && set.get('id'));
const releaseEventSetID = _.get(currentEntity, ['releaseEventSet', 'id']);
const oldReleaseEventSet = await (
releaseEventSetID &&
orm.ReleaseEventSet.forge({id: releaseEventSetID})
.fetch({transacting, withRelated: ['releaseEvents']})
);
const releaseEvents = _.get(body, 'releaseEvents') || [];
// if areaId is not present, set it to null.
// otherwise it shows error while comparing old and new releaseEvent;
if (releaseEvents[0]) {
if (_.isNil(releaseEvents[0].areaId)) {
releaseEvents[0].areaId = null;
}
if (releaseEvents[0].date === '') {
releaseEvents[0].date = null;
}
}
const newReleaseEventSetIDPromise =
orm.func.releaseEvent.updateReleaseEventSet(
orm, transacting, oldReleaseEventSet, releaseEvents
)
.then((set) => set && set.get('id'));
return commonUtils.makePromiseFromObject<ProcessEditionSetsResult>({
languageSetId: newLanguageSetIDPromise,
publisherSetId: newPublisherSetIDPromise,
releaseEventSetId: newReleaseEventSetIDPromise
});
}
type ProcessWorkSetsResult = {languageSetId: number[]};
async function processWorkSets(
orm, currentEntity: Record<string, unknown> | null | undefined, body: {languages: Array<Language>},
transacting: Transaction
): Promise<ProcessWorkSetsResult> {
const id = _.get(currentEntity, ['languageSet', 'id']);
const oldSet = await (
id &&
orm.LanguageSet.forge({id})
.fetch({transacting, withRelated: ['languages']})
);
const languages = _.get(body, 'languages') || [];
return commonUtils.makePromiseFromObject<ProcessWorkSetsResult>({
languageSetId: orm.func.language.updateLanguageSet(
orm, transacting, oldSet,
languages.map((languageID) => ({id: languageID}))
).then((set) => set && set.get('id'))
});
}
function processEntitySets(
orm: any,
currentEntity: Record<string, unknown> | null | undefined,
entityType: EntityTypeString,
body: any,
transacting: Transaction
): Promise<ProcessEditionSetsResult | ProcessWorkSetsResult | null> {
if (entityType === 'Edition') {
return processEditionSets(orm, currentEntity, body, transacting);
}
if (entityType === 'Work') {
return processWorkSets(orm, currentEntity, body, transacting);
}
return new Promise(resolve => resolve(null));
}
async function getNextAliasSet(orm, transacting, currentEntity, body) {
const {AliasSet} = orm;
const id = _.get(currentEntity, ['aliasSet', 'id']);
const oldAliasSet = await (
id &&
new AliasSet({id}).fetch({require: false, transacting, withRelated: ['aliases']})
);
return orm.func.alias.updateAliasSet(
orm, transacting, oldAliasSet,
oldAliasSet && oldAliasSet.get('defaultAliasId'),
body.aliases || []
);
}
async function getNextIdentifierSet(orm, transacting, currentEntity, body) {
const {IdentifierSet} = orm;
const id = _.get(currentEntity, ['identifierSet', 'id']);
const oldIdentifierSet = await (
id &&
new IdentifierSet({id}).fetch({
require: false,
transacting, withRelated: ['identifiers']
})
);
return orm.func.identifier.updateIdentifierSet(
orm, transacting, oldIdentifierSet, body.identifiers || []
);
}
async function getNextRelationshipSets(
orm, transacting, currentEntity, body
) {
const {RelationshipSet} = orm;
const id = _.get(currentEntity, ['relationshipSet', 'id']);
const oldRelationshipSet = await (
id &&
new RelationshipSet({id}).fetch({
require: false,
transacting, withRelated: ['relationships']
})
);
return orm.func.relationship.updateRelationshipSets(
orm, transacting, oldRelationshipSet, body.relationships || []
);
}
async function getNextAnnotation(
orm, transacting, currentEntity, body, revision
) {
const {Annotation} = orm;
const id = _.get(currentEntity, ['annotation', 'id']);
const oldAnnotation = await (
id && new Annotation({id}).fetch({require: false, transacting})
);
return body.annotation ? orm.func.annotation.updateAnnotation(
orm, transacting, oldAnnotation, body.annotation, revision
) : new Promise(resolve => resolve(null));
}
async function getNextDisambiguation(orm, transacting, currentEntity, body) {
const {Disambiguation} = orm;
const id = _.get(currentEntity, ['disambiguation', 'id']);
const oldDisambiguation = await (
id && new Disambiguation({id}).fetch({require: false, transacting})
);
return orm.func.disambiguation.updateDisambiguation(
orm, transacting, oldDisambiguation, body.disambiguation
);
}
async function getChangedProps(
orm, transacting, isNew, currentEntity, body, entityType,
newRevision, derivedProps
) {
const aliasSetPromise =
getNextAliasSet(orm, transacting, currentEntity, body);
const identSetPromise =
getNextIdentifierSet(orm, transacting, currentEntity, body);
const annotationPromise = getNextAnnotation(
orm, transacting, currentEntity, body, newRevision
);
const disambiguationPromise =
getNextDisambiguation(orm, transacting, currentEntity, body);
const entitySetIdsPromise =
processEntitySets(orm, currentEntity, entityType, body, transacting);
const [
aliasSet, identSet, annotation, disambiguation, entitySetIds
] = await Promise.all([
aliasSetPromise, identSetPromise, annotationPromise,
disambiguationPromise, entitySetIdsPromise
]);
const propsToSet = {
aliasSetId: aliasSet && aliasSet.get('id'),
annotationId: annotation && annotation.get('id'),
disambiguationId:
disambiguation && disambiguation.get('id'),
identifierSetId: identSet && identSet.get('id'),
...derivedProps,
...entitySetIds
};
if (isNew) {
return propsToSet;
}
// Construct a set of differences between the new values and old
return _.reduce(propsToSet, (result, value, key) => {
if (!_.isEqual(value, currentEntity[key]) &&
// If both items are null or undefined, consider them equal (null !=== undefined)
!(_.isNil(value) && _.isNil(currentEntity[key]))
) {
result[key] = value;
}
return result;
}, {});
}
function fetchEntitiesForRelationships(
orm, transacting, currentEntity, relationshipSets
) {
const bbidsToFetch = _.without(
_.keys(relationshipSets), _.get(currentEntity, 'bbid')
);
return Promise.all(bbidsToFetch.map(
(bbid) =>
getEntityByBBID(orm, transacting, bbid)
));
}
/**
* @param {any} orm - The BookBrainz ORM
* @param {any} newEdition - The ORM model of the newly created Edition
* @param {any} transacting - The ORM transaction object
* @description Edition Groups will be created automatically by the ORM if no EditionGroup BBID is set on a new Edition.
* This method fetches and indexes (search) those potential new EditionGroups that may have been created automatically.
*/
async function indexAutoCreatedEditionGroup(orm, newEdition, transacting) {
const {EditionGroup} = orm;
const bbid = newEdition.get('editionGroupBbid');
try {
const editionGroup = await new EditionGroup({bbid})
.fetch({
require: true,
transacting,
withRelated: 'aliasSet.aliases'
});
await search.indexEntity(editionGroup.toJSON());
}
catch (err) {
log.error('Could not reindex edition group after edition creation:', err);
}
}
export function handleCreateOrEditEntity(
req: PassportRequest,
res: $Response,
entityType: EntityTypeString,
derivedProps: Record<string, unknown>,
isMergeOperation: boolean
) {
const {orm}: {orm?: any} = req.app.locals;
const {Entity, Revision, bookshelf} = orm;
const editorJSON = req.user;
const {body}: {body: any} = req;
const {locals: resLocals}: {locals: any} = res;
let currentEntity: {
aliasSet: {id: number} | null | undefined,
annotation: {id: number} | null | undefined,
bbid: string,
disambiguation: {id: number} | null | undefined,
identifierSet: {id: number} | null | undefined,
type: EntityTypeString
} | null | undefined = resLocals.entity;
const entityEditPromise = bookshelf.transaction(async (transacting) => {
try {
// Determine if a new entity is being created
const isNew = !currentEntity;
if (isNew) {
const newEntity = await new Entity({type: entityType})