-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquery.yml
More file actions
2122 lines (2115 loc) · 194 KB
/
Copy pathquery.yml
File metadata and controls
2122 lines (2115 loc) · 194 KB
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
#Released: 2025-08-08
query:
index-query-name: index_elicitation
index-query: SELECT boui.code as "Facility Id (Datim)", state.name AS "State", lga.name AS "LGA", facility.name AS "Facility" , hc.client_code AS "Client Code",
pp.uuid AS "Patient Id",
hc.uuid AS "Index HTS Uuid",
(CASE WHEN hc.test1->>'result' ILIKE 'Yes' THEN 'Positive' ELSE 'Negative' END) AS "HIV Status of Index",
hc.index_notification_services_elicitation ->> 'OfferedIns' AS "Offered INS",
hc.index_notification_services_elicitation ->> 'AcceptedIns' AS "Accepted INS",
hc.client_code AS "Index Code",
hie.dob AS "Date of Birth",
se.display AS "Sex",
noti_method.display AS "Notification Method",
sexually_un.display AS "Sexually uncomfortable",
CASE WHEN hie.currently_live_with_partner IS TRUE THEN 'Yes' ELSE 'No' END AS "Currently living with partner",
relationship.display AS "Relationship with index client",
hie.date_partner_came_for_testing AS "Date Partner Came For Testing"
FROM hts_client hc
LEFT JOIN patient_person pp ON pp.uuid=hc.person_uuid
INNER JOIN hts_index_elicitation hie ON hie.hts_client_uuid = hc.uuid
LEFT JOIN base_application_codeset se ON se.id=hie.sex
LEFT JOIN base_application_codeset noti_method ON noti_method.id=hie.notification_method
LEFT JOIN base_application_codeset sexually_un ON sexually_un.id=hie.sexually_uncomfortable
LEFT JOIN base_application_codeset relationship ON relationship.id=hie.relationship_with_index_client
LEFT JOIN base_organisation_unit facility ON facility.id=hc.facility_id
LEFT JOIN base_organisation_unit state ON state.id=facility.parent_organisation_unit_id
LEFT JOIN base_organisation_unit lga ON lga.id=state.parent_organisation_unit_id
LEFT JOIN base_organisation_unit_identifier boui ON boui.organisation_unit_id=hc.facility_id AND boui.name='DATIM_ID'
WHERE hc.archived=0 AND hc.facility_id=%d AND
hc.date_visit BETWEEN CAST('%s' AS DATE)
AND CAST('%s' AS DATE)
biometric-query-name: biometric
biometric-query: SELECT result.state AS "State", result.lga AS "LGA", result.facility AS "Facility",
result.uuid AS "Patient ID", result.hospitalNumber AS "Hospital Number",
base.enrollment_date AS "Date Base Biometrics Enrolled (yyyy-mm-dd)",
base.count AS "Number of Base Fingerprint Captured",
first_recapture.enrollment_date AS "Date of 1st Biometric Recapture",
first_recapture.count AS "Number of 1st Biometric Recaptured Fingerprints",
first_recapture.perfectMatch AS "Baseline Match Perfect", first_recapture.imperfectMatch AS "Baseline Match Imperfect",
first_recapture.noMatch AS "Baseline Match No-Match",
second_recapture.enrollment_date AS "Date of 2nd Biometric Recapture",
second_recapture.count AS "Number of 2nd Recapture Fingerprints Captured",
second_recapture.perfectMatch AS "Recapture Match Perfect", second_recapture.imperfectMatch AS "Recapture Match Imperfect",
second_recapture.noMatch AS "Recapture Match No-Match",
third_recapture.enrollment_date AS "Date of 3rd Biometric Recapture",
third_recapture.count AS "Number of 3rd Recapture Fingerprints Captured",
third_recapture.perfectMatch AS " 3rd Recapture Match Perfect", third_recapture.imperfectMatch AS "3rd Recapture Match Imperfect",
third_recapture.noMatch AS "3rd Recapture Match No-Match",
recentData.recentEnrollmentDate AS "Date of last Recapture", recentData.recentCapture AS "Number of Recapture Done",
(CASE WHEN second_recapture.replace_date IS NOT NULL THEN second_recapture.replace_date
WHEN first_recapture.replace_date IS NOT NULL THEN first_recapture.replace_date
WHEN base.replace_date IS NOT NULL THEN base.replace_date
ELSE NULL END) AS "Date Base Fingerprint Replaced"
FROM
(SELECT pp.hospital_number AS hospitalNumber, pp.facility_id,
pp.uuid, facility.name AS facility, state.name AS state, lga.name AS lga
FROM patient_person pp
INNER JOIN hiv_enrollment he ON he.person_uuid=pp.uuid AND he.archived=0
LEFT JOIN base_organisation_unit facility ON facility.id=pp.facility_id
LEFT JOIN base_organisation_unit state ON state.id=facility.parent_organisation_unit_id
LEFT JOIN base_organisation_unit lga ON lga.id=state.parent_organisation_unit_id
LEFT JOIN base_organisation_unit_identifier boui ON boui.organisation_unit_id=pp.facility_id
AND boui.name='DATIM_ID'
WHERE pp.archived=0
AND pp.facility_id=%d
AND pp.date_of_registration BETWEEN CAST('%s' AS DATE) AND CAST('%s' AS DATE)
) AS result
LEFT JOIN (
SELECT
person_uuid,
MAX(enrollment_date) enrollment_date, replace_date,
count
FROM
biometric
WHERE
recapture = 0
AND archived=0
AND count is not null
AND enrollment_date is not null
AND version_iso_20 IS TRUE
GROUP BY person_uuid, count, replace_date
) base ON result.uuid = base.person_uuid
LEFT JOIN (
SELECT
person_uuid,
MAX(enrollment_date) AS enrollment_date,
replace_date,
COUNT(CASE WHEN match_type = 'Perfect Match' THEN 1 ELSE NULL END) AS perfectMatch,
COUNT(CASE WHEN match_type = 'Imperfect Match' THEN 1 ELSE NULL END) AS imperfectMatch,
COUNT(CASE WHEN match_type = 'No Match' THEN 1 ELSE NULL END) AS noMatch,
count FROM biometric WHERE
(recapture = 1)
AND archived = 0
AND count IS NOT NULL
AND enrollment_date IS NOT NULL
AND version_iso_20 IS TRUE GROUP BY person_uuid, count, replace_date
) AS first_recapture ON result.uuid = first_recapture.person_uuid
LEFT JOIN (
SELECT
person_uuid,
MAX(enrollment_date) enrollment_date, replace_date,
COUNT(CASE WHEN match_type = 'Perfect Match' THEN 1 ELSE NULL END) AS perfectMatch,
COUNT(CASE WHEN match_type = 'Imperfect Match' THEN 1 ELSE NULL END) AS imperfectMatch,
COUNT(CASE WHEN match_type = 'No Match' THEN 1 ELSE NULL END) AS noMatch,
count
FROM biometric WHERE
(recapture = 2)
AND archived=0
AND count is not null
AND enrollment_date is not null
AND version_iso_20 IS TRUE
GROUP BY person_uuid, count, replace_date
) AS second_recapture ON result.uuid = second_recapture.person_uuid
LEFT JOIN (
SELECT
person_uuid,
MAX(enrollment_date) enrollment_date, replace_date,
COUNT(CASE WHEN match_type = 'Perfect Match' THEN 1 ELSE NULL END) AS perfectMatch,
COUNT(CASE WHEN match_type = 'Imperfect Match' THEN 1 ELSE NULL END) AS imperfectMatch,
COUNT(CASE WHEN match_type = 'No Match' THEN 1 ELSE NULL END) AS noMatch,
count
FROM biometric WHERE
(recapture = 3)
AND archived=0
AND count is not null
AND enrollment_date is not null
AND version_iso_20 IS TRUE
GROUP BY person_uuid, count, replace_date ) AS third_recapture ON result.uuid = third_recapture.person_uuid
LEFT JOIN (SELECT * FROM (SELECT person_uuid, enrollment_date AS recentEnrollmentDate, MAX(recapture) AS recentCapture, ROW_NUMBER () OVER (PARTITION BY person_uuid ORDER BY enrollment_date DESC) AS rank1
FROM biometric WHERE
archived=0
AND count is not null
AND enrollment_date is not null
AND version_iso_20 IS TRUE
GROUP BY person_uuid, count, enrollment_date) recent where rank1 = 1 ) recentData ON recentData.person_uuid = result.uuid
pmtct-hts-query-name: pmtct-hts
pmtct-hts-query: select pmtct."State", pmtct."LGA", pmtct."Facility", pmtct."Patient ID", pmtct."ANC Number", pmtct."Mother''s Hospital Num", pmtct."Mother''s Date of Birth", pmtct."Age", pmtct."Marital Status", pmtct."ANC Setting", pmtct."Point of Entry", pmtct."Modality", pmtct."Date of registration in index pregnancy",
pmtct."Gestational Age (Weeks) @ First ANC visit", pmtct."Gravida", pmtct."Parity", pmtct."Date Tested for HIV", pmtct."HIV Test Result", pmtct."Date Tested for Hepatitis B", pmtct."Hepatitis B Test Result",pmtct."Date Tested for Hepatitis C", pmtct."Hepatitis C Test Result", pmtct."Date tested for Syphillis", pmtct."Syphillis Test Result",
pmtct."If Recency Testing Opt In", pmtct."Recency ID", pmtct."Recency Test Type", pmtct."Recency Test Date (yyyy_mm_dd)", pmtct."Recency Interpretation", pmtct."Viral Load Sample Collection Date", pmtct."Viral Load Confirmation Result", pmtct."Viral Load Confirmation Date (yyyyy-mm-dd)", pmtct."Final Recency Result",
pmtct."Date Of Maternal Retesting", pmtct."Maternal Retesting Result", pmtct."Mother''s ART Start Date", pmtct."Previously Known HIV Status", pmtct."Mother''s Unique ID", pmtct."Linked to Syphilis Treatment"
from (
SELECT DISTINCT ON (p.uuid)p.uuid AS PersonUuid,
facility_state.name as "State",
facility_lga.name as "LGA",
facility.name as "Facility",
p.uuid as "Patient ID",
p.id,
anc.anc_no as "ANC Number",
p.hospital_number as "Mother''s Hospital Num",
p.date_of_birth AS "Mother''s Date of Birth",
EXTRACT(YEAR from AGE(CAST('?3' AS DATE), date_of_birth)) as "Age",
p.marital_status->>'display' as "Marital Status",
anc.anc_setting_anc as "ANC Setting",
anc.first_anc_date,
anc.gaweeks_anc as "Gestational Age (Weeks) @ First ANC visit",
anc.gravida_anc as "Gravida",
anc.parity_anc as "Parity",
delivery.hbstatus_delivery,
anc.tested_syphilis_anc,
anc.test_result_syphilis_anc ,
anc.syphillisStatus AS Partner_syphilis_status,
p.date_of_registration as dateOfRegistration,
he.date_started AS hivEnrollmentDate,
anc.acceptHivTest AS Partner_acceptHivTest,
anc.referredTo AS Partner_syphilis_status,
anc.age AS Partner_age,
he.date_of_registration as dateOfRegistrationOnHiv,
he.date_confirmed_hiv,
he.date_started as "Mother''s ART Start Date",
anc.previously_known_hiv_status as "Previously Known HIV Status",
(CASE WHEN hts_client.hepatitisBTestResult IS NOT NULL THEN hts_client.date_created_hts_client ELSE NULL END) as "Date Tested for Hepatitis B",
hts_client.hepatitisBTestResult as "Hepatitis B Test Result",
(CASE WHEN hts_client.hepatitisCTestResult IS NOT NULL THEN hts_client.date_created_hts_client ELSE NULL END) as "Date Tested for Hepatitis C",
hts_client.hepatitisCTestResult as "Hepatitis C Test Result",
anc.hivRestested AS hivRestested,
CAST (anc.max_created_date_anc AS DATE) as "Date tested for Syphillis",
anc.test_result_syphilis_anc AS "Syphillis Test Result",
anc.acceptedHIVTesting AS acceptedHIVTesting,
hts_client.hiv_test_result2_hts_client AS "HIV Test Result",
hts_client.date_created_hts_client AS "Date Tested for HIV",
anc.receivedHivRetestedResult AS receivedHivRetestedResult,
anc.previouslyKnownHIVPositive AS previouslyKnownHIVPositive,
(select display from base_application_codeset where code = hts_rst.entry_point) AS "Point of Entry",
bac.display AS "Modality",
pmtctenroll.pmtct_enrollment_date AS "Date of registration in index pregnancy",
he.unique_id AS "Mother''s Unique ID",
hts_retest.date_visit as "Date Of Maternal Retesting",
hts_retest.hiv_test_result2 as "Maternal Retesting Result",
anc.syphilis_treatment_status as "Linked to Syphilis Treatment",
hts_client.optOutRTRI_status as "If Recency Testing Opt In",
hts_client.rencencyId as "Recency ID",
hts_client.sampleType as "Recency Test Type",
hts_client.rencencyTestDate as "Recency Test Date (yyyy_mm_dd)",
hts_client.rencencyInterpretation as "Recency Interpretation",
pmtctdov.date_of_viral_load as "Viral Load Sample Collection Date",
hts_client.finalRecencyResult as "Final Recency Result",
labResult.result_reported as "Viral Load Confirmation Result",
labResult.date_result_reported as "Viral Load Confirmation Date (yyyyy-mm-dd)"
FROM patient_person p
INNER JOIN (
SELECT * FROM (SELECT p.id, CONCAT(CAST(address_object->>'city' AS VARCHAR), ' ', REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(CAST(address_object->>'line' AS text), '\\\\\\\\', ''), ']', ''), '[', ''), 'null',''), '\\\\\\\', '')) AS address,
CASE WHEN address_object->>'stateId' ~ '^\\\\d+(\\\\.\\\\d+)?$' THEN address_object->>'stateId' ELSE null END AS stateId,
CASE WHEN address_object->>'district' ~ '^\\\\d+(\\\\.\\\\d+)?$' THEN address_object->>'district' ELSE null END AS lgaId
FROM patient_person p,
jsonb_array_elements(p.address-> 'address') with ordinality l(address_object)) as result
) r ON r.id=p.id
LEFT JOIN (
SELECT person_uuid AS person_uuid_anc,
(select display from base_application_codeset where code = anc_setting) AS anc_setting_anc,
previously_known_hiv_status,
first_anc_date AS first_anc_date,
gaweeks AS gaweeks_anc,
gravida AS gravida_anc,
parity As parity_anc,
tested_syphilis AS tested_syphilis_anc,
test_result_syphilis AS test_result_syphilis_anc,
CASE
WHEN treated_syphilis = 'Yes' THEN 'Treated'
WHEN referred_syphilis_treatment = 'Yes' THEN 'Referred for Treatment'
ELSE 'No treatment'
END as syphilis_treatment_status,
partner_information->>'age' AS age,
partner_information->>'syphillisStatus' AS syphillisStatus,
partner_information->>'acceptHivTest' AS acceptHivTest,
partner_information->>'referredTo' AS referredTo,
pmtct_hts_info->>'hivRestested' AS hivRestested,
pmtct_hts_info->>'hivTestResult' AS hivTestResult,
pmtct_hts_info->>'acceptedHIVTesting' AS acceptedHIVTesting,
pmtct_hts_info->>'dateTestedHivPositive' AS dateTestedHivPositive,
pmtct_hts_info->>'receivedHivRetestedResult' AS receivedHivRetestedResult,
pmtct_hts_info->>'previouslyKnownHIVPositive' AS previouslyKnownHIVPositive,
anc_no AS anc_no,
static_hiv_status,
MAX(created_date) AS max_created_date_anc
FROM pmtct_anc
GROUP BY person_uuid, anc_setting, first_anc_date, gaweeks, gravida, parity, tested_syphilis, test_result_syphilis, partner_information, anc_no, static_hiv_status,
pmtct_hts_info,syphilis_treatment_status,previously_known_hiv_status
) AS anc ON p.uuid = anc.person_uuid_anc
LEFT JOIN (
SELECT person_uuid AS person_uuid_delivery,
hbstatus AS hbstatus_delivery,
MAX(created_date) AS max_created_date_delivery
FROM pmtct_delivery
GROUP BY person_uuid, hbstatus
) AS delivery ON p.uuid = delivery.person_uuid_delivery
LEFT JOIN pmtct_delivery panc ON p.uuid = panc.person_uuid AND panc.created_date = delivery.max_created_date_delivery
LEFT JOIN base_organisation_unit facility ON facility.id=p.facility_id
LEFT JOIN base_organisation_unit facility_lga ON facility_lga.id=facility.parent_organisation_unit_id
LEFT JOIN base_organisation_unit facility_state ON facility_state.id=facility_lga.parent_organisation_unit_id
LEFT JOIN base_organisation_unit res_state ON res_state.id=CAST(r.stateid AS BIGINT)
LEFT JOIN base_organisation_unit res_lga ON res_lga.id=CAST(r.lgaid AS BIGINT)
LEFT JOIN base_organisation_unit_identifier boui ON boui.organisation_unit_id=p.facility_id AND boui.name='DATIM_ID'
LEFT JOIN (
SELECT person_uuid, date_visit, (CASE WHEN (hiv_test_result2 IS NULL OR hiv_test_result2 = '') THEN hiv_test_result ELSE hiv_test_result2 END) as hiv_test_result2,
ROW_NUMBER() OVER (PARTITION BY person_uuid ORDER BY date_visit DESC) AS rowNums
FROM hts_client
WHERE testing_setting IN ('TEST_SETTING_STANDALONE_HTS', 'TEST_SETTING_OTHERS')
AND date_visit BETWEEN CAST('?2' AS DATE) AND CAST('?3' AS DATE)
) as hts_retest ON p.uuid = hts_retest.person_uuid AND rowNums > 1
LEFT JOIN (
SELECT person_uuid as person_uuid_hts_client,
(CASE WHEN (hiv_test_result2 IS NULL OR hiv_test_result2 = '') THEN hiv_test_result ELSE hiv_test_result2 END) as hiv_test_result2_hts_client,
risk_stratification_code as risk_stratification_code_hts_client,
(CASE WHEN hepatitis_testing->>'hepatitisBTestResult' = 'Yes' THEN 'Positive' WHEN hepatitis_testing->>'hepatitisBTestResult' = 'No' THEN 'Negative' ELSE hepatitis_testing->>'hepatitisBTestResult' END) AS hepatitisBTestResult,
(CASE WHEN hepatitis_testing->>'hepatitisCTestResult' = 'Yes' THEN 'Positive' WHEN hepatitis_testing->>'hepatitisCTestResult' = 'No' THEN 'Negative' ELSE hepatitis_testing->>'hepatitisCTestResult' END) AS hepatitisCTestResult,
recency->>'optOutRTRI' AS optOutRTRI,
CASE
WHEN recency->>'optOutRTRI' = 'false' THEN 'No'
WHEN recency->>'optOutRTRI' = 'true' THEN 'Yes'
ELSE recency->>'optOutRTRI'
END AS optOutRTRI_status,
recency->>'rencencyId' AS rencencyId,
recency->>'sampleType' AS sampleType,
recency->>'optOutRTRITestDate' AS rencencyTestDate,
recency->>'rencencyInterpretation' AS rencencyInterpretation,
recency->>'finalRecencyResult' AS finalRecencyResult,
(CASE WHEN (hiv_test_result2 IS NOT NULL OR hiv_test_result2 != '') THEN
date_visit ELSE NULL END) as date_created_hts_client,
MAX(date_visit) AS max_date_created_hts_client,
date_visit
FROM hts_client
WHERE archived = 0
GROUP BY person_uuid, date_visit, hiv_test_result, hiv_test_result2,risk_stratification_code,hepatitis_testing,date_created,recency,optOutRTRI
) as hts_client ON p.uuid = hts_client.person_uuid_hts_client
LEFT JOIN
public.hts_risk_stratification hts_rst
ON hts_client.risk_stratification_code_hts_client = hts_rst.code
LEFT JOIN
public.base_application_codeset bac
ON hts_rst.modality = bac.code
LEFT JOIN
public.pmtct_enrollment pmtctenroll
ON hts_client.person_uuid_hts_client = pmtctenroll.person_uuid
LEFT JOIN
public.pmtct_mother_visitation pmtctdov
ON hts_client.person_uuid_hts_client = pmtctdov.person_uuid
LEFT JOIN
public.laboratory_order labOrder
ON p.uuid = labOrder.patient_uuid
LEFT JOIN
public.laboratory_test labTest
ON labOrder.id = labTest.lab_order_id
LEFT JOIN
public.laboratory_result labResult
ON labResult.test_id = labTest.id
LEFT JOIN hiv_enrollment he ON he.person_uuid = p.uuid
WHERE p.archived=0 and p.sex='Female' AND hts_rst.testing_setting IN ('TEST_SETTING_OTHERS', 'TEST_SETTING_CPMTCT', 'TEST_SETTING_STANDALONE_HTS') AND hts_rst.modality IN ('TEST_SETTING_STANDALONE_HTS_POST_ANC1_PREGNANT_L&D','TEST_SETTING_STANDALONE_HTS_POST_ANC1_BREASTFEEDING','TEST_SETTING_STANDALONE_HTS_PMTCT_(ANC1_ONLY)','TEST_SETTING_OTHERS_PMTCT_(ANC1_ONLY)','TEST_SETTING_OTHERS_POST_ANC1_BREASTFEEDING','TEST_SETTING_OTHERS_POST_ANC1_PREGNANT_L&D', 'TEST_SETTING_CPMTCT_CONGREGATIONAL_SETTING','TEST_SETTING_CPMTCT_DELIVERY_HOMES', 'TEST_SETTING_CPMTCT_SPOKE_HEALTH_FACILITY', 'TEST_SETTING_CPMTCT_TBA_ORTHODX', 'TEST_SETTING_CPMTCT_TBA_RT-HCW') AND p.facility_id=?1
AND hts_client.date_visit BETWEEN CAST('?2' AS DATE) AND CAST('?3' AS DATE)
) as pmtct
pmtct-maternal-cohort-query-name: pmtct-maternal-cohort
pmtct-maternal-cohort-query: with target_pharmacies as (select * from hiv_art_pharmacy where person_uuid in (select distinct person_uuid from pmtct_mother_visitation)),
target_statuses as (select * from hiv_status_tracker where person_id in (select distinct person_uuid from pmtct_mother_visitation)),
art_status as (
( SELECT DISTINCT ON (pharmacy.person_uuid) pharmacy.person_uuid AS cuPersonUuid,
(
CASE
WHEN stat.hiv_status ILIKE '%DEATH%' OR stat.hiv_status ILIKE '%Died%' THEN 'Died'
WHEN( stat.status_date > pharmacy.maxdate AND (stat.hiv_status ILIKE '%stop%' OR stat.hiv_status ILIKE '%out%' OR stat.hiv_status ILIKE '%Invalid %'))
THEN stat.hiv_status
ELSE pharmacy.status
END
) AS status
FROM
(
SELECT
(
CASE
WHEN hp.visit_date + hp.refill_period + INTERVAL '29 day' < CAST('?3' AS DATE) THEN 'IIT'
ELSE 'Active'
END
) status,
(
CASE
WHEN hp.visit_date + hp.refill_period + INTERVAL '29 day' < CAST('?3' AS DATE) THEN hp.visit_date + hp.refill_period + INTERVAL '29 day'
ELSE hp.visit_date
END
) AS visit_date,
hp.person_uuid, MAXDATE
FROM
target_pharmacies hp
INNER JOIN (
SELECT hap.person_uuid, hap.visit_date AS MAXDATE, ROW_NUMBER() OVER (PARTITION BY hap.person_uuid ORDER BY hap.visit_date DESC) as rnkkk3
FROM target_pharmacies hap
INNER JOIN hiv_enrollment h ON h.person_uuid = hap.person_uuid AND h.archived = 0
inner join jsonb_array_elements(hap.extra->'regimens') as ex(data) on true
INNER JOIN public.hiv_regimen r on r.description = ex.data->>'name' and r.active=true
INNER JOIN public.hiv_regimen_type rt on rt.id = r.regimen_type_id
WHERE r.regimen_type_id in (1,2,3,4,14)
AND hap.archived = 0
AND hap.visit_date < CAST('?3' AS DATE)
) MAX ON MAX.MAXDATE = hp.visit_date AND MAX.person_uuid = hp.person_uuid
AND MAX.rnkkk3 = 1 WHERE
hp.archived = 0
AND hp.visit_date < CAST('?3' AS DATE)
) pharmacy
LEFT JOIN (
SELECT
hst.hiv_status,
hst.person_id,
hst.cause_of_death, hst.va_cause_of_death,
hst.status_date
FROM
(
SELECT * FROM (SELECT DISTINCT (person_id) person_id, status_date, cause_of_death, va_cause_of_death,
hiv_status, ROW_NUMBER() OVER (PARTITION BY person_id ORDER BY status_date DESC)
FROM target_statuses WHERE archived=0 AND status_date <= CAST('?3' AS DATE) )s
WHERE s.row_number=1
) hst
INNER JOIN hiv_enrollment he ON he.person_uuid = hst.person_id
WHERE hst.status_date < CAST('?3' AS DATE)
) stat ON stat.person_id = pharmacy.person_uuid
)
),cvl as (
SELECT * FROM (
SELECT CAST(ls.date_sample_collected AS DATE ) AS dateOfCurrentViralLoadSample, sm.patient_uuid as person_uuid130 , sm.facility_id as vlFacility, sm.archived as vlArchived, acode.display as viralLoadIndication, sm.result_reported as currentViralLoad,CAST(sm.date_result_reported AS DATE) as dateOfCurrentViralLoad,
ROW_NUMBER () OVER (PARTITION BY sm.patient_uuid ORDER BY date_result_reported DESC) as rank2
FROM public.laboratory_result sm
INNER JOIN public.laboratory_test lt on sm.test_id = lt.id
INNER JOIN public.laboratory_sample ls on ls.test_id = lt.id
INNER JOIN public.base_application_codeset acode on acode.id = lt.viral_load_indication
WHERE lt.lab_test_id = 16
AND lt.viral_load_indication !=719
AND sm. date_result_reported IS NOT NULL
AND sm.result_reported is NOT NULL
)as vl_result
WHERE vl_result.rank2 = 1
AND (vl_result.vlArchived = 0 OR vl_result.vlArchived is null)
)
select pmtct."State", pmtct."LGA", pmtct."Facility", pmtct."Patient ID", pmtct."Mother''s Hospital Number", pmtct."Mother''s Unique ID",pmtct."Mother''s Date of Birth", pmtct."Age", pmtct."Marital Status", pmtct."ANC Setting",
pmtct."Modality",pmtct."Point of Entry", pmtct."Date of First Visit", pmtct."Date of Index ANC Registration", pmtct."LMP Date", pmtct."Gestational Age (Weeks) @ First ANC visit", pmtct."Gravida", pmtct."Parity", pmtct."PCV @ANC registration", pmtct."Hepatitis B Test Result",
pmtct."Treated for Hepatitis B", pmtct."Syphilis Test Result",pmtct."Treated for Syphilis", pmtct."TB screening Status",pmtct."Date tested for HIV",pmtct."Type of HIV test",pmtct."Mother''s ART Start Date",pmtct."Timing of ART initiation in mother",pmtct. "Current Pregnancy Status",
pmtct."GA at last visit (weeks)",pmtct."Mother''s Current ART Status",pmtct."Visit Status",pmtct."Mother''s DSD Status",pmtct."Due Date for VL Sample collection @ 32 weeks",pmtct."Date for VL sample collection @ 32 weeks",
pmtct."VL result at 32-36 weeks GA", pmtct."Date of VL result at 32-36 weeks GA", pmtct."Current Viral load Result",pmtct."Date of Current VL",pmtct."Date of Delivery",pmtct."Place of Delivery",pmtct."Mode of Delivery" ,pmtct."Fetal outcome (Child status)",pmtct."Child''s hospital ID number",
pmtct."Sex - Child",pmtct."Birth Weight",pmtct."Date of ARV Prophylaxis Commencemment",pmtct."Type of Prophylaxis (ePNP or regular)",/*pmtct.age_at_ctx,*/pmtct."Date of CTX (Cotrimoxazole)",pmtct."Current infant feeding options",
pmtct."Date of First DNA PCR Sample collection",pmtct."Result of first DNA PCR test", pmtct."Date first DNA PCR result was received",pmtct."Date of Second DNA PCR test sample collection",pmtct."Result of second DNA PCR test",pmtct."Date second DNA PCR result was received",pmtct."Date of third DNA PCR test sample collection",pmtct."Result of third DNA PCR test",pmtct."Date third DNA PCR result was received",pmtct."Date of fourth DNA PCR test sample collection",pmtct."Result of fourth DNA PCR test",pmtct."Date fourth DNA PCR result was received",
pmtct."Date of confirmatory DNA PCR test sample collection",pmtct."Result of confirmatory DNA PCR test",pmtct."Date confirmatory DNA PCR result was received",
pmtct."Date of Child Final Outcome test",pmtct."Result (Child Final Outcome)",pmtct."Child''s ART Start Date",pmtct."Child Unique ID"
from (
SELECT DISTINCT pii.hospital_number, p.uuid AS PersonUuid,
facility_state.name as "State",
facility_lga.name as "LGA",
facility.name as "Facility",
p.uuid as "Patient ID",
p.hospital_number as "Mother''s Hospital Number",
he.unique_id as "Mother''s Unique ID",
p.date_of_birth as "Mother''s Date of Birth",
EXTRACT(YEAR from AGE(CAST('?3' AS DATE), date_of_birth)) as "Age",
p.marital_status->>'display' as "Marital Status",
anc.anc_setting_anc as "ANC Setting",
(select display from base_application_codeset where code = anc.anc_setting_anc) as "Modality",
(select display from base_application_codeset where code = pmtctenroll.entry_point) as "Point of Entry", firstVisitDate.dateOfVisit AS "Date of First Visit",
anc.first_anc_date as "Date of Index ANC Registration",
(case when anc.anc_no is not null then anc.lmp else pmtctenroll.lmp end) AS "LMP Date",
anc.gaweeks_anc as "Gestational Age (Weeks) @ First ANC visit",
(case when anc.anc_no is not null then anc.gravida_anc else pmtctenroll.gravida end) as "Gravida",
anc.parity_anc as "Parity",
'' as "PCV @ANC registration",
pmtctenroll.hepatitisb as "Hepatitis B Test Result",
anc.test_result_syphilis_anc as "Syphilis Test Result",
anc.treatedHepatitisB as "Treated for Hepatitis B",
anc.treated_syphilis as "Treated for Syphilis",
(select display from base_application_codeset where code = pmtctenroll.tb_status) as "TB screening Status",
hts_retest.date_visit as "Date tested for HIV",
(CASE WHEN hts_retest.rowNums > 1 THEN 'Retesting' WHEN hts_retest.rowNums <= 1 THEN 'First test' END ) as "Type of HIV test",
pmtctenroll.art_start_date as "Mother''s ART Start Date",
(select display from base_application_codeset where code = pmtctenroll.art_start_time) as "Timing of ART initiation in mother",
(select display from base_application_codeset where code = hc.pregnancy_status) as "Current Pregnancy Status",
pmv.ga_of_viral_load as "GA at last visit (weeks)",
ast.status as "Mother''s Current ART Status",
(select display from base_application_codeset where code = pmv.visit_status) as "Visit Status",
(select display from base_application_codeset where code = pmv.dsd_option) as "Mother''s DSD Status",
CAST(anc.lmp + interval '32 weeks'AS DATE) as "Due Date for VL Sample collection @ 32 weeks",
gaViral.date_of_viral_load as "Date for VL sample collection @ 32 weeks",
gaViral.ga_of_viral_load as "VL result at 32-36 weeks GA",
gaViral.result_of_viral_load as "Date of VL result at 32-36 weeks GA",
cvl.currentviralload as "Current Viral load Result",
cvl.dateofcurrentviralload as "Date of Current VL",
delivery.date_of_delivery as "Date of Delivery",
(select display from base_application_codeset where code = delivery.place_of_delivery) as "Place of Delivery",
(select display from base_application_codeset where code = delivery.mode_of_delivery) as "Mode of Delivery",
(select display from base_application_codeset where code = delivery.child_status) as "Fetal outcome (Child status)",
pii.hospital_number as "Child''s hospital ID number",
(select display from base_application_codeset where code = pii.sex) as "Sex - Child",
pii.body_weight as "Birth Weight",
pia.infant_arv_time as "Date of ARV Prophylaxis Commencemment",
(select display from base_application_codeset where code = pia.infant_arv_type) as "Type of Prophylaxis (ePNP or regular)",
(select display from base_application_codeset where code = pia.age_at_ctx) as "Date of CTX (Cotrimoxazole)",
(select display from base_application_codeset where code = delivery.feeding_decision) as "Current infant feeding options",
first.date_sample_collected as "Date of First DNA PCR Sample collection",
(select display from base_application_codeset where code = first.results) as "Result of first DNA PCR test",
first.date_result_received_at_facility as "Date first DNA PCR result was received",
first.date_sample_collected as "Date of first DNA PCR test sample collection",
second.date_sample_collected as "Date of Second DNA PCR test sample collection",
(select display from base_application_codeset where code = second.results) as "Result of second DNA PCR test",
second.date_result_received_at_facility as "Date second DNA PCR result was received",
third.date_sample_collected as "Date of third DNA PCR test sample collection",
(select display from base_application_codeset where code = third.results) as "Result of third DNA PCR test",
third.date_result_received_at_facility as "Date third DNA PCR result was received",
fourth.date_sample_collected as "Date of fourth DNA PCR test sample collection",
(select display from base_application_codeset where code = fourth.results) as "Result of fourth DNA PCR test",
fourth.date_result_received_at_facility as "Date fourth DNA PCR result was received",
confirm.date_sample_collected as "Date of confirmatory DNA PCR test sample collection",
(select display from base_application_codeset where code = confirm.results) as "Result of confirmatory DNA PCR test",
confirm.date_result_received_at_facility as "Date confirmatory DNA PCR result was received",
'' as "Sample collection date for Confirmatory DBS (if DBS positive)",
'' as "Result of Confirmatory DBS",
'' as "Date of Child Final Outcome test",
'' as "Result (Child Final Outcome)",
'' as "Child''s ART Start Date",
'' as "Child Unique ID"
FROM patient_person p
LEFT join hiv_enrollment he on he.person_uuid = p.uuid
LEFT JOIN (SELECT * FROM (
SELECT person_uuid personUuid, date_of_visit dateOfVisit,
ROW_NUMBER() OVER (PARTITION BY person_uuid ORDER BY date_of_visit ASC) AS rowNums
FROM pmtct_mother_visitation WHERE date_of_visit BETWEEN '?2' AND '?3'
) subQ WHERE rowNums = 1)firstVisitDate ON firstVisitDate.personUuid = p.uuid
left JOIN (select distinct on (person_uuid) person_uuid,date_of_observation,data from hiv_observation order by 1,2 desc ) as ho
on ho.person_uuid = p.uuid
left JOIN (select distinct on (person_uuid) person_uuid,visit_date,pregnancy_status from hiv_art_clinical order by 1,2 desc ) as hc
on hc.person_uuid = p.uuid
INNER JOIN (
SELECT * FROM (SELECT p.id, CONCAT(CAST(address_object->>'city' AS VARCHAR), ' ', REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(CAST(address_object->>'line' AS text), '\\\\\\\\', ''), ']', ''), '[', ''), 'null',''), '\\\\\\\', '')) AS address,
CASE WHEN address_object->>'stateId' ~ '^\\\\d+(\\\\.\\\\d+)?$' THEN address_object->>'stateId' ELSE null END AS stateId,
CASE WHEN address_object->>'district' ~ '^\\\\d+(\\\\.\\\\d+)?$' THEN address_object->>'district' ELSE null END AS lgaId
FROM patient_person p,
jsonb_array_elements(p.address-> 'address') with ordinality l(address_object)) as result
) r ON r.id=p.id
LEFT JOIN (
SELECT person_uuid AS person_uuid_anc,
(CASE WHEN community_setting = 'PMTCT (ANC1 Only)' THEN 'PMTCT (ANC1 Only)' ELSE (select display from base_application_codeset where code = community_setting) END) AS anc_setting_anc,
first_anc_date AS first_anc_date,
lmp,
gaweeks AS gaweeks_anc,
gravida AS gravida_anc,
parity As parity_anc,
tested_syphilis AS tested_syphilis_anc,
test_result_syphilis AS test_result_syphilis_anc,
treated_syphilis,
partner_information->>'age' AS age,
partner_information->>'syphillisStatus' AS syphillisStatus,
partner_information->>'acceptHivTest' AS acceptHivTest,
partner_information->>'referredTo' AS referredTo,
pmtct_hts_info->>'hivRestested' AS hivRestested,
pmtct_hts_info->>'hivTestResult' AS hivTestResult,
pmtct_hts_info->>'acceptedHIVTesting' AS acceptedHIVTesting,
pmtct_hts_info->>'dateTestedHivPositive' AS dateTestedHivPositive,
pmtct_hts_info->>'receivedHivRetestedResult' AS receivedHivRetestedResult,
pmtct_hts_info->>'previouslyKnownHIVPositive' AS previouslyKnownHIVPositive,
anc_no AS anc_no, treated_hepatitisb AS treatedHepatitisB,
static_hiv_status
FROM pmtct_anc
WHERE archived = 0
) AS anc ON p.uuid = anc.person_uuid_anc
LEFT JOIN (
SELECT person_uuid, date_visit, hiv_test_result2,
ROW_NUMBER() OVER (PARTITION BY person_uuid ORDER BY date_visit DESC) AS rowNums
FROM hts_client
WHERE hiv_test_result2 = 'Positive'
AND date_visit BETWEEN CAST('?2' AS DATE) AND CAST('?3' AS DATE)
) as hts_retest ON p.uuid = hts_retest.person_uuid
LEFT JOIN base_organisation_unit facility ON facility.id=p.facility_id
LEFT JOIN base_organisation_unit facility_lga ON facility_lga.id=facility.parent_organisation_unit_id
LEFT JOIN base_organisation_unit facility_state ON facility_state.id=facility_lga.parent_organisation_unit_id
LEFT JOIN base_organisation_unit res_state ON res_state.id=CAST(r.stateid AS BIGINT)
LEFT JOIN base_organisation_unit res_lga ON res_lga.id=CAST(r.lgaid AS BIGINT)
LEFT JOIN base_organisation_unit_identifier boui ON boui.organisation_unit_id=p.facility_id AND boui.name='DATIM_ID'
INNER JOIN pmtct_enrollment pmtctenroll ON pmtctenroll.person_uuid = p.uuid
LEFT JOIN (
SELECT * from pmtct_delivery order by person_uuid,date_of_delivery desc
) AS delivery ON pmtctenroll.person_uuid = delivery.person_uuid
left join (select distinct on (person_uuid) person_uuid,date_of_visit,dsd_option,visit_status,ga_of_viral_load, date_of_viral_load, result_of_viral_load from pmtct_mother_visitation order by 1,2 desc) pmv on pmv.person_uuid = p.uuid
left join art_status ast on p.uuid = ast.cuPersonUuid
left join pmtct_infant_information pii on pii.mother_person_uuid = delivery.person_uuid
left join pmtct_infant_arv pia on pia.uuid = p.uuid
left join (select * from pmtct_infant_pcr where (test_type ilike '%INFANT_TESTING_PCR_1ST_PCR%')) first on first.infant_hospital_number = pii.hospital_number
left join (select * from pmtct_infant_pcr where (test_type ilike '%INFANT_TESTING_PCR_2ND_PCR%')) second on second.infant_hospital_number = pii.hospital_number
left join (select * from pmtct_infant_pcr where (test_type = 'INFANT_TESTING_PCR_CONFIRMATORY_PCR___IF_PREVIOUS_TEST_POSITIVE')) third on third.infant_hospital_number = pii.hospital_number
left join (select * from pmtct_infant_pcr where (test_type ilike '%INFANT_TESTING_PCR_4TH_PCR%')) fourth on fourth.infant_hospital_number = pii.hospital_number
left join (select * from pmtct_infant_pcr where (test_type = 'INFANT_TESTING_PCR_CONFIRMATORY_PCR')) confirm on confirm.infant_hospital_number = pii.hospital_number
left join cvl on cvl.person_uuid130 = p.uuid
LEFT JOIN (SELECT * FROM (SELECT person_uuid, ga_of_viral_load, date_of_viral_load, result_of_viral_load, ROW_NUMBER () OVER (PARTITION BY person_uuid ORDER BY date_of_viral_load DESC) AS rnkkkk
FROM pmtct_mother_visitation WHERE date_of_viral_load BETWEEN CAST('?2' AS DATE) AND CAST('?3' AS DATE) AND result_of_viral_load IS NOT NULL AND result_of_viral_load BETWEEN 32 AND 36) subQuery where rnkkkk = 1) gaViral ON gaViral.person_uuid = p.uuid
WHERE p.archived=0 and p.sex='Female' and (anc.anc_no is not null or pmtctenroll.entry_point ilike '%PMTCT_ENTRY%')
AND p.facility_id=?1 AND p.date_of_registration BETWEEN CAST('?2' AS DATE) AND CAST('?3' AS DATE)
) as pmtct
prep-query-name: prep
prep-query: SELECT prep.datimid AS "Facility Id (Datim)",
prep.state AS "State", prep.lga AS "LGA", prep.facilityname AS "Facility Name",
prep.personuuid AS "Patient Identifier", prep.hospitalNumber AS "Hospital Number",
prep.sex AS "Sex",
prep.age AS "Age", prep.dateofbirth AS "Date Of Birth (yyyy-mm-dd)",
prep.phone AS "Phone Number", prep.maritalstatus AS "Marital Status",
prep.residentiallga AS "LGA of Residence", prep.residentialstate AS "State Of Residence",
prep.education AS "Education", prep.occupation AS "Occupation", prep.populationType AS "Population Type", prep.visitType AS "Visit Type", prep.dateScreened AS "Date Screened for PrEP", prep.dateScreened AS "Date Eligible for PrEP", prep.dateScreened AS "Date offered PrEP", prep.dateScreened AS "Date willing to commence PrEP", prep.eligibleForPrep AS "Eligible for PrEP", prep.offeredPrep AS "Offered PrEP", prep.willingCommencedPrep AS "Willing to Commence PREP", prep.acceptedToCommencedPrep AS "Accepted to Commence PrEP", prep.reasonsForDecliningPrep AS "Reasons for Declining PrEP",
prep.dateofregistration AS "Date Of Registration (yyyy-mm-dd)", prep.prepCommencedDate AS "Date Of Commencement (yyyy-mm-dd)",
prep.baselineregimen AS "Baseline Regimen", prep.prepType AS "Prep Type", prep.previousClinicPrepType AS "Previous clinic PrEP Type", prep.prepdistributionsetting AS "Prep Distribution Setting",
prep.baselinesystolicbp AS "Baseline Systolic bp", prep.baselinediastolicbp AS "Baseline Diastolic bp", prep.baselineweight AS "Baseline Weight (kg)",
prep.baselineheight AS "Baseline Height (cm)", prep.baseLinecreatinine AS "Baseline Creatinine", prep.baseLineHepatitisB AS "Baseline Hepatitis B",
prep.baselinehepatitisc AS "Baseline Hepatitis C", prep.hivstatusatprepinitiation AS "HIV status at PrEP Initiation",
prep.baselineurinalysis AS "Baseline Urinalysis", prep.baselineurinalysisdate AS "Baseline Urinalysis Date", prep.baseLineliverFunctionTestResult AS "Baseline Liver Function Test", prep.baseLineDateOfLiverFunctionResult AS "Baseline Liver Function Test Date", prep.baseLineAst AS "Baseline AST",
prep.baseLineAlt AS "Baseline ALT", prep.baseLineHbsag AS "Baseline HBsAG", prep.baseLineHbPcv AS "Baseline HB/PCV", prep.baseLineWbc AS "Baseline WBC", prep.baseLineChestXray AS "Baseline Chest Xray", prep.baseLineLipid AS "Baseline Lipid Profile",
prep.currentregimen AS "Current Regimen", prep.previousClinicRegimen AS "Previous clinic Visit Regimen", prep.duration AS "Drug refill period (duration)", prep.currentPrepType AS "Current Prep Type", prep.currentPrepDistributionSetting AS "Current Prep Distribution Setting", prep.DateOfLastPickup AS "Date Of Last Pickup (yyyy-mm-dd)", prep.previousVisitDate AS " Date of Previous Visit",
prep.previousStatus AS " Previous Status", prep.previousStatusDate AS "Previous Status Date",prep.CurrentStatus AS "Current Status", prep.DateOfCurrentStatus AS "Date Of Current Status (yyyy-mm-dd)", prep.currentSystolicBP AS "Current Systolic bp",
prep.currentDiastolicBP AS "Current Diastolic bp", prep.drugHistory AS "History of Drug-Drug Interactions", prep.currentWeight AS "Current Weight (kg)", prep.currentHeight AS "Current Height (cm)",
prep.currentHivStatus AS "Current HIV Status", prep.DateOfCurrentHIVStatus AS "Date of Current HIV Status (yyyy-mm-dd)",
prep.urinalysiResult AS "Current Urinalysis", prep.urinalysisTestDate AS "Date of Current Urinalysis",
prep.altTestDate AS "Date of Current ALT", prep.altTesult AS "Current ALT",
prep.hbsAgTestDate AS "Date of Current HBsAG", prep.hbsAgResult AS "Current HBsAG",
prep.hbpcvTestDate AS "Date of Current HB/PCV", prep.hbpcvResult AS "Current HB/PCV",
prep.wbcTestDate AS "Date of Current WBC", prep.wbcResult AS "Current WBC", prep.dateOfLiverFunctionResult AS "Date of Current Liver Function Test", prep.liverFunctionTestResult AS "Current Liver Function Test", prep.astTestDate AS "Date of Current AST", prep.astResult AS "Current AST",prep.creatineTestDate AS "Date of Current Creatinine", prep.creatineResult AS "Current Creatinine", prep.chestXrayTestDate AS "Date of Current Chest Xray", prep.chestXrayResult AS "Current Chest Xray", prep.lipidTestDate AS "Date of Current Lipid Profile", prep.lipidResult AS "Current Lipid Profile",
prep.pregnancyStatus AS "Pregnancy Status", prep.InterruptionType as "PrEP Discontinuation Type", prep.InterruptionReason AS "Reasons for discontinuation/Stopped",
prep.InterruptionDate AS "Date of Discontinuation/Stopped", prep.hivEnrollmentDate AS "Date Of HIV Enrollment (yyyy-mm-dd)", prep.healthCareWorker AS "Service Provider", prep.evenDate AS "Date of Adverse Events", prep.eventDescription AS "Adverse Events"
FROM (
SELECT DISTINCT ON (p.uuid)p.uuid AS PersonUuid, p.id, p.uuid,p.hospital_number as hospitalNumber,
INITCAP(p.surname) AS surname, INITCAP(p.first_name) as firstName,
he.date_of_registration AS hivEnrollmentDate, pCommenced.encounter_date AS prepCommencedDate,
EXTRACT(YEAR from AGE(CAST('?3' AS DATE), date_of_birth)) as age,
p.other_name as otherName, p.sex as sex, p.date_of_birth as dateOfBirth,
p.date_of_registration as dateOfRegistration, p.marital_status->>'display' as maritalStatus,
education->>'display' as education, p.employment_status->>'display' as occupation,
facility.name as facilityName, facility_lga.name as lga, facility_state.name as state,(CASE WHEN contact_point->'contactPoint'->0->>'type'='phone' THEN contact_point->'contactPoint'->0->>'value' ELSE null END) AS phone,
boui.code as datimId, (SELECT name FROM base_organisation_unit WHERE id = CAST(NULLIF(p.address->'address'->0 ->'stateId' ->> 0,'') AS BIGINT)) as residentialState, (SELECT name FROM base_organisation_unit WHERE id = CAST(CASE WHEN p.address->'address'->0->'district'->>0 ~ '^[0-9\\\\.]+$' THEN NULLIF(p.address->'address'->0->'district'->>0, '') ELSE NULL END AS BIGINT)) AS residentialLga,
previousClinic.encounter_date AS previousVisitDate, (select display from base_application_codeset where code = previousClinic.prep_type) AS previousClinicPrepType, (SELECT regimen From prep_regimen where id = previousClinic.regimen_id) AS previousClinicRegimen,
(SELECT display FROM base_application_codeset where code = current_pc.history_of_drug_to_drug_interaction) AS drugHistory,
(CASE WHEN p.sex='Male' THEN NULL
WHEN current_pc.pregnant IS NOT NULL THEN (SELECT display FROM base_application_codeset WHERE code = current_pc.pregnant)
ELSE current_pc.pregnant END) AS pregnancyStatus, (select regimen from prep_regimen WHERE id = baselineClinic.regimenId) AS baselineRegimen,
(select display from base_application_codeset where code = (select prep_type from prep_regimen WHERE id = baselineClinic.regimenId) ) as prepType,
(select display from base_application_codeset where code = baselineClinic.prep_distribution_setting) AS prepDistributionSetting,
baselineClinic.systolic AS baselineSystolicBP, baselineClinic.diastolic AS baselineDiastolicBP, baselineClinic.weight AS baselineWeight, baselineClinic.height AS baselineHeight, COALESCE (baselineClinic.creatineResult, baselineClinic.creatinine->>'result') AS baseLineCreatinine, COALESCE (CAST(baselineClinic.creatineTestDate AS DATE), CAST(NULLIF(baselineClinic.creatinine->>'testDate', '') AS DATE)) AS baseLineCreatinineDate,
baselineClinic.altTesult AS baseLineAlt, baselineClinic.hbsAgResult AS baseLineHbsag, baselineClinic.hbpcvResult AS baseLineHbPcv, COALESCE (baselineClinic.urinalysiResult, baselineClinic.urinalysis->>'result') AS baseLineUrinalysis, COALESCE (CAST(baselineClinic.urinalysisTestDate AS DATE), CAST(NULLIF(baselineClinic.urinalysis->>'testDate', '') AS DATE)) AS baseLineUrinalysisDate,
baselineClinic.wbcResult AS baseLineWbc, baselineClinic.lipidResult AS baseLineLipid, baselineClinic.chestXrayResult AS baseLineChestXray, baselineClinic.astResult AS baseLineAst, baselineClinic.baseLineHepatitisB AS baseLineHepatitisB, baselineClinic.baseLineHepatitisC AS baseLineHepatitisC,
(select regimen from prep_regimen WHERE id = current_pc.regimen_id) AS currentRegimen,
current_pc.duration AS duration, (select display from base_application_codeset where code = (select prep_type from prep_regimen WHERE id = current_pc.regimen_id)) as currentPrepType,
(select display from base_application_codeset where code = current_pc.prep_distribution_setting) AS currentPrepDistributionSetting, current_pc.encounter_date AS DateOfLastPickup, current_pc.systolic AS currentSystolicBP, current_pc.diastolic AS currentDiastolicBP,
current_pc.weight AS currentWeight, current_pc.height AS currentHeight, (CASE WHEN current_pc.hiv_test_result ILIKE '%Negative%' THEN 'Negative' WHEN current_pc.hiv_test_result ILIKE '%Positive%' THEN 'Positive' ELSE NULL END) AS currentHivStatus,
current_pc.encounter_date AS DateOfCurrentHIVStatus, (select display from base_application_codeset where code = current_pi.interruption_type) as InterruptionType, current_pi.reason_stopped AS InterruptionReason, current_pi.interruption_date AS InterruptionDate,
current_pc.health_care_worker_signature AS healthCareWorker, CASE WHEN current_pc.visit_type = 'PREP_VISIT_TYPE_METHOD_SWITCH' THEN (select display from base_application_codeset where code = current_pc.prep_type) ELSE null END AS methodSwitch,
(select display from base_application_codeset where code = current_pc.population_type) AS populationType,
(CASE
WHEN current_pi.interruption_date <= current_pc.encounter_date
THEN
(CASE
WHEN (current_pi.interruption_type ILIKE '%Stopped%' OR current_pi.interruption_type ILIKE '%Discon%') AND prepc.status ILIKE '%Active%'
THEN 'Restart'
ELSE current_pi.interruption_type
END)
ELSE prepc.status
END)
AS CurrentStatus,
COALESCE (prepc.statusDate,current_pc.encounter_date) AS DateOfCurrentStatus,
(CASE
WHEN previousClinic.encounter_date IS NULL THEN NULL
WHEN current_pi.interruption_date <= current_pc.encounter_date THEN current_pi.interruption_type
WHEN (previousClinic.encounter_date + previousClinic.duration) <= current_pc.encounter_date THEN 'Defaulted'
ELSE 'Active' END) AS previousStatus,
(CASE
WHEN current_pi.interruption_date <= current_pc.encounter_date THEN current_pi.interruption_date
WHEN previousClinic.encounter_date IS NULL THEN NULL
WHEN (previousClinic.encounter_date + previousClinic.duration) <= current_pc.encounter_date THEN previousClinic.encounter_date
ELSE previousClinic.encounter_date END) AS previousStatusDate,
COALESCE (current_pc.creatineResult, current_pc.creatinine->>'result') AS creatineResult,
COALESCE (CAST(current_pc.creatineTestDate AS DATE), CAST(NULLIF(current_pc.creatinine->>'testDate', '') AS DATE)) AS creatineTestDate, current_pc.altTesult, CAST(NULLIF(current_pc.altTestDate, NULL) AS DATE) AS altTestDate, current_pc.hbsAgResult, CAST(NULLIF(current_pc.hbsAgTestDate, NULL) AS DATE) AS hbsAgTestDate, current_pc.hbpcvResult, CAST(NULLIF(current_pc.hbpcvTestDate, null) AS DATE) AS hbpcvTestDate,
COALESCE (current_pc.urinalysiResult, current_pc.urinalysis->>'result') AS urinalysiResult, COALESCE (CAST(current_pc.urinalysisTestDate AS DATE), CAST(NULLIF(current_pc.urinalysis->>'testDate', '') AS DATE)) AS urinalysisTestDate,
current_pc.wbcResult, CAST(NULLIF(current_pc.wbcTestDate, NULL) AS DATE) AS wbcTestDate, current_pc.lipidResult, CAST(NULLIF(current_pc.lipidTestDate, NULL) AS DATE) AS lipidTestDate, current_pc.chestXrayResult, CAST(NULLIF(current_pc.chestXrayTestDate, NULL) AS DATE) AS chestXrayTestDate, current_pc.astResult, CAST(NULLIF(current_pc.astTestDate, NULL) AS DATE) AS astTestDate,
(CASE WHEN baselineClinic.hiv_test_result ILIKE '%Negative%' THEN 'Negative' WHEN baselineClinic.hiv_test_result ILIKE '%Positive%' THEN 'Positive' ELSE NULL END) AS HIVStatusAtPrEPInitiation,
current_pc.liverFunctionResult AS liverFunctionTestResult, current_pc.date_of_liver_function_test_results AS dateOfLiverFunctionResult,
baselineClinic.liverFunctionResult AS baseLineliverFunctionTestResult, baselineClinic.date_of_liver_function_test_results AS baseLineDateOfLiverFunctionResult,
pEligiblity.willingCommencedPrep, pEligiblity.reasonsForDecliningPrep, pEligiblity.dateScreened,
(CASE WHEN hc.hiv_test_result = 'Positive' THEN 'No' WHEN hc.prep_offered IS true THEN 'Yes' WHEN hc.prep_offered IS false THEN 'No' ELSE NULL END) AS offeredPrep, (CASE WHEN hc.hiv_test_result = 'Positive' THEN 'No' WHEN hc.prep_accepted IS true THEN 'Yes' WHEN hc.prep_accepted IS FALSE THEN 'No' ELSE NULL END) AS acceptedToCommencedPrep, (CASE WHEN hc.hiv_test_result = 'Negative' OR pEligiblity.score = 1 THEN 'Yes' ELSE 'No' END) AS eligibleForPrep,
adr.adverse_effect->>'eventDescription' AS eventDescription, adr.report_date AS evenDate, (SELECT display from base_application_codeset where code = current_pc.visit_type) AS visitType
FROM patient_person p
INNER JOIN prep_enrollment prepe ON prepe.person_uuid = p.uuid AND prepe.archived = 0
LEFT JOIN hts_client hc ON hc.person_uuid = prepe.person_uuid AND hc.archived = 0
LEFT JOIN adr_table adr ON adr.patient_uuid = prepe.person_uuid
LEFT JOIN hiv_enrollment he ON he.person_uuid = prepe.person_uuid
INNER JOIN (
SELECT * FROM (SELECT p.id, REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(CAST(address_object->>'line' AS text), '"', ''), ']', ''), '[', ''), 'null',''), '\\\\\\\', '') AS address,
CASE WHEN address_object->>'stateId' ~ '^\\\\d(\\\\.\\\\d)?$' THEN address_object->>'stateId' ELSE null END AS stateId,
CASE WHEN address_object->>'district' ~ '^\\\\d(\\\\.\\\\d)?$' THEN address_object->>'district' ELSE null END AS lgaId
FROM patient_person p,
jsonb_array_elements(p.address-> 'address') with ordinality l(address_object)) as result
) r ON r.id=p.id
LEFT JOIN base_organisation_unit facility ON facility.id=p.facility_id
LEFT JOIN base_organisation_unit facility_lga ON facility_lga.id=facility.parent_organisation_unit_id
LEFT JOIN base_organisation_unit facility_state ON facility_state.id=facility_lga.parent_organisation_unit_id
LEFT JOIN base_organisation_unit res_state ON res_state.id=CAST(r.stateid AS BIGINT)
LEFT JOIN base_organisation_unit res_lga ON res_lga.id=CAST(r.lgaid AS BIGINT)
LEFT JOIN base_organisation_unit_identifier boui ON boui.organisation_unit_id=p.facility_id AND boui.name='DATIM_ID'
LEFT JOIN prep_clinic pCommenced ON pCommenced.person_uuid = prepe.person_uuid AND is_commencement IS TRUE AND pCommenced.archived = 0
LEFT JOIN (
SELECT * FROM (
SELECT pi.person_uuid, (select display from base_application_codeset where code = pi.interruption_type) AS interruption_type, pi.interruption_date, pi.interruption_reason, reason_stopped, ROW_NUMBER() OVER (PARTITION BY pi.person_uuid ORDER BY pi.interruption_date DESC) rnk FROM prep_interruption pi
WHERE archived = 0 AND pi.interruption_date BETWEEN CAST('?2' AS DATE) AND CAST('?3' AS DATE)
) interruption WHERE rnk = 1 )
current_pi ON current_pi.person_uuid=p.uuid
LEFT JOIN (
SELECT * FROM(
SELECT DISTINCT pc.*,
currentCreatine.result AS creatineResult,currentCreatine.test_date AS creatineTestDate, currentALt.result AS altTesult, currentALt.test_date AS altTestDate, currentHbsAg.result AS hbsAgResult, currentHbsAg.test_date AS hbsAgTestDate,
currentHbpcv.result AS hbpcvResult, currentHbpcv.test_date AS hbpcvTestDate, currentUrinalysis.result AS urinalysiResult, currentUrinalysis.test_date AS urinalysisTestDate, currentWbc.result AS wbcResult, currentWbc.test_date AS wbcTestDate,
currentLipidProfile.result AS lipidResult, currentLipidProfile.test_date AS lipidTestDate, currentChestXray.result AS chestXrayResult, currentChestXray.test_date AS chestXrayTestDate, currentAst.result AS astResult, currentAst.test_date AS astTestDate, liverResult.liverFunctionResult,
ROW_NUMBER() OVER (PARTITION BY person_uuid ORDER BY encounter_date DESC) rnk
FROM prep_clinic pc
LEFT JOIN LATERAL (
SELECT STRING_AGG((SELECT display FROM base_application_codeset WHERE code = liverResult), ', ') AS liverFunctionResult
FROM jsonb_array_elements_text(pc.liver_function_test_results) AS liverResult
) liverResult ON TRUE
LEFT JOIN LATERAL (
SELECT arr.object->>'name' AS other_test_name,arr.object->>'result' AS result,arr.object->>'testDate' AS test_date
FROM jsonb_array_elements(pc.other_tests_done) arr(object) WHERE arr.object->>'otherTestName' ILIKE '%PREP_OTHER_TEST_CREATININE%' OR arr.object->>'otherTestsDone' ILIKE '%PREP_OTHER_TEST_CREATININE%'
LIMIT 1
) currentCreatine ON TRUE
LEFT JOIN LATERAL (
SELECT arr.object->>'name' AS other_test_name,arr.object->>'result' AS result,arr.object->>'testDate' AS test_date
FROM jsonb_array_elements(pc.other_tests_done) arr(object)
WHERE arr.object->>'otherTestName' ILIKE '%PREP_OTHER_TEST_ALT%' OR arr.object->>'otherTestsDone' ILIKE '%PREP_OTHER_TEST_ALT%'
LIMIT 1
) currentALt ON TRUE
LEFT JOIN LATERAL (
SELECT arr.object->>'name' AS other_test_name, arr.object->>'result' AS result, arr.object->>'testDate' AS test_date
FROM jsonb_array_elements(pc.other_tests_done) arr(object)
WHERE arr.object->>'otherTestName' ILIKE '%PREP_OTHER_TEST_HBSAG%' OR arr.object->>'otherTestsDone' ILIKE '%PREP_OTHER_TEST_HBSAG%'
LIMIT 1
) currentHbsAg ON TRUE
LEFT JOIN LATERAL (
SELECT arr.object->>'name' AS other_test_name, arr.object->>'result' AS result, arr.object->>'testDate' AS test_date
FROM jsonb_array_elements(pc.other_tests_done) arr(object)
WHERE arr.object->>'otherTestName' ILIKE '%PREP_OTHER_TEST_HB_PCV%' OR arr.object->>'otherTestsDone' ILIKE '%PREP_OTHER_TEST_HB_PCV%'
LIMIT 1
) currentHbpcv ON TRUE
LEFT JOIN LATERAL (
SELECT arr.object->>'name' AS other_test_name, arr.object->>'result' AS result, arr.object->>'testDate' AS test_date
FROM jsonb_array_elements(pc.other_tests_done) arr(object)
WHERE arr.object->>'otherTestName' ILIKE '%PREP_OTHER_TEST_URINALYSIS%' OR arr.object->>'otherTestsDone' ILIKE '%PREP_OTHER_TEST_URINALYSIS%'
LIMIT 1
) currentUrinalysis ON TRUE
LEFT JOIN LATERAL (
SELECT arr.object->>'name' AS other_test_name, arr.object->>'result' AS result, arr.object->>'testDate' AS test_date
FROM jsonb_array_elements(pc.other_tests_done) arr(object)
WHERE arr.object->>'otherTestName' ILIKE '%PREP_OTHER_TEST_WBC_+_DIFF%' OR arr.object->>'otherTestsDone' ILIKE '%PREP_OTHER_TEST_WBC_+_DIFF%'
LIMIT 1
) currentWbc ON TRUE
LEFT JOIN LATERAL (
SELECT arr.object->>'name' AS other_test_name, arr.object->>'result' AS result, arr.object->>'testDate' AS test_date
FROM jsonb_array_elements(pc.other_tests_done) arr(object)
WHERE arr.object->>'otherTestName' ILIKE '%PREP_OTHER_TEST_LIPID_PROFILE%' OR arr.object->>'otherTestsDone' ILIKE '%PREP_OTHER_TEST_LIPID_PROFILE%'
LIMIT 1
) currentLipidProfile ON TRUE
LEFT JOIN LATERAL (
SELECT arr.object->>'name' AS other_test_name, arr.object->>'result' AS result, arr.object->>'testDate' AS test_date
FROM jsonb_array_elements(pc.other_tests_done) arr(object)
WHERE arr.object->>'otherTestName' ILIKE '%PREP_OTHER_TEST_CHEST_XRAY_%' OR arr.object->>'otherTestsDone' ILIKE '%PREP_OTHER_TEST_CHEST_XRAY_%'
LIMIT 1
) currentChestXray ON TRUE
LEFT JOIN LATERAL (
SELECT arr.object->>'name' AS other_test_name, arr.object->>'result' AS result, arr.object->>'testDate' AS test_date
FROM jsonb_array_elements(pc.other_tests_done) arr(object)
WHERE arr.object->>'otherTestName' ILIKE '%PREP_OTHER_TEST_AST%' OR arr.object->>'otherTestsDone' ILIKE '%PREP_OTHER_TEST_AST%'
LIMIT 1
) currentAst ON TRUE
WHERE is_commencement = false AND pc.archived = 0 ) subQ where rnk = 1 AND encounter_date BETWEEN CAST('?2' AS DATE) AND CAST('?3' AS DATE)
)current_pc ON current_pc.person_uuid=prepe.person_uuid
LEFT JOIN (
SELECT person_uuid, encounter_date, regimen_id, prep_type, duration, rnk FROM (
SELECT person_uuid, encounter_date, regimen_id, prep_type, duration, ROW_NUMBER() OVER (PARTITION BY person_uuid ORDER BY encounter_date DESC) rnk
FROM prep_clinic WHERE archived = 0 AND is_commencement = false AND archived = 0
AND encounter_date BETWEEN CAST('?2' AS DATE) AND CAST('?3' AS DATE)
) subQ
WHERE rnk = 2
) previousClinic ON previousClinic.person_uuid = prepe.person_uuid
LEFT JOIN (
SELECT
pc.person_uuid,
CASE
WHEN (is_on.interruption_date > pc.encounter_date) THEN is_on.status
WHEN pc.visit_type ILIKE '%PREP_VISIT_TYPE_INITIATION%' AND pc.regimen_id = 2 THEN
CASE
WHEN pc.encounter_date + pc.duration + INTERVAL '29 day' < CAST('?3' AS DATE) THEN 'Discontinued'
WHEN CAST((pc.encounter_date + pc.duration + INTERVAL '7 day') AS DATE) < CAST('?3' AS DATE) THEN 'Delayed Injection'
ELSE 'Active'
END
WHEN pc.visit_type ILIKE '%PREP_VISIT_TYPE_SECOND_INITIATION%' AND pc.regimen_id = 2 THEN
CASE
WHEN pc.encounter_date + pc.duration + INTERVAL '29 day' < CAST('?3' AS DATE) THEN 'Discontinued'
WHEN CAST((pc.encounter_date + pc.duration + INTERVAL '7 day') AS DATE) < CAST('?3' AS DATE) THEN 'Delayed Injection'
ELSE 'Active'
END
WHEN (pc.encounter_date + pc.duration) > CAST('?3' AS DATE)
THEN 'Active'
ELSE 'Defaulted'
END AS status,
CASE
WHEN (is_on.interruption_date > pc.encounter_date) THEN is_on.interruption_date
WHEN (pc.encounter_date + pc.duration) > CAST('?3' AS DATE)
THEN pc.encounter_date
ELSE null
END AS statusDate
FROM (
SELECT
person_uuid, encounter_date, duration,regimen_id, next_appointment, visit_type,
ROW_NUMBER() OVER (PARTITION BY person_uuid ORDER BY encounter_date DESC ) AS rank
FROM
prep_clinic
WHERE
archived = 0 AND is_commencement IS FALSE
) pc
LEFT JOIN (
SELECT
person_uuid, interruption_date, interruption.display AS status,
ROW_NUMBER() OVER (PARTITION BY person_uuid ORDER BY interruption_date DESC) AS rank
FROM
prep_interruption pi
LEFT JOIN base_application_codeset interruption
ON interruption.code = pi.interruption_type
WHERE
pi. archived = 0 AND interruption_date <= CAST('?3' AS DATE)
) is_on
ON is_on.person_uuid = pc.person_uuid AND is_on.rank = 1
WHERE
pc.rank = 1
) prepc ON prepc.person_uuid=p.uuid
LEFT JOIN (
SELECT * FROM (
SELECT
person_uuid as personUuidBaseline, systolic, diastolic, weight, height, encounter_date, regimen_id AS regimenId, prep_distribution_setting, hiv_test_result, liver_function_test_result, date_of_liver_function_test_results,
CASE WHEN hepatitis->>'result' LIKE 'Hepatitis B%' THEN hepatitis->>'result' ELSE NULL END AS baseLineHepatitisB, creatinine, urinalysis,
CASE WHEN hepatitis->>'result' LIKE 'Hepatitis C%' THEN hepatitis->>'result' ELSE NULL END AS baseLineHepatitisC,
baselineCreatine.result AS creatineResult, baselineCreatine.test_date AS creatineTestDate, baselineALt.result AS altTesult, baselineALt.test_date AS altTestDate, baselineHbsAg.result AS hbsAgResult,
baselineHbsAg.test_date AS hbsAgTestDate, baselineHbpcv.result AS hbpcvResult, baselineHbpcv.test_date AS hbpcvTestDate, baselineUrinalysis.result AS urinalysiResult, baselineUrinalysis.test_date AS urinalysisTestDate,
baselineWbc.result AS wbcResult, baselineWbc.test_date AS wbcTestDate, baselineLipidProfile.result AS lipidResult, baselineLipidProfile.test_date AS lipidTestDate, baselineChestXray.result AS chestXrayResult,
baselineChestXray.test_date AS chestXrayTestDate, baselineAst.result AS astResult, baselineAst.test_date AS astTestDate, baselineLiverResult.liverFunctionResult,
ROW_NUMBER() OVER (PARTITION BY person_uuid ORDER BY encounter_date ASC) AS rnk
FROM
prep_clinic pc
LEFT JOIN LATERAL (
SELECT STRING_AGG((SELECT display FROM base_application_codeset WHERE code = liverResult), ', ') AS liverFunctionResult
FROM jsonb_array_elements_text(pc.liver_function_test_results) AS liverResult
) baselineLiverResult ON TRUE
LEFT JOIN LATERAL (
SELECT arr.object->>'name' AS other_test_name,arr.object->>'result' AS result,arr.object->>'testDate' AS test_date
FROM jsonb_array_elements(pc.other_tests_done) arr(object) WHERE arr.object->>'otherTestName' ILIKE '%PREP_OTHER_TEST_CREATININE%' OR arr.object->>'otherTestsDone' ILIKE '%PREP_OTHER_TEST_CREATININE%'
LIMIT 1
) baselineCreatine ON TRUE
LEFT JOIN LATERAL (
SELECT arr.object->>'name' AS other_test_name,arr.object->>'result' AS result,arr.object->>'testDate' AS test_date
FROM jsonb_array_elements(pc.other_tests_done) arr(object)
WHERE arr.object->>'otherTestName' ILIKE '%PREP_OTHER_TEST_ALT%' OR arr.object->>'otherTestsDone' ILIKE '%PREP_OTHER_TEST_ALT%'
LIMIT 1
) baselineALt ON TRUE
LEFT JOIN LATERAL (
SELECT arr.object->>'name' AS other_test_name, arr.object->>'result' AS result, arr.object->>'testDate' AS test_date
FROM jsonb_array_elements(pc.other_tests_done) arr(object)
WHERE arr.object->>'otherTestName' ILIKE '%PREP_OTHER_TEST_HBSAG%' OR arr.object->>'otherTestsDone' ILIKE '%PREP_OTHER_TEST_HBSAG%'
LIMIT 1
) baselineHbsAg ON TRUE
LEFT JOIN LATERAL (
SELECT arr.object->>'name' AS other_test_name, arr.object->>'result' AS result, arr.object->>'testDate' AS test_date
FROM jsonb_array_elements(pc.other_tests_done) arr(object)
WHERE arr.object->>'otherTestName' ILIKE '%PREP_OTHER_TEST_HB_PCV%' OR arr.object->>'otherTestsDone' ILIKE '%PREP_OTHER_TEST_HB_PCV%'
LIMIT 1
) baselineHbpcv ON TRUE
LEFT JOIN LATERAL (
SELECT arr.object->>'name' AS other_test_name, arr.object->>'result' AS result, arr.object->>'testDate' AS test_date
FROM jsonb_array_elements(pc.other_tests_done) arr(object)
WHERE arr.object->>'otherTestName' ILIKE '%PREP_OTHER_TEST_URINALYSIS%' OR arr.object->>'otherTestsDone' ILIKE '%PREP_OTHER_TEST_URINALYSIS%'
LIMIT 1
) baselineUrinalysis ON TRUE
LEFT JOIN LATERAL (
SELECT arr.object->>'name' AS other_test_name, arr.object->>'result' AS result, arr.object->>'testDate' AS test_date
FROM jsonb_array_elements(pc.other_tests_done) arr(object)
WHERE arr.object->>'otherTestName' ILIKE '%PREP_OTHER_TEST_WBC_+_DIFF%' OR arr.object->>'otherTestsDone' ILIKE '%PREP_OTHER_TEST_WBC_+_DIFF%'
LIMIT 1
) baselineWbc ON TRUE
LEFT JOIN LATERAL (
SELECT arr.object->>'name' AS other_test_name, arr.object->>'result' AS result, arr.object->>'testDate' AS test_date
FROM jsonb_array_elements(pc.other_tests_done) arr(object)
WHERE arr.object->>'otherTestName' ILIKE '%PREP_OTHER_TEST_LIPID_PROFILE%' OR arr.object->>'otherTestsDone' ILIKE '%PREP_OTHER_TEST_LIPID_PROFILE%'
LIMIT 1
) baselineLipidProfile ON TRUE
LEFT JOIN LATERAL (
SELECT arr.object->>'name' AS other_test_name, arr.object->>'result' AS result, arr.object->>'testDate' AS test_date
FROM jsonb_array_elements(pc.other_tests_done) arr(object)
WHERE arr.object->>'otherTestName' ILIKE '%PREP_OTHER_TEST_CHEST_XRAY_%' OR arr.object->>'otherTestsDone' ILIKE '%PREP_OTHER_TEST_CHEST_XRAY_%'
LIMIT 1
) baselineChestXray ON TRUE
LEFT JOIN LATERAL (
SELECT arr.object->>'name' AS other_test_name, arr.object->>'result' AS result, arr.object->>'testDate' AS test_date
FROM jsonb_array_elements(pc.other_tests_done) arr(object)
WHERE arr.object->>'otherTestName' ILIKE '%PREP_OTHER_TEST_AST%' OR arr.object->>'otherTestsDone' ILIKE '%PREP_OTHER_TEST_AST%'
LIMIT 1
) baselineAst ON TRUE
WHERE
is_commencement = FALSE
AND archived = 0
) baselineRecords where rnk = 1
) baselineClinic ON prepe.person_uuid = baselineClinic.personUuidBaseline
LEFT JOIN (
select
unique_id, uuid, visit_date AS dateScreened, score, visit_type,
(CASE WHEN services_received_by_client->>'willingToCommencePrep' = 'true' THEN 'Yes' WHEN services_received_by_client->>'willingToCommencePrep' = 'false' THEN 'No' ELSE null END) AS willingCommencedPrep, (SELECT display FROM base_application_codeset where code = REPLACE(REPLACE(REPLACE(services_received_by_client->>'reasonsForDecline', '[',''),']',''),'"','')) AS reasonsForDecliningPrep
from prep_eligibility
WHERE archived = 0
) pEligiblity ON prepe.prep_eligibility_uuid = pEligiblity.uuid
WHERE p.archived=0 AND p.facility_id=?1
AND p.date_of_registration BETWEEN CAST('?2' AS DATE) AND CAST('?3' AS DATE)
) prep
ahd-query-name: ahd
ahd-query: WITH careCardCD4 AS (
SELECT
visit_date,
COALESCE(CAST(cd_4 AS VARCHAR), cd4_semi_quantitative) AS cd_4,
person_uuid AS cccd4_person_uuid
FROM
public.hiv_art_clinical
WHERE
is_commencement IS TRUE
AND archived = 0
AND cd_4 != 0
),
labCD4 AS (
SELECT * FROM (
SELECT
sm.patient_uuid AS cd4_person_uuid,
sm.result_reported AS cd4Lb,
sm.date_result_reported AS dateOfCD4Lb,
ROW_NUMBER() OVER (PARTITION BY sm.patient_uuid ORDER BY date_result_reported DESC) AS rnk
FROM
public.laboratory_result sm
INNER JOIN
public.laboratory_test lt ON sm.test_id = lt.id
WHERE
lt.lab_test_id IN (1, 50)
AND sm.date_result_reported IS NOT NULL
AND sm.archived = 0
) AS cd4_result
WHERE
cd4_result.rnk = 1
),
sample_collection_date AS (
SELECT
CAST(sample.date_sample_collected AS DATE) AS DateOfViralLoadSampleCollection,
sample.patient_uuid AS person_uuid120
FROM (
SELECT
sm.facility_id,
sm.date_sample_collected,
sm.patient_uuid,
sm.archived,
ROW_NUMBER() OVER (PARTITION BY sm.patient_uuid ORDER BY date_sample_collected DESC) AS rnkk
FROM
public.laboratory_sample sm
INNER JOIN
public.laboratory_test lt ON lt.id = sm.test_id
WHERE
lt.lab_test_id = 16
AND lt.viral_load_indication != 719
AND date_sample_collected IS NOT NULL
AND date_sample_collected <= '?3'
) AS sample
WHERE
sample.rnkk = 1
AND (sample.archived IS NULL OR sample.archived = 0)
AND sample.facility_id = ?1
),
current_vl_result AS (
SELECT * FROM (
SELECT
CAST(ls.date_sample_collected AS DATE) AS dateOfCurrentViralLoadSample,
sm.patient_uuid AS person_uuid130,
sm.result_reported AS currentViralLoad,
acode.display AS viralLoadIndication,
CAST(sm.date_result_reported AS DATE) AS dateOfCurrentViralLoad,
ROW_NUMBER() OVER (PARTITION BY sm.patient_uuid ORDER BY date_result_reported DESC) AS rank2
FROM
public.laboratory_result sm
INNER JOIN
public.laboratory_test lt ON sm.test_id = lt.id
INNER JOIN
public.laboratory_sample ls ON ls.test_id = lt.id
INNER JOIN
public.base_application_codeset acode ON acode.id = lt.viral_load_indication
WHERE
lt.lab_test_id = 16
AND lt.viral_load_indication != 719
AND sm.date_result_reported IS NOT NULL
AND sm.date_result_reported <= '?3'
AND sm.result_reported IS NOT NULL
) AS vl_result
WHERE
vl_result.rank2 = 1
),
last_cd4 AS (
SELECT
p.uuid AS person_uuid,
COALESCE(
cd.cd4Lb,
ccd.cd_4
) AS lastCd4Count,
COALESCE(
CAST(cd.dateOfCD4Lb AS DATE),
CAST(ccd.visit_date AS DATE)
) AS dateOfLastCd4Count
FROM
patient_person p
LEFT JOIN
labCD4 cd ON cd.cd4_person_uuid = p.uuid
LEFT JOIN
careCardCD4 ccd ON ccd.cccd4_person_uuid = p.uuid
),
viralLoad AS (
SELECT
CAST(ls.date_sample_collected AS DATE) AS dateOfCurrentViralLoadSample,
sm.patient_uuid AS person_uuid,
sm.result_reported AS currentViralLoad,
acode.display AS viralLoadIndication,
CAST(sm.date_result_reported AS DATE) AS dateOfCurrentViralLoad,
ROW_NUMBER() OVER (PARTITION BY sm.patient_uuid ORDER BY date_result_reported DESC) AS rank2
FROM
public.laboratory_result sm
INNER JOIN
public.laboratory_test lt ON sm.test_id = lt.id
INNER JOIN
public.laboratory_sample ls ON ls.test_id = lt.id
INNER JOIN
public.base_application_codeset acode ON acode.id = lt.viral_load_indication
WHERE
lt.lab_test_id = 16
AND lt.viral_load_indication != 719
AND sm.date_result_reported IS NOT NULL
AND sm.date_result_reported <= '?3'
AND sm.result_reported IS NOT NULL
AND sm.date_result_reported BETWEEN CURRENT_DATE - INTERVAL '1 year' AND CURRENT_DATE
),
ahd AS (
SELECT DISTINCT ON (p.uuid)
p.uuid AS PersonUuid,
p.id,