Newer
Older
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
import { Client, Q, QueryDefinition } from 'cozy-client'
import {
ECOGESTURE_DOCTYPE,
PROFILE_DOCTYPE,
EGL_DAY_DOCTYPE,
EGL_MONTH_DOCTYPE,
EGL_YEAR_DOCTYPE,
ENEDIS_DAY_DOCTYPE,
ENEDIS_MINUTE_DOCTYPE,
ENEDIS_MONTH_DOCTYPE,
ENEDIS_YEAR_DOCTYPE,
GRDF_DAY_DOCTYPE,
GRDF_MONTH_DOCTYPE,
GRDF_YEAR_DOCTYPE,
CHALLENGE_DOCTYPE,
DUEL_DOCTYPE,
QUIZ_DOCTYPE,
EXPLORATION_DOCTYPE,
} from 'doctypes'
import { FluidType } from 'enum/fluid.enum'
import { Dataload, FluidStatus, Profile, UserChallenge } from 'models'
import EcogestureService from 'services/ecogesture.service'
import ChallengeService from 'services/challenge.service'
import ecogestureData from 'db/ecogestureData.json'
import challengeEntityData from 'db/challengeEntity.json'
import duelEntityData from 'db/duelEntity.json'
import quizEntityData from 'db/quizEntity.json'
import explorationEntityData from 'db/explorationEntity.json'
import ProfileService from 'services/profile.service'
import profileData from 'db/profileData.json'
import KonnectorStatusService from 'services/konnectorStatus.service'
import KonnectorService from 'services/konnector.service'
import AccountService from 'services/account.service'
import FluidService from 'services/fluid.service'
import DuelService from 'services/duel.service'
import QuizService from 'services/quiz.service'
import ExplorationService from 'services/exploration.service'
import { hashFile } from 'utils/hash'
import { getActualAnalysisDate } from 'utils/date'
import { TimeStep } from 'enum/timeStep.enum'
import ConsumptionDataManager from './consumption.service'
import { UserChallengeUpdateFlag } from 'enum/userChallenge.enum'
import { getRoundFloat } from 'utils/math'
import { DateTime } from 'luxon'
export default class InitializationService {
private readonly _client: Client
constructor(_client: Client) {
this._client = _client
}
/*
* Call a query with where clause to create the index if not exist
*/
private async createIndex(
doctype: string,
timestep: TimeStep
): Promise<object> {
const getMongoSelector = () => {
switch (timestep) {
case TimeStep.YEAR:
return {
year: {
$lte: 9999,
},
}
case TimeStep.MONTH:
return {
year: {
$lte: 9999,
},
month: {
$lte: 12,
},
}
case TimeStep.DAY:
case TimeStep.HALF_AN_HOUR:
return {
year: {
$lte: 9999,
},
month: {
$lte: 12,
},
day: {
$lte: 31,
},
}
default:
return {}
}
}
const query: QueryDefinition = Q(doctype)
.where(getMongoSelector())
.limitBy(1)
return await this._client.query(query)
}
/*
* create index for each Doctype
* sucess return: true
* failure throw error
*/
public async initIndex(): Promise<boolean> {
try {
const accountService = new AccountService(this._client)
const konnectorService = new KonnectorService(this._client)
await Promise.all([
this.createIndex(EGL_YEAR_DOCTYPE, TimeStep.YEAR),
this.createIndex(EGL_MONTH_DOCTYPE, TimeStep.MONTH),
this.createIndex(EGL_DAY_DOCTYPE, TimeStep.DAY),
this.createIndex(ENEDIS_YEAR_DOCTYPE, TimeStep.YEAR),
this.createIndex(ENEDIS_MONTH_DOCTYPE, TimeStep.MONTH),
this.createIndex(ENEDIS_DAY_DOCTYPE, TimeStep.DAY),
this.createIndex(ENEDIS_MINUTE_DOCTYPE, TimeStep.HALF_AN_HOUR),
this.createIndex(GRDF_YEAR_DOCTYPE, TimeStep.YEAR),
this.createIndex(GRDF_MONTH_DOCTYPE, TimeStep.MONTH),
this.createIndex(GRDF_DAY_DOCTYPE, TimeStep.DAY),
konnectorService.createIndexKonnector(),
accountService.createIndexAccount(),
])
console.log(
'%c Initialization: Indexes created',
'background: #222; color: white'
)
return true
} catch (error) {
console.log('Initialization error - initIndex: ', error)
throw error
}
}
/*
* Check if profil exist
* If not, the profil is created
* sucess return: profil
* failure return: null
*/
public async initProfile(): Promise<Profile | null> {
const profileService = new ProfileService(this._client)
try {
const loadedProfile = await profileService.getProfile()
if (!loadedProfile) {
// Population with the data
const { data: newProfile } = await this._client.create(
PROFILE_DOCTYPE,
profileData[0]
)
if (newProfile) {
console.log(
'%c Initialization: Profile created',
'background: #222; color: white'
)
} else {
throw new Error('initProfile: Profile not created')
}
} else {
console.log(
'%c Initialization: Profile loaded',
'background: #222; color: white'
)
}
const updatedProfile = await profileService.updateProfile({
lastConnectionDate: DateTime.local().setZone('utc', {
keepLocalTime: true,
}),
})
return updatedProfile
} catch (error) {
console.log('Initialization error - initProfile: ', error)
throw error
}
}
public async initEcogesture(hash: string): Promise<string> {
const hashEcogestureType = hashFile(ecogestureData)
const ecogestureService = new EcogestureService(this._client)
// Populate data if none ecogesture exists
const loadedEcogestures = await ecogestureService.getAllEcogestures()
if (
!loadedEcogestures ||
(loadedEcogestures && loadedEcogestures.length === 0)
) {
// Populate the doctype with data
try {
for (let i = 0; i <= ecogestureData.length - 1; i++) {
await this._client.create(ECOGESTURE_DOCTYPE, ecogestureData[i])
}
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
// Check of created document based on count
const checkCount = await ecogestureService.getAllEcogestures()
if (
!checkCount ||
(checkCount && checkCount.length !== ecogestureData.length)
) {
throw new Error(
'initEcogesture: Created ecogesture type entities does not match'
)
}
console.log(
'%c Initialization: Ecogesture created',
'background: #222; color: white'
)
return hashEcogestureType
} catch (error) {
console.log('Initialization error - initEcogesture: ', error)
throw error
}
}
// Update if the hash is not the same as the one from profile
if (hash !== hashEcogestureType) {
// Update the doctype
try {
// Deletion of all documents
await ecogestureService.deleteAllEcogestures()
// Population with the data
await Promise.all(
ecogestureData.map(async ecogesture => {
await this._client.create(ECOGESTURE_DOCTYPE, ecogesture)
})
)
// Check of created document based on count
const checkCount = await ecogestureService.getAllEcogestures()
if (
!checkCount ||
(checkCount && checkCount.length !== ecogestureData.length)
) {
throw new Error(
'initEcogesture: Created ecogesture type entities does not match'
)
}
console.log(
'%c Initialization: Ecogesture updated',
'background: #222; color: white'
)
return hashEcogestureType
} catch (error) {
console.log('Initialization error - initEcogesture: ', error)
throw error
}
} else {
// Doctype already up to date
console.log(
'%c Initialization: Ecogesture loaded',
'background: #222; color: white'
)
return hashEcogestureType
}
}
public async initChallengeEntity(hash: string): Promise<string> {
const challengeHash = hashFile(challengeEntityData)
const challengeService = new ChallengeService(this._client)
// Populate data if none challengeEntity exists
const loadedChallengeEntity = await challengeService.getAllChallengeEntities()
if (
!loadedChallengeEntity ||
(loadedChallengeEntity && loadedChallengeEntity.length === 0)
) {
// Populate the doctype with data
try {
for (let i = 0; i <= challengeEntityData.length - 1; i++) {
await this._client.create(CHALLENGE_DOCTYPE, challengeEntityData[i])
}
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
// Check of created document
const checkCount = await challengeService.getAllChallengeEntities()
if (
!checkCount ||
(checkCount && checkCount.length !== challengeEntityData.length)
) {
throw new Error(
'initChallengeEntity: Created challenge entities does not match'
)
}
console.log(
'%c Initialization: Challenge entities created',
'background: #222; color: white'
)
return challengeHash
} catch (error) {
console.log('Initialization error - initChallengeEntity: ', error)
throw error
}
}
// Update if the hash is not the same as the one from profile
if (hash !== challengeHash) {
// Update the doctype
try {
// Deletion of all documents
await challengeService.deleteAllChallengeEntities()
// Population with the data
await Promise.all(
challengeEntityData.map(async challengeEntity => {
await this._client.create(CHALLENGE_DOCTYPE, challengeEntity)
})
)
// Check of created document
const checkCount = await challengeService.getAllChallengeEntities()
if (
!checkCount ||
(checkCount && checkCount.length !== challengeEntityData.length)
) {
throw new Error(
'initChallengeEntity: Created challenge entities does not match'
)
}
console.log(
'%c Initialization: Challenge entities updated',
'background: #222; color: white'
)
return challengeHash
} catch (error) {
console.log('Initialization error - initChallengeEntity: ', error)
throw error
}
} else {
// Doctype already up to date
console.log(
'%c Initialization: Challenge Entity loaded',
'background: #222; color: white'
)
return challengeHash
}
}
public async initDuelEntity(hash: string): Promise<string> {
const hashDuelEntity = hashFile(duelEntityData)
const duelService = new DuelService(this._client)
// Populate data if none DuelEntity exists
const loadedDuelTypes = await duelService.getAllDuelEntities()
if (!loadedDuelTypes || (loadedDuelTypes && loadedDuelTypes.length === 0)) {
// Populate the doctype with data
try {
for (let i = 0; i <= duelEntityData.length - 1; i++) {
await this._client.create(DUEL_DOCTYPE, duelEntityData[i])
}
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
// Check of created document
const checkCount = await duelService.getAllDuelEntities()
if (
!checkCount ||
(checkCount && checkCount.length !== duelEntityData.length)
) {
throw new Error(
'initDuelEntity: Created duel entities does not match'
)
}
console.log(
'%c Initialization: UserDuel entities created',
'background: #222; color: white'
)
return hashDuelEntity
} catch (error) {
console.log('Initialization error - initDuelEntity: ', error)
throw error
}
}
// Update if the hash is not the same as the one from profile
if (hash !== hashDuelEntity) {
// Update the doctype
try {
// Deletion of all documents
await duelService.deleteAllDuelEntities()
// Population with the data
await Promise.all(
duelEntityData.map(async duelEntity => {
await this._client.create(DUEL_DOCTYPE, duelEntity)
})
)
// Check of created document
const checkCount = await duelService.getAllDuelEntities()
if (
!checkCount ||
(checkCount && checkCount.length !== duelEntityData.length)
) {
throw new Error(
'initDuelEntity: Created duel entities does not match'
)
}
console.log(
'%c Initialization: UserDuel entities updated',
'background: #222; color: white'
)
return hashDuelEntity
} catch (error) {
console.log('Initialization error - initDuelEntity: ', error)
throw error
}
} else {
// Doctype already up to date
console.log(
'%c Initialization: Challenge Entity loaded',
'background: #222; color: white'
)
return hashDuelEntity
}
}
public async initQuizEntity(hash: string): Promise<string> {
const quizHash = hashFile(quizEntityData)
const quizService = new QuizService(this._client)
// Populate data if none quizEntity exists
const loadedQuizEntity = await quizService.getAllQuizEntities()
if (
!loadedQuizEntity ||
(loadedQuizEntity && loadedQuizEntity.length === 0)
) {
// Populate the doctype with data
try {
for (let i = 0; i <= quizEntityData.length - 1; i++) {
await this._client.create(QUIZ_DOCTYPE, quizEntityData[i])
}
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
// Check of created document
const checkCount = await quizService.getAllQuizEntities()
if (
!checkCount ||
(checkCount && checkCount.length !== quizEntityData.length)
) {
throw new Error(
'initQuizEntity: Created quiz entities does not match'
)
}
console.log(
'%c Initialization: Quiz entities created',
'background: #222; color: white'
)
return quizHash
} catch (error) {
console.log('Initialization error - initQuizEntity: ', error)
throw error
}
}
// Update if the hash is not the same as the one from profile
if (hash !== quizHash) {
// Update the doctype
try {
// Deletion of all documents
await quizService.deleteAllQuizEntities()
// Population with the data
await Promise.all(
quizEntityData.map(async quizEntity => {
await this._client.create(QUIZ_DOCTYPE, quizEntity)
})
)
// Check of created document
const checkCount = await quizService.getAllQuizEntities()
if (
!checkCount ||
(checkCount && checkCount.length !== quizEntityData.length)
) {
throw new Error(
'initQuizEntity: Created quiz entities does not match'
)
}
console.log(
'%c Initialization: Quiz entities updated',
'background: #222; color: white'
)
return quizHash
} catch (error) {
console.log('Initialization error - initQuizEntity: ', error)
throw error
}
} else {
// Doctype already up to date
console.log(
'%c Initialization: Quiz Entity loaded',
'background: #222; color: white'
)
return quizHash
}
}
public async initExplorationEntity(hash: string): Promise<string> {
const explorationHash = hashFile(explorationEntityData)
const explorationService = new ExplorationService(this._client)
// Populate data if none explorationEntity exists
const loadedExplorationEntity = await explorationService.getAllExplorationEntities()
if (
!loadedExplorationEntity ||
(loadedExplorationEntity && loadedExplorationEntity.length === 0)
) {
// Populate the doctype with data
try {
for (let i = 0; i <= explorationEntityData.length - 1; i++) {
await this._client.create(
EXPLORATION_DOCTYPE,
explorationEntityData[i]
)
}
// Check of created document
const checkCount = await explorationService.getAllExplorationEntities()
if (
!checkCount ||
(checkCount && checkCount.length !== explorationEntityData.length)
) {
throw new Error(
'initExplorationEntity: Created exploration entities does not match'
)
}
console.log(
'%c Initialization: Exploration entities created',
'background: #222; color: white'
)
return explorationHash
} catch (error) {
console.log('Initialization error - initExplorationEntity: ', error)
throw error
}
}
// Update if the hash is not the same as the one from profile
if (hash !== explorationHash) {
// Update the doctype
try {
// Deletion of all documents
await explorationService.deleteAllExplorationEntities()
// Population with the data
await Promise.all(
explorationEntityData.map(async explorationEntity => {
await this._client.create(EXPLORATION_DOCTYPE, explorationEntity)
})
)
// Check of created document
const checkCount = await explorationService.getAllExplorationEntities()
if (
!checkCount ||
(checkCount && checkCount.length !== explorationEntityData.length)
) {
throw new Error(
'initExplorationEntity: Created exploration entities does not match'
)
}
console.log(
'%c Initialization: Exploration entities updated',
'background: #222; color: white'
)
return explorationHash
} catch (error) {
console.log('Initialization error - initExplorationEntity: ', error)
throw error
}
} else {
// Doctype already up to date
console.log(
'%c Initialization: Exploration Entity loaded',
'background: #222; color: white'
)
return explorationHash
}
}
public async initAnalysis(
profile: Profile
): Promise<{
monthlyAnalysisDate: DateTime
haveSeenLastAnalysis: boolean
}> {
try {
const actualAnalysisDate = getActualAnalysisDate()
if (
profile.monthlyAnalysisDate &&
actualAnalysisDate <= profile.monthlyAnalysisDate
) {
return {
monthlyAnalysisDate: profile.monthlyAnalysisDate,
haveSeenLastAnalysis: profile.haveSeenLastAnalysis,
}
} else {
console.log(
'%c Initialization: Analysis information from profile updated',
'background: #222; color: white'
)
return {
monthlyAnalysisDate: actualAnalysisDate,
haveSeenLastAnalysis: profile.isFirstConnection ? true : false,
}
}
} catch (error) {
console.log('Initialization error - initAnalysis: ', error)
throw error
}
}
/*
* Check if FluidTypes exist
* sucess return: FluidType[]
* failure throw error
*/
public async initFluidTypes(): Promise<FluidType[]> {
const kss = new KonnectorStatusService(this._client)
try {
const fluidtypes = await kss.getKonnectorAccountStatus()
if (fluidtypes) {
console.log(
'%c Initialization: Fluid Types loaded',
'background: #222; color: white'
)
return fluidtypes
} else {
throw new Error('initFluidTypes: FluidTypes not found')
}
} catch (error) {
console.log('Initialization error - initFluidTypes: ', error)
throw error
}
}
/*
* For each fluid get the trigger status and the last data date
* sucess return: FluidStatus[]
* failure throw error
*/
public async initFluidStatus(): Promise<FluidStatus[]> {
const fs = new FluidService(this._client)
try {
const fluidStatus = await fs.getFluidStatus()
if (fluidStatus) {
console.log(
'%c Initialization: Fluid Status loaded',
'background: #222; color: white'
)
return fluidStatus
} else {
throw new Error('initFluidStatus: fluidStatus not found')
}
} catch (error) {
console.log('Initialization error - initFluidStatus: ', error)
throw error
}
}
/*
* Build the userChallengeList
* sucess return: UserChallenge[]
* failure throw error
*/
public async initUserChallenges(
fluidStatus: FluidStatus[]
): Promise<UserChallenge[]> {
const challengeService = new ChallengeService(this._client)
try {
const userChallengeList = await challengeService.buildUserChallengeList(
fluidStatus
)
if (userChallengeList) {
console.log(
'%c Initialization: Challenges loaded',
'background: #222; color: white'
)
return userChallengeList
} else {
throw new Error('initUserChallenges: userChallengeList not found')
}
} catch (error) {
console.log('Initialization error - initUserChallenges: ', error)
throw error
}
}
/*
* Retrieve dataloads for ongoing duel
* sucess return: UserChallenge, Dataload[]
* failure throw error
*/
public async initDuelProgress(
userChallenge: UserChallenge
): Promise<{
updatedUserChallenge: UserChallenge
dataloads: Dataload[]
}> {
const challengeService = new ChallengeService(this._client)
const consumptionService = new ConsumptionDataManager(this._client)
try {
const dataloads: Dataload[] = await challengeService.getUserChallengeDataload(
userChallenge
)
const userConsumption: number = getRoundFloat(
consumptionService.calculatePerformanceIndicatorValue(dataloads)
)
const _userChallenge: UserChallenge = {
...userChallenge,
duel: {
...userChallenge.duel,
userConsumption: userConsumption,
},
}
const updatedUserChallenge: UserChallenge = await challengeService.updateUserChallenge(
_userChallenge,
UserChallengeUpdateFlag.DUEL_CONSUMPTION
)
return { updatedUserChallenge, dataloads }
} catch (error) {
console.log('Initialization error: ', error)
throw error
}
}
}