-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathopenfn-e5d0c9ec-bad5-48c8-add9-970b3e248d82-spec.yaml
3712 lines (3372 loc) · 166 KB
/
openfn-e5d0c9ec-bad5-48c8-add9-970b3e248d82-spec.yaml
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
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
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
415
416
417
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
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
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
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
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
name: social-sciences
description: |
Workflows for WCS & Partners in Social Sciences
collections: null
credentials:
aisha@openfn.org-AK-Asana:
name: AK Asana
owner: aisha@openfn.org
rediet@openfn.org-Rediet-Googlesheet:
name: Rediet Googlesheet
owner: rediet@openfn.org
rediet@openfn.org-WCS-Kobo:
name: WCS Kobo
owner: rediet@openfn.org
rediet@openfn.org-WCS-Kobo-Raw:
name: WCS Kobo Raw
owner: rediet@openfn.org
rediet@openfn.org-WCS-Kobo-Raw-with-URL:
name: WCS Kobo Raw with URL
owner: rediet@openfn.org
rediet@openfn.org-WCS-MSSQL-Test-DB:
name: WCS MSSQL Test DB
owner: rediet@openfn.org
workflows:
"1A.-Get-BNS-FormsList-(Ongoing)":
name: '1A. Get BNS FormsList (Ongoing)'
jobs:
BNS-1A-1-Get-FormsList-Ongoing:
name: BNS 1A 1 Get FormsList Ongoing
adaptor: '@openfn/language-googlesheets@2.3.0'
credential: rediet@openfn.org-Rediet-Googlesheet
body: |
//== Job to be used for getting a list of "deployed" Kobo forms from sheets to auto-sync ==//
// This can be run on-demand at any time by clicking "run" or modify manualCursor below //
getValues(
'1xexwj6HKJGHJM-sOzIOGqPHolgpdnp0GmjMIXwoV7OE',
'wcs-bns-DEPLOYED!A:L', //get Deployed forms list from Sheet
state => {
const [headers, ...values] = state.data.values;
const mapHeaderToValue = value => {
return headers.reduce((obj, header) => {
obj[header] = value[headers.indexOf(header)];
return obj;
}, {});
};
state.sheetsData = values
.filter(
item =>
item.includes('TRUE') //return forms where auto-sync = TRUE
//&& item.includes('bns_survey', 'nrgt_current')
)
.map(item => mapHeaderToValue(item));
return state;
}
);
fn(state => {
const { sheetsData } = state;
// Set a manual cursor if you'd like to only fetch data after this date...
//e.g., '2023-01-01T23:51:45.491+01:00'
const manualCursor = '2024-12-06T00:00:00.000Z'; //lastUsed: 2024-11-21T00:00:00.000Z
console.log('manualCursor defined?', manualCursor);
//...otherwise the job will use this dynamicCursor
const dynamicCursor = getTodayISODate();
function getTodayISODate() {
const today = new Date();
today.setUTCHours(0, 0, 0, 0); // Set hours, minutes, seconds, and milliseconds to 0
return today.toISOString(); // Convert to ISO string
}
//UNCOMMENT FOR FUTURE
// const cursorValue = dynamicCursor || manualCursor ;
const cursorValue = manualCursor ;
// const cursorValue = manualCursor ;
console.log('Cursor value to use in query:', cursorValue);
const formsList = sheetsData.map(survey => ({
formId: survey.uid,
tag: survey.tag,
name: survey.name
}));
console.log('# of deployed forms detected in Sheet:: ', formsList.length);
console.log('List of forms to auto-sync:: ', JSON.stringify(formsList, null, 2));
state.data = {
surveys: sheetsData.map(survey => ({
formId: survey.uid,
tag: survey.tag,
name: survey.name,
owner: survey.owner,
url: `https://kf.kobotoolbox.org/api/v2/assets/${survey.uid}/data/?format=json`,
query: `&query={"start":{"$gte":"${cursorValue}"}}`,
})),
};
return state;
});
BNS-1A-Get-BNS-NRGT-Forms-Ongoing:
name: BNS 1A Get BNS NRGT Forms Ongoing
adaptor: '@openfn/language-http@6.1.0'
credential: rediet@openfn.org-WCS-Kobo-Raw
body: |
// Here we fetch submissions for all "Deployed" forms in GoogleSheet
// NOTE: See linked job "[BNS-1A] 1.Get FormsList (Ongoing)" for cursor & GoogleSheet query logic
//**********************************************************//
fn(state => {
state.surveySubmissions = [];
state.errors = [];
state.globalIndex = 0;
console.log('surveys ::', JSON.stringify(state.data.surveys, null, 2));
return state;
});
each('$.data.surveys[*]', state => {
const { url, query, tag, formId, name, owner } = state.data;
console.log('Sending GET to ::', `${url}${query}`);
return get(`${url}${query}`)(state)
.then(state => {
const results = state.data.results.map(submission => {
const uniqueIndex = state.globalIndex++;
return {
i: uniqueIndex,
// Here we append the tags defined above to the Kobo form submission data
form: tag,
formName: name,
formOwner: owner,
body: submission,
};
});
state.surveySubmissions.push(...results);
const count = results.length;
console.log(`Fetched ${count} submissions from ${formId} (${tag}).`);
//Once we fetch the data, we want to post each individual Kobo survey
//back to the OpenFn inbox to run through the jobs =========================
return state;
})
.catch(err => {
state.errors.push({
formId,
message: err.message,
});
console.log(`Error fetching submissions from ${formId}::`, err.message);
return state;
});
});
// each(
// '$.surveySubmissions[*]',
// post(
// state => state.configuration.openfnInboxUrl,
// state => {
// const {i, formName} = state.data;
// const count = state.surveySubmissions.length;
// console.log(`Posting ${i} of ${count} from ${formName}`);
// return { body: state.data };
// }
// )
// );
Trigger-WF-Inbox:
name: Trigger WF Inbox
adaptor: '@openfn/language-http@latest'
credential: null
body: |
// Check out the Job Writing Guide for help getting started:
// https://docs.openfn.org/documentation/jobs/job-writing-guide
each(
'$.surveySubmissions[*]',
post(
"https://app.openfn.org/i/b3f86593-f37e-4139-80b8-852b9d3c49f4",
state => {
const {i, formName} = state.data;
const count = state.surveySubmissions.length;
console.log(`Posting ${i} of ${count} from ${formName}`);
return { body: state.data };
}
)
);
triggers:
cron:
type: cron
cron_expression: '0 */3 * * *'
enabled: false
edges:
cron->BNS-1A-1-Get-FormsList-Ongoing:
source_trigger: cron
target_job: BNS-1A-1-Get-FormsList-Ongoing
condition_type: always
enabled: true
BNS-1A-1-Get-FormsList-Ongoing->BNS-1A-Get-BNS-NRGT-Forms-Ongoing:
source_job: BNS-1A-1-Get-FormsList-Ongoing
target_job: BNS-1A-Get-BNS-NRGT-Forms-Ongoing
condition_type: on_job_success
enabled: true
BNS-1A-Get-BNS-NRGT-Forms-Ongoing->Trigger-WF-Inbox:
source_job: BNS-1A-Get-BNS-NRGT-Forms-Ongoing
target_job: Trigger-WF-Inbox
condition_type: on_job_success
enabled: true
1B.-Get-BNS-FormsList-Historical-sync:
name: 1B. Get BNS FormsList Historical sync
jobs:
BNS-1B-1-Get-FormsList-Historical-sync:
name: BNS-1B 1 Get FormsList Historical sync
adaptor: '@openfn/language-googlesheets@2.3.0'
credential: rediet@openfn.org-Rediet-Googlesheet
body: |
getValues(
'1xexwj6HKJGHJM-sOzIOGqPHolgpdnp0GmjMIXwoV7OE',
'wcs-bns-DEPLOYED!A:O', //get Deployed forms list from Sheet
state => {
const [headers, ...values] = state.data.values;
const mapHeaderToValue = value => {
return headers.reduce((obj, header) => {
obj[header] = value[headers.indexOf(header)];
return obj;
}, {});
};
console.log("deployedData", values);
state.deployedData = values
.map(item => mapHeaderToValue(item))
.filter(item => item['historical_sync'] === 'TRUE');
return state;
}
);
//== Job to be used for getting a list of "archived" Kobo forms from sheets to auto-sync ==//
// This can be run on-demand at any time by clicking "run" //
getValues(
'1xexwj6HKJGHJM-sOzIOGqPHolgpdnp0GmjMIXwoV7OE',
'wcs-bns-ARCHIVED!A:O', //get Deployed forms list from Sheet
state => {
const [headers, ...values] = state.data.values;
const mapHeaderToValue = value => {
return headers.reduce((obj, header) => {
obj[header] = value[headers.indexOf(header)];
return obj;
}, {});
};
console.log("archivedData", values);
state.archivedData = values
.map(item => mapHeaderToValue(item))
.filter(item => item['historical_sync'] === 'TRUE');
return state;
}
);
fn(state => {
const { archivedData, deployedData } = state;
// Set a manual cursor if you'd like to only fetch data after this date...
//e.g., '2023-01-01T23:51:45.491+01:00'
// const manualCursor = ''; //lastUsed: 2024-04-01T00:00:00.000Z
// console.log('manualCursor defined?', manualCursor);
//...otherwise the job will use this dynamicCursor
// const dynamicCursor = getTodayISODate();
// function getTodayISODate() {
// const today = new Date();
// today.setUTCHours(0, 0, 0, 0); // Set hours, minutes, seconds, and milliseconds to 0
// return today.toISOString(); // Convert to ISO string
// }
// const cursorValue = manualCursor || dynamicCursor;
// console.log('Cursor value to use in query:', cursorValue);
const combinedData = [...deployedData, ...archivedData];
const formsList = combinedData.map(survey => ({
formId: survey.uid,
tag: survey.tag,
name: survey.name,
}));
console.log('# of forms detected in Sheet:: ', formsList.length);
console.log(
'List of forms to re-sync:: ',
JSON.stringify(formsList, null, 2)
);
state.data = {
surveys: combinedData.map(survey => ({
formId: survey.uid,
tag: survey.tag,
name: survey.name,
owner: survey.owner,
url: `https://kf.kobotoolbox.org/api/v2/assets/${survey.uid}/data/?format=json`,
//query: `&query={"end":{"$gte":"${cursorValue}"}}`, //get ALL forms for historical job
})),
};
return state;
});
//Clear final state
fn(state => {
delete state.references;
delete state.response;
return state;
});
Get-BNS-NRGT-Forms-Historical:
name: Get BNS NRGT Forms Historical
adaptor: '@openfn/language-http@3.1.11'
credential: rediet@openfn.org-WCS-Kobo-Raw
body: |
// Here we fetch submissions for all "Archived" forms in GoogleSheet
// NOTE: See linked job "[BNS-1B] 1.Get FormsList (Historical)" for GoogleSheet query logic
//**********************************************************//
each(dataPath('surveys[*]'), state => {
const { url, tag, formId, name, owner } = state.data;
const query = "&query={\"start\":{\"$gte\":\"2021-10-29T00:00:00.000Z\"}}"
return get(`${url}${query}`, {}, state => {
console.log(state.data.result)
state.data.submissions = state.data.results.map((submission, i) => {
return {
i,
// Here we append the tags defined above to the Kobo form submission data
form: tag,
formName: name,
formOwner: owner,
body: submission,
};
});
const count = state.data.submissions.length;
console.log('Finding historical forms to resync...');
console.log(`Fetched ${count} submissions from ${formId} (${tag}).`);
//Once we fetch the data, we want to post each individual Kobo survey
//back to the OpenFn inbox to run through the jobs =========================
return each(dataPath('submissions[*]'), state => {
console.log(`Posting ${state.data.i + 1} of ${count}...`);
return post("https://app.openfn.org/i/b3f86593-f37e-4139-80b8-852b9d3c49f4", {
body: state => state.data,
})(state);
})(state);
})(state)
});
triggers:
cron:
type: cron
cron_expression: '0 22 1 * *'
enabled: false
edges:
BNS-1B-1-Get-FormsList-Historical-sync->Get-BNS-NRGT-Forms-Historical:
source_job: BNS-1B-1-Get-FormsList-Historical-sync
target_job: Get-BNS-NRGT-Forms-Historical
condition_type: on_job_success
enabled: true
cron->BNS-1B-1-Get-FormsList-Historical-sync:
source_trigger: cron
target_job: BNS-1B-1-Get-FormsList-Historical-sync
condition_type: always
enabled: true
2.-Sync-BNS-and-NRGT-Forms:
name: 2. Sync BNS and NRGT Forms
jobs:
Triage-jobs:
name: Triage jobs
adaptor: '@openfn/language-common@latest'
credential: null
body: |
// Check out the Job Writing Guide for help getting started:
// https://docs.openfn.org/documentation/jobs/job-writing-guide
BNS-2A-BNS-Price:
name: BNS-2A BNS Price
adaptor: '@openfn/language-mssql@3.0.0'
credential: rediet@openfn.org-WCS-MSSQL-Test-DB
body: |
// NOTE: This data cleaning operation returns state, modified as needed.
fn(state => {
//try {
const { body, formName, instance, formOwner } = state.data;
const { _submission_time, _id, _xform_id_string } = body;
let cleanedSubmission = {};
for (const key in body) {
switch (body[key]) {
case 'yes':
cleanedSubmission[key] = 1;
break;
case 'no':
cleanedSubmission[key] = 0;
break;
default:
cleanedSubmission[key] = body[key];
break;
}
}
cleanedSubmission.instance = instance;
const landscapeMap = {
Ndoki: 'ndoki',
'Lac Télé': 'lac_tele',
Ituri: 'ituri',
Kahuzi: 'kahuzi',
MTKB: 'kahuzi',
'Cross River': 'crossriver',
Soariake: 'soariake',
Ankarea: 'ankarea',
ABS: 'baie_antongil',
'Nosy Be': 'tandavandriva',
Makira: 'makira',
'BNS Ndoki Prix 2020': 'ndoki',
PNMD: 'pnmd',
//formName: landscapeValue,
//other values
};
return {
...state,
landscapeMap,
formName,
formOwner,
data: {
...cleanedSubmission,
durableUUID: `${_submission_time}-${_xform_id_string}-${_id}`,
datasetId: `${formName}-${_xform_id_string}`,
end: cleanedSubmission.end.slice(0, 10),
},
};
/* } catch (error) {
state.connection.close();
throw error;
}*/
});
// Refactor this for scale so it doesn't perform a no-op delete 9/10 times.
// Maybe check result of previous op, then only delete if it was an update.
sql({
query: state =>
`DELETE FROM WCSPROGRAMS_KoboBnsPrice where AnswerId = '${state.data._id}'`,
});
fn(state => {
const { good } = state.data;
if (!good || good.length === 0) {
return state;
}
const data = good.map((g, i) => ({
// Id: state.data._id,
Id: i + 1,
AnswerId: state.data._id,
DatasetUuidId: state.data.datasetId,
Surveyor: state.data.surveyor,
Village: state.data.village,
Gs: g[`good/name`],
Price: g[`good/price`],
LastUpdate: new Date().toISOString(),
//Landscape: state.landscapeMap[state.data.formName], //see L24 for mappings. We want to use formName to look-up a new value
Landscape: () => {
for (let val in state.landscapeMap)
if (state.formName.includes(val)) return state.landscapeMap[val];
return '';
},
SurveyDate: state.data.today,
}));
// console.log('data', data);
return insertMany('WCSPROGRAMS_KoboBnsPrice', data)(state);
});
fn(state => {
console.log('DatasetName ::', state.formName);
console.log('DatasetOwner ::', state.formOwner);
console.log('form submission id ::', state.data['_id']);
console.log('DatasetUuidId ::', state.data['datasetId']);
//console.log('data to upload ::', state.data);
return state;
});
upsert('WCSPROGRAMS_KoboData', 'DatasetUuidId', {
//AnswerId: dataValue('durableUUID'),
DatasetName: state => state.formName,
DatasetOwner: state => state.formOwner,
Landscape: dataValue('landscape'),
DatasetUuidId: dataValue('datasetId'),
DatasetYear: new Date().getFullYear(),
LastSubmissionTime: dataValue('_submission_time'),
LastCheckedTime: dataValue('_submission_time'),
LastUpdateTime: new Date().toISOString(),
KoboManaged: true,
Tags: dataValue('_tags'),
Citation: dataValue('instance'),
});
fn(state => {
console.log('data uploaded ::', state.data);
return state;
});
BNS-2B-BNS-Survey:
name: BNS 2B BNS Survey
adaptor: '@openfn/language-mssql@2.6.1'
credential: rediet@openfn.org-WCS-MSSQL-Test-DB
body: |
// NOTE: This data cleaning operation returns state, modified as needed.
fn(state => {
try {
const { body, formName, formOwner, instance } = state.data;
const { _submission_time, _id, _xform_id_string } = body;
let cleanedSubmission = {};
for (const key in body) {
switch (body[key]) {
case 'yes':
cleanedSubmission[key] = 1;
break;
case 'no':
cleanedSubmission[key] = 0;
break;
default:
cleanedSubmission[key] = body[key];
break;
}
}
// NOTE: This assumes all device-collected geo data follows specific lat, log data format
if (cleanedSubmission.gps_method === 'device') {
cleanedSubmission['gps/lat'] =
cleanedSubmission.geo && cleanedSubmission.geo.split(' ')[0];
cleanedSubmission['gps/long'] =
cleanedSubmission.geo && cleanedSubmission.geo.split(' ')[1];
} else if (
Math.abs(parseFloat(cleanedSubmission['gps/lat'])) > 90 ||
Math.abs(parseFloat(cleanedSubmission['gps/long'])) > 180
) {
console.log(
`WARNING: Discarding invalid manual GPS entry: 'gps/lat': ${cleanedSubmission['gps/lat']}; 'gps/long': ${cleanedSubmission['gps/long']}`
);
delete cleanedSubmission['gps/lat'];
delete cleanedSubmission['gps/long'];
}
cleanedSubmission.durableUUID = `${_submission_time}-${_xform_id_string}-${_id}`; //survey uuid
cleanedSubmission.datasetId = `${formName}-${_xform_id_string}`; //dataset uuid
cleanedSubmission.instance = instance;
state.data = cleanedSubmission;
state.landscapeMap = {
tns: 'ndoki',
ltlt: 'lac_tele',
mamabay: 'makira',
mtkb: 'kahuzi',
};
// Cleaning datasetId if formName is 'BNS Cross River 2017-2020'==============
if (formName.replace(/\s/g, '') === 'BNSCrossRiver2017-2020') {
state.data.datasetId = `${state.data.datasetId}${
body.today.split('-')[0]
}`;
}
// ===========================================================================
// ===========================================================================
// NOTE: These job mappings assume a specific Kobo form metadata naming syntax!
// 'NR' and 'BNS matrix' questions should follow the naming conventions below
// See Docs to learn more about the assumptions made here.
// ===========================================================================
// If a partner creates a form with slightly different field names, this
// section will need to be updated by WCS. If future forms are being designed,
// we'd recommend using a repeat group that allows the partner to select the
// type of 'nr' or 'matrix' they're reporting on. The current approach treats
// the form field names in Kobo _AS_ data themselves.
state.nr = Object.keys(state.data)
.filter(key => key.startsWith('nr/'))
.map(key => ({
DatasetUuidId: state.data.datasetId,
AnswerId: state.data._id,
Id: state.data._id,
LastUpdate: new Date().toISOString(),
Nr: key.substring(3),
NrCollect: state.data[key],
}));
const matrix = Object.keys(state.data)
.filter(key => key.includes('bns_matrix_'))
.map(key => {
const item = key.substring(
key.lastIndexOf('bns_matrix_') + 'bns_matrix_'.length,
key.lastIndexOf('_')
);
return {
Dataset_Id: state.data.datasetId, //DatasetUuidId
DatasetUuidId: state.data.datasetId,
//Id: state.data._id,
AnswerId: state.data._id,
gs: item.replace(/_/g, ' '),
have:
state.data[
`hh_assets/bns_matrix_${item}/bns_matrix_${item}_possess`
] || state.data[`bns_matrix_${item}/bns_matrix_${item}_possess`],
necessary:
state.data[
`hh_assets/bns_matrix_${item}/bns_matrix_${item}_necessary`
] || state.data[`bns_matrix_${item}/bns_matrix_${item}_necessary`],
quantity:
state.data[
`hh_assets/bns_matrix_${item}/bns_matrix_${item}_number`
] || state.data[`bns_matrix_${item}/bns_matrix_${item}_number`],
};
});
state.matrix = matrix.filter(
(x, i) => matrix.findIndex(y => y.gs == x.gs) == i
);
// ===========================================================================
// console.log(
// 'The bns_matrix',
// JSON.stringify(state.matrix, null, 2),
// `contains ${state.matrix.length} items.`
// );
console.log('instance: ', instance);
return {...state, formOwner, formName};
} catch (error) {
state.connection.close();
throw error;
}
});
upsert('WCSPROGRAMS_KoboBnsAnswer', 'AnswerId', {
DatasetUuidId: dataValue('datasetId'),
//Id: dataValue('durableUUID'), //Q: does not exist, to add for consistency?
SubmissionUuid: dataValue('_uuid'),
AnswerId: dataValue('_id'),
LastUpdate: new Date().toISOString(),
SurveyDate: state => {
const date = state.data.today || state.data._submission_time;
const year = Number(date.trim().split('-')[0]);
const formName = dataValue('formName');
if (year <= 2010) return Number(formName.trim().split(' ').at(-1));
return year;
},
Landscape: state => {
var landscape = dataValue('landscape')(state);
return state.landscapeMap[landscape] || landscape;
},
Surveyor: dataValue('surveyor'),
Participant: dataValue('participant'),
Arrival: dataValue('arrival'),
District: dataValue('district'),
Village: dataValue('village'),
HhId: dataValue('hh_id'),
BenefProject: dataValue('benef_project'),
HhTypeControl: state => (state.data.hh_type === 'control' ? 1 : 0),
HhTypeOrgBenef: state => (state.data.hh_type === 'wcs_benef' ? 1 : 0),
HhTypeOtherBenef: state => (state.data.hh_type === 'other_benef' ? 1 : 0),
ExplainProject: dataValue('explain_project'),
KnowPa: dataValue('know_PA'),
BenefPa: dataValue('benef_PA'),
ExplainBenefPa: dataValue('explain_benef_PA'),
Livelihood1: dataValue('livelihoods/l1'),
Livelihood2: dataValue('livelihoods/l2'),
Livelihood3: dataValue('livelihoods/l3'),
Livelihood4: dataValue('livelihoods/l4'),
BnsPlus: dataValue('bns_plus'),
});
// Refactor this for scale so it doesn't perform a no-op delete 9/10 times.
// Maybe check result of previous op, then only delete if it was an update.
sql({
query: state =>
`DELETE FROM WCSPROGRAMS_KoboBnsAnswerhhmembers where AnswerId = '${state.data._id}'`,
});
insert('WCSPROGRAMS_KoboBnsAnswerhhmembers', {
//insert hh head first
DatasetUuidId: dataValue('datasetId'),
Id: '0',
//Id: state => state.data.hh_members.length,
AnswerId: dataValue('_id'),
Head: dataValue('gender_head') ? '1' : '0',
Gender: dataValue('gender_head'),
Ethnicity: dataValue('ethnicity_head'),
Birth: state => {
var birth = dataValue('birth_head')(state);
return birth ? parseInt(birth.substring(0, 4)) : null;
},
LastUpdate: new Date().toISOString(),
});
fn(state => {
if (state.data.hh_members) {
return insertMany(
'WCSPROGRAMS_KoboBnsAnswerhhmembers',
(
state //then insert other members
) =>
state.data.hh_members.map((member, i) => ({
DatasetUuidId: state.data.datasetId,
// Id: state.data._id,
Id: i + 1,
AnswerId: state.data._id,
Head: '0',
Gender:
member[`hh_members/gender`] || member[`hh_members/gender_001`],
Ethnicity: member[`hh_members/ethnicity`],
Birth: parseInt(member[`hh_members/birth`].substring(0, 4)),
LastUpdate: new Date().toISOString(),
}))
)(state);
}
console.log('No household members found.');
return state;
});
// Refactor this for scale so it doesn't perform a no-op delete 9/10 times.
// Maybe check result of previous op, then only delete if it was an update.
sql({
query: state =>
`DELETE FROM WCSPROGRAMS_KoboBnsAnswernr where AnswerId = '${state.data._id}'`,
});
fn(state => {
if (state.nr && state.nr.length > 0) {
return insertMany('WCSPROGRAMS_KoboBnsAnswernr', state => state.nr)(state);
}
console.log('No natural resource found.');
return state;
});
// Refactor this for scale so it doesn't perform a no-op delete 9/10 times.
// Maybe check result of previous op, then only delete if it was an update.
//sql({ query: state => `DELETE FROM WCSPROGRAMS_KoboBnsAnswergs where AnswerId = '${state.data._id}'` }); //ERROR: AnswerId does not exist
sql({
query: state =>
`DELETE FROM WCSPROGRAMS_KoboBnsAnswerGS where AnswerId = '${state.data._id}'`,
});
fn(state => {
if (state.matrix && state.matrix.length > 0) {
return insertMany(
'WCSPROGRAMS_KoboBnsAnswerGS',
state => state.matrix
)(state);
}
console.log('No matrix found.');
return state;
});
upsert('WCSPROGRAMS_KoboBnsAnswergps', 'AnswerId', {
DatasetUuidId: dataValue('datasetId'), //Q: Add new column
AnswerId: dataValue('_id'),
Id: dataValue('_id'),
Geom: dataValue('_geolocation'),
Lat: state => {
return dataValue('gps/lat')(state)
? dataValue('gps/lat')(state)
: state.data._geolocation[0] || undefined;
},
Long: state => {
return dataValue('gps/long')(state)
? dataValue('gps/long')(state)
: state.data._geolocation[1] || undefined;
},
LastUpdate: new Date().toISOString(),
});
fn(state => {
console.log('DatasetName ::', state.formName);
console.log('DatasetOwner ::', state.formOwner);
console.log('form submission id ::', state.data['_id']);
console.log('DatasetUuidId ::', state.data['datasetId']);
//console.log('data to upload ::', state.data);
return state;
})
upsert('WCSPROGRAMS_KoboData', 'DatasetUuidId', {
//renamed from DatasetUuid
//AnswerId: dataValue('_id'), //KoboData = 1 Dataset (not 1 survey)
DatasetName: state => state.formName,
DatasetOwner: state => state.formOwner,
Landscape: dataValue('landscape'),
DatasetUuidId: dataValue('datasetId'),
Citation: dataValue('instance'),
DatasetYear: state => {
const date = state.data.today || state.data._submission_time;
const year = Number(date.trim().split('-')[0]);
const formName = dataValue('formName')(state);
const yearToReturn = year;
if (year <= 2010) yearToReturn = Number(formName.trim().split(' ').at(-1));
console.log(yearToReturn);
return yearToReturn;
// const formName = dataValue('formName')(state);
// if (formName === 'BNS Cross River 2017-2020') {
return state.data.body.today.split('-')[0];
// }
//const year = dataValue('body.today');
//console.log(year);
return new Date().getFullYear(); // Here we don't want the date of today we want the year of the value today
//console.log(Date(year).getFullYear());
},
LastSubmissionTime: dataValue('_submission_time'),
LastCheckedTime: dataValue('_submission_time'),
LastUpdateTime: new Date().toISOString(),
KoboManaged: true,
Tags: dataValue('_tags'),
});
BNS-2C-NRGT---Historical-Version:
name: BNS-2C NRGT - Historical Version
adaptor: '@openfn/language-mssql@3.0.0'
credential: rediet@openfn.org-WCS-MSSQL-Test-DB
body: |
// NOTE: This data cleaning operation returns state, modified as needed.
alterState(state => {
try {
const { body, formName, instance } = state.data;
const { _submission_time, _id, _xform_id_string } = body;
let cleanedSubmission = {};
for (const key in body) {
switch (body[key]) {
case 'yes':
cleanedSubmission[key] = 1;
break;
case 'no':
cleanedSubmission[key] = 0;
break;
default:
cleanedSubmission[key] = body[key];
break;
}
}
state.landscapeMap = {
tns: 'ndoki',
mamabay: 'makira',
mtkb: 'kahuzi',
lactele: 'lac_tele',
};
cleanedSubmission.durableUUID = `${_submission_time}-${_xform_id_string}-${_id}`;
cleanedSubmission.datasetId = `${formName}-${_xform_id_string}`;
cleanedSubmission.instance = instance;
state.data = cleanedSubmission;
return state;
} catch (error) {
state.connection.close();
throw error;
}
});
upsert('WCSPROGRAMS_KoboNrgtNrgtanswer', 'AnswerId', {
DatasetUuidId: dataValue('datasetId'),
AnswerId: dataValue('_id'),
Landscape: state => {
var landscape = dataValue('landscape')(state);
return state.landscapeMap[landscape] || landscape;
},
GovGroup: dataValue('gov_group'),
Jurisdiction: dataValue('jurisdiction'),
Objective: dataValue('objective'),
Members: dataValue('members'),
Women: dataValue('women'),
LastUpdate: new Date().toISOString(),
});
upsert('WCSPROGRAMS_KoboNrgtNrgtanswergs', 'AnswerId', {
DatasetUuidId: dataValue('datasetId'),
Id: dataValue('_id'),
AnswerId: dataValue('_id'),
SurveyDate: dataValue('today'),
Code: dataValue('code'),
Gender: dataValue('gender'),
Member: dataValue('member'),
Legitimacy: dataValue('legitimacy'),
Accountability: dataValue('accountability'),
Transparency: dataValue('transparency'),
Participation: dataValue('participation'),
Fairness: dataValue('fairness'),
KnowledgeSkills: dataValue('knowledge_skills'),
Resources: dataValue('resources'),
InstutionalFramework: dataValue('institutional_framework'),
Motivation: dataValue('motivation'),
EnactDecision: dataValue('enact_decision'),
HeldAccountable: dataValue('held_accountable'),
Diversity: dataValue('diversity'),
LastUpdate: new Date().toISOString(),
});
upsert('WCSPROGRAMS_KoboData', 'DatasetUuidId', {
//AnswerId: dataValue('_id'),
DatasetName: state.data.formName,
DatasetOwner: state.data.formOwner,
DatasetUuidId: dataValue('datasetId'),
Citation: dataValue('instance'),
DatasetYear: new Date().getFullYear(),
LastSubmissionTime: dataValue('_submission_time'),
LastCheckedTime: dataValue('_submission_time'),
LastUpdateTime: new Date().toISOString(),
KoboManaged: true,
Tags: dataValue('_tags'),
});
BNS-2D-NRGT-2019:
name: BNS-2D NRGT 2019
adaptor: '@openfn/language-mssql@3.0.0'
credential: rediet@openfn.org-WCS-MSSQL-Test-DB
body: |
// NOTE: This data cleaning operation returns state, modified as needed.
alterState(state => {
try {
const { body, formName, instance } = state.data;
const { _submission_time, _id, _xform_id_string } = body;
let cleanedSubmission = {};
for (const key in body) {
switch (body[key]) {
case 'yes':
cleanedSubmission[key] = 1;
break;
case 'no':
cleanedSubmission[key] = 0;
break;
default:
cleanedSubmission[key] = body[key];
break;
}
}
state.landscapeMap = {
tns: 'ndoki',
mamabay: 'makira',
mtkb: 'kahuzi',
};
cleanedSubmission.durableUUID = `${_submission_time}-${_xform_id_string}-${_id}`;
cleanedSubmission.datasetId = `${formName}-${_xform_id_string}`;
cleanedSubmission.instance = instance;
state.data = cleanedSubmission;
return state;
} catch (error) {
state.connection.close();
throw error;
}
});
upsert('WCSPROGRAMS_KoboNrgtNrgtanswer', 'AnswerId', {
DatasetUuidId: dataValue('datasetId'),
AnswerId: dataValue('_id'),
Landscape: state => {
var landscape = dataValue('landscape')(state);
return state.landscapeMap[landscape] || landscape;
},
Surveyor: dataValue('surveyor'),
GovGroup: dataValue('gov_group'),
SurveyDate: state => {
const date = state.data.today || state.data._submission_time
if (Number(date.split('-')[0]) >= 2014 ) {
return date
}
return 2019
// If the time/date is not properly set on the device used to collect the data, the year of "today" will be 2000.
// With the code above we are replacing any 2000 by 2019:
},
LastUpdate: new Date().toISOString(),
});
upsert('WCSPROGRAMS_KoboNrgtNrgtanswergs', 'AnswerId', {
// upsert('WCSPROGRAMS_KoboNrgtNrgtanswergs', 'DatasetUuidId', {
DatasetUuidId: dataValue('datasetId'),
Id: dataValue('_id'),
AnswerId: dataValue('_id'),
SurveyDate: state => {
const date = state.data.today || state.data._submission_time
if (Number(date.split('-')[0]) >= 2014 ) {
return date
}
return 2019