This repository has been archived by the owner on Apr 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
administrations-update.ts
99 lines (77 loc) · 2.62 KB
/
administrations-update.ts
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
import { IAdministration } from '../../types'
import {
administrationsGet,
administrationsUpsert
} from '../../database/queries/administrations'
import {
organismeDepartementGet,
organismesDepartementsGet
} from '../../tools/api-administrations/index'
import { objectsDiffer } from '../../tools/index'
import { userSuper } from '../../database/user-super'
const administrationsUpdatedFind = (
administrationsOld: IAdministration[],
administrationsNew: IAdministration[]
) =>
administrationsNew.reduce((acc: IAdministration[], administrationNew) => {
const administrationOld = administrationsOld.find(
a =>
a.departementId === administrationNew.departementId &&
a.typeId === administrationNew.typeId
)
const updated =
!administrationOld || objectsDiffer(administrationNew, administrationOld)
if (updated) {
acc.push(administrationNew)
}
return acc
}, [])
const apiAdministrationGetTest = async () =>
organismeDepartementGet(
'01',
'prefecture'
) as unknown as IAdministration | null
const apiAdministrationsGet = async (departementsIds: string[]) => {
const departementsIdsNoms = departementsIds.map(departementId => ({
departementId,
nom: departementId === '75' ? 'paris_ppp' : 'prefecture'
}))
return organismesDepartementsGet(departementsIdsNoms)
}
const administrationsUpdate = async (administrationsIds?: string[]) => {
console.info()
console.info('administrations…')
const apiAdministrationsTest = await apiAdministrationGetTest()
if (!apiAdministrationsTest) return []
const administrationsOld = await administrationsGet(
{ administrationsIds },
{},
userSuper
)
// mise à jour de l'administrations grâce à l'API Administration
const departementsIds = administrationsOld.reduce((acc, a) => {
if (a.departementId) {
acc.push(a.departementId)
}
return acc
}, [] as string[])
if (!departementsIds.length) return []
const administrationsNew = await apiAdministrationsGet(departementsIds)
// si aucune administration n'est retournée,
// on n'efface pas les administrations correspondantes de la base
// pour éviter de perdre des données en base
const administrationsUpdated = administrationsUpdatedFind(
administrationsOld,
administrationsNew
)
if (administrationsUpdated.length) {
await administrationsUpsert(administrationsUpdated)
const log = {
type: 'administrations (mise à jour) ->',
value: administrationsUpdated.map(a => a.id).join(', ')
}
console.info(log.type, log.value)
}
return administrationsUpdated
}
export { administrationsUpdate }