aggregatorUsageEvents.ts 42.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import logger from 'cozy-logger'
import { Client } from 'cozy-client'
import { runService } from './service'
import UsageEventService from 'services/usageEvent.service'
import ProfileService from 'services/profile.service'
import ConsumptionService from 'services/consumption.service'
import { FluidStatus, PerformanceIndicator, UsageEvent } from 'models'
import { UsageEventType } from 'enum/usageEvent.enum'
import { DateTime } from 'luxon'
import { toNumber, uniq } from 'lodash'
import FluidService from 'services/fluid.service'
import { FluidState, FluidType } from 'enum/fluid.enum'
import { getFluidType } from 'utils/utils'
import { TimeStep } from 'enum/timeStep.enum'
15
import EnvironmentService from 'services/environment.service'
16
17
18
19
import { DaccEvent } from 'enum/dacc.enum'
import { UsageEventProperties } from 'enum/usageEventProperties.enum'
import ChallengeService from 'services/challenge.service'
import { UserChallengeState } from 'enum/userChallenge.enum'
20
import ProfileTypeEntityService from 'services/profileTypeEntity.service'
21
import TermsService from 'services/terms.service'
22
import { WarmingType } from 'enum/profileType.enum'
Hugo SUBTIL's avatar
Hugo SUBTIL committed
23
import { FluidSlugType } from 'enum/fluidSlug.enum'
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

const log = logger.namespace('aggregatorUsageEvents')

interface AggregatorUsageEventsProps {
  client: Client
}

interface Indicator {
  createdBy: string
  measureName: string
  startDate: string
  value: number | null
  group1?: object
  group2?: object
  group3?: object
}

// Store all id of events read during the process
const readUsageEvents: UsageEvent[] = []

44
45
46
// Store error events
const errorEvent: { error: any; doctype: string }[] = []

47
48
49
50
51
const sendIndicator = async (
  indicator: Indicator,
  client: Client
): Promise<boolean> => {
  try {
52
    const environmentService = new EnvironmentService()
53
54
    log(
      'info',
55
      environmentService.isProduction()
56
57
58
        ? 'Sending data to dacc'
        : 'Sending data to dacc-dev'
    )
59

60
    // /!\ In order to test locally, please replace /remote/cc.cozycloud.dacc with http://localhost:8081
61
62
63
64
    await client
      .getStackClient()
      .fetchJSON(
        'POST',
65
        environmentService.isProduction()
66
67
68
69
70
71
72
73
74
75
          ? '/remote/cc.cozycloud.dacc'
          : '/remote/cc.cozycloud.dacc.dev',
        {
          data: JSON.stringify(indicator),
        }
      )
    return true
  } catch (error) {
    log(
      'error',
76
      `Error while sending indicator ${indicator.measureName} to remote doctype: ${error.message}`
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
    )
    throw error
  }
}

const reduceEvents = (
  events: UsageEvent[]
): { [key: string]: UsageEvent[] } => {
  return events.reduce(function(
    acc: {
      [key: string]: UsageEvent[]
    },
    event: UsageEvent
  ) {
    const key = `${event.eventDate.startOf('day').toString()}|${event.target}|${
      event.result
    }|${event.context}`
    if (!acc[key]) {
      acc[key] = []
    }
    acc[key].push(event)
    readUsageEvents.push(event)
    return acc
  }, {})
}

const sendAggregatedEventByDay = async (
  events: UsageEvent[],
  eventType: DaccEvent,
  client: Client,
  groupsKeys: { group1: string; group2?: string; group3?: string },
  groupsIndexes: number[],
  customValues?: (string | null)[]
) => {
  const reducedEvents = reduceEvents(events)
  for (const item of Object.keys(reducedEvents)) {
    const splitedKey = item.split('|')
    let group1 = {}
    let group2 = {}
    let group3 = {}
    if (
      groupsKeys.group1 &&
      (groupsIndexes[0] !== 0 || (customValues && customValues[0]))
    ) {
      group1 = {
        [groupsKeys.group1]:
          customValues && customValues[0]
            ? customValues[0]
            : splitedKey[groupsIndexes[0]],
      }
    }
    if (
      groupsKeys.group2 &&
      (groupsIndexes[1] !== 0 || (customValues && customValues[1]))
    ) {
      group2 = {
        [groupsKeys.group2]:
          customValues && customValues[1]
            ? customValues[1]
            : splitedKey[groupsIndexes[1]],
      }
    }
    if (
      groupsKeys.group3 &&
      (groupsIndexes[2] !== 0 || (customValues && customValues[2]))
    ) {
      group3 = {
        [groupsKeys.group3]:
          customValues && customValues[2]
            ? customValues[2]
            : splitedKey[groupsIndexes[2]],
      }
    }
    const indicator: Indicator = {
      createdBy: 'ecolyo',
      measureName: eventType,
      startDate: DateTime.fromISO(splitedKey[0]).toISODate(),
      value: reducedEvents[item].length,
      group1: group1,
      ...(Object.keys(group2).length > 0 && { group2: group2 }),
      ...(Object.keys(group3).length > 0 && { group3: group3 }),
    }
    const result = await sendIndicator(indicator, client)
    if (result) {
      readUsageEvents.push(...reducedEvents[item])
    }
  }
}

const handleQuizStars = async (events: UsageEvent[], client: Client) => {
  events.forEach(async event => {
    const indicator: Indicator = {
      createdBy: 'ecolyo',
      measureName: DaccEvent.QUIZ_STARS,
      startDate: event.startDate ? event.startDate.toISODate() : '',
      value: parseInt(event.result ? event.result : '0'),
      // eslint-disable-next-line @typescript-eslint/camelcase
      group1: { challenge_id: event.context ? event.context : '' },
      // eslint-disable-next-line @typescript-eslint/camelcase
      group2: { quiz_id: event.target ? event.target : '' },
    }
    const result = await sendIndicator(indicator, client)
    if (result) {
      readUsageEvents.push(event)
    }
  })
}

const calculSessionTime = async (events: UsageEvent[], client: Client) => {
  let startSessionDate: DateTime | null = null
  let isFirstConnection = false
  let navigationCount = 0
  for (const [index, event] of events.entries()) {
    if (event.type === UsageEventType.CONNECTION_EVENT) {
      if (
        startSessionDate &&
        index > 0 &&
        events[index - 1].type !== UsageEventType.CONNECTION_EVENT
      ) {
        const endDate = events[index - 1].eventDate
        const duration = endDate.diff(startSessionDate, ['seconds']).toObject()
          .seconds
        const sessionIndicator: Indicator = {
          createdBy: 'ecolyo',
          measureName: DaccEvent.SESSION_DURATION,
          startDate: startSessionDate.toISODate(),
          value: duration === undefined ? 0 : duration,
          // eslint-disable-next-line @typescript-eslint/camelcase
          group1: { number_pages: navigationCount.toString() },
          // eslint-disable-next-line @typescript-eslint/camelcase
          group2: { session_type: isFirstConnection ? 'first' : 'any' },
        }
        await sendIndicator(sessionIndicator, client)
        navigationCount = 0
      }
      startSessionDate = event.eventDate
      isFirstConnection =
        event.result && event.result === 'firstConnection' ? true : false
    } else if (event.type === UsageEventType.NAVIGATION_EVENT) {
      if (startSessionDate) {
        navigationCount += 1
      }
    } else if (index === events.length - 1) {
      if (startSessionDate) {
        const endDate = event.eventDate
        const duration = endDate.diff(startSessionDate, ['seconds']).toObject()
          .seconds
        const sessionIndicator: Indicator = {
          createdBy: 'ecolyo',
          measureName: DaccEvent.SESSION_DURATION,
          startDate: startSessionDate.toISODate(),
          value: duration === undefined ? 0 : duration,
          // eslint-disable-next-line @typescript-eslint/camelcase
          group1: { number_pages: navigationCount.toString() },
          // eslint-disable-next-line @typescript-eslint/camelcase
          group2: { session_type: isFirstConnection ? 'first' : 'any' },
        }
        await sendIndicator(sessionIndicator, client)
      }
    }
  }
}

const calculPeriodBetweenFirstConnectionAndFirstChallenge = async (
  events: UsageEvent[],
  firstConnectionEvent: UsageEvent,
  client: Client
) => {
  const challengeLaunchEvents: UsageEvent[] = events.filter(
    (event: UsageEvent) => event.type === UsageEventType.CHALLENGE_LAUNCH_EVENT
  )
  if (
    challengeLaunchEvents.length > 0 &&
    challengeLaunchEvents[0].target === 'CHALLENGE0001'
  ) {
    const periodIndicator: Indicator = {
      createdBy: 'ecolyo',
      measureName: DaccEvent.EVENT_DURATION,
      startDate: firstConnectionEvent.eventDate.toISODate(),
      value: challengeLaunchEvents[0].eventDate.diff(
        firstConnectionEvent.eventDate
      ).seconds,
      // eslint-disable-next-line @typescript-eslint/camelcase
      group1: { start_event: 'first_session' },
      // eslint-disable-next-line @typescript-eslint/camelcase
      group2: { end_event: 'first_challenge' },
263
      group3: { params: '' },
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
    }
    const result = await sendIndicator(periodIndicator, client)
    if (result) {
      readUsageEvents.push(challengeLaunchEvents[0])
    }
  }
}

const calculPeriodBetweenChallenge = async (
  events: UsageEvent[],
  client: Client
) => {
  const challengeLaunchEvents: UsageEvent[] = events.filter(
    (event: UsageEvent) => event.type === UsageEventType.CHALLENGE_LAUNCH_EVENT
  )
  if (challengeLaunchEvents.length > 0) {
    const allEndedChallengeEvents: UsageEvent[] = await UsageEventService.getEvents(
      client,
      {
        type: UsageEventType.CHALLENGE_END_EVENT,
      }
    )
    for (const event of challengeLaunchEvents) {
      if (event.target && event.target !== 'CHALLENGE0001') {
        const challengeId: number = toNumber(
          event.target.substr(event.target.length - 4)
        )
        const prevChallengeId = `CHALLENGE${(challengeId - 1)
          .toString()
          .padStart(4, '0')}`
        const previousEndedChallengeIndex: number = allEndedChallengeEvents.findIndex(
          (endedEvent: UsageEvent) => endedEvent.target === prevChallengeId
        )
        if (previousEndedChallengeIndex > -1) {
          const periodChallengeIndicator: Indicator = {
            createdBy: 'ecolyo',
            measureName: DaccEvent.EVENT_DURATION,
            startDate: allEndedChallengeEvents[
              previousEndedChallengeIndex
            ].eventDate.toISODate(),
            value: event.eventDate.diff(
              allEndedChallengeEvents[previousEndedChallengeIndex].eventDate
            ).seconds,
            // eslint-disable-next-line @typescript-eslint/camelcase
            group1: { start_event: 'first_session' },
            // eslint-disable-next-line @typescript-eslint/camelcase
            group2: { end_event: 'first_challenge' },
            group3: { params: event.target + ':' + prevChallengeId },
          }
          await sendIndicator(periodChallengeIndicator, client)
        }
      }
    }
  }
}

/**
 * Format a string with all konnectors in success state
 * @param konnectorfluidTypes FluidType[]
 * @returns string
 */
const getConnectedKonnectorSlug = (
  konnectorfluidTypes: FluidType[]
): string => {
  let slug = ''
  if (konnectorfluidTypes.includes(FluidType.ELECTRICITY)) {
    slug += 'electricity'
  }
  if (konnectorfluidTypes.includes(FluidType.GAS)) {
    if (slug.length > 0) {
      slug += ':'
    }
    slug += 'gas'
  }
  if (konnectorfluidTypes.includes(FluidType.WATER)) {
    if (slug.length > 0) {
      slug += ':'
    }
    slug += 'water'
  }
  return slug
}

const calculateConnectedKonnectorPerDay = async (client: Client) => {
  const fluidService: FluidService = new FluidService(client)
  const fluidStatus: FluidStatus[] = await fluidService.getFluidStatus()
  const connectedKonnectors = fluidStatus.filter(
    fluid => fluid.status === FluidState.DONE
  )
  log('info', 'calculateConnectedKonnectorPerDay')
  if (connectedKonnectors.length > 0) {
    const konnectorfluidTypes: FluidType[] = []
    for (const konnector of connectedKonnectors) {
      konnectorfluidTypes.push(konnector.fluidType)
    }
    const KonnectorConnectedPerDayIndicator: Indicator = {
      createdBy: 'ecolyo',
      measureName: DaccEvent.KONNECTOR_CONNECTED_PER_DAY,
      startDate: DateTime.local()
        .setZone('utc', {
          keepLocalTime: true,
        })
        .startOf('day')
        .toISODate(),
      value: connectedKonnectors.length,
      group1: { categories: getConnectedKonnectorSlug(konnectorfluidTypes) },
    }
    await sendIndicator(KonnectorConnectedPerDayIndicator, client)
  }
}

/**
 * Build indicator group string with handling of : ECS, heating for gas and electricity.
 *
 * @param client Client
 * @param fluidType FluidType
 * @returns Promise<string>
 */
const buildProfileWithFuildType = async (
  client: Client,
384
385
  fluidType: FluidType,
  monthToAggregate?: number
386
387
388
389
390
): Promise<string> => {
  let formatedProfile = ''
  const profile = await new ProfileService(client).getProfile()
  // If profile is not filled, return empty string

391
392
393
394
395
396
397
398
399
400
401
  if (profile && !profile.isProfileTypeCompleted) return formatedProfile
  const date = monthToAggregate
    ? DateTime.local()
        .setZone('utc', {
          keepLocalTime: true,
        })
        .set({ month: monthToAggregate })
    : null
  const profileType = await new ProfileTypeEntityService(client).getProfileType(
    date
  )
402
403
404
  if (fluidType === FluidType.ELECTRICITY) {
    if (
      profile &&
405
      profileType &&
406
      profileType.warmingFluid === WarmingType.ELECTRICITY
407
408
409
    ) {
      formatedProfile = 'chauffage élec'
    }
410
411
412
413
414
415
416
417
418
419
420
421
422
423
    if (
      profile &&
      profileType &&
      profileType.warmingFluid === WarmingType.WOOD
    ) {
      formatedProfile = 'chauffage bois'
    }
    if (
      profile &&
      profileType &&
      profileType.warmingFluid === WarmingType.FUEL
    ) {
      formatedProfile = 'chauffage fuel'
    }
424
425
    if (
      profile &&
426
427
      profileType &&
      profileType.hotWaterFluid === FluidType.ELECTRICITY
428
429
430
431
432
433
434
435
436
    ) {
      if (formatedProfile.length === 0) {
        formatedProfile = 'ECS'
      } else {
        formatedProfile += ':ECS'
      }
    }
    if (
      profile &&
437
438
      profileType &&
      profileType.cookingFluid === FluidType.ELECTRICITY
439
440
441
442
443
444
445
446
447
448
449
450
451
    ) {
      if (formatedProfile.length === 0) {
        formatedProfile = 'cuisine élec'
      } else {
        formatedProfile += ':cuisine élec'
      }
    }
    if (formatedProfile.length === 0) {
      return 'électricité spécifique'
    } else {
      return formatedProfile
    }
  } else if (fluidType === FluidType.GAS) {
452
453
454
455
456
    if (
      profile &&
      profileType &&
      profileType.warmingFluid === WarmingType.GAS
    ) {
457
458
      formatedProfile = 'chauffage gaz'
    }
459
    if (profile && profileType && profileType.hotWaterFluid === FluidType.GAS) {
460
461
462
463
464
465
      if (formatedProfile.length === 0) {
        formatedProfile = 'ECS'
      } else {
        formatedProfile += ':ECS'
      }
    }
466
    if (profile && profileType && profileType.cookingFluid === FluidType.GAS) {
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
      if (formatedProfile.length === 0) {
        formatedProfile = 'cuisine gaz'
      } else {
        formatedProfile += ':cuisine gaz'
      }
    }
    if (formatedProfile.length === 0) {
      return 'autre'
    } else {
      return formatedProfile
    }
  }
  return formatedProfile
}

const getConsumptionValue = async (
  client: Client,
484
485
  fluidType: FluidType[],
  monthToAggregate?: number
486
487
): Promise<PerformanceIndicator[]> => {
  const consumptionService = new ConsumptionService(client)
488
489
490
491
492
  const analysisDate = monthToAggregate
    ? DateTime.local()
        .setZone('utc', { keepLocalTime: true })
        .set({ month: monthToAggregate })
    : DateTime.local().setZone('utc', { keepLocalTime: true })
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
  const periods = {
    timePeriod: {
      startDate: analysisDate.minus({ month: 1 }).startOf('month'),
      endDate: analysisDate.minus({ month: 1 }).endOf('month'),
    },
    comparisonTimePeriod: {
      startDate: analysisDate.minus({ month: 2 }).startOf('month'),
      endDate: analysisDate.minus({ month: 2 }).endOf('month'),
    },
  }
  const fetchedPerformanceIndicators = await consumptionService.getPerformanceIndicators(
    periods.timePeriod,
    TimeStep.MONTH,
    fluidType,
    periods.comparisonTimePeriod
  )
  return fetchedPerformanceIndicators
}

/**
 * Send an indicator on the consumption variation in % for each fluid type.
 * @param client
 * @group [{ slug }, { seniority (in month) }, { profile (ECS, chauffage, etc...) }],
 */
517
518
519
520
const calculateConsumptionVariation = async (
  client: Client,
  monthToAggregate?: number
) => {
521
  log('info', `calculateConsumptionVariation`)
522
523
524
525
526
  const consumptionData = await getConsumptionValue(
    client,
    [FluidType.ELECTRICITY, FluidType.GAS, FluidType.WATER],
    monthToAggregate
  )
527
528
529
530
531
532
533
534
535
536
537
538
539
  for (const fluidType in [
    FluidType.ELECTRICITY,
    FluidType.GAS,
    FluidType.WATER,
  ]) {
    if (fluidType < FluidType.MULTIFLUID.toFixed()) {
      // Seniority process
      const [firstConnectionEvent] = await UsageEventService.getEvents(client, {
        type: UsageEventType.CONNECTION_EVENT,
        result: 'firstConnection',
      })

      if (firstConnectionEvent) {
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
        const seniority = 0
        // Seniority is set to 0, otherwise the indicator is too specific
        // monthToAggregate
        //   ? DateTime.local()
        //       .setZone('utc', {
        //         keepLocalTime: true,
        //       })
        //       .set({ month: monthToAggregate })
        //       .diff(firstConnectionEvent.eventDate, 'month')
        //       .get('month')
        //   : DateTime.local()
        //       .setZone('utc', {
        //         keepLocalTime: true,
        //       })
        //       .diff(firstConnectionEvent.eventDate, 'month')
        //       .get('month')
556

557
        const consumptionVariationIndicator: Indicator = {
558
559
          createdBy: 'ecolyo',
          measureName: DaccEvent.CONSUMPTION_VARIATION_MONTHLY,
560
561
562
563
564
565
566
567
568
569
570
571
572
573
          startDate: monthToAggregate
            ? DateTime.local()
                .setZone('utc', {
                  keepLocalTime: true,
                })
                .set({ month: monthToAggregate })
                .startOf('day')
                .toISODate()
            : DateTime.local()
                .setZone('utc', {
                  keepLocalTime: true,
                })
                .startOf('day')
                .toISODate(),
574
575
576
577
578
579
          value:
            consumptionData[fluidType] &&
            consumptionData[fluidType].percentageVariation
              ? consumptionData[fluidType].percentageVariation
              : 0, // in percent
          // eslint-disable-next-line @typescript-eslint/camelcase
Hugo SUBTIL's avatar
Hugo SUBTIL committed
580
          group1: { fluid_type: FluidType[fluidType].toLowerCase() },
581
          // eslint-disable-next-line @typescript-eslint/camelcase
582
          group2: { seniority: Math.round(seniority).toString() },
583
          group3: {
Hugo SUBTIL's avatar
Hugo SUBTIL committed
584
585
            // eslint-disable-next-line @typescript-eslint/camelcase
            fluid_usage: await buildProfileWithFuildType(
586
              client,
587
588
              getFluidType(FluidType[fluidType]),
              monthToAggregate
589
590
591
592
593
594
            ),
          },
        }

        // if user wasnt connected during current month, dont send indicator
        const events: UsageEvent[] = await UsageEventService.getEvents(client, {
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
          eventDate: monthToAggregate
            ? {
                $lt: DateTime.local()
                  .setZone('utc', {
                    keepLocalTime: true,
                  })
                  .set({ month: monthToAggregate })
                  .endOf('month')
                  .minus({ month: 1 })
                  .toString(),
                $gt: DateTime.local()
                  .setZone('utc', {
                    keepLocalTime: true,
                  })
                  .set({ month: monthToAggregate })
                  .startOf('month')
                  .minus({ month: 1 })
                  .toString(),
              }
            : {
                $lt: DateTime.local()
                  .setZone('utc', {
                    keepLocalTime: true,
                  })
                  .endOf('month')
                  .minus({ month: 1 })
                  .toString(),
                $gt: DateTime.local()
                  .setZone('utc', {
                    keepLocalTime: true,
                  })
                  .startOf('month')
                  .minus({ month: 1 })
                  .toString(),
              },
630
631
        })

632
        if (events.length > 0 && consumptionVariationIndicator.value !== 0) {
633
634
635
636
637
638
          log(
            'info',
            `Send variation indicator for ${monthToAggregate} : ${JSON.stringify(
              consumptionVariationIndicator
            )}`
          )
639
          await sendIndicator(consumptionVariationIndicator, client)
640
641
642
643
644
645
        }
      }
    }
  }
}

646
647
648
649
const sendConnectionCount = async (
  client: Client,
  monthToAggregate?: number
) => {
Hugo SUBTIL's avatar
Hugo SUBTIL committed
650
651
652
653
  log('info', `sendConnectionCount`)
  // Get daily connexion
  const events: UsageEvent[] = await UsageEventService.getEvents(client, {
    type: UsageEventType.CONNECTION_EVENT,
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
    eventDate: monthToAggregate
      ? {
          $lt: DateTime.local()
            .setZone('utc', {
              keepLocalTime: true,
            })
            .set({ month: monthToAggregate })
            .minus({ month: 1 })
            .endOf('month')
            .toString(),
          $gt: DateTime.local()
            .setZone('utc', {
              keepLocalTime: true,
            })
            .set({ month: monthToAggregate })
            .minus({ month: 1 })
            .startOf('month')
            .toString(),
        }
      : {
          $lt: DateTime.local()
            .setZone('utc', {
              keepLocalTime: true,
            })
            .endOf('month')
            .minus({ month: 1 })
            .toString(),
          $gt: DateTime.local()
            .setZone('utc', {
              keepLocalTime: true,
            })
            .startOf('month')
            .minus({ month: 1 })
            .toString(),
        },
Hugo SUBTIL's avatar
Hugo SUBTIL committed
689
690
  })

691
  let uniqueDates = 0
Hugo SUBTIL's avatar
Hugo SUBTIL committed
692
693
  // If there is at least one connection, filter each unique connection in order to send it
  if (events.length > 0) {
694
    uniqueDates = events
Hugo SUBTIL's avatar
Hugo SUBTIL committed
695
      .map(s => s.eventDate.day)
696
697
      .filter((s, i, a) => a.indexOf(s) == i).length
  }
Hugo SUBTIL's avatar
Hugo SUBTIL committed
698

699
700
701
  const connectionMonthly: Indicator = {
    createdBy: 'ecolyo',
    measureName: DaccEvent.CONNECTION_COUNT_MONTHLY,
702
703
704
705
706
707
708
709
710
711
712
713
714
715
    startDate: monthToAggregate
      ? DateTime.local()
          .setZone('utc', {
            keepLocalTime: true,
          })
          .set({ month: monthToAggregate })
          .startOf('day')
          .toISODate()
      : DateTime.local()
          .setZone('utc', {
            keepLocalTime: true,
          })
          .startOf('day')
          .toISODate(),
716
    value: uniqueDates,
Hugo SUBTIL's avatar
Hugo SUBTIL committed
717
  }
718
719
720
721
722
723
  log(
    'info',
    `Send connectionMonthly indicator for ${monthToAggregate} : ${JSON.stringify(
      connectionMonthly
    )}`
  )
724
  await sendIndicator(connectionMonthly, client)
Hugo SUBTIL's avatar
Hugo SUBTIL committed
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
}

const sendProfileCount = async (client: Client) => {
  log('info', `sendProfileCount`)
  // Get profile setEvents
  const events: UsageEvent[] = await UsageEventService.getEvents(client, {
    type: UsageEventType.PROFILE_SET_EVENT,
  })

  // If there is at least one connection, filter each unique connection in order to send it
  if (events.length > 0) {
    const profileSet: Indicator = {
      createdBy: 'ecolyo',
      measureName: DaccEvent.PROFILE_COUNT_MONTHLY,
      startDate: DateTime.local()
        .setZone('utc', {
          keepLocalTime: true,
        })
        .startOf('day')
        .toISODate(),
      value: events.length,
    }
    await sendIndicator(profileSet, client)
  }
}

751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
const sendEmailSubscription = async (client: Client) => {
  log('info', `sendEmailSubscription`)
  const profile = await new ProfileService(client).getProfile()
  if (profile && profile.sendAnalysisNotification) {
    const cameBackFromEmail: Indicator = {
      createdBy: 'ecolyo',
      measureName: DaccEvent.SUMMARY_SUBSCRIPTION_MONTHLY,
      startDate: DateTime.local()
        .setZone('utc', {
          keepLocalTime: true,
        })
        .startOf('day')
        .toISODate(),
      value: profile.sendAnalysisNotification ? 1 : 0,
      // eslint-disable-next-line @typescript-eslint/camelcase
      group1: { event_type: 'subscribed' },
    }
    await sendIndicator(cameBackFromEmail, client)
  }
}

772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
/**
 * Send indicator to dacc, if user has half-hour data.
 * @param client CozyClient
 */
const sendHalfHourConsumption = async (client: Client) => {
  log('info', `sendHalfHourConsumption`)
  const consumptionService = new ConsumptionService(client)

  const data = await consumptionService.getLastHourData(
    client,
    DateTime.local()
      .minus({ month: 1 })
      .startOf('month').month
  )

  const halfHourConsumption: Indicator = {
    createdBy: 'ecolyo',
789
790
791
792
793
    measureName: DaccEvent.FLUID_DATA_GRANULARITY,
    // eslint-disable-next-line @typescript-eslint/camelcase
    group1: { fluid_type: 'electricity' },
    // eslint-disable-next-line @typescript-eslint/camelcase
    group2: { granularity: 'half_hour' },
794
795
796
797
798
799
800
801
802
803
804
    startDate: DateTime.local()
      .setZone('utc', {
        keepLocalTime: true,
      })
      .startOf('day')
      .toISODate(),
    value: data && data.length > 0 ? 1 : 0,
  }
  await sendIndicator(halfHourConsumption, client)
}

Hugo SUBTIL's avatar
Hugo SUBTIL committed
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
/**
 * Send indicator to dacc, each month send if user has succed to configure a connector with the number of try.
 * @param client CozyClient
 */
const sendKonnectorEvents = async (client: Client) => {
  log('info', `sendKonnectorEvents`)
  const slugs = Object.values(FluidSlugType)
  const today = DateTime.local().setZone('utc', {
    keepLocalTime: true,
  })
  slugs.forEach(async slug => {
    let successEvents: UsageEvent[] = await UsageEventService.getEvents(
      client,
      {
        type: UsageEventType.KONNECTOR_CONNECT_EVENT,
        target: slug,
        result: 'success',
        eventDate: {
          $lte: today
            .endOf('month')
            .minus({ month: 1 })
            .toString(),
          $gte: today
            .startOf('month')
            .minus({ month: 1 })
            .toString(),
        },
      },
      true
    )

    // If there is no success in month, send nothing
    if (successEvents && successEvents.length > 0) {
      // Get all success events
      successEvents = await UsageEventService.getEvents(
        client,
        {
          type: UsageEventType.KONNECTOR_CONNECT_EVENT,
          target: slug,
          result: 'success',
        },
        true
      )
      // Remove success from other month, they should have been already proceced
      // successEvents.length = successEventsOfCurrentMonth

      for (let index = 0; index < successEvents.length; index++) {
        const successEvent = successEvents[index]
        let query = null

        // If there is a previous value take it as reference for the query
        // Else get all previous because it's the first one
        if (index + 1 < successEvents.length) {
          query = {
            type: UsageEventType.KONNECTOR_CONNECT_EVENT,
            target: slug,
            result: 'error',
            eventDate: {
              $lte: successEvent.eventDate,
              $gte: successEvents[index + 1].eventDate,
            },
          }
        } else {
          query = {
            type: UsageEventType.KONNECTOR_CONNECT_EVENT,
            target: slug,
            result: 'error',
            eventDate: {
              $lte: successEvent.eventDate,
            },
          }
        }

        const allConnectionEvents: UsageEvent[] = await UsageEventService.getEvents(
          client,
          query,
          true
        )

        const konnectorSuccess: Indicator = {
          createdBy: 'ecolyo',
          measureName: DaccEvent.PARTNER_SUCESS_MONTHLY,
          // eslint-disable-next-line @typescript-eslint/camelcase
          group1: { fluid_type: slug },
          startDate: DateTime.local()
            .setZone('utc', {
              keepLocalTime: true,
            })
            .startOf('day')
            .toISODate(),
          value: allConnectionEvents.length + 1, //+1 in order to count the success
        }
        // Send indicator if it's in current month
        if (successEvent.eventDate.month === today.minus({ month: 1 }).month) {
          await sendIndicator(konnectorSuccess, client)
        }
      }
    }
  })
}

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
/**
 * Send the total number of partner connection attempts and the number of success
 * @param client CozyClient
 */
const sendKonnectorAttemptsMonthly = async (client: Client) => {
  log('info', `sendkonnectorAttemptsMonthly`)
  const slugs = Object.values(FluidSlugType)
  const today = DateTime.local().setZone('utc', {
    keepLocalTime: true,
  })
  // Count the number of connection and refresh events
  slugs.forEach(async slug => {
    const konnectorEvents: UsageEvent[] = await UsageEventService.getEvents(
      client,
      {
        type: UsageEventType.KONNECTOR_ATTEMPT_EVENT,
        target: slug,
        eventDate: {
          $lte: today
            .endOf('month')
            .minus({ month: 1 })
            .toString(),
          $gte: today
            .startOf('month')
            .minus({ month: 1 })
            .toString(),
        },
      },
      true
    )
    log('info', ` : ${JSON.stringify(konnectorEvents)}`)

    // Check if there is a success (will be false or true since the event is triggered only for the first connexion)
    const success: boolean =
      konnectorEvents.filter(event => event.result == 'success').length > 0

    const konnectorAttempts: Indicator = {
      createdBy: 'ecolyo',
      measureName: DaccEvent.UNINITIALIZED_KONNECTOR_ATTEMPTS_MONTHLY,
      // eslint-disable-next-line @typescript-eslint/camelcase
      group1: { slug: slug },
      group2: { success: success },
      startDate: DateTime.local()
        .setZone('utc', {
          keepLocalTime: true,
        })
        .startOf('day')
        .toISODate(),
      value: konnectorEvents.length,
    }
    // Send indicator if there is connection events
    if (konnectorEvents.length > 0) {
      await sendIndicator(konnectorAttempts, client)
    }
  })
}

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
const aggregateEvents = async (
  events: UsageEvent[],
  eventType: UsageEventType,
  firstConnectionEvent: UsageEvent,
  client: Client
) => {
  let reducedEvents = null // Used to store reducedEvents during calculation
  switch (eventType) {
    case UsageEventType.CONNECTION_EVENT:
      await sendAggregatedEventByDay(
        events,
        DaccEvent.CONNECTION_COUNT_DAILY,
        client,
        { group1: 'device' },
        [UsageEventProperties.CONTEXT]
      )
      break
    case UsageEventType.KONNECTOR_CONNECT_EVENT:
      await sendAggregatedEventByDay(
        events,
        DaccEvent.KONNECTOR_EVENT_DAILY,
        client,
        { group1: 'slug', group2: 'event_type', group3: 'status' },
        [UsageEventProperties.TARGET, 0, UsageEventProperties.RESULT],
        [null, 'connexion', null]
      )
      break
    case UsageEventType.KONNECTOR_REFRESH_EVENT:
      await sendAggregatedEventByDay(
        events,
        DaccEvent.KONNECTOR_EVENT_DAILY,
        client,
        { group1: 'slug', group2: 'event_type', group3: 'status' },
        [UsageEventProperties.TARGET, 0, UsageEventProperties.RESULT],
        [null, 'refresh', null]
      )
      break
    case UsageEventType.NAVIGATION_EVENT: