-
Notifications
You must be signed in to change notification settings - Fork 732
Expand file tree
/
Copy pathmemberService.ts
More file actions
1450 lines (1282 loc) · 50.1 KB
/
memberService.ts
File metadata and controls
1450 lines (1282 loc) · 50.1 KB
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
/* eslint-disable no-continue */
import { randomUUID } from 'crypto'
import lodash from 'lodash'
import moment from 'moment-timezone'
import validator from 'validator'
import { captureApiChange, memberUnmergeAction } from '@crowd/audit-logs'
import { Error400, calculateReach, getProperDisplayName, isDomainExcluded } from '@crowd/common'
import { CommonMemberService } from '@crowd/common_services'
import { findMemberAffiliations } from '@crowd/data-access-layer/src/member_segment_affiliations'
import {
MemberField,
addMemberRole,
fetchManyMemberOrgsWithOrgData,
fetchMemberBotSuggestionsBySegment,
fetchMemberIdentities,
findMemberById,
findMemberIdentitiesByValue,
findMemberIdentityById,
insertMemberSegmentAggregates,
queryMembersAdvanced,
removeMemberRole,
} from '@crowd/data-access-layer/src/members'
import { addMergeAction, setMergeAction } from '@crowd/data-access-layer/src/mergeActions/repo'
import { QueryExecutor, optionsQx } from '@crowd/data-access-layer/src/queryExecutor'
import { fetchManySegments } from '@crowd/data-access-layer/src/segments'
import { LoggerBase } from '@crowd/logging'
import {
IMemberIdentity,
IMemberRoleWithOrganization,
IMemberUnmergeBackup,
IMemberUnmergePreviewResult,
IOrganization,
IUnmergePreviewResult,
MemberAttributeType,
MemberIdentityType,
MemberRoleUnmergeStrategy,
MergeActionState,
MergeActionStep,
MergeActionType,
OrganizationIdentityType,
SyncMode,
} from '@crowd/types'
import { MergeActionsRepository } from '@/database/repositories/mergeActionsRepository'
import OrganizationRepository from '@/database/repositories/organizationRepository'
import { IRepositoryOptions } from '../database/repositories/IRepositoryOptions'
import MemberAttributeSettingsRepository from '../database/repositories/memberAttributeSettingsRepository'
import MemberRepository from '../database/repositories/memberRepository'
import SequelizeRepository from '../database/repositories/sequelizeRepository'
import {
BasicMemberIdentity,
IActiveMemberFilter,
IMemberMergeSuggestion,
mapUsernameToIdentities,
} from '../database/repositories/types/memberTypes'
import telemetryTrack from '../segment/telemetryTrack'
import { IServiceOptions } from './IServiceOptions'
import { getGithubInstallationToken } from './helpers/githubToken'
import MemberAttributeSettingsService from './memberAttributeSettingsService'
import MemberOrganizationService from './memberOrganizationService'
import OrganizationService from './organizationService'
import SearchSyncService from './searchSyncService'
import SettingsService from './settingsService'
export default class MemberService extends LoggerBase {
options: IServiceOptions
constructor(options: IServiceOptions) {
super(options.log)
this.options = options
}
/**
* Validates the attributes against its saved settings.
*
* Throws 400 Errors if the attribute does not exist in settings,
* or if the sent attribute type does not match the type in the settings.
* Also restructures custom attributes that come only as a value, without platforms.
*
* Example custom attributes restructuring
* {
* attributes: {
* someAttributeName: 'someValue'
* }
* }
*
* This object is transformed into:
* {
* attributes: {
* someAttributeName: {
* custom: 'someValue'
* },
* }
* }
*
* @param attributes
* @returns restructured object
*/
async validateAttributes(
attributes: { [key: string]: any },
transaction = null,
): Promise<object> {
// check attribute exists in memberAttributeSettings
const memberAttributeSettings = (
await MemberAttributeSettingsRepository.findAndCountAll(
{},
{ ...this.options, ...(transaction && { transaction }) },
)
).rows.reduce((acc, attribute) => {
acc[attribute.name] = attribute
return acc
}, {})
for (const attributeName of Object.keys(attributes)) {
if (!memberAttributeSettings[attributeName]) {
this.log.error('Attribute does not exist', {
attributeName,
attributes,
})
delete attributes[attributeName]
continue
}
if (typeof attributes[attributeName] !== 'object') {
attributes[attributeName] = {
custom: attributes[attributeName],
}
}
for (const platform of Object.keys(attributes[attributeName])) {
if (
attributes[attributeName][platform] !== undefined &&
attributes[attributeName][platform] !== null
) {
if (
!MemberAttributeSettingsService.isCorrectType(
attributes[attributeName][platform],
memberAttributeSettings[attributeName].type,
{ options: memberAttributeSettings[attributeName].options },
)
) {
this.log.error('Failed to validate attributee', {
attributeName,
platform,
attributeValue: attributes[attributeName][platform],
attributeType: memberAttributeSettings[attributeName].type,
options: memberAttributeSettings[attributeName].options,
})
throw new Error400(
this.options.language,
'settings.memberAttributes.wrongType',
attributeName,
memberAttributeSettings[attributeName].type,
)
}
}
}
}
return attributes
}
/**
* Sets the attribute.default key as default values of attribute
* object using the priority array stored in the settings.
* Throws a 400 Error if priority array does not exist.
* @param attributes
* @returns attribute object with default values
*/
async setAttributesDefaultValues(attributes: object): Promise<object> {
if (!(await SettingsService.platformPriorityArrayExists(this.options))) {
throw new Error400(this.options.language, 'settings.memberAttributes.priorityArrayNotFound')
}
const priorityArray = this.options.currentTenant.settings[0].get({ plain: true })
.attributeSettings.priorities
for (const attributeName of Object.keys(attributes)) {
const highestPriorityPlatform = MemberService.getHighestPriorityPlatformForAttributes(
Object.keys(attributes[attributeName]),
priorityArray,
)
if (highestPriorityPlatform !== undefined) {
attributes[attributeName].default = attributes[attributeName][highestPriorityPlatform]
} else {
delete attributes[attributeName]
}
}
return attributes
}
/**
* Returns the highest priority platform from an array of platforms
* If any of the platforms does not exist in the priority array, returns
* the first platform sent as the highest priority platform.
* @param platforms Array of platforms to select the highest priority platform
* @param priorityArray zero indexed priority array. Lower index means higher priority
* @returns the highest priority platform or undefined if values are incorrect
*/
public static getHighestPriorityPlatformForAttributes(
platforms: string[],
priorityArray: string[],
): string | undefined {
if (platforms.length <= 0) {
return undefined
}
const filteredPlatforms = priorityArray.filter((i) => platforms.includes(i))
return filteredPlatforms.length > 0 ? filteredPlatforms[0] : platforms[0]
}
/**
* Upsert a member. If the member exists, it updates it. If it does not exist, it creates it.
* The update is done with a deep merge of the original and the new member.
* The member is returned without relations
* Only the fields that have changed are updated.
* @param data Data for the member
* @param existing If the member already exists. If it does not, false. Othwerwise, the member.
* @returns The created member
*/
async upsert(
data,
existing: boolean | any = false,
fireCrowdWebhooks: boolean = true,
syncToOpensearch = true,
) {
const logger = this.options.log
const searchSyncService = new SearchSyncService(this.options)
const errorDetails: any = {}
if (data.identities && data.identities.length > 0) {
// map identities to username
const username = {}
for (const i of data.identities as IMemberIdentity[]) {
if (!username[i.platform]) {
username[i.platform] = [] as BasicMemberIdentity[]
}
if (!data.platform && i.type === MemberIdentityType.USERNAME) {
data.platform = i.platform
}
username[i.platform].push({
value: i.value,
type: i.type,
})
}
data.username = username
}
if (!('platform' in data)) {
throw new Error400(this.options.language, 'activity.platformRequiredWhileUpsert')
}
data.username = mapUsernameToIdentities(data.username, data.platform)
if (!(data.platform in data.username)) {
throw new Error400(this.options.language, 'activity.platformAndUsernameNotMatching')
}
if (!data.displayName) {
data.displayName = getProperDisplayName(data.username[data.platform][0].username)
}
if (!(data.platform in data.username)) {
throw new Error400(this.options.language, 'activity.platformAndUsernameNotMatching')
}
if (!data.displayName) {
data.displayName = data.username[data.platform].username
}
const transaction = await SequelizeRepository.createTransaction(this.options)
try {
const { platform } = data
if (data.attributes) {
data.attributes = await this.validateAttributes(data.attributes, transaction)
}
if (data.reach) {
data.reach = typeof data.reach === 'object' ? data.reach : { [platform]: data.reach }
data.reach = calculateReach(data.reach, {})
} else {
data.reach = { total: -1 }
}
delete data.platform
if (!('joinedAt' in data)) {
data.joinedAt = moment.tz('Europe/London').toDate()
}
if (!existing) {
existing = await this.memberExists(data.username, platform)
} else {
// let's look just in case for an existing member and if they are different we should log them because they will probably fail to insert
const tempExisting = await this.memberExists(data.username, platform)
if (!tempExisting) {
logger.warn(
{ existingMemberId: existing.id },
'We have received an existing member but actually we could not find him by username and platform!',
)
errorDetails.reason = 'member_service_upsert_existing_member_not_found'
errorDetails.details = {
existingMemberId: existing.id,
username: data.username,
platform,
}
} else if (existing.id !== tempExisting.id) {
logger.warn(
{ existingMemberId: existing.id, actualExistingMemberId: tempExisting.id },
'We found a member with the same username and platform but different id!',
)
errorDetails.reason = 'member_service_upsert_existing_member_mismatch'
errorDetails.details = {
existingMemberId: existing.id,
actualExistingMemberId: tempExisting.id,
username: data.username,
platform,
}
}
}
// Collect IDs for relation
const organizations = []
// If organizations are sent
if (data.organizations) {
for (const organization of data.organizations) {
if (typeof organization === 'string' && validator.isUUID(organization)) {
// If an ID was already sent, we simply push it to the list
organizations.push(organization)
} else if (typeof organization === 'object' && organization.id) {
organizations.push(organization)
} else {
// Otherwise, either another string or an object was sent
const organizationService = new OrganizationService(this.options)
let data = {}
if (typeof organization === 'string') {
// If a string was sent, we assume it is the name of the organization
data = {
identities: [
{
name: organization,
platform,
},
],
}
} else {
// Otherwise, we assume it is an object with the data of the organization
data = organization
}
// We createOrUpdate the organization and add it to the list of IDs
const organizationRecord = await organizationService.createOrUpdate(
data as IOrganization,
{
doSync: syncToOpensearch,
mode: SyncMode.ASYNCHRONOUS,
},
)
organizations.push({ id: organizationRecord.id })
}
}
}
// Auto assign member to organization if email domain matches
if (data.emails) {
const emailDomains = new Set<string>()
// Collect unique domains
for (const email of data.emails) {
if (email) {
const domain = email.split('@')[1]
if (!isDomainExcluded(domain)) {
emailDomains.add(domain)
}
}
}
// Fetch organization ids for these domains
const organizationService = new OrganizationService(this.options)
for (const domain of emailDomains) {
if (domain) {
const org = await organizationService.createOrUpdate(
{
displayName: domain,
attributes: {
name: {
default: domain,
custom: [domain],
},
},
identities: [
{
value: domain,
type: OrganizationIdentityType.PRIMARY_DOMAIN,
platform: 'email',
verified: true,
},
],
},
{
doSync: syncToOpensearch,
mode: SyncMode.ASYNCHRONOUS,
},
)
if (org) {
organizations.push({ id: org.id })
}
}
}
}
// Remove dups
if (organizations.length > 0) {
data.organizations = lodash.uniqBy(organizations, 'id')
}
let record
if (existing) {
const { id } = existing
delete existing.id
const toUpdate = CommonMemberService.membersMerge(existing, data)
if (toUpdate.attributes) {
toUpdate.attributes = await this.setAttributesDefaultValues(toUpdate.attributes)
}
// It is important to call it with doPopulateRelations=false
// because otherwise the performance is greatly decreased in integrations
record = await MemberRepository.update(id, toUpdate, {
...this.options,
transaction,
})
} else {
// It is important to call it with doPopulateRelations=false
// because otherwise the performance is greatly decreased in integrations
if (data.attributes) {
data.attributes = await this.setAttributesDefaultValues(data.attributes)
}
record = await MemberRepository.create(data, {
...this.options,
transaction,
})
telemetryTrack(
'Member created',
{
id: record.id,
createdAt: record.createdAt,
identities: record.identities,
},
this.options,
)
}
const qx = SequelizeRepository.getQueryExecutor({ ...this.options, transaction })
await (async function includeMemberInSegments(
qx: QueryExecutor,
memberId: string,
segmentIds: string[],
) {
const segments = await fetchManySegments(qx, segmentIds)
const data = segments.reduce((acc, s) => {
for (const segmentId of [s.id, s.parentId, s.grandparentId]) {
acc.push({
memberId,
segmentId,
activityCount: 0,
lastActive: '1970-01-01',
activityTypes: [],
activeOn: [],
averageSentiment: null,
})
}
return acc
}, [])
await insertMemberSegmentAggregates(qx, data)
})(
qx,
record.id,
this.options.currentSegments.map((s) => s.id),
)
await SequelizeRepository.commitTransaction(transaction)
if (syncToOpensearch) {
await searchSyncService.triggerMemberSync(record.id)
}
if (!fireCrowdWebhooks) {
this.log.info('Ignoring outgoing webhooks because of fireCrowdWebhooks!')
}
return record
} catch (error) {
const reason = errorDetails.reason || undefined
const details = errorDetails.details || undefined
if (error.name && error.name.includes('Sequelize')) {
logger.error(
error,
{
query: error.sql,
errorMessage: error.original.message,
reason,
details,
},
'Error during member upsert!',
)
} else {
logger.error(error, { reason, details }, 'Error during member upsert!')
}
await SequelizeRepository.rollbackTransaction(transaction)
SequelizeRepository.handleUniqueFieldError(error, this.options.language, 'member')
throw { ...error, reason, details }
}
}
/**
* Checks if given user already exists by username and platform.
* Username can be given as a plain string or as dictionary with
* related platforms.
* Ie:
* username = 'anil' || username = { github: 'anil' } || username = { github: 'anil', twitter: 'some-other-username' } || username = { github: { username: 'anil' } } || username = { github: [{ username: 'anil' }] }
* @param username username of the member
* @param platform platform of the member
* @returns null | found member
*/
async memberExists(username: object | string, platform: string) {
const fillRelations = false
const usernames: string[] = []
if (typeof username === 'string') {
usernames.push(username)
} else if (typeof username === 'object') {
if ('username' in username) {
usernames.push((username as any).username)
} else if (platform in username) {
if (typeof username[platform] === 'string') {
usernames.push(username[platform])
} else if (Array.isArray(username[platform])) {
if (username[platform].length === 0) {
throw new Error400(this.options.language, 'activity.platformAndUsernameNotMatching')
} else if (typeof username[platform] === 'string') {
usernames.push(username[platform])
} else if (typeof username[platform][0] === 'object') {
usernames.push(...username[platform].map((u) => u.username))
}
} else if (typeof username[platform] === 'object') {
usernames.push(username[platform].username)
} else {
throw new Error400(this.options.language, 'activity.platformAndUsernameNotMatching')
}
} else {
throw new Error400(this.options.language, 'activity.platformAndUsernameNotMatching')
}
}
// It is important to call it with doPopulateRelations=false
// because otherwise the performance is greatly decreased in integrations
const existing = await MemberRepository.memberExists(
usernames,
platform,
{
...this.options,
},
fillRelations,
)
return existing
}
/**
* Unmerges two members given a preview payload.
* Payload is returned from unmerge/preview endpoint, and confirmed by the user
* Payload.primary has the primary member's unmerged data, current member will be updated using these fields.
* Payload.secondary has the member that'll be unmerged/extracted from the primary member. This member will be created
* Activity moving, syncing to opensearch, recalculating activity.organizationIds and notifying frontend via websockets
* is done asynchronously, via entity-merge temporal worker finishMemberUnmerging workflow.
* @param memberId memberId of the primary member
* @param payload unmerge preview payload
*/
async unmerge(
memberId: string,
payload: IUnmergePreviewResult<IMemberUnmergePreviewResult>,
): Promise<void> {
let tx
// this field is purely for rendering the preview, we'll set the secondary member roles using the payload.secondary.memberOrganizations field
// consequentially this field is checked in member.create - we'll instead handle roles manually after creation
delete payload.secondary.organizations
try {
const { member, secondaryMember } = await captureApiChange(
this.options,
memberUnmergeAction(memberId, async (captureOldState, captureNewState) => {
const qx = SequelizeRepository.getQueryExecutor(this.options)
const member = await findMemberById(qx, memberId, [
MemberField.ID,
MemberField.DISPLAY_NAME,
])
captureOldState({
primary: payload.primary,
})
const repoOptions: IRepositoryOptions =
await SequelizeRepository.createTransactionalRepositoryOptions(this.options)
tx = repoOptions.transaction
// remove identities in secondary member from primary member
await MemberRepository.removeIdentitiesFromMember(
memberId,
payload.secondary.identities.filter(
(i) =>
i.verified === undefined || // backwards compatibility for old identity backups
i.verified === true ||
(i.verified === false &&
!payload.primary.identities.some(
(pi) =>
pi.verified === false &&
pi.platform === i.platform &&
pi.value === i.value &&
pi.type === i.type,
)),
),
repoOptions,
)
// we need to exclude identities in secondary that still exists in some other member
const identitiesToExclude = await MemberRepository.findAlreadyExistingIdentities(
payload.secondary.identities.filter((i) => i.verified),
repoOptions,
)
payload.secondary.identities = payload.secondary.identities.filter(
(i) =>
!identitiesToExclude.some(
(ie) =>
ie.platform === i.platform &&
ie.value === i.value &&
ie.type === i.type &&
ie.verified,
),
)
// create the secondary member
const secondaryMember = await MemberRepository.create(payload.secondary, repoOptions)
// track merge action
await addMergeAction(
optionsQx(repoOptions),
MergeActionType.MEMBER,
member.id,
secondaryMember.id,
MergeActionStep.UNMERGE_STARTED,
MergeActionState.IN_PROGRESS,
)
// move affiliations
if (payload.secondary.affiliations.length > 0) {
await MemberRepository.moveSelectedAffiliationsBetweenMembers(
memberId,
secondaryMember.id,
payload.secondary.affiliations.map((a) => a.id),
repoOptions,
)
}
// move memberOrganizations
if (payload.secondary.memberOrganizations.length > 0) {
const nonExistingOrganizationIds = await OrganizationRepository.findNonExistingIds(
payload.secondary.memberOrganizations.map((o) => o.organizationId),
repoOptions,
)
for (const role of payload.secondary.memberOrganizations.filter(
(r) => !nonExistingOrganizationIds.includes(r.organizationId),
)) {
await addMemberRole(optionsQx(repoOptions), { ...role, memberId: secondaryMember.id })
}
const memberOrganizationsMap = await fetchManyMemberOrgsWithOrgData(
optionsQx(repoOptions),
[member.id],
)
const memberOrganizations = memberOrganizationsMap.get(member.id)
// check if anything to delete in primary
const rolesToDelete = memberOrganizations.filter(
(r) =>
r.source !== 'ui' &&
!payload.primary.memberOrganizations.some(
(pr) =>
pr.organizationId === r.organizationId &&
pr.title === r.title &&
pr.dateStart === r.dateStart &&
pr.dateEnd === r.dateEnd,
),
)
for (const role of rolesToDelete) {
await removeMemberRole(optionsQx(repoOptions), role)
}
}
// delete relations from payload, since we already handled those
delete payload.primary.identities
delete payload.primary.username
delete payload.primary.memberOrganizations
delete payload.primary.organizations
delete payload.primary.affiliations
captureNewState({
primary: payload.primary,
secondary: {
...payload.secondary,
...secondaryMember,
},
})
// update rest of the primary member fields
await MemberRepository.update(memberId, payload.primary, repoOptions)
// add primary and secondary to no merge so they don't get suggested again
await MemberRepository.addNoMerge(memberId, secondaryMember.id, repoOptions)
// trigger entity-merging-worker to move activities in the background
await SequelizeRepository.commitTransaction(tx)
return { member, secondaryMember }
}),
)
await setMergeAction(
optionsQx(this.options),
MergeActionType.MEMBER,
member.id,
secondaryMember.id,
{
step: MergeActionStep.UNMERGE_SYNC_DONE,
},
)
// responsible for moving member's activities, syncing to opensearch afterwards, recalculating activity.organizationIds and notifying frontend via websockets
await this.options.temporal.workflow.start('finishMemberUnmerging', {
taskQueue: 'entity-merging',
workflowId: `finishMemberUnmerging/${member.id}/${secondaryMember.id}`,
retry: {
maximumAttempts: 10,
},
args: [
member.id,
secondaryMember.id,
payload.secondary.identities,
member.displayName,
secondaryMember.displayName,
this.options.currentUser.id,
],
searchAttributes: {
TenantId: [this.options.currentTenant.id],
},
})
} catch (err) {
if (tx) {
await SequelizeRepository.rollbackTransaction(tx)
}
throw err
}
}
/**
* Returns a preview of primary and secondary members after a possible unmerge operation
* If revertMerge flag is set, preview will be for an in-place unmerge between two members with the corresponding mergeAction.unmergeBackup
* Otherwise, preview will be for an identity extraction
* For email identities, all related identities across sources will be extracted
* This will only return a preview, users will be able to edit the preview and confirm the payload
* Unmerge will be done in /unmerge endpoint with the confirmed payload from the user.
* @param memberId member for identity extraction/unmerge
* @param identityId identity to be extracted/unmerged
* @param revertMerge flag to determine if we should revert a merge or do an identity extraction
*/
async unmergePreview(
memberId: string,
identityId: string,
revertPreviousMerge: boolean = false,
): Promise<IUnmergePreviewResult<IMemberUnmergePreviewResult>> {
const relationships = ['identities', 'affiliations']
try {
const qx = SequelizeRepository.getQueryExecutor(this.options)
const memberById = await findMemberById(qx, memberId, [
MemberField.ID,
MemberField.TENANT_ID,
MemberField.DISPLAY_NAME,
MemberField.ATTRIBUTES,
MemberField.REACH,
MemberField.CONTRIBUTIONS,
MemberField.MANUALLY_CHANGED_FIELDS,
])
this.options.log.info('[0] Getting member information (identities, affiliations)... ')
const [memberOrganizationsMap, identities, affiliations] = await Promise.all([
fetchManyMemberOrgsWithOrgData(qx, [memberId]),
fetchMemberIdentities(qx, memberId),
findMemberAffiliations(qx, memberId),
])
this.options.log.info('[0] Done!')
const memberOrganizations = memberOrganizationsMap.get(memberId)
const member = {
...memberById,
memberOrganizations,
identities,
affiliations,
}
const identity = await findMemberIdentityById(qx, memberId, identityId)
if (!identity) {
throw new Error400(this.options.language, 'merge.errors.identityMismatch')
}
if (revertPreviousMerge) {
this.options.log.info('[1] Finding merge backup...')
const mergeAction = await MergeActionsRepository.findMergeBackup(
memberId,
MergeActionType.MEMBER,
identity,
this.options,
)
if (!mergeAction) {
throw new Error('No previous merge action found to revert for member!')
}
this.options.log.info('[1] Done!')
// mergeAction is found, unmerge preview will be generated
const primaryBackup = mergeAction.unmergeBackup.primary as IMemberUnmergeBackup
const secondaryBackup = mergeAction.unmergeBackup.secondary as IMemberUnmergeBackup
const remainingIdentitiesInCurrentMember = member.identities.filter(
(i) =>
!secondaryBackup.identities.some(
(s) => s.platform === i.platform && s.value === i.value && s.type === i.type,
),
)
// Only unmerge when primary member still has some identities left after removing identities in the secondary backup
// if not fall back to identity extraction
if (remainingIdentitiesInCurrentMember.length > 0) {
// construct primary member with best effort
for (const key of MemberService.MEMBER_MERGE_FIELDS) {
// delay relationships for later
if (!(key in relationships) && !(member.manuallyChangedFields || []).includes(key)) {
if (key === 'attributes') {
// 1) if both primary and secondary backup have the attribute, check any platform specific value came from merge, if current member has it, revert it
// 2) if primary backup doesn't have the attribute, and secondary backup does, check if current member has the same value, if yes revert it (it came through merge)
// 3) if primary backup has the attribute, and secondary doesn't, keep the current value
// 4) if both backups doesn't have the value, but current member does, keep the current value
// we only need to act on cases 1 and 2, because we don't need to change current member's attributes for other cases
// loop through current member attributes
for (const attributeKey of Object.keys(member.attributes)) {
if (
!(member.manuallyChangedFields || []).some((f) => f === `attributes.${key}`)
) {
// both backups have the attribute
if (
primaryBackup.attributes[attributeKey] &&
secondaryBackup.attributes[attributeKey]
) {
// find platform key values that exist on secondary, but not on primary backup
const platformKeysThatOnlyExistOnSecondaryBackup = Object.keys(
secondaryBackup.attributes[attributeKey],
).filter(
(key) =>
primaryBackup.attributes[attributeKey][key] === null ||
primaryBackup.attributes[attributeKey][key] === undefined ||
primaryBackup.attributes[attributeKey][key] === '',
)
for (const platformKey of platformKeysThatOnlyExistOnSecondaryBackup) {
// check current member still has this value for the attribute[key][platform], and primary backup didn't have this value
if (
member.attributes[attributeKey][platformKey] ===
secondaryBackup.attributes[attributeKey][platformKey] &&
primaryBackup.attributes[attributeKey][platformKey] !==
member.attributes[attributeKey][platformKey]
) {
delete member.attributes[attributeKey][platformKey]
}
if (Object.keys(member.attributes[attributeKey]).length === 0) {
delete member.attributes[attributeKey]
}
}
} else if (
!primaryBackup.attributes[attributeKey] &&
secondaryBackup.attributes[attributeKey]
) {
// remove platform keys that has the same value with current member
if (member.attributes[attributeKey]) {
for (const platformKey of Object.keys(member.attributes[attributeKey])) {
if (
member.attributes[attributeKey][platformKey] ===
secondaryBackup.attributes[attributeKey][platformKey]
) {
delete member.attributes[attributeKey][platformKey]
}
}
// check any platform keys remaining on current member, if not remove the attribute completely
if (Object.keys(member.attributes[attributeKey]).length === 0) {
delete member.attributes[attributeKey]
}
}
}
}
}
} else if (key === 'reach') {
// only act on reach if current member has some data
for (const reachKey of Object.keys(member.reach)) {
if (
reachKey !== 'total' &&
secondaryBackup.reach[reachKey] === member.reach[reachKey]
) {
delete member.reach[reachKey]
}
}
// check if there are any keys other than total, if yes recalculate total, else set total to -1
if (Object.keys(member.reach).length > 1) {
delete member.reach.total
member.reach.total = lodash.sum(Object.values(member.reach))
} else {
member.reach.total = -1
}
} else if (key === 'contributions') {
// check secondary member has any contributions to extract from current member
if (member.contributions && Array.isArray(member.contributions)) {
const secondaryContributions = Array.isArray(secondaryBackup.contributions)
? secondaryBackup.contributions
: []
member.contributions = member.contributions.filter(
(c) => !secondaryContributions.some((s) => s.id === c.id),
)
}
} else if (
primaryBackup[key] !== member[key] &&
secondaryBackup[key] === member[key]
) {
member[key] = null
}
}
}
// identities: Remove identities coming from secondary backup
member.identities = member.identities.filter(
(i) =>
!secondaryBackup.identities.some(
(s) => s.platform === i.platform && s.value === i.value && s.type === i.type,
),
)
// affiliations: Remove affiliations coming from secondary backup
member.affiliations = member.affiliations.filter(
(a) => !secondaryBackup.affiliations.some((s) => s.id === a.id),
)
// member organizations
const unmergedRoles = MemberOrganizationService.unmergeRoles(
member.memberOrganizations,
primaryBackup.memberOrganizations,
secondaryBackup.memberOrganizations,
MemberRoleUnmergeStrategy.SAME_MEMBER,
)
member.memberOrganizations = unmergedRoles as IMemberRoleWithOrganization[]
return {
primary: {