aggregatorUsageEvents.ts 30.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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'
import EnvironementService from 'services/environement.service'
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
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

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[] = []

41
42
43
// Store error events
const errorEvent: { error: any; doctype: string }[] = []

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
const sendIndicator = async (
  indicator: Indicator,
  client: Client
): Promise<boolean> => {
  try {
    const environementService = new EnvironementService()
    log(
      'info',
      environementService.isProduction()
        ? 'Sending data to dacc'
        : 'Sending data to dacc-dev'
    )
    await client
      .getStackClient()
      .fetchJSON(
        'POST',
        environementService.isProduction()
          ? '/remote/cc.cozycloud.dacc'
          : '/remote/cc.cozycloud.dacc.dev',
        {
          data: JSON.stringify(indicator),
        }
      )
    return true
  } catch (error) {
    log(
      'error',
      `Error while sending indicator to remote doctype: ${error.message}`
    )
    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' },
    }
    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,
  fluidType: FluidType
): Promise<string> => {
  let formatedProfile = ''
  const profile = await new ProfileService(client).getProfile()
  // If profile is not filled, return empty string
  if (profile && !profile.isProfileTypeCompleted) return formatedProfile

385
386
387
  const profileType = await new ProfileTypeEntityService(
    client
  ).getProfileType()
388
389
390
  if (fluidType === FluidType.ELECTRICITY) {
    if (
      profile &&
391
392
      profileType &&
      profileType.warmingFluid === FluidType.ELECTRICITY
393
394
395
396
397
    ) {
      formatedProfile = 'chauffage élec'
    }
    if (
      profile &&
398
399
      profileType &&
      profileType.hotWaterFluid === FluidType.ELECTRICITY
400
401
402
403
404
405
406
407
408
    ) {
      if (formatedProfile.length === 0) {
        formatedProfile = 'ECS'
      } else {
        formatedProfile += ':ECS'
      }
    }
    if (
      profile &&
409
410
      profileType &&
      profileType.cookingFluid === FluidType.ELECTRICITY
411
412
413
414
415
416
417
418
419
420
421
422
423
    ) {
      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) {
424
    if (profile && profileType && profileType.warmingFluid === FluidType.GAS) {
425
426
      formatedProfile = 'chauffage gaz'
    }
427
    if (profile && profileType && profileType.hotWaterFluid === FluidType.GAS) {
428
429
430
431
432
433
      if (formatedProfile.length === 0) {
        formatedProfile = 'ECS'
      } else {
        formatedProfile += ':ECS'
      }
    }
434
    if (profile && profileType && profileType.cookingFluid === FluidType.GAS) {
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
      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,
  fluidType: FluidType[]
): Promise<PerformanceIndicator[]> => {
  const consumptionService = new ConsumptionService(client)
  const analysisDate = DateTime.local().setZone('utc', { keepLocalTime: true })
  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...) }],
 */
const calculateConsumptionVariation = async (client: Client) => {
  log('info', `calculateConsumptionVariation`)
  const consumptionData = await getConsumptionValue(client, [
    FluidType.ELECTRICITY,
    FluidType.GAS,
    FluidType.WATER,
  ])
  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) {
        const seniority = DateTime.local()
          .setZone('utc', {
            keepLocalTime: true,
          })
          .diff(firstConnectionEvent.eventDate).months

506
        const consumptionVariationIndicator: Indicator = {
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
          createdBy: 'ecolyo',
          measureName: DaccEvent.CONSUMPTION_VARIATION_MONTHLY,
          startDate: DateTime.local()
            .setZone('utc', {
              keepLocalTime: true,
            })
            .startOf('day')
            .toISODate(),
          value:
            consumptionData[fluidType] &&
            consumptionData[fluidType].percentageVariation
              ? consumptionData[fluidType].percentageVariation
              : 0, // in percent
          // eslint-disable-next-line @typescript-eslint/camelcase
          group1: { slug: FluidType[fluidType].toLowerCase() },
          // eslint-disable-next-line @typescript-eslint/camelcase
          group2: { seniority: seniority.toString() },
          group3: {
            profile: await buildProfileWithFuildType(
              client,
              getFluidType(FluidType[fluidType])
            ),
          },
        }

        // if user wasnt connected during current month, dont send indicator
        const events: UsageEvent[] = await UsageEventService.getEvents(client, {
          eventDate: {
            $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(),
          },
        })

552
553
        if (events.length > 0 || consumptionVariationIndicator.value !== 0) {
          await sendIndicator(consumptionVariationIndicator, client)
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
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)
  }
}

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
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:
      await sendAggregatedEventByDay(
        events,
        DaccEvent.NAVIGATION_COUNT_DAILY,
        client,
        { group1: 'page' },
        [UsageEventProperties.TARGET]
      )
      break
    case UsageEventType.PROFILE_SET_EVENT:
      await sendAggregatedEventByDay(
        events,
        DaccEvent.NAVIGATION_ACTION_DAILY,
        client,
        { group1: 'page', group2: 'action', group3: 'params' },
        [0, 0, 0],
        ['profile', 'profile_completed', '']
      )
      break
    case UsageEventType.CONSUMPTION_COMPARE_EVENT:
      reducedEvents = reduceEvents(events)
      for (const item of Object.keys(reducedEvents)) {
        const splitedKey = item.split('|')
        const indicator: Indicator = {
          createdBy: 'ecolyo',
          measureName: DaccEvent.NAVIGATION_ACTION_DAILY,
          startDate: DateTime.fromISO(splitedKey[0]).toISODate(),
          value: reducedEvents[item].length,
          group1: {
            page: 'consumption',
          },
          group2: {
            feature: 'compare',
          },
          group3: {
            params:
              splitedKey[UsageEventProperties.CONTEXT] +
              ':' +
              splitedKey[UsageEventProperties.TARGET],
          },
        }
        const result = await sendIndicator(indicator, client)
        if (result) {
          readUsageEvents.push(...reducedEvents[item])
        }
      }
      break
    case UsageEventType.CONSUMPTION_CHANGE_TIMESTEP_EVENT:
      reducedEvents = reduceEvents(events)
      for (const item of Object.keys(reducedEvents)) {
        const splitedKey = item.split('|')
        const indicator: Indicator = {
          createdBy: 'ecolyo',
          measureName: DaccEvent.NAVIGATION_ACTION_DAILY,
          startDate: DateTime.fromISO(splitedKey[0]).toISODate(),
          value: reducedEvents[item].length,
          group1: {
            page: 'consumption',
          },
          group2: {
            feature: 'changestep',
          },
          group3: {
            params:
              splitedKey[UsageEventProperties.CONTEXT] +
              ':' +
              splitedKey[UsageEventProperties.TARGET],
          },
        }
        const result = await sendIndicator(indicator, client)
        if (result) {
          readUsageEvents.push(...reducedEvents[item])
        }
      }
      break
    case UsageEventType.ACTION_CHANGE_EVENT:
      reducedEvents = reduceEvents(events)
      for (const item of Object.keys(reducedEvents)) {
        const splitedKey = item.split('|')
        const indicator: Indicator = {
          createdBy: 'ecolyo',
          measureName: DaccEvent.NAVIGATION_ACTION_DAILY,
          startDate: DateTime.fromISO(splitedKey[0]).toISODate(),
          value: reducedEvents[item].length,
          group1: {
            page: 'action',
          },
          group2: {
            feature: 'change_ecogesture',
          },
          group3: {
            params:
              splitedKey[UsageEventProperties.TARGET] +
              ':' +
              splitedKey[UsageEventProperties.CONTEXT],
          },
        }
        const result = await sendIndicator(indicator, client)
        if (result) {
          readUsageEvents.push(...reducedEvents[item])
        }
      }
      break
    case UsageEventType.CHALLENGE_END_EVENT:
      for (const event of events) {
        const duelLaunchIndicator: Indicator = {
          createdBy: 'ecolyo',
          measureName: DaccEvent.EVENT_DURATION,
          startDate: event.eventDate.toISODate(),
          value: event.startDate
            ? event.eventDate.diff(event.startDate, ['seconds']).seconds
            : 0,
          // eslint-disable-next-line @typescript-eslint/camelcase
          group1: { start_event: 'start_challenge' },
          // eslint-disable-next-line @typescript-eslint/camelcase
          group2: { end_event: 'end_challenge' },
          group3: { params: event.target ? event.target : '' },
        }
        const result = await sendIndicator(duelLaunchIndicator, client)

        if (result) {
          readUsageEvents.push(event)
        }
      }
      break
    case UsageEventType.QUIZ_END_EVENT:
      handleQuizStars(events, client)
      break
    case UsageEventType.EXPLORATION_END_EVENT:
      for (const event of events) {
        const duelLaunchIndicator: Indicator = {
          createdBy: 'ecolyo',
          measureName: DaccEvent.EVENT_DURATION,
          startDate: event.eventDate.toISODate(),
          value: event.startDate
            ? event.eventDate.diff(event.startDate, ['seconds']).seconds
            : 0,
          // eslint-disable-next-line @typescript-eslint/camelcase
          group1: { start_event: 'start_exploration' },
          // eslint-disable-next-line @typescript-eslint/camelcase
          group2: { end_event: 'end_exploration' },
          group3: { params: event.context + ':' + event.target },
        }
        const result = await sendIndicator(duelLaunchIndicator, client)

        if (result) {
          readUsageEvents.push(event)
        }
      }
      break
    case UsageEventType.ACTION_END_EVENT:
      for (const event of events) {
        const duelLaunchIndicator: Indicator = {
          createdBy: 'ecolyo',
          measureName: DaccEvent.EVENT_DURATION,
          startDate: event.eventDate.toISODate(),
          value: event.startDate
            ? event.eventDate.diff(event.startDate, ['seconds']).seconds
            : 0,
          // eslint-disable-next-line @typescript-eslint/camelcase
          group1: { start_event: 'start_action' },
          // eslint-disable-next-line @typescript-eslint/camelcase
          group2: { end_event: 'end_action' },
          group3: { params: event.target + ':' + event.context },
        }
        const result = await sendIndicator(duelLaunchIndicator, client)

        if (result) {
          readUsageEvents.push(event)
        }
      }
      break
    case UsageEventType.DUEL_END_EVENT:
      for (const event of events) {
        const duelLaunchIndicator: Indicator = {
          createdBy: 'ecolyo',
          measureName: DaccEvent.EVENT_DURATION,
          startDate: event.eventDate.toISODate(),
          value: event.startDate
            ? event.eventDate.diff(event.startDate, ['seconds']).seconds
            : 0,
          // eslint-disable-next-line @typescript-eslint/camelcase
          group1: { start_event: 'start_duel' },
          // eslint-disable-next-line @typescript-eslint/camelcase
          group2: { end_event: 'end_duel' },
          group3: {
            params: event.target + ':' + event.context + ':' + event.result,
          },
        }
        const result = await sendIndicator(duelLaunchIndicator, client)

        if (result) {
          readUsageEvents.push(event)
        }
      }
      break
    case UsageEventType.DUEL_LAUNCH_EVENT:
      // Get challenge ID
      const challenges = await new ChallengeService(
        client
      ).getAllUserChallengeEntities()
      const filteredCurrentChallenge = challenges.filter(
        challenge =>
          challenge.state === UserChallengeState.ONGOING ||
          challenge.state === UserChallengeState.DUEL
      )
      const currentChallenge = filteredCurrentChallenge[0]
        ? filteredCurrentChallenge[0]
        : null

      let starNumbers = 0
      if (currentChallenge && currentChallenge.progress) {
        starNumbers =
          currentChallenge.progress.actionProgress +
          currentChallenge.progress.explorationProgress +
          currentChallenge.progress.quizProgress
      }

      for (const event of events) {
        const duelLaunchIndicator: Indicator = {
          createdBy: 'ecolyo',
          measureName: DaccEvent.EVENT_DURATION,
          startDate: event.eventDate.toISODate(),
          value: event.startDate
            ? event.eventDate.diff(event.startDate, ['seconds']).seconds
            : 0,
          // eslint-disable-next-line @typescript-eslint/camelcase
          group1: { start_event: 'start_duel' },
          // eslint-disable-next-line @typescript-eslint/camelcase
          group2: { end_event: 'start_duel' },
          group3: {
            params: event.target + ':' + event.context + ':' + starNumbers,
          },
        }
        const result = await sendIndicator(duelLaunchIndicator, client)

        if (result) {
          readUsageEvents.push(event)
        }
      }
      break
    case UsageEventType.CHALLENGE_LAUNCH_EVENT:
      await calculPeriodBetweenFirstConnectionAndFirstChallenge(
        events,
        firstConnectionEvent,
        client
      )
      await calculPeriodBetweenChallenge(events, client)
      break
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
    case UsageEventType.REPORT_FROM_EMAIL:
      for (const event of events) {
        const cameBackFromEmail: Indicator = {
          createdBy: 'ecolyo',
          measureName: DaccEvent.SUMMARY_SUBSCRIPTION_MONTHLY,
          startDate: event.eventDate.toISODate(),
          value: 1,
          // eslint-disable-next-line @typescript-eslint/camelcase
          group1: { event_type: 'email' },
        }
        const result = await sendIndicator(cameBackFromEmail, client)

        if (result) {
          readUsageEvents.push(event)
        }
      }
      break
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
    default:
      break
  }
}

const AggregatorUsageEvents = async ({
  client,
}: AggregatorUsageEventsProps) => {
  log('info', 'Launch service')
  const events: UsageEvent[] = await UsageEventService.getEvents(client, {
    aggregated: false,
    eventDate: {
      $lt: DateTime.local()
        .setZone('utc', {
          keepLocalTime: true,
        })
        .startOf('day'),
    },
  })
  const [firstConnectionEvent] = await UsageEventService.getEvents(client, {
    type: UsageEventType.CONNECTION_EVENT,
    result: 'firstConnection',
  })
  if (events.length > 0) {
    log('info', `Fetching Sessions`)
    calculSessionTime(events, client)
    for (const eventType of Object.values(UsageEventType)) {
      log('info', `Fetching ${eventType}`)
      const filteredEvents: UsageEvent[] = events.filter(
        event => event.type === eventType
      )
      if (filteredEvents.length > 0) {
        await aggregateEvents(
          filteredEvents,
          eventType,
          firstConnectionEvent,
          client
        )
      }
    }
  }
  // Daily events
  calculateConnectedKonnectorPerDay(client)
  // Monthly events
  const profile = await new ProfileService(client).getProfile()
  if (
    profile &&
    DateTime.local()
      .setZone('utc', {
        keepLocalTime: true,
      })
      .startOf('day').day === profile.monthlyAnalysisDate.day
  ) {
    calculateConsumptionVariation(client)
938
    sendEmailSubscription(client)
939
940
941
942
943
944
945
946
947
948
  }
  const uniqueReadUsageEvents: UsageEvent[] = uniq(readUsageEvents)
  log(
    'info',
    `Tag aggregated usage: total of ${uniqueReadUsageEvents.length} events`
  )
  await UsageEventService.updateUsageEventsAggregated(
    client,
    uniqueReadUsageEvents
  )
949
950
951
952
953
954
955
956
957
958
959

  if (errorEvent.length > 0) {
    // Build error
    let error = `Process end with ${errorEvent.length} errors : `
    errorEvent.forEach(el => {
      error += `${el.doctype}, `
    })
    log('error', error)
    throw error
  }

960
961
962
963
  log('info', 'End of service')
}

runService(AggregatorUsageEvents)