-
Notifications
You must be signed in to change notification settings - Fork 731
Expand file tree
/
Copy pathorganizationRepository.ts
More file actions
1859 lines (1619 loc) · 52.4 KB
/
organizationRepository.ts
File metadata and controls
1859 lines (1619 loc) · 52.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 lodash, { uniq } from 'lodash'
import { QueryTypes } from 'sequelize'
import validator from 'validator'
import {
captureApiChange,
organizationCreateAction,
organizationEditIdentitiesAction,
organizationUpdateAction,
} from '@crowd/audit-logs'
import { Error400, Error404, Error409, RawQueryParser } from '@crowd/common'
import { queryActivities, queryActivityRelations } from '@crowd/data-access-layer'
import { findManyLfxMemberships } from '@crowd/data-access-layer/src/lfx_memberships'
import {
IDbOrgAttribute,
IDbOrganization,
OrgIdentityField,
OrganizationField,
addOrgIdentity,
addOrgsToSegments,
cleanUpOrgIdentities,
cleanupForOganization,
deleteOrganizationAttributes,
fetchManyOrgIdentities,
fetchManyOrgSegments,
fetchOrgIdentities,
findManyOrgAttributes,
findOrgAttributes,
findOrgById,
markOrgAttributeDefault,
queryOrgIdentities,
updateOrgIdentityVerifiedFlag,
upsertOrgAttributes,
} from '@crowd/data-access-layer/src/organizations'
import { findAttribute } from '@crowd/data-access-layer/src/organizations/attributesConfig'
import { optionsQx } from '@crowd/data-access-layer/src/queryExecutor'
import { findSegmentById } from '@crowd/data-access-layer/src/segments'
import {
IMemberRenderFriendlyRole,
IMemberRoleWithOrganization,
IOrganizationIdentity,
MergeActionState,
MergeActionType,
OrganizationIdentityType,
SegmentData,
} from '@crowd/types'
import {
IFetchOrganizationMergeSuggestionArgs,
SimilarityScoreRange,
} from '@/types/mergeSuggestionTypes'
import { IRepositoryOptions } from './IRepositoryOptions'
import { OrganizationQueryCache } from './organizationsQueryCache'
import SegmentRepository from './segmentRepository'
import SequelizeRepository from './sequelizeRepository'
interface IOrganizationId {
id: string
}
class OrganizationRepository {
public static QUERY_FILTER_COLUMN_MAP: Map<string, string> = new Map([
// id fields
['id', 'o.id'],
['segmentId', 'osa."segmentId"'],
// basic fields for filtering
['size', 'o.size'],
['industry', 'o.industry'],
['employees', 'o."employees"'],
['founded', 'o."founded"'],
['headline', 'o."headline"'],
['location', 'o."location"'],
['tags', 'o."tags"'],
['type', 'o."type"'],
['isTeamOrganization', 'o."isTeamOrganization"'],
['isAffiliationBlocked', 'o."isAffiliationBlocked"'],
// basic fields for querying
['displayName', 'o."displayName"'],
['revenueRange', 'o."revenueRange"'],
['employeeGrowthRate', 'o."employeeGrowthRate"'],
// derived fields
['employeeChurnRate12Month', `(o."employeeChurnRate"->>'12_month')::decimal`],
['employeeGrowthRate12Month', `(o."employeeGrowthRate"->>'12_month')::decimal`],
['revenueRangeMin', `(o."revenueRange"->>'min')::integer`],
['revenueRangeMax', `(o."revenueRange"->>'max')::integer`],
// aggregated fields
['activityCount', 'coalesce(osa."activityCount", 0)::integer'],
['memberCount', 'coalesce(osa."memberCount", 0)::integer'],
['activeOn', 'coalesce(osa."activeOn", \'{}\'::text[])'],
['joinedAt', 'osa."joinedAt"'],
['lastActive', 'osa."lastActive"'],
['avgContributorEngagement', 'coalesce(osa."avgContributorEngagement", 0)::integer'],
// org fields for display
['logo', 'o."logo"'],
['description', 'o."description"'],
// enrichment
['lastEnrichedAt', 'oe."lastUpdatedAt"'],
])
static async create(data, options: IRepositoryOptions) {
const currentUser = SequelizeRepository.getCurrentUser(options)
const tenant = SequelizeRepository.getCurrentTenant(options)
const transaction = SequelizeRepository.getTransaction(options)
if (!data.displayName) {
data.displayName = data.identities[0].name
}
const toInsert = {
...lodash.pick(data, [
'displayName',
'description',
'headline',
'logo',
'importHash',
'isTeamOrganization',
'isAffiliationBlocked',
'lastEnrichedAt',
'manuallyCreated',
]),
tenantId: tenant.id,
createdById: currentUser.id,
updatedById: currentUser.id,
}
const record = await options.database.organization.create(toInsert, {
transaction,
})
// prepare attributes object
const attributes = {} as any
if (data.logo) {
attributes.logo = {
custom: [data.logo],
default: data.logo,
}
}
await this.updateOrgAttributes(record.id, { attributes }, options)
await captureApiChange(
options,
organizationCreateAction(record.id, async (captureState) => {
captureState(toInsert)
}),
)
await record.setMembers(data.members || [], {
transaction,
})
if (data.identities && data.identities.length > 0) {
await OrganizationRepository.setIdentities(record.id, data.identities, options)
}
await addOrgsToSegments(
optionsQx(options),
options.currentSegments.map((s) => s.id),
[record.id],
)
return this.findById(record.id, options)
}
static async excludeOrganizationsFromSegments(
organizationIds: string[],
options: IRepositoryOptions,
) {
const seq = SequelizeRepository.getSequelize(options)
const transaction = SequelizeRepository.getTransaction(options)
const bulkDeleteOrganizationSegments = `DELETE FROM "organizationSegments" WHERE "organizationId" in (:organizationIds) and "segmentId" in (:segmentIds);`
await seq.query(bulkDeleteOrganizationSegments, {
replacements: {
organizationIds,
segmentIds: SequelizeRepository.getSegmentIds(options),
},
type: QueryTypes.DELETE,
transaction,
})
}
static async excludeOrganizationsFromAllSegments(
organizationIds: string[],
options: IRepositoryOptions,
) {
const seq = SequelizeRepository.getSequelize(options)
const transaction = SequelizeRepository.getTransaction(options)
const bulkDeleteOrganizationSegments = `DELETE FROM "organizationSegments" WHERE "organizationId" in (:organizationIds);`
await seq.query(bulkDeleteOrganizationSegments, {
replacements: {
organizationIds,
},
type: QueryTypes.DELETE,
transaction,
})
}
static ORGANIZATION_UPDATE_COLUMNS = [
'importHash',
'isTeamOrganization',
'isAffiliationBlocked',
'headline',
'lastEnrichedAt',
// default attributes
'type',
'industry',
'founded',
'size',
'employees',
'displayName',
'description',
'logo',
'tags',
'location',
'employees',
'revenueRange',
'employeeChurnRate',
'employeeGrowthRate',
]
static isEqual = {
displayName: (a, b) => a === b,
description: (a, b) => a === b,
emails: (a, b) => lodash.isEqual((a || []).sort(), (b || []).sort()),
phoneNumbers: (a, b) => lodash.isEqual((a || []).sort(), (b || []).sort()),
logo: (a, b) => a === b,
location: (a, b) => a === b,
isTeamOrganization: (a, b) => a === b,
isAffiliationBlocked: (a, b) => a === b,
attributes: (a, b) => lodash.isEqual(a, b),
}
static convertOrgAttributesForInsert(data: any) {
const orgAttributes = []
const defaultColumns = {}
for (const [name, attribute] of Object.entries(data.attributes)) {
const attributeDefinition = findAttribute(name)
if (!(attribute as any).custom) {
continue // eslint-disable-line no-continue
}
for (const value of (attribute as any).custom) {
const isDefault = value === (attribute as any).default
orgAttributes.push({
type: attributeDefinition.type,
name,
source: 'custom',
default: isDefault,
value,
})
if (isDefault && attributeDefinition.defaultColumn) {
defaultColumns[attributeDefinition.defaultColumn] = value
}
}
}
return {
orgAttributes,
defaultColumns,
}
}
static convertOrgAttributesForDisplay(attributes: IDbOrgAttribute[]) {
return attributes.reduce((acc, a) => {
if (!acc[a.name]) {
acc[a.name] = {}
}
if (!acc[a.name][a.source]) {
acc[a.name][a.source] = []
}
acc[a.name][a.source].push(a.value)
if (a.default) {
acc[a.name].default = a.value
}
return acc
}, {})
}
static async updateOrgAttributes(organizationId: string, data: any, options: IRepositoryOptions) {
const qx = SequelizeRepository.getQueryExecutor(options)
const { orgAttributes, defaultColumns } =
OrganizationRepository.convertOrgAttributesForInsert(data)
await upsertOrgAttributes(qx, organizationId, orgAttributes)
for (const attr of orgAttributes) {
if (attr.default) {
await markOrgAttributeDefault(qx, organizationId, attr)
}
}
return defaultColumns
}
static async update(
id,
data,
options: IRepositoryOptions,
overrideIdentities = false,
manualChange = false,
) {
const currentUser = SequelizeRepository.getCurrentUser(options)
const transaction = SequelizeRepository.getTransaction(options)
const currentTenant = SequelizeRepository.getCurrentTenant(options)
const seq = SequelizeRepository.getSequelize(options)
const record = await captureApiChange(
options,
organizationUpdateAction(id, async (captureOldState, captureNewState) => {
const record = await options.database.organization.findOne({
where: {
id,
tenantId: currentTenant.id,
},
transaction,
})
if (!record) {
throw new Error404()
}
captureOldState(record.get({ plain: true }))
if (data.identities) {
const primaryDomainIdentity = data.identities.find(
(i) => i.type === OrganizationIdentityType.PRIMARY_DOMAIN && i.verified,
)
// check if domain already exists in another organization in the same tenant
if (primaryDomainIdentity) {
const existingOrg = (await seq.query(
`
select "organizationId"
from "organizationIdentities"
where
"tenantId" = :tenantId and
"organizationId" <> :id and
type = :type and
value = :value and
verified = true
`,
{
replacements: {
tenantId: currentTenant.id,
id: record.id,
type: OrganizationIdentityType.PRIMARY_DOMAIN,
value: primaryDomainIdentity.value,
},
type: QueryTypes.SELECT,
transaction,
},
)) as any[]
// ensure that it's not the same organization
if (existingOrg && existingOrg.length > 0) {
throw new Error409(
options.language,
'errors.alreadyExists',
existingOrg[0].organizationId,
)
}
}
}
if (data.attributes) {
const defaultColumns = await OrganizationRepository.updateOrgAttributes(
record.id,
data,
options,
)
for (const col of Object.keys(defaultColumns)) {
data[col] = defaultColumns[col]
}
}
const updatedData = {
...lodash.pick(data, this.ORGANIZATION_UPDATE_COLUMNS),
updatedById: currentUser.id,
}
captureNewState(updatedData)
await options.database.organization.update(updatedData, {
where: {
id: record.id,
},
transaction,
})
return record
}),
!manualChange, // skip audit log if not a manual change
)
if (data.members) {
await record.setMembers(data.members || [], {
transaction,
})
}
if (
data.isTeamOrganization === true ||
data.isTeamOrganization === 'true' ||
data.isTeamOrganization === false ||
data.isTeamOrganization === 'false'
) {
await this.setOrganizationIsTeam(record.id, data.isTeamOrganization, options)
}
if (data.segments) {
await addOrgsToSegments(
optionsQx(options),
options.currentSegments.map((s) => s.id),
[record.id],
)
}
await captureApiChange(
options,
organizationEditIdentitiesAction(id, async (captureOldState, captureNewState) => {
const qx = SequelizeRepository.getQueryExecutor(options)
const initialIdentities = await fetchOrgIdentities(qx, id)
function convertIdentitiesForAudit(identities: IOrganizationIdentity[]) {
return identities.reduce((acc, r) => {
if (!acc[r.platform]) {
acc[r.platform] = []
}
acc[r.platform].push({
value: r.value,
type: r.type,
verified: r.verified,
})
acc[r.platform] = acc[r.platform].sort((a, b) =>
`${a.value}:${a.type}:${a.verified}`.localeCompare(
`${b.value}:${b.type}:${b.verified}`,
),
)
return acc
}, {})
}
captureOldState(convertIdentitiesForAudit(initialIdentities))
if (data.identities && data.identities.length > 0) {
if (overrideIdentities) {
captureNewState(
convertIdentitiesForAudit(
data.identities.map((i) => ({
platform: i.platform,
value: i.value,
type: i.type,
verified: i.verified,
})),
),
)
await this.setIdentities(id, data.identities, options)
} else {
captureNewState(convertIdentitiesForAudit([...initialIdentities, ...data.identities]))
await OrganizationRepository.addIdentities(id, data.identities, options)
}
}
}),
)
return this.findById(record.id, options)
}
/**
* Marks/unmarks an organization's members as team members
* @param organizationId
* @param isTeam
* @param options
*/
static async setOrganizationIsTeam(
organizationId: string,
isTeam: boolean,
options: IRepositoryOptions,
): Promise<void> {
const transaction = SequelizeRepository.getTransaction(options)
await options.database.sequelize.query(
`update members as m
set attributes = jsonb_set("attributes", '{isTeamMember}', '{"default": ${isTeam}}'::jsonb)
from "memberOrganizations" as mo
where mo."memberId" = m.id
and mo."organizationId" = :organizationId
and mo."deletedAt" is null
and m."tenantId" = :tenantId;
`,
{
replacements: {
isTeam,
organizationId,
tenantId: options.currentTenant.id,
},
type: QueryTypes.UPDATE,
transaction,
},
)
}
static async destroy(id, options: IRepositoryOptions, force = false) {
const transaction = SequelizeRepository.getTransaction(options)
const currentTenant = SequelizeRepository.getCurrentTenant(options)
const record = await options.database.organization.findOne({
where: {
id,
tenantId: currentTenant.id,
},
transaction,
})
if (!record) {
throw new Error404()
}
await OrganizationRepository.excludeOrganizationsFromAllSegments([id], {
...options,
transaction,
})
const qx = SequelizeRepository.getQueryExecutor(options)
await cleanupForOganization(qx, id)
await deleteOrganizationAttributes(qx, [id])
await record.destroy({
transaction,
force,
})
}
static async setIdentities(
organizationId: string,
identities: IOrganizationIdentity[],
options: IRepositoryOptions,
): Promise<void> {
const qx = SequelizeRepository.getQueryExecutor(options)
await cleanUpOrgIdentities(qx, organizationId)
await OrganizationRepository.addIdentities(organizationId, identities, options)
}
static async addIdentities(
organizationId: string,
identities: IOrganizationIdentity[],
options: IRepositoryOptions,
) {
for (const identity of identities) {
await OrganizationRepository.addIdentity(organizationId, identity, options)
}
}
static async updateIdentity(
organizationId: string,
identity: IOrganizationIdentity,
options: IRepositoryOptions,
): Promise<void> {
const qx = SequelizeRepository.getQueryExecutor(options)
await updateOrgIdentityVerifiedFlag(qx, {
organizationId,
platform: identity.platform,
value: identity.value,
type: identity.type,
verified: identity.verified,
})
}
static async addIdentity(
organizationId: string,
identity: IOrganizationIdentity,
options: IRepositoryOptions,
): Promise<void> {
const qx = SequelizeRepository.getQueryExecutor(options)
await addOrgIdentity(qx, {
organizationId,
platform: identity.platform,
source: identity.source,
sourceId: identity.sourceId || null,
value: identity.value,
type: identity.type,
verified: identity.verified,
integrationId: identity.integrationId || null,
})
}
static async getIdentities(
organizationIds: string[],
options: IRepositoryOptions,
): Promise<IOrganizationIdentity[]> {
const transaction = SequelizeRepository.getTransaction(options)
const sequelize = SequelizeRepository.getSequelize(options)
const results = await sequelize.query(
`
select "sourceId", "source", platform, value, type, verified, "integrationId", "organizationId" from "organizationIdentities"
where "organizationId" in (:organizationIds)
`,
{
replacements: {
organizationIds,
},
type: QueryTypes.SELECT,
transaction,
},
)
return results as IOrganizationIdentity[]
}
static async moveIdentitiesBetweenOrganizations(
fromOrganizationId: string,
toOrganizationId: string,
identitiesToMove: IOrganizationIdentity[],
options: IRepositoryOptions,
): Promise<void> {
const transaction = SequelizeRepository.getTransaction(options)
const seq = SequelizeRepository.getSequelize(options)
const query = `
update "organizationIdentities"
set
"organizationId" = :newOrganizationId
where
"organizationId" = :oldOrganizationId and
platform = :platform and
value = :value and
type = :type and
verified = :verified;
`
for (const identity of identitiesToMove) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [_, count] = await seq.query(query, {
replacements: {
oldOrganizationId: fromOrganizationId,
newOrganizationId: toOrganizationId,
platform: identity.platform,
value: identity.value,
type: identity.type,
verified: identity.verified,
},
type: QueryTypes.UPDATE,
transaction,
})
if (count !== 1) {
throw new Error('One row should be updated!')
}
}
}
static async addNoMerge(
organizationId: string,
noMergeId: string,
options: IRepositoryOptions,
): Promise<void> {
const seq = SequelizeRepository.getSequelize(options)
const transaction = SequelizeRepository.getTransaction(options)
const query = `
insert into "organizationNoMerge" ("organizationId", "noMergeId", "createdAt", "updatedAt")
values
(:organizationId, :noMergeId, now(), now()),
(:noMergeId, :organizationId, now(), now())
on conflict do nothing;
`
try {
await seq.query(query, {
replacements: {
organizationId,
noMergeId,
},
type: QueryTypes.INSERT,
transaction,
})
} catch (error) {
options.log.error('Error adding organizations no merge!', error)
throw error
}
}
static async removeToMerge(
organizationId: string,
toMergeId: string,
options: IRepositoryOptions,
): Promise<void> {
const seq = SequelizeRepository.getSequelize(options)
const transaction = SequelizeRepository.getTransaction(options)
const query = `
delete from "organizationToMerge"
where ("organizationId" = :organizationId and "toMergeId" = :toMergeId) or ("organizationId" = :toMergeId and "toMergeId" = :organizationId);
`
try {
await seq.query(query, {
replacements: {
organizationId,
toMergeId,
},
type: QueryTypes.DELETE,
transaction,
})
} catch (error) {
options.log.error('Error while removing organizations to merge!', error)
throw error
}
}
static async findNonExistingIds(ids: string[], options: IRepositoryOptions): Promise<string[]> {
const transaction = SequelizeRepository.getTransaction(options)
const seq = SequelizeRepository.getSequelize(options)
let idValues = ``
for (let i = 0; i < ids.length; i++) {
idValues += `('${ids[i]}'::uuid)`
if (i !== ids.length - 1) {
idValues += ','
}
}
const query = `WITH id_list (id) AS (
VALUES
${idValues}
)
SELECT id
FROM id_list
WHERE NOT EXISTS (
SELECT 1
FROM organizations o
WHERE o.id = id_list.id
);`
try {
const results: IOrganizationId[] = await seq.query(query, {
type: QueryTypes.SELECT,
transaction,
})
return results.map((r) => r.id)
} catch (error) {
options.log.error('error while getting non existing organizations from db', error)
throw error
}
}
static async countOrganizationMergeSuggestions(
organizationFilter: string,
similarityFilter: string,
displayNameFilter: string,
replacements: {
segmentIds: string[]
organizationId?: string
displayName?: string
mergeActionType: MergeActionType
mergeActionStatus: MergeActionState
},
options: IRepositoryOptions,
): Promise<number> {
const organizationsJoin = displayNameFilter
? `JOIN organizations o1 ON o1.id = otm."organizationId"
JOIN organizations o2 ON o2.id = otm."toMergeId"`
: ''
const result = await options.database.sequelize.query(
`
SELECT COUNT(DISTINCT Greatest(
Hashtext(Concat(otm."organizationId", otm."toMergeId")),
Hashtext(Concat(otm."toMergeId", otm."organizationId"))
)) AS total_count
FROM "organizationToMerge" otm
${organizationsJoin}
LEFT JOIN "mergeActions" ma
ON ma.type = :mergeActionType
AND (
(ma."primaryId" = otm."organizationId" AND ma."secondaryId" = otm."toMergeId")
OR (ma."primaryId" = otm."toMergeId" AND ma."secondaryId" = otm."organizationId")
)
WHERE EXISTS (
SELECT 1 FROM "organizationSegmentsAgg" os1
WHERE os1."organizationId" = otm."organizationId" AND os1."segmentId" IN (:segmentIds)
)
AND EXISTS (
SELECT 1 FROM "organizationSegmentsAgg" os2
WHERE os2."organizationId" = otm."toMergeId" AND os2."segmentId" IN (:segmentIds)
)
AND (ma.id IS NULL OR ma.state = :mergeActionStatus)
${organizationFilter}
${similarityFilter}
${displayNameFilter}
`,
{
replacements,
type: QueryTypes.SELECT,
},
)
return result[0]?.total_count || 0
}
static async findOrganizationsWithMergeSuggestions(
args: IFetchOrganizationMergeSuggestionArgs,
options: IRepositoryOptions,
) {
const HIGH_CONFIDENCE_LOWER_BOUND = 0.9
const MEDIUM_CONFIDENCE_LOWER_BOUND = 0.7
const currentSegments = SequelizeRepository.getSegmentIds(options)
const segmentIds = (
await new SegmentRepository(options).getSegmentSubprojects(currentSegments)
).map((s) => s.id)
let similarityFilter = ''
const similarityConditions = []
for (const similarity of args.filter?.similarity || []) {
if (similarity === SimilarityScoreRange.HIGH) {
similarityConditions.push(`(otm.similarity >= ${HIGH_CONFIDENCE_LOWER_BOUND})`)
} else if (similarity === SimilarityScoreRange.MEDIUM) {
similarityConditions.push(
`(otm.similarity >= ${MEDIUM_CONFIDENCE_LOWER_BOUND} and otm.similarity < ${HIGH_CONFIDENCE_LOWER_BOUND})`,
)
} else if (similarity === SimilarityScoreRange.LOW) {
similarityConditions.push(`(otm.similarity < ${MEDIUM_CONFIDENCE_LOWER_BOUND})`)
}
}
if (similarityConditions.length > 0) {
similarityFilter = ` and (${similarityConditions.join(' or ')})`
}
const organizationFilter = args.filter?.organizationId
? ` AND ("otm"."organizationId" = :organizationId OR "otm"."toMergeId" = :organizationId)`
: ''
const displayNameFilter = args.filter?.displayName
? ` and (o1."displayName" ilike :displayName OR o2."displayName" ilike :displayName)`
: ''
let order =
'"organizationsToMerge".similarity desc, "organizationsToMerge"."id", "organizationsToMerge"."toMergeId"'
if (args.orderBy?.length > 0) {
order = ''
for (const orderBy of args.orderBy) {
const [field, direction] = orderBy.split('_')
if (['similarity'].includes(field) && ['asc', 'desc'].includes(direction.toLowerCase())) {
order += `"organizationsToMerge".${field} ${direction}, `
}
}
order += '"organizationsToMerge"."id", "organizationsToMerge"."toMergeId"'
}
if (args.countOnly) {
const totalCount = await this.countOrganizationMergeSuggestions(
organizationFilter,
similarityFilter,
displayNameFilter,
{
segmentIds,
displayName: args?.filter?.displayName ? `${args.filter.displayName}%` : undefined,
organizationId: args?.filter?.organizationId,
mergeActionType: MergeActionType.ORG,
mergeActionStatus: MergeActionState.ERROR,
},
options,
)
return { count: totalCount }
}
const orgs = await options.database.sequelize.query(
`WITH
cte AS (
SELECT
Greatest(Hashtext(Concat(otm."organizationId", otm."toMergeId")), Hashtext(Concat(otm."toMergeId", otm."organizationId"))) as hash,
otm."organizationId" as id,
otm."toMergeId",
o1."createdAt",
otm."similarity",
o1."displayName" as "primaryDisplayName",
o1.logo as "primaryLogo",
o2."displayName" as "secondaryDisplayName",
o2.logo as "secondaryLogo",
(SELECT os1."segmentId" FROM "organizationSegmentsAgg" os1
WHERE os1."organizationId" = otm."organizationId" AND os1."segmentId" IN (:segmentIds)
LIMIT 1) as "primarySegmentId",
(SELECT os2."segmentId" FROM "organizationSegmentsAgg" os2
WHERE os2."organizationId" = otm."toMergeId" AND os2."segmentId" IN (:segmentIds)
LIMIT 1) as "secondarySegmentId"
FROM "organizationToMerge" otm
JOIN organizations o1 ON o1.id = otm."organizationId"
JOIN organizations o2 ON o2.id = otm."toMergeId"
LEFT JOIN "mergeActions" ma
ON ma.type = :mergeActionType
AND (
(ma."primaryId" = otm."organizationId" AND ma."secondaryId" = otm."toMergeId")
OR (ma."primaryId" = otm."toMergeId" AND ma."secondaryId" = otm."organizationId")
)
WHERE EXISTS (
SELECT 1 FROM "organizationSegmentsAgg" os1
WHERE os1."organizationId" = otm."organizationId" AND os1."segmentId" IN (:segmentIds)
)
AND EXISTS (
SELECT 1 FROM "organizationSegmentsAgg" os2
WHERE os2."organizationId" = otm."toMergeId" AND os2."segmentId" IN (:segmentIds)
)
AND (ma.id IS NULL OR ma.state = :mergeActionStatus)
${organizationFilter}
${similarityFilter}
${displayNameFilter}
),
count_cte AS (
SELECT COUNT(DISTINCT hash) AS total_count
FROM cte
),
final_select AS (
SELECT DISTINCT ON (hash)
id,
"toMergeId",
"primaryDisplayName",
"primaryLogo",
"secondaryDisplayName",
"secondaryLogo",
"createdAt",
"similarity",
"primarySegmentId",
"secondarySegmentId"
FROM cte
ORDER BY hash, id
)
SELECT
"organizationsToMerge".id,
"organizationsToMerge"."toMergeId",
"organizationsToMerge"."primaryDisplayName",
"organizationsToMerge"."primaryLogo",
"organizationsToMerge"."secondaryDisplayName",
"organizationsToMerge"."secondaryLogo",
"organizationsToMerge"."primarySegmentId",
"organizationsToMerge"."secondarySegmentId",
count_cte."total_count",
"organizationsToMerge"."similarity"
FROM
final_select AS "organizationsToMerge",
count_cte
ORDER BY
${order}
LIMIT :limit OFFSET :offset
`,
{
replacements: {
segmentIds,
limit: args.limit,
offset: args.offset,
displayName: args?.filter?.displayName ? `${args.filter.displayName}%` : undefined,
mergeActionType: MergeActionType.ORG,
mergeActionStatus: MergeActionState.ERROR,
organizationId: args?.filter?.organizationId,
},