-
Notifications
You must be signed in to change notification settings - Fork 733
Expand file tree
/
Copy pathintegrationRepository.ts
More file actions
684 lines (566 loc) · 19 KB
/
integrationRepository.ts
File metadata and controls
684 lines (566 loc) · 19 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
import lodash from 'lodash'
import Sequelize, { QueryTypes } from 'sequelize'
import { captureApiChange, integrationConnectAction } from '@crowd/audit-logs'
import { Error404 } from '@crowd/common'
import {
fetchGlobalIntegrations,
fetchGlobalIntegrationsCount,
fetchGlobalIntegrationsStatusCount,
fetchGlobalNotConnectedIntegrations,
fetchGlobalNotConnectedIntegrationsCount,
} from '@crowd/data-access-layer/src/integrations'
import { IntegrationRunState, PlatformType } from '@crowd/types'
import SequelizeFilterUtils from '../utils/sequelizeFilterUtils'
import { IRepositoryOptions } from './IRepositoryOptions'
import AuditLogRepository from './auditLogRepository'
import QueryParser from './filters/queryParser'
import { QueryOutput } from './filters/queryTypes'
import SequelizeRepository from './sequelizeRepository'
const { Op } = Sequelize
const log: boolean = false
class IntegrationRepository {
static async create(data, options: IRepositoryOptions) {
const currentUser = SequelizeRepository.getCurrentUser(options)
const tenant = SequelizeRepository.getCurrentTenant(options)
const transaction = SequelizeRepository.getTransaction(options)
const segment = SequelizeRepository.getStrictlySingleActiveSegment(options)
const toInsert = {
...lodash.pick(data, [
'platform',
'status',
'limitCount',
'limitLastResetAt',
'token',
'refreshToken',
'settings',
'integrationIdentifier',
'importHash',
'emailSentAt',
]),
segmentId: segment.id,
tenantId: tenant.id,
createdById: currentUser.id,
updatedById: currentUser.id,
}
const record = await options.database.integration.create(toInsert, {
transaction,
})
await captureApiChange(
options,
integrationConnectAction(record.id, async (captureState) => {
captureState(toInsert)
}),
)
await this._createAuditLog(AuditLogRepository.CREATE, record, data, options)
return this.findById(record.id, options)
}
static async update(id, data, options: IRepositoryOptions) {
const currentUser = SequelizeRepository.getCurrentUser(options)
const transaction = SequelizeRepository.getTransaction(options)
const currentTenant = SequelizeRepository.getCurrentTenant(options)
let record = await options.database.integration.findOne({
where: {
id,
tenantId: currentTenant.id,
segmentId: SequelizeRepository.getSegmentIds(options),
},
transaction,
})
if (!record) {
throw new Error404()
}
record = await record.update(
{
...lodash.pick(data, [
'platform',
'status',
'limitCount',
'limitLastResetAt',
'token',
'refreshToken',
'settings',
'integrationIdentifier',
'importHash',
'emailSentAt',
]),
updatedById: currentUser.id,
},
{
transaction,
},
)
await this._createAuditLog(AuditLogRepository.UPDATE, record, data, options)
return this.findById(record.id, options)
}
static async destroy(id, options: IRepositoryOptions) {
const transaction = SequelizeRepository.getTransaction(options)
const currentTenant = SequelizeRepository.getCurrentTenant(options)
const record = await options.database.integration.findOne({
where: {
id,
tenantId: currentTenant.id,
},
transaction,
})
if (!record) {
throw new Error404()
}
await record.destroy({
transaction,
})
// also mark integration runs as deleted
const seq = SequelizeRepository.getSequelize(options)
await seq.query(
`update integration.runs set state = :newState
where "integrationId" = :integrationId and state in (:delayed, :pending, :processing)`,
{
replacements: {
newState: IntegrationRunState.INTEGRATION_DELETED,
delayed: IntegrationRunState.DELAYED,
pending: IntegrationRunState.PENDING,
processing: IntegrationRunState.PROCESSING,
integrationId: id,
},
transaction,
},
)
await this._createAuditLog(AuditLogRepository.DELETE, record, record, options)
}
static async findAllByPlatform(platform, options: IRepositoryOptions) {
const transaction = SequelizeRepository.getTransaction(options)
const include = []
const currentTenant = SequelizeRepository.getCurrentTenant(options)
const records = await options.database.integration.findAll({
where: {
platform,
tenantId: currentTenant.id,
},
include,
transaction,
})
return records.map((record) => record.get({ plain: true }))
}
static async findByPlatform(platform, options: IRepositoryOptions) {
const transaction = SequelizeRepository.getTransaction(options)
const segment = SequelizeRepository.getStrictlySingleActiveSegment(options)
const include = []
const currentTenant = SequelizeRepository.getCurrentTenant(options)
const record = await options.database.integration.findOne({
where: {
platform,
tenantId: currentTenant.id,
segmentId: segment.id,
},
include,
transaction,
})
if (!record) {
throw new Error404()
}
return this._populateRelations(record)
}
static async findActiveIntegrationByPlatform(platform: PlatformType, tenantId: string) {
const options = await SequelizeRepository.getDefaultIRepositoryOptions()
const record = await options.database.integration.findOne({
where: {
platform,
tenantId,
},
})
if (!record) {
throw new Error404()
}
return this._populateRelations(record)
}
/**
* Find all active integrations for a platform
* @param platform The platform we want to find all active integrations for
* @returns All active integrations for the platform
*/
static async findAllActive(platform: string, page: number, perPage: number): Promise<any[]> {
const options = await SequelizeRepository.getDefaultIRepositoryOptions()
const records = await options.database.integration.findAll({
where: {
status: 'done',
platform,
},
limit: perPage,
offset: (page - 1) * perPage,
order: [['id', 'ASC']],
})
if (!records) {
throw new Error404()
}
return Promise.all(records.map((record) => this._populateRelations(record)))
}
static async findByStatus(
status: string,
page: number,
perPage: number,
options: IRepositoryOptions,
): Promise<any[]> {
const query = `
select * from integrations where status = :status
limit ${perPage} offset ${(page - 1) * perPage}
`
const seq = SequelizeRepository.getSequelize(options)
const transaction = SequelizeRepository.getTransaction(options)
const integrations = await seq.query(query, {
replacements: {
status,
},
type: QueryTypes.SELECT,
transaction,
})
return integrations as any[]
}
/**
* Find an integration using the integration identifier and a platform.
* Tenant not needed.
* @param identifier The integration identifier
* @returns The integration object
*/
// TODO: Test
static async findByIdentifier(identifier: string, platform: string): Promise<Array<Object>> {
const options = await SequelizeRepository.getDefaultIRepositoryOptions()
const record = await options.database.integration.findOne({
where: {
integrationIdentifier: identifier,
platform,
deletedAt: null,
},
})
if (!record) {
throw new Error404()
}
return this._populateRelations(record)
}
static async findById(id, options: IRepositoryOptions) {
const transaction = SequelizeRepository.getTransaction(options)
const include = []
const currentTenant = SequelizeRepository.getCurrentTenant(options)
const record = await options.database.integration.findOne({
where: {
id,
tenantId: currentTenant.id,
},
include,
transaction,
})
if (!record) {
throw new Error404()
}
return this._populateRelations(record)
}
static async filterIdInTenant(id, options: IRepositoryOptions) {
return lodash.get(await this.filterIdsInTenant([id], options), '[0]', null)
}
static async filterIdsInTenant(ids, options: IRepositoryOptions) {
if (!ids || !ids.length) {
return []
}
const currentTenant = SequelizeRepository.getCurrentTenant(options)
const where = {
id: {
[Op.in]: ids,
},
tenantId: currentTenant.id,
}
const records = await options.database.integration.findAll({
attributes: ['id'],
where,
})
return records.map((record) => record.id)
}
static async count(filter, options: IRepositoryOptions) {
const transaction = SequelizeRepository.getTransaction(options)
const tenant = SequelizeRepository.getCurrentTenant(options)
return options.database.integration.count({
where: {
...filter,
tenantId: tenant.id,
},
transaction,
})
}
/**
* Finds global integrations based on the provided parameters.
*
* @param {string} tenantId - The ID of the tenant for which integrations are to be found.
* @param {Object} filters - An object containing various filter options.
* @param {string} [filters.platform=null] - The platform to filter integrations by.
* @param {string[]} [filters.status=['done']] - The status of the integrations to be filtered.
* @param {string} [filters.query=''] - The search query to filter integrations.
* @param {number} [filters.limit=20] - The maximum number of integrations to return.
* @param {number} [filters.offset=0] - The offset for pagination.
* @param {IRepositoryOptions} options - The repository options for querying.
* @returns {Promise<Object>} The result containing the rows of integrations and metadata about the query.
*/
static async findGlobalIntegrations(
{ platform = null, status = ['done'], query = '', limit = 20, offset = 0 },
options: IRepositoryOptions,
) {
const tenantId = options.currentTenant.id
const qx = SequelizeRepository.getQueryExecutor(options)
if (status.includes('not-connected')) {
const rows = await fetchGlobalNotConnectedIntegrations(
qx,
tenantId,
platform,
query,
limit,
offset,
)
const [result] = await fetchGlobalNotConnectedIntegrationsCount(qx, tenantId, platform, query)
return { rows, count: +result.count, limit: +limit, offset: +offset }
}
const rows = await fetchGlobalIntegrations(qx, tenantId, status, platform, query, limit, offset)
const [result] = await fetchGlobalIntegrationsCount(qx, tenantId, status, platform, query)
return { rows, count: +result.count, limit: +limit, offset: +offset }
}
/**
* Retrieves the count of global integrations statuses for a specified tenant and platform.
* This method aggregates the count of different integration statuses including a 'not-connected' status.
*
* @param {Object} param1 - The optional parameters.
* @param {string|null} [param1.platform=null] - The platform to filter the integrations. Default is null.
* @param {IRepositoryOptions} options - The options for the repository operations.
* @return {Promise<Array<Object>>} A promise that resolves to an array of objects containing the statuses and their counts.
*/
static async findGlobalIntegrationsStatusCount({ platform = null }, options: IRepositoryOptions) {
const tenantId = options.currentTenant.id
const qx = SequelizeRepository.getQueryExecutor(options)
const [result] = await fetchGlobalNotConnectedIntegrationsCount(qx, tenantId, platform, '')
const rows = await fetchGlobalIntegrationsStatusCount(qx, tenantId, platform)
return [...rows, { status: 'not-connected', count: +result.count }]
}
static async findAndCountAll(
{ filter = {} as any, advancedFilter = null as any, limit = 0, offset = 0, orderBy = '' },
options: IRepositoryOptions,
) {
const include = []
// If the advanced filter is empty, we construct it from the query parameter filter
if (!advancedFilter) {
advancedFilter = { and: [] }
if (filter.id) {
advancedFilter.and.push({
id: filter.id,
})
}
if (filter.platform) {
advancedFilter.and.push({
platform: filter.platform,
})
}
if (filter.status) {
advancedFilter.and.push({
status: filter.status,
})
}
if (filter.limitCountRange) {
const [start, end] = filter.limitCountRange
if (start !== undefined && start !== null && start !== '') {
advancedFilter.and.push({
limitCount: {
gte: start,
},
})
}
if (end !== undefined && end !== null && end !== '') {
advancedFilter.and.push({
limitCount: {
lte: end,
},
})
}
}
if (filter.limitLastResetAtRange) {
const [start, end] = filter.limitLastResetAtRange
if (start !== undefined && start !== null && start !== '') {
advancedFilter.and.push({
limitLastResetAt: {
gte: start,
},
})
}
if (end !== undefined && end !== null && end !== '') {
advancedFilter.and.push({
limitLastResetAt: {
lte: end,
},
})
}
}
if (filter.integrationIdentifier) {
advancedFilter.and.push({
integrationIdentifier: filter.integrationIdentifier,
})
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange
if (start !== undefined && start !== null && start !== '') {
advancedFilter.and.push({
createdAt: {
gte: start,
},
})
}
if (end !== undefined && end !== null && end !== '') {
advancedFilter.and.push({
createdAt: {
lte: end,
},
})
}
}
}
const parser = new QueryParser(
{
nestedFields: {
sentiment: 'sentiment.sentiment',
},
},
options,
)
const parsed: QueryOutput = parser.parse({
filter: advancedFilter,
orderBy: orderBy || ['createdAt_DESC'],
limit,
offset,
})
let {
rows,
count, // eslint-disable-line prefer-const
} = await options.database.integration.findAndCountAll({
...(parsed.where ? { where: parsed.where } : {}),
...(parsed.having ? { having: parsed.having } : {}),
order: parsed.order,
limit: limit ? parsed.limit : undefined,
offset: offset ? parsed.offset : undefined,
include,
transaction: SequelizeRepository.getTransaction(options),
})
rows = await this._populateRelationsForRows(rows)
// Some integrations (i.e GitHub, Discord, Discourse, Groupsio) receive new data via webhook post-onboarding.
// We track their last processedAt separately, and not using updatedAt.
const seq = SequelizeRepository.getSequelize(options)
const integrationIds = rows.map((row) => row.id)
if (integrationIds.length > 0) {
const webhookQuery = `
SELECT "integrationId", MAX("processedAt") AS "webhookProcessedAt"
FROM "incomingWebhooks"
WHERE "integrationId" IN (:integrationIds) AND state = 'PROCESSED'
GROUP BY "integrationId"
`
const runQuery = `
SELECT "integrationId", MAX("processedAt") AS "runProcessedAt"
FROM integration.runs
WHERE "integrationId" IN (:integrationIds)
GROUP BY "integrationId"
`
const [webhookResults, runResults] = await Promise.all([
seq.query(webhookQuery, {
replacements: { integrationIds },
type: QueryTypes.SELECT,
transaction: SequelizeRepository.getTransaction(options),
}),
seq.query(runQuery, {
replacements: { integrationIds },
type: QueryTypes.SELECT,
transaction: SequelizeRepository.getTransaction(options),
}),
])
const processedAtMap = integrationIds.reduce((map, id) => {
const webhookResult: any = webhookResults.find(
(r: { integrationId: string }) => r.integrationId === id,
)
const runResult: any = runResults.find(
(r: { integrationId: string }) => r.integrationId === id,
)
map[id] = {
webhookProcessedAt: webhookResult ? webhookResult.webhookProcessedAt : null,
runProcessedAt: runResult ? runResult.runProcessedAt : null,
}
return map
}, {})
rows.forEach((row) => {
const processedAt = processedAtMap[row.id]
// Use the latest processedAt from either webhook or run, or fall back to updatedAt
row.lastProcessedAt = processedAt
? new Date(
Math.max(
processedAt.webhookProcessedAt
? new Date(processedAt.webhookProcessedAt).getTime()
: 0,
processedAt.runProcessedAt ? new Date(processedAt.runProcessedAt).getTime() : 0,
new Date(row.updatedAt).getTime(),
),
)
: row.updatedAt
})
}
return { rows, count, limit: parsed.limit, offset: parsed.offset }
}
static async findAllAutocomplete(query, limit, options: IRepositoryOptions) {
const tenant = SequelizeRepository.getCurrentTenant(options)
const whereAnd: Array<any> = [
{
tenantId: tenant.id,
},
]
if (query) {
whereAnd.push({
[Op.or]: [
{ id: SequelizeFilterUtils.uuid(query) },
{
[Op.and]: SequelizeFilterUtils.ilikeIncludes('integration', 'platform', query),
},
],
})
}
const where = { [Op.and]: whereAnd }
const records = await options.database.integration.findAll({
attributes: ['id', 'platform'],
where,
limit: limit ? Number(limit) : undefined,
order: [['platform', 'ASC']],
})
return records.map((record) => ({
id: record.id,
label: record.platform,
}))
}
static async _createAuditLog(action, record, data, options: IRepositoryOptions) {
if (log) {
let values = {}
if (data) {
values = {
...record.get({ plain: true }),
}
}
await AuditLogRepository.log(
{
entityName: 'integration',
entityId: record.id,
action,
values,
},
options,
)
}
}
static async _populateRelationsForRows(rows) {
if (!rows) {
return rows
}
return Promise.all(rows.map((record) => this._populateRelations(record)))
}
static async _populateRelations(record) {
if (!record) {
return record
}
const output = record.get({ plain: true })
return output
}
}
export default IntegrationRepository