-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlocations.go
296 lines (274 loc) · 9.54 KB
/
locations.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
package main
import (
"airqo-integrator/config"
"airqo-integrator/db"
"airqo-integrator/models"
"airqo-integrator/utils"
"airqo-integrator/utils/dbutils"
"encoding/json"
"fmt"
"github.com/buger/jsonparser"
_ "github.com/lib/pq"
log "github.com/sirupsen/logrus"
"net/url"
"strings"
"time"
)
// LoadOuLevels populates organisation unit levels in our DB from base DHIS2
func LoadOuLevels() {
var id int
err := db.GetDB().Get(&id, "SELECT count(*) FROM orgunitlevel")
if err != nil {
log.WithError(err).Info("Error reading organisation unit levels:")
return
}
if id != 0 {
log.WithField("ouCount:", id).Info("Base Organisation units levels found!")
return
} else {
log.WithField("ouCount:", id).Info("Base Organisation units levels not found!")
apiURL := config.AirQoIntegratorConf.API.AIRQODHIS2BaseURL + "/organisationUnitLevels.json"
p := url.Values{}
p.Add("fields", "id,name,level")
p.Add("paging", "false")
ouURL := apiURL + "?" + p.Encode()
fmt.Println(ouURL)
resp, err := utils.GetWithBasicAuth(ouURL, config.AirQoIntegratorConf.API.AIRQODHIS2User,
config.AirQoIntegratorConf.API.AIRQODHIS2Password)
if err != nil {
log.WithError(err).Info("Failed to fetch organisation unit levels")
return
}
// fmt.Println(string(resp))
v, _, _, err := jsonparser.Get(resp, "organisationUnitLevels")
if err != nil {
log.WithError(err).Error("No organisationUnitLevels found by json parser")
return
}
// fmt.Printf("Entries: %s", v)
var ouLevels []models.OrgUnitLevel
err = json.Unmarshal(v, &ouLevels)
if err != nil {
fmt.Println("Error unmarshaling orgunit level response body:", err)
return
}
for i := range ouLevels {
ouLevels[i].UID = ouLevels[i].ID
log.WithFields(
log.Fields{"uid": ouLevels[i].ID, "name": ouLevels[i].Name, "level": ouLevels[i].Level}).Info("Creating New Orgunit Level")
ouLevels[i].NewOrgUnitLevel()
}
}
}
// LoadOuGroups populates organisation unit groups in our DB from base DHIS2
func LoadOuGroups() {
var id int
err := db.GetDB().Get(&id, "SELECT count(*) FROM orgunitgroup")
if err != nil {
log.WithError(err).Info("Error reading organisation unit groups:")
return
}
if id != 0 {
log.WithField("ouCount:", id).Info("Base Organisation unit groups found!")
return
} else {
log.WithField("ouCount:", id).Info("Base Organisation unit groups not found!")
apiURL := config.AirQoIntegratorConf.API.AIRQODHIS2BaseURL + "/organisationUnitGroups.json"
p := url.Values{}
p.Add("fields", "id,name,shortName")
p.Add("paging", "false")
ouURL := apiURL + "?" + p.Encode()
fmt.Println(ouURL)
resp, err := utils.GetWithBasicAuth(ouURL, config.AirQoIntegratorConf.API.AIRQODHIS2User,
config.AirQoIntegratorConf.API.AIRQODHIS2Password)
if err != nil {
log.WithError(err).Info("Failed to fetch organisation unit groups")
return
}
v, _, _, err := jsonparser.Get(resp, "organisationUnitGroups")
if err != nil {
log.WithError(err).Error("json parser failed to get organisationUnitGroups key")
return
}
var ouGroups []models.OrgUnitGroup
err = json.Unmarshal(v, &ouGroups)
if err != nil {
fmt.Println("Error unmarshaling orgunit groups response body:", err)
return
}
for i := range ouGroups {
ouGroups[i].UID = ouGroups[i].ID
if len(ouGroups[i].ShortName) == 0 {
ouGroups[i].ShortName = ouGroups[i].Name
}
log.WithFields(
log.Fields{"uid": ouGroups[i].ID, "name": ouGroups[i].Name, "level": ouGroups[i].ShortName}).Info("Creating New Orgunit Group")
ouGroups[i].NewOrgUnitGroup()
}
}
}
// LoadAttributes fetches OU related attributes from DHIS2 to our DB
func LoadAttributes() {
apiURL := config.AirQoIntegratorConf.API.AIRQODHIS2BaseURL + "/attributes.json"
p := url.Values{}
fields := `id~rename(uid),name,displayName,code,shortName,valueType`
p.Add("fields", fields)
p.Add("paging", "false")
p.Add("filter", "organisationUnitAttribute:eq:true")
attrURL := apiURL + "?" + p.Encode()
resp, err := utils.GetWithBasicAuth(attrURL, config.AirQoIntegratorConf.API.AIRQODHIS2User,
config.AirQoIntegratorConf.API.AIRQODHIS2Password)
if err != nil {
log.WithError(err).Info("Failed to fetch organisation unit attributes")
return
}
v, _, _, err := jsonparser.Get(resp, "attributes")
if err != nil {
log.WithError(err).Error("json parser failed to get attributes key")
return
}
var attributes []models.Attribute
err = json.Unmarshal(v, &attributes)
if err != nil {
log.WithError(err).Error("Error unmarshalling attributes to attribute list:")
return
}
for _, attribute := range attributes {
if attribute.ExistsInDB() {
log.WithFields(log.Fields{
"uid": attribute.UID, "name": attribute.Name}).Info("Attribute Exists in DB")
} else {
log.WithFields(log.Fields{
"uid": attribute.UID, "name": attribute.Name}).Info("Creating OU attribute:")
attribute.OrganisationUnitAttribute = true
attribute.NewAttribute()
if len(attribute.Code) > 0 {
attribute.UpdateCode(attribute.Code)
}
}
}
}
// LoadLocations populates organisation units in our DB from base DHIS2
func LoadLocations() {
var id int
err := db.GetDB().Get(&id, "SELECT count(*) FROM organisationunit WHERE hierarchylevel=1")
if err != nil {
log.WithError(err).Info("Error reading organisation units:")
return
}
if id != 0 {
log.WithField("ouCount:", id).Info("Base Organisation units hierarchy found!")
return
} else {
log.WithField("ouCount:", id).Info("Base Organisation units hierarchy not found!")
apiURL := config.AirQoIntegratorConf.API.AIRQODHIS2BaseURL + "/organisationUnits.json"
p := url.Values{}
fields := `id,name,displayName,code,shortName,openingDate,phoneNumber,` +
`path,level,description,geometry,organisatoinUnitGroups[id,name]`
p.Add("fields", fields)
p.Add("paging", "false")
for i := 1; i < config.AirQoIntegratorConf.API.AIRQODHIS2FacilityLevel; i++ {
p.Add("level", fmt.Sprintf("%d", i))
ouURL := apiURL + "?" + p.Encode()
fmt.Println(ouURL)
resp, err := utils.GetWithBasicAuth(ouURL, config.AirQoIntegratorConf.API.AIRQODHIS2User,
config.AirQoIntegratorConf.API.AIRQODHIS2Password)
if err != nil {
log.WithError(err).Info("Failed to fetch organisation units")
return
}
v, _, _, err := jsonparser.Get(resp, "organisationUnits")
if err != nil {
log.WithError(err).Error("json parser failed to get organisationUnit key")
return
}
var ous []models.OrganisationUnit
err = json.Unmarshal(v, &ous)
if err != nil {
log.WithError(err).Error("Error unmarshalling response body:")
return
}
for i := range ous {
ous[i].UID = ous[i].ID
log.WithFields(
log.Fields{"uid": ous[i].ID, "name": ous[i].Name, "level": ous[i].Level,
"Geometry-Type": ous[i].Geometry.Type}).Info("Creating New Orgunit")
ous[i].NewOrgUnit()
}
p.Del("level")
}
}
}
func SanitizeShortName(name string) string {
if len(name) <= 50 {
return name
}
newName := strings.ReplaceAll(name, "Health Centre", "HC")
newName = strings.ReplaceAll(newName, "Hospital", "")
if len(newName) <= 50 {
return newName
}
return newName[:50]
}
// SyncLocationsToDHIS2Instances syncs the DHIS2 base hierarchy to subscribing DHIS2 instances
func SyncLocationsToDHIS2Instances() {
for _, serverName := range strings.Split(config.AirQoIntegratorConf.API.AIRQOCCDHIS2HierarchyServers, ",") {
models.SyncLocationsToServer(serverName)
}
}
// CreateOrgUnitGroupPayload ...
func CreateOrgUnitGroupPayload(ou models.MetadataOu) map[string][]byte {
ouGroupReqs := make(map[string][]byte)
if len(ou.OrganisationUnitGroups) > 0 {
for _, g := range ou.OrganisationUnitGroups {
groupId := g.Get("id", "")
ouGroupReqs[groupId.(string)] = []byte(fmt.Sprintf(
`[{"op": "add", "path": "/organisationUnits/-", "value": {"id": "%s"}}]`, ou.UID))
}
}
return ouGroupReqs
}
// MakeOrgUnitGroupsAdditionRequests ....
func MakeOrgUnitGroupsAdditionRequests(
ouGroupPayloads map[string][]byte, dependency dbutils.Int, facilityUID string) []models.RequestForm {
var requests []models.RequestForm
for k, v := range ouGroupPayloads {
if len(k) == 0 {
continue
}
year, week := time.Now().ISOWeek()
var reqF = models.RequestForm{
// DependsOn: dependency,
Source: "localhost", Destination: "base_OU_GroupAdd", ContentType: "application/json-patch+json",
Year: fmt.Sprintf("%d", year), Week: fmt.Sprintf("%d", week),
Month: fmt.Sprintf("%d", int(time.Now().Month())), Period: "", Facility: facilityUID, BatchID: "", SubmissionID: "",
CCServers: strings.Split(config.AirQoIntegratorConf.API.AIRQOCCDHIS2OuGroupAddServers, ","),
URLSuffix: fmt.Sprintf("/%s", k),
Body: string(v), ObjectType: "ORGUNIT_GROUP_ADD", ReportType: "OUGROUP_ADD",
}
if dependency > 0 {
reqF.DependsOn = dependency
}
requests = append(requests, reqF)
}
return requests
}
func GenerateUpdateMetadataRequest(update []models.MetadataObject, facilityUID string, district string) models.RequestForm {
req := models.RequestForm{}
body, err := json.Marshal(update)
if err != nil {
log.WithError(err).Error("Failed to parse facility update metadata")
return req
}
year, week := time.Now().ISOWeek()
reqF := models.RequestForm{
Source: "localhost", Destination: "base_OU_Update", ContentType: "application/json-patch+json",
Year: fmt.Sprintf("%d", year), Week: fmt.Sprintf("%d", week),
Month: fmt.Sprintf("%d", int(time.Now().Month())), Period: "", Facility: facilityUID, BatchID: "", SubmissionID: "",
District: district,
CCServers: strings.Split(config.AirQoIntegratorConf.API.AIRQOCCDHIS2UpdateServers, ","),
URLSuffix: fmt.Sprintf("/%s", facilityUID),
Body: string(body),
}
return reqF
}