-
Notifications
You must be signed in to change notification settings - Fork 731
Expand file tree
/
Copy pathorganizations.ts
More file actions
1291 lines (1157 loc) · 38.4 KB
/
Copy pathorganizations.ts
File metadata and controls
1291 lines (1157 loc) · 38.4 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
import {
IMemberOrganization,
IMemberOrganizationAffiliationOverride,
IMemberRoleWithOrganization,
MemberOrganizationUpdate,
OrganizationSource,
} from '@crowd/types'
import {
changeMemberOrganizationAffiliationOverrides,
findMemberAffiliationOverrides,
findOrganizationAffiliationOverrides,
} from '../member-organization-affiliation'
import { deleteMemberSegmentAffiliations } from '../member_segment_affiliations'
import { EntityType } from '../old/apps/script_executor_worker/types'
import { QueryExecutor } from '../queryExecutor'
import { EmailDomainMemberOrganizationActivityDate } from './types'
/* eslint-disable @typescript-eslint/no-explicit-any */
const toIsoString = (v: Date | string): string =>
v instanceof Date ? v.toISOString() : new Date(v).toISOString()
export async function fetchMemberOrganizations(
qx: QueryExecutor,
memberId: string,
): Promise<IMemberOrganization[]> {
return qx.select(
`
SELECT "id", "organizationId", "dateStart", "dateEnd", "title", "memberId", "source"
FROM "memberOrganizations"
WHERE "memberId" = $(memberId)
AND "deletedAt" IS NULL
ORDER BY
CASE
WHEN "dateEnd" IS NULL AND "dateStart" IS NOT NULL THEN 1
WHEN "dateEnd" IS NOT NULL AND "dateStart" IS NOT NULL THEN 2
WHEN "dateEnd" IS NULL AND "dateStart" IS NULL THEN 3
ELSE 4
END ASC,
"dateEnd" DESC,
"dateStart" DESC
`,
{
memberId,
},
)
}
export async function fetchMemberOrganizationById(
qx: QueryExecutor,
id: string,
): Promise<IMemberOrganization | undefined> {
return qx.selectOneOrNone(
`SELECT * FROM "memberOrganizations" WHERE "id" = $(id) AND "deletedAt" IS NULL`,
{ id },
)
}
/**
* Fetches member organizations for a source, optionally including soft-deleted rows.
*/
export async function fetchMemberOrganizationsBySource(
qx: QueryExecutor,
memberId: string,
source: OrganizationSource,
{ withDeleted = false }: { withDeleted?: boolean } = {},
): Promise<IMemberOrganization[]> {
const deletedClause = withDeleted ? '' : 'AND "deletedAt" IS NULL'
return qx.select(
`
SELECT
"id",
"organizationId",
"dateStart",
"dateEnd",
"title",
"memberId",
"source",
"deletedAt"
FROM "memberOrganizations"
WHERE "memberId" = $(memberId)
AND "source" = $(source)
${deletedClause}
`,
{ memberId, source },
)
}
export async function fetchEmailDomainMemberOrganizationsWithoutDates(
qx: QueryExecutor,
limit: number,
afterMemberId?: string,
): Promise<string[]> {
const rows = await qx.select(
`
SELECT DISTINCT "memberId"
FROM "memberOrganizations"
WHERE "source" = 'email-domain'
AND "dateStart" IS NULL
AND "dateEnd" IS NULL
AND "deletedAt" IS NULL
${afterMemberId ? `AND "memberId" > $(afterMemberId)` : ''}
ORDER BY "memberId"
LIMIT $(limit)
`,
{ limit, afterMemberId },
)
return rows.map((r) => r.memberId)
}
export async function fetchEmailDomainMemberOrganizationActivityDates(
qx: QueryExecutor,
memberId: string,
): Promise<EmailDomainMemberOrganizationActivityDate[]> {
return qx.select(
`
WITH email_domain_member_orgs AS (
SELECT DISTINCT
mo."memberId",
mo."organizationId",
lower(oi.value) AS domain
FROM "memberOrganizations" mo
INNER JOIN "organizationIdentities" oi
ON oi."organizationId" = mo."organizationId"
AND oi.type = 'primary-domain'
AND oi.verified = true
WHERE mo."memberId" = $(memberId)
AND mo."source" = 'email-domain'
AND mo."deletedAt" IS NULL
)
SELECT DISTINCT
edmo."memberId",
edmo."organizationId",
ar."timestamp"::date::text AS date
FROM email_domain_member_orgs edmo
INNER JOIN "memberIdentities" mi
ON mi."memberId" = edmo."memberId"
AND mi.verified = true
AND mi.type = 'email'
AND mi."deletedAt" IS NULL
AND lower(split_part(mi.value, '@', 2)) = edmo.domain
INNER JOIN "activityRelations" ar
ON ar."memberId" = mi."memberId"
AND ar.platform = mi.platform
AND lower(ar.username) = lower(mi.value)
AND ar."timestamp" IS NOT NULL
ORDER BY edmo."memberId", edmo."organizationId", date
`,
{ memberId },
)
}
export async function fetchOrganizationMemberIds(
qx: QueryExecutor,
organizationId: string,
limit: number,
afterMemberId?: string,
): Promise<string[]> {
const result = await qx.select(
`
SELECT DISTINCT "memberId"
FROM "memberOrganizations"
WHERE "organizationId" = $(organizationId)
AND "deletedAt" IS NULL
${afterMemberId ? `AND "memberId" > $(afterMemberId)` : ''}
ORDER BY "memberId"
LIMIT $(limit);
`,
{
organizationId,
limit,
afterMemberId,
},
)
return result.map((r) => r.memberId)
}
export async function fetchManyMemberOrgs(
qx: QueryExecutor,
memberIds: string[],
): Promise<{ memberId: string; organizations: IMemberOrganization[] }[]> {
return qx.select(
`
SELECT
mo."memberId",
JSONB_AGG(
TO_JSONB(mo) || JSONB_BUILD_OBJECT(
'affiliationOverride',
CASE WHEN moao."isPrimaryWorkExperience" IS NOT NULL
THEN JSONB_BUILD_OBJECT('isPrimaryWorkExperience', moao."isPrimaryWorkExperience")
ELSE NULL
END
) ORDER BY mo."createdAt"
) AS "organizations"
FROM "memberOrganizations" mo
LEFT JOIN "memberOrganizationAffiliationOverrides" moao
ON moao."memberOrganizationId" = mo.id
WHERE mo."memberId" IN ($(memberIds:csv))
AND mo."deletedAt" IS NULL
GROUP BY mo."memberId"
`,
{
memberIds,
},
)
}
export async function fetchManyMemberOrgsWithOrgData(
qx: QueryExecutor,
memberIds: string[],
{ withDomains = false }: { withDomains?: boolean } = {},
): Promise<Map<string, IMemberRoleWithOrganization[]>> {
const domainSelect = withDomains
? `,
COALESCE(oid.domains, '{}') AS "organizationDomains"`
: ''
const domainJoin = withDomains
? `
LEFT JOIN (
SELECT
oi."organizationId",
array_agg(DISTINCT lower(oi.value) ORDER BY lower(oi.value)) AS domains
FROM "organizationIdentities" oi
WHERE oi.type = 'primary-domain'
AND oi.verified = true
AND oi."organizationId" IN (
SELECT DISTINCT mo2."organizationId"
FROM "memberOrganizations" mo2
WHERE mo2."memberId" IN ($(memberIds:csv))
AND mo2."deletedAt" IS NULL
)
GROUP BY oi."organizationId"
) oid ON oid."organizationId" = mo."organizationId"`
: ''
const sql = `
SELECT
mo.*,
o."displayName" AS "organizationName",
o.logo AS "organizationLogo"
${domainSelect}
FROM "memberOrganizations" mo
JOIN organizations o ON o.id = mo."organizationId"
${domainJoin}
WHERE mo."memberId" IN ($(memberIds:csv))
AND mo."deletedAt" IS NULL;
`
const memberRoles = (await qx.select(sql, {
memberIds,
})) as IMemberRoleWithOrganization[]
const result = new Map<string, IMemberRoleWithOrganization[]>()
for (const memberId of memberIds) {
result.set(memberId, [])
}
for (const role of memberRoles) {
const roles = result.get(role.memberId)
if (roles) {
roles.push(role)
}
}
return result
}
export async function fetchManyOrganizationAffiliationPolicies(
qx: QueryExecutor,
organizationIds: string[],
): Promise<Map<string, boolean>> {
if (organizationIds.length === 0) return new Map()
const results = await qx.select(
`SELECT id, "isAffiliationBlocked"
FROM organizations
WHERE id IN ($(organizationIds:csv))`,
{ organizationIds },
)
return new Map(
results.map((r: { id: string; isAffiliationBlocked: boolean }) => [
r.id,
r.isAffiliationBlocked ?? false,
]),
)
}
export async function createMemberOrganization(
qx: QueryExecutor,
memberId: string,
data: Partial<IMemberOrganization>,
): Promise<string | undefined> {
const result = await qx.selectOneOrNone(
`
INSERT INTO "memberOrganizations"(
"memberId",
"organizationId",
"dateStart",
"dateEnd",
"title",
"source",
"verified",
"verifiedBy",
"createdAt",
"updatedAt"
)
VALUES(
$(memberId),
$(organizationId),
$(dateStart),
$(dateEnd),
$(title),
$(source),
$(verified),
$(verifiedBy),
now(),
now()
)
ON CONFLICT DO NOTHING
RETURNING id
`,
{
memberId,
organizationId: data.organizationId,
dateStart: data.dateStart ?? null,
dateEnd: data.dateEnd ?? null,
title: data.title ?? null,
source: data.source ?? null,
verified: data.verified ?? false,
verifiedBy: data.verifiedBy ?? null,
},
)
return result?.id
}
export async function createOrUpdateMemberOrganizations(
qx: QueryExecutor,
memberId: string,
organizationId: string,
source: string,
title: string | null | undefined,
dateStart: string | null | undefined,
dateEnd: string | null | undefined,
): Promise<string | undefined> {
if (dateStart) {
const whereClause = `
"memberId" = $(memberId)
AND "title" = $(title)
AND "organizationId" = $(organizationId)
AND "dateStart" IS NULL
AND "dateEnd" IS NULL
`
// clean up organizations without dates if we're getting ones with dates
await qx.result(
`
UPDATE "memberOrganizations"
SET "deletedAt" = NOW()
WHERE ${whereClause}
`,
{
memberId,
title,
organizationId,
},
)
// always clean up affiliation overrides for any organization we soft-delete
// to prevent stale override data pointing to soft-deleted organizations
await qx.result(
`
DELETE FROM "memberOrganizationAffiliationOverrides"
WHERE "memberOrganizationId" IN (
SELECT id FROM "memberOrganizations" WHERE ${whereClause}
)
`,
{
memberId,
title,
organizationId,
},
)
} else {
const rows = await qx.select(
`
SELECT COUNT(*) AS count FROM "memberOrganizations"
WHERE "memberId" = $(memberId)
AND "title" = $(title)
AND "organizationId" = $(organizationId)
AND "dateStart" IS NOT NULL
AND "deletedAt" IS NULL
`,
{
memberId,
title,
organizationId,
},
)
const row = rows[0] as any
if (row.count > 0) {
// if we're getting organization without dates, but there's already one with dates, don't insert
return
}
}
let conflictCondition = `("memberId", "organizationId", "dateStart", "dateEnd")`
if (!dateEnd) {
conflictCondition = `("memberId", "organizationId", "dateStart") WHERE "dateEnd" IS NULL`
}
if (!dateStart) {
conflictCondition = `("memberId", "organizationId") WHERE "dateStart" IS NULL AND "dateEnd" IS NULL`
}
const onConflict =
source === OrganizationSource.UI
? `ON CONFLICT ${conflictCondition} DO UPDATE SET "title" = $(title), "dateStart" = $(dateStart), "dateEnd" = $(dateEnd), "deletedAt" = NULL, "source" = $(source)`
: 'ON CONFLICT DO NOTHING'
const result = await qx.selectOneOrNone(
`
INSERT INTO "memberOrganizations" ("memberId", "organizationId", "createdAt", "updatedAt", "title", "dateStart", "dateEnd", "source")
VALUES ($(memberId), $(organizationId), NOW(), NOW(), $(title), $(dateStart), $(dateEnd), $(source))
${onConflict}
returning id
`,
{
memberId,
organizationId,
title: title || null,
dateStart: dateStart || null,
dateEnd: dateEnd || null,
source: source || null,
},
)
return result?.id
}
export async function updateMemberOrganization(
qx: QueryExecutor,
memberId: string,
id: string,
data: MemberOrganizationUpdate,
): Promise<IMemberOrganization | undefined> {
const setClause = Object.keys(data).map((key) => `"${key}" = $(${key})`)
setClause.push('"updatedAt" = now()')
const params = { memberId, id, ...data }
const query = `
UPDATE "memberOrganizations"
SET ${setClause.join(', ')}
WHERE "id" = $(id)
AND "memberId" = $(memberId)
AND "deletedAt" IS NULL
RETURNING *;
`
return qx.selectOneOrNone(query, params)
}
export async function deleteMemberOrganizations(
qx: QueryExecutor,
memberId: string,
ids?: string[],
softDelete = true,
): Promise<void> {
// Base query depends on soft vs hard delete
const baseQuery = softDelete
? 'UPDATE "memberOrganizations" SET "deletedAt" = NOW()'
: 'DELETE FROM "memberOrganizations"'
// Build WHERE clause
const conditions = ['"memberId" = $(memberId)']
const params: Record<string, unknown> = { memberId }
if (ids?.length) {
conditions.push(`"id" IN ($(ids:csv))`)
params.ids = ids
}
const whereClause = conditions.join(' AND ')
const query = `${baseQuery} WHERE ${whereClause};`
await qx.tx(async (tx) => {
// Capture affected org IDs before the delete — needed for the cleanup step below,
// since a hard delete removes rows before we can look them up.
const affectedOrgs: { organizationId: string }[] = await tx.select(
`SELECT DISTINCT "organizationId" FROM "memberOrganizations" WHERE ${whereClause}`,
params,
)
const affectedOrgIds = affectedOrgs.map((r) => r.organizationId)
// First delete from memberOrganizationAffiliationOverrides using the same conditions
await tx.result(
`DELETE FROM "memberOrganizationAffiliationOverrides"
WHERE "memberOrganizationId" IN (
SELECT "id" FROM "memberOrganizations"
WHERE ${whereClause}
)`,
params,
)
// Then perform the soft/hard delete on memberOrganizations
await tx.result(query, params)
// Clean up segment affiliations for orgs that no longer have any active work experiences
if (affectedOrgIds.length > 0) {
await tx.result(
`DELETE FROM "memberSegmentAffiliations" msa
WHERE msa."memberId" = $(memberId)
AND msa."organizationId" IN ($(orgIds:csv))
AND NOT EXISTS (
SELECT 1 FROM "memberOrganizations" mo
WHERE mo."memberId" = $(memberId)
AND mo."organizationId" = msa."organizationId"
AND mo."deletedAt" IS NULL
)`,
{ memberId, orgIds: affectedOrgIds },
)
}
})
}
export async function deleteUndatedMemberOrganizations(
qx: QueryExecutor,
memberId: string,
organizationIds: string[],
): Promise<void> {
if (organizationIds.length === 0) {
return
}
const whereClause = `
"memberId" = $(memberId)
AND "organizationId" IN ($(organizationIds:csv))
AND "dateStart" IS NULL
AND "dateEnd" IS NULL
AND "deletedAt" IS NULL
`
const params = { memberId, organizationIds }
await qx.tx(async (tx) => {
await tx.result(
`
DELETE FROM "memberOrganizationAffiliationOverrides"
WHERE "memberOrganizationId" IN (
SELECT "id" FROM "memberOrganizations" WHERE ${whereClause}
)
`,
params,
)
await tx.result(
`
UPDATE "memberOrganizations"
SET "deletedAt" = NOW()
WHERE ${whereClause}
`,
params,
)
})
}
export async function cleanSoftDeletedMemberOrganization(
qx: QueryExecutor,
memberId: string,
organizationId: string,
data: Partial<IMemberOrganization>,
): Promise<void> {
const whereClause = `
"memberId" = $(memberId)
AND "organizationId" = $(organizationId)
AND (("dateStart" = $(dateStart)) OR ("dateStart" IS NULL AND $(dateStart) IS NULL))
AND (("dateEnd" = $(dateEnd)) OR ("dateEnd" IS NULL AND $(dateEnd) IS NULL))
AND "deletedAt" IS NOT NULL
`
const params = {
memberId,
organizationId,
dateStart: data.dateStart ?? null,
dateEnd: data.dateEnd ?? null,
}
return qx.tx(async (tx) => {
await tx.result(
`
DELETE FROM "memberOrganizationAffiliationOverrides"
WHERE "memberOrganizationId" IN (
SELECT "id" FROM "memberOrganizations" WHERE ${whereClause}
)
`,
params,
)
await tx.result(
`
DELETE FROM "memberOrganizations"
WHERE ${whereClause}
`,
params,
)
})
}
export enum EntityField {
memberId = 'memberId',
organizationId = 'organizationId',
}
export interface IMergeStrat {
entityIdField: EntityField
intersectBasedOnField: EntityField
entityId(a: IMemberOrganization): string
intersectBasedOn(a: IMemberOrganization): string
worthMerging(a: IMemberOrganization, b: IMemberOrganization): boolean
targetMemberId(role: IMemberOrganization): string
targetOrganizationId(role: IMemberOrganization): string
}
type RoleToAdd = IMemberOrganization & { originalRoleIds: string[] }
const MemberMergeStrat = (primaryMemberId: string): IMergeStrat => ({
entityIdField: EntityField.memberId,
intersectBasedOnField: EntityField.organizationId,
entityId(role: IMemberOrganization): string {
return role.memberId
},
intersectBasedOn(role: IMemberOrganization): string {
return role.organizationId
},
worthMerging(a: IMemberOrganization, b: IMemberOrganization): boolean {
return a.organizationId === b.organizationId
},
targetMemberId(): string {
return primaryMemberId
},
targetOrganizationId(role: IMemberOrganization): string {
return role.organizationId
},
})
const OrgMergeStrat = (primaryOrganizationId: string): IMergeStrat => ({
entityIdField: EntityField.organizationId,
intersectBasedOnField: EntityField.memberId,
entityId(role: IMemberOrganization): string {
return role.organizationId
},
intersectBasedOn(role: IMemberOrganization): string {
return role.memberId
},
worthMerging(a: IMemberOrganization, b: IMemberOrganization): boolean {
return a.memberId === b.memberId
},
targetMemberId(role: IMemberOrganization): string {
return role.memberId
},
targetOrganizationId(): string {
return primaryOrganizationId
},
})
export async function findRolesBelongingToBothEntities(
qx: QueryExecutor,
primaryId: string,
secondaryId: string,
entityIdField: EntityField,
intersectBasedOnField: EntityField,
): Promise<IMemberOrganization[]> {
const results = await qx.select(
`
SELECT mo.*
FROM "memberOrganizations" AS mo
WHERE mo."deletedAt" is null and
mo."${intersectBasedOnField}" IN (
SELECT "${intersectBasedOnField}"
FROM "memberOrganizations"
WHERE "${entityIdField}" = $(primaryId)
)
AND mo."${intersectBasedOnField}" IN (
SELECT "${intersectBasedOnField}"
FROM "memberOrganizations"
WHERE "${entityIdField}" = $(secondaryId))
AND mo."${entityIdField}" IN ($(primaryId), $(secondaryId));
`,
{
primaryId,
secondaryId,
},
)
return results as IMemberOrganization[]
}
export async function findNonIntersectingRoles(
qx: QueryExecutor,
primaryId: string,
secondaryId: string,
entityIdField: EntityField,
intersectBasedOnField: EntityField,
): Promise<IMemberOrganization[]> {
const remainingRoles = (await qx.select(
`
SELECT *
FROM "memberOrganizations"
WHERE "${entityIdField}" = $(secondaryId)
AND "deletedAt" IS NULL
AND "${intersectBasedOnField}" NOT IN (
SELECT "${intersectBasedOnField}"
FROM "memberOrganizations"
WHERE "${entityIdField}" = $(primaryId)
AND "deletedAt" IS NULL
);
`,
{
primaryId,
secondaryId,
},
)) as IMemberOrganization[]
return remainingRoles
}
export async function removeMemberRole(qx: QueryExecutor, role: IMemberOrganization) {
const conditions = ['"organizationId" = $(organizationId)', '"memberId" = $(memberId)']
const replacements: Record<string, unknown> = {
organizationId: role.organizationId,
memberId: role.memberId,
}
if (role.dateStart === null) {
conditions.push('"dateStart" IS NULL')
} else {
conditions.push('"dateStart" = $(dateStart)')
replacements.dateStart = toIsoString(role.dateStart)
}
if (role.dateEnd === null) {
conditions.push('"dateEnd" IS NULL')
} else {
conditions.push('"dateEnd" = $(dateEnd)')
replacements.dateEnd = toIsoString(role.dateEnd)
}
const whereClause = conditions.join(' AND ')
await qx.tx(async (tx) => {
// Delete affiliation overrides first using subquery
await tx.result(
`
DELETE FROM "memberOrganizationAffiliationOverrides"
WHERE "memberOrganizationId" IN (
SELECT id FROM "memberOrganizations"
WHERE ${whereClause}
)
`,
replacements,
)
// Then delete the role
await tx.result(
`
DELETE FROM "memberOrganizations"
WHERE ${whereClause}
`,
replacements,
)
})
}
export async function addMemberRole(
qx: QueryExecutor,
role: IMemberOrganization,
): Promise<string | undefined> {
const query = `
insert into "memberOrganizations" ("memberId", "organizationId", "createdAt", "updatedAt", "title", "dateStart", "dateEnd", "source")
values ($(memberId), $(organizationId), NOW(), NOW(), $(title), $(dateStart), $(dateEnd), $(source))
on conflict do nothing returning id;
`
const row = await qx.selectOneOrNone(query, {
memberId: role.memberId,
organizationId: role.organizationId,
title: role.title || null,
dateStart: role.dateStart,
dateEnd: role.dateEnd,
source: role.source || null,
})
return row?.id
}
async function moveRolesBetweenEntities(
qx: QueryExecutor,
primaryId: string,
secondaryId: string,
mergeStrat: IMergeStrat,
entityType: EntityType,
): Promise<{ shouldRecalculateAffiliations: boolean }> {
let shouldRecalculateAffiliations = false
const rolesForBothEntities = await findRolesBelongingToBothEntities(
qx,
primaryId,
secondaryId,
mergeStrat.entityIdField,
mergeStrat.intersectBasedOnField,
)
const primaryRoles = rolesForBothEntities.filter((m) => mergeStrat.entityId(m) === primaryId)
const secondaryRoles = rolesForBothEntities.filter((m) => mergeStrat.entityId(m) === secondaryId)
const findAffiliationOverrides =
entityType === EntityType.MEMBER
? findMemberAffiliationOverrides
: findOrganizationAffiliationOverrides
const primaryAffiliationOverrides = await findAffiliationOverrides(qx, primaryId)
const secondaryAffiliationOverrides = await findAffiliationOverrides(qx, secondaryId)
const organizationIds = new Set<string>()
for (const role of rolesForBothEntities) {
organizationIds.add(role.organizationId)
organizationIds.add(mergeStrat.targetOrganizationId(role))
}
if (entityType === EntityType.ORGANIZATION) {
organizationIds.add(primaryId)
organizationIds.add(secondaryId)
}
const orgAffiliationPolicyById = await fetchManyOrganizationAffiliationPolicies(qx, [
...organizationIds,
])
if (
entityType === EntityType.ORGANIZATION &&
(orgAffiliationPolicyById.get(primaryId) || orgAffiliationPolicyById.get(secondaryId))
) {
shouldRecalculateAffiliations = true
}
const mergeResult = await mergeRoles(
qx,
primaryRoles,
secondaryRoles,
primaryAffiliationOverrides,
secondaryAffiliationOverrides,
mergeStrat,
orgAffiliationPolicyById,
)
if (mergeResult.shouldRecalculateAffiliations) {
shouldRecalculateAffiliations = true
}
const remainingRoles = await findNonIntersectingRoles(
qx,
primaryId,
secondaryId,
mergeStrat.entityIdField,
mergeStrat.intersectBasedOnField,
)
// Fetch policies for org IDs not yet in the map (member merge edge case)
const missingOrgIds = [
...new Set(
remainingRoles
.flatMap((r) => [r.organizationId, mergeStrat.targetOrganizationId(r)])
.filter((id) => !orgAffiliationPolicyById.has(id)),
),
]
if (missingOrgIds.length > 0) {
const additional = await fetchManyOrganizationAffiliationPolicies(qx, missingOrgIds)
for (const [id, blocked] of additional) {
orgAffiliationPolicyById.set(id, blocked)
}
}
for (const role of remainingRoles) {
const existingOverride = secondaryAffiliationOverrides.find(
(o) => o.memberOrganizationId === role.id,
)
await removeMemberRole(qx, role)
const newRoleId = await addMemberRole(qx, {
title: role.title,
dateStart: role.dateStart,
dateEnd: role.dateEnd,
memberId: mergeStrat.targetMemberId(role),
organizationId: mergeStrat.targetOrganizationId(role),
source: role.source,
deletedAt: role.deletedAt,
})
if (!newRoleId) continue
const targetOrgId = mergeStrat.targetOrganizationId(role)
const isTargetBlocked = orgAffiliationPolicyById.get(targetOrgId) ?? false
const isSourceBlocked = orgAffiliationPolicyById.get(role.organizationId) ?? false
let isPrimaryWorkExp = existingOverride?.isPrimaryWorkExperience ?? false
if (isPrimaryWorkExp) {
const alreadyHasIt = primaryAffiliationOverrides.some((o) => o.isPrimaryWorkExperience)
if (alreadyHasIt) isPrimaryWorkExp = false
}
const preserveManualBlock = existingOverride?.allowAffiliation === false && !isSourceBlocked
const targetMemberId = mergeStrat.targetMemberId(role)
const shouldWriteOverride = isTargetBlocked || preserveManualBlock || isPrimaryWorkExp
const finalAllowAffiliation = isTargetBlocked || preserveManualBlock ? false : undefined
if (shouldWriteOverride) {
await changeMemberOrganizationAffiliationOverrides(qx, [
{
memberId: targetMemberId,
memberOrganizationId: newRoleId,
allowAffiliation: finalAllowAffiliation,
isPrimaryWorkExperience: isPrimaryWorkExp || undefined,
},
])
// If the affiliation is blocked, delete any existing MSAs to prevent the member from
// remaining affiliated through a manually created affiliation.
if (finalAllowAffiliation === false) {
await deleteMemberSegmentAffiliations(qx, {
memberId: targetMemberId,
organizationId: targetOrgId,
})
}
shouldRecalculateAffiliations = true
}
if (!isTargetBlocked && existingOverride?.allowAffiliation === false && isSourceBlocked) {
shouldRecalculateAffiliations = true
}
}
return { shouldRecalculateAffiliations }
}
export async function moveMembersBetweenOrganizations(
qx: QueryExecutor,
secondaryOrganizationId: string,
primaryOrganizationId: string,
): Promise<{ shouldRecalculateAffiliations: boolean }> {
return moveRolesBetweenEntities(
qx,
primaryOrganizationId,
secondaryOrganizationId,
OrgMergeStrat(primaryOrganizationId),
EntityType.ORGANIZATION,
)
}
export async function moveOrgsBetweenMembers(
qx: QueryExecutor,
primaryMemberId: string,
secondaryMemberId: string,
): Promise<{ shouldRecalculateAffiliations: boolean }> {
return moveRolesBetweenEntities(
qx,
primaryMemberId,
secondaryMemberId,
MemberMergeStrat(primaryMemberId),
EntityType.MEMBER,
)
}
export async function mergeRoles(
qx: QueryExecutor,
primaryRoles: IMemberOrganization[],
secondaryRoles: IMemberOrganization[],
primaryAffiliationOverrides: IMemberOrganizationAffiliationOverride[],
secondaryAffiliationOverrides: IMemberOrganizationAffiliationOverride[],
mergeStrat: IMergeStrat,
orgAffiliationPolicyById: Map<string, boolean>,
): Promise<{ shouldRecalculateAffiliations: boolean }> {
const isDefinedId = (id: string | undefined): id is string => !!id
const areDatesEqual = (a: Date | string | null, b: Date | string | null): boolean => {
if (a === null && b === null) return true
if (a === null || b === null) return false
return new Date(a).getTime() === new Date(b).getTime()
}