forked from I-TECH/openmrs-module-kenyaemr
-
Notifications
You must be signed in to change notification settings - Fork 71
/
KenyaemrCoreRestController.java
3127 lines (2773 loc) · 158 KB
/
KenyaemrCoreRestController.java
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
/**
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can
* obtain one at http:https://mozilla.org/MPL/2.0/. OpenMRS is also distributed under
* the terms of the Healthcare Disclaimer located at http:https://openmrs.org/license.
*
* Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS
* graphic logo is a trademark of OpenMRS Inc.
*/
package org.openmrs.module.kenyaemr.web.controller;
import org.openmrs.Form;
import org.openmrs.GlobalProperty;
import org.openmrs.Location;
import org.openmrs.Patient;
import org.openmrs.Visit;
import org.openmrs.Encounter;
import org.openmrs.Obs;
import org.openmrs.Person;
import org.openmrs.Program;
import org.openmrs.PatientProgram;
import org.openmrs.Relationship;
import org.openmrs.DrugOrder;
import org.openmrs.Concept;
import org.openmrs.EncounterType;
import org.openmrs.api.context.Context;
import org.openmrs.api.AdministrationService;
import org.openmrs.api.ConceptService;
import org.openmrs.api.PatientService;
import org.openmrs.PersonAttribute;
import org.openmrs.PersonAttributeType;
import org.openmrs.PatientIdentifier;
import org.openmrs.PatientIdentifierType;
import org.openmrs.module.kenyaemr.api.KenyaEmrService;
import org.openmrs.calculation.result.CalculationResultMap;
import org.openmrs.calculation.patient.PatientCalculationService;
import org.openmrs.calculation.result.CalculationResult;
import org.openmrs.calculation.patient.PatientCalculationContext;
import org.openmrs.calculation.result.ListResult;
import org.openmrs.module.metadatadeploy.MetadataUtils;
import org.openmrs.module.kenyaemrorderentry.util.Utils;
import org.openmrs.module.kenyaemr.calculation.library.tb.TbDiseaseClassificationCalculation;
import org.openmrs.module.kenyaemr.calculation.library.tb.TbPatientClassificationCalculation;
import org.openmrs.module.kenyaemr.calculation.library.tb.TbTreatmentNumberCalculation;
import org.openmrs.module.kenyaemr.calculation.library.tb.PatientInTbProgramCalculation;
import org.openmrs.module.kenyaemr.calculation.EmrCalculationUtils;
import org.openmrs.module.kenyaemr.calculation.library.hiv.art.LastCd4CountDateCalculation;
import org.openmrs.module.kenyaemr.calculation.library.hiv.art.WhoStageAtArtStartCalculation;
import org.openmrs.module.kenyaemr.calculation.library.hiv.art.InitialArtStartDateCalculation;
import org.openmrs.module.kenyaemr.calculation.library.hiv.LastCd4PercentageCalculation;
import org.openmrs.module.kenyaemr.calculation.library.hiv.LastWhoStageCalculation;
import org.openmrs.module.kenyaemr.calculation.library.hiv.HIVEnrollment;
import org.openmrs.module.kenyaemr.calculation.library.hiv.art.ViralLoadAndLdlCalculation;
import org.openmrs.module.kenyaemr.calculation.library.hiv.art.BMICalculation;
import org.openmrs.module.kenyaemr.calculation.library.hiv.art.TransferInDateCalculation;
import org.openmrs.module.kenyaemr.calculation.library.mchms.EligibleForMchmsDischargeCalculation;
import org.openmrs.module.kenyaemr.metadata.CommonMetadata;
import org.openmrs.module.kenyaemr.EmrConstants;
import org.openmrs.module.kenyaemr.util.ZScoreUtil;
import org.openmrs.module.kenyaemr.util.EmrUtils;
import org.openmrs.module.kenyaemr.metadata.HivMetadata;
import org.openmrs.module.kenyaemr.metadata.TbMetadata;
import org.openmrs.module.kenyaemr.metadata.OTZMetadata;
import org.openmrs.module.kenyaemr.metadata.OVCMetadata;
import org.openmrs.module.kenyaemr.metadata.MchMetadata;
import org.openmrs.module.kenyaemr.metadata.VMMCMetadata;
import org.openmrs.module.kenyaemr.nupi.UpiUtilsDataExchange;
import org.openmrs.module.kenyaemr.regimen.RegimenConfiguration;
import org.openmrs.module.kenyaemr.wrapper.EncounterWrapper;
import org.openmrs.module.kenyaemr.Dictionary;
import org.openmrs.module.kenyaemr.util.EncounterBasedRegimenUtils;
import org.openmrs.module.kenyaemr.wrapper.PatientWrapper;
import org.openmrs.module.kenyaemr.wrapper.Enrollment;
import org.openmrs.module.kenyaemr.metadata.IPTMetadata;
import org.openmrs.module.kenyacore.CoreContext;
import org.openmrs.module.kenyacore.calculation.CalculationManager;
import org.openmrs.module.kenyacore.calculation.PatientFlagCalculation;
import org.openmrs.module.kenyacore.form.FormDescriptor;
import org.openmrs.module.kenyacore.form.FormManager;
import org.openmrs.module.kenyacore.program.ProgramDescriptor;
import org.openmrs.module.kenyacore.program.ProgramManager;
import org.openmrs.module.kenyacore.calculation.Calculations;
import org.openmrs.module.kenyacore.calculation.CalculationUtils;
import org.openmrs.module.kenyacore.CoreUtils;
import org.openmrs.module.kenyacore.CoreConstants;
import org.openmrs.ConceptName;
import org.openmrs.module.kenyaemr.calculation.library.hiv.art.CD4AtARTInitiationCalculation;
import org.openmrs.module.kenyaemr.calculation.library.hiv.AllCd4CountCalculation;
import org.openmrs.module.kenyaemr.calculation.library.hiv.AllVlCountCalculation;
import org.openmrs.module.kenyaemr.calculation.library.rdqa.PatientProgramEnrollmentCalculation;
import org.openmrs.module.kenyaemr.calculation.library.hiv.art.TransferOutDateCalculation;
import org.openmrs.module.kenyaemr.calculation.library.hiv.LastReturnVisitDateCalculation;
import org.openmrs.module.kenyaemr.calculation.library.rdqa.DateOfDeathCalculation;
import org.openmrs.ui.framework.SimpleObject;
import org.openmrs.module.webservices.rest.web.RestConstants;
import org.openmrs.module.webservices.rest.web.v1_0.controller.BaseRestController;
import org.openmrs.ui.framework.annotation.SpringBean;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.xml.sax.SAXException;
import org.springframework.beans.factory.annotation.Autowired;
import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.node.ArrayNode;
import org.codehaus.jackson.node.JsonNodeFactory;
import org.codehaus.jackson.node.ObjectNode;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Date;
import java.util.Calendar;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.ArrayList;
import org.joda.time.DateTime;
import org.joda.time.Weeks;
import org.joda.time.Years;
import java.util.HashSet;
import java.util.Set;
import java.util.Collections;
import java.util.Locale;
import java.util.Comparator;
import org.springframework.http.MediaType;
/**
* The rest controller for exposing resources through kenyacore and kenyaemr modules
*/
@Controller
@RequestMapping(value = "/rest/" + RestConstants.VERSION_1 + "/kenyaemr")
public class KenyaemrCoreRestController extends BaseRestController {
protected final Log log = LogFactory.getLog(getClass());
static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
@Autowired
private ProgramManager programManager;
public static String HIV_PROGRAM_UUID = "dfdc6d40-2f2f-463d-ba90-cc97350441a8";
public static String MCH_CHILD_PROGRAM_UUID = "c2ecdf11-97cd-432a-a971-cfd9bd296b83";
public static String MCH_MOTHER_PROGRAM_UUID = "b5d9e05f-f5ab-4612-98dd-adb75438ed34";
public static String TB_PROGRAM_UUID = "9f144a34-3a4a-44a9-8486-6b7af6cc64f6";
public static String TPT_PROGRAM_UUID = "335517a1-04bc-438b-9843-1ba49fb7fcd9";
public static String OVC_PROGRAM_UUID = "6eda83f0-09d9-11ea-8d71-362b9e155667";
public static String OTZ_PROGRAM_UUID = "24d05d30-0488-11ea-8d71-362b9e155667";
public static String VMMC_PROGRAM_UUID = "228538f4-cad9-476b-84c3-ab0086150bcc";
public static String PREP_PROGRAM_UUID = "214cad1c-bb62-4d8e-b927-810a046daf62";
public static String KP_PROGRAM_UUID = "7447305a-18a7-11e9-ab14-d663bd873d93";
public static final String KP_CLIENT_ENROLMENT = "c7f47cea-207b-11e9-ab14-d663bd873d93";
public static final String KP_CLIENT_DISCONTINUATION = "1f76643e-2495-11e9-ab14-d663bd873d93";
public static final String PREP_ENROLLMENT_FORM = "d5ca78be-654e-4d23-836e-a934739be555";
public static final String PREP_DISCONTINUATION_FORM = "467c4cc3-25eb-4330-9cf6-e41b9b14cc10";
public static final String MCH_DELIVERY_FORM_UUID = "496c7cc3-0eea-4e84-a04c-2292949e2f7f";
public static final String MCH_DISCHARGE_FORM_UUID = "af273344-a5f9-11e8-98d0-529269fb1459";
public static final Locale LOCALE = Locale.ENGLISH;
public String name = null;
public static String ISONIAZID_DRUG_UUID = "78280AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
public static String RIFAMPIN_ISONIAZID_DRUG_UUID = "1194AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
/**
* Gets a list of available/completed forms for a patient
* @param request
* @param patientUuid
* @return
*/
@RequestMapping(method = RequestMethod.GET, value = "/forms") // gets all visit forms for a patient
@ResponseBody
public Object getAllAvailableFormsForVisit(HttpServletRequest request, @RequestParam("patientUuid") String patientUuid) {
if (StringUtils.isBlank(patientUuid)) {
return new ResponseEntity<Object>("You must specify patientUuid in the request!",
new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
Patient patient = Context.getPatientService().getPatientByUuid(patientUuid);
if (patient == null) {
return new ResponseEntity<Object>("The provided patient was not found in the system!",
new HttpHeaders(), HttpStatus.NOT_FOUND);
}
List<Visit> activeVisits = Context.getVisitService().getActiveVisitsByPatient(patient);
ArrayNode formList = JsonNodeFactory.instance.arrayNode();
ObjectNode allFormsObj = JsonNodeFactory.instance.objectNode();
if (!activeVisits.isEmpty()) {
Visit patientVisit = activeVisits.get(0);
/**
* {uuid: string;
* encounterType?: EncounterType;
* name: string;
* display: string;
* version: string;
* published: boolean;
* retired: boolean;}
*/
FormManager formManager = CoreContext.getInstance().getManager(FormManager.class);
List<FormDescriptor> uncompletedFormDescriptors = formManager.getAllUncompletedFormsForVisit(patientVisit);
if (!uncompletedFormDescriptors.isEmpty()) {
for (FormDescriptor descriptor : uncompletedFormDescriptors) {
if(!descriptor.getTarget().getRetired()) {
ObjectNode formObj = generateFormDescriptorPayload(descriptor);
formObj.put("formCategory", "available");
formList.add(formObj);
}
}
PatientWrapper patientWrapper = new PatientWrapper(patient);
Encounter lastMchEnrollment = patientWrapper.lastEncounter(MetadataUtils.existing(EncounterType.class, MchMetadata._EncounterType.MCHMS_ENROLLMENT));
if(lastMchEnrollment != null) {
ObjectNode delivery = JsonNodeFactory.instance.objectNode();
delivery.put("uuid", MCH_DELIVERY_FORM_UUID);
delivery.put("name", "Delivery");
delivery.put("display", "MCH Delivery Form");
delivery.put("version", "1.0");
delivery.put("published", true);
delivery.put("retired", false);
formList.add(delivery);
}
CalculationResult eligibleForDischarge = EmrCalculationUtils.evaluateForPatient(EligibleForMchmsDischargeCalculation.class, null, patient);
if((Boolean) eligibleForDischarge.getValue() == true) {
ObjectNode discharge = JsonNodeFactory.instance.objectNode();
discharge.put("uuid", MCH_DISCHARGE_FORM_UUID);
discharge.put("name", "Discharge");
discharge.put("display", "MCH Discharge Form");
discharge.put("version", "1.0");
discharge.put("published", true);
discharge.put("retired", false);
formList.add(discharge);
}
}
}
allFormsObj.put("results", formList);
return allFormsObj.toString();
}
/**
* Gets a list of flags for a patient
* @param request
* @param patientUuid
* @return
*/
@RequestMapping(method = RequestMethod.GET, value = "/flags") // gets all flags for a patient
@ResponseBody
public Object getAllPatientFlags(HttpServletRequest request, @RequestParam("patientUuid") String patientUuid, @SpringBean CalculationManager calculationManager) {
if (StringUtils.isBlank(patientUuid)) {
return new ResponseEntity<Object>("You must specify patientUuid in the request!",
new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
Patient patient = Context.getPatientService().getPatientByUuid(patientUuid);
ObjectNode flagsObj = JsonNodeFactory.instance.objectNode();
if (patient == null) {
return new ResponseEntity<Object>("The provided patient was not found in the system!",
new HttpHeaders(), HttpStatus.NOT_FOUND);
}
calculationManager.refresh();
ArrayNode flags = JsonNodeFactory.instance.arrayNode();
for (PatientFlagCalculation calc : calculationManager.getFlagCalculations()) {
try {
CalculationResult result = Context.getService(PatientCalculationService.class).evaluate(patient.getId(), calc);
if (result != null && (Boolean) result.getValue()) {
flags.add(calc.getFlagMessage());
}
}
catch (Exception ex) {
log.error("Error evaluating " + calc.getClass(), ex);
return new ResponseEntity<Object>("ERROR EVALUATING!"+ calc.getFlagMessage(),
new HttpHeaders(), HttpStatus.NOT_FOUND);
}
}
flagsObj.put("results", flags);
return flagsObj.toString();
}
/**
* Returns custom patient object
* @param patientUuid
* @return
*/
@RequestMapping(method = RequestMethod.GET, value = "/patient")
@ResponseBody
public Object getPatientIdByPatientUuid(@RequestParam("patientUuid") String patientUuid) {
ObjectNode patientNode = JsonNodeFactory.instance.objectNode();
if (StringUtils.isBlank(patientUuid)) {
return new ResponseEntity<Object>("You must specify patientUuid in the request!",
new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
Patient patient = Context.getPatientService().getPatientByUuid(patientUuid);
ObjectNode patientObj = JsonNodeFactory.instance.objectNode();
if (patient == null) {
return new ResponseEntity<Object>("The provided patient was not found in the system!",
new HttpHeaders(), HttpStatus.NOT_FOUND);
}
patientNode.put("patientId", patient.getPatientId());
patientNode.put("name", patient.getPerson().getPersonName().getFullName());
patientNode.put("age", patient.getAge());
patientObj.put("results", patientNode);
return patientObj.toString();
}
/**
* Returns regimen history for a patient
* @param category // ARV or TB
* @param patientUuid
* @return
*/
@RequestMapping(method = RequestMethod.GET, value = "/regimenHistory")
@ResponseBody
public Object getRegimenHistory(@RequestParam("patientUuid") String patientUuid, @RequestParam("category") String category) {
ObjectNode regimenObj = JsonNodeFactory.instance.objectNode();
if (StringUtils.isBlank(patientUuid)) {
return new ResponseEntity<Object>("You must specify patientUuid in the request!",
new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
Patient patient = Context.getPatientService().getPatientByUuid(patientUuid);
if (patient == null) {
return new ResponseEntity<Object>("The provided patient was not found in the system!",
new HttpHeaders(), HttpStatus.NOT_FOUND);
}
ArrayNode regimenNode = JsonNodeFactory.instance.arrayNode();
List<SimpleObject> obshistory = EncounterBasedRegimenUtils.getRegimenHistoryFromObservations(patient, category);
for (SimpleObject obj : obshistory) {
ObjectNode node = JsonNodeFactory.instance.objectNode();;
node.put("startDate", obj.get("startDate").toString());
node.put("endDate", obj.get("endDate").toString());
node.put("regimenShortDisplay", obj.get("regimenShortDisplay").toString());
node.put("regimenLine", obj.get("regimenLine").toString());
node.put("regimenLongDisplay", obj.get("regimenLongDisplay").toString());
node.put("changeReasons", obj.get("changeReasons").toString());
node.put("regimenUuid", obj.get("regimenUuid").toString());
node.put("current", obj.get("current").toString());
regimenNode.add(node);
}
regimenObj.put("results", regimenNode);
return regimenObj.toString();
}
/**
* Fetches default facility
*
* @return custom location object
*/
@RequestMapping(method = RequestMethod.GET, value = "/default-facility")
@ResponseBody
public Object getDefaultConfiguredFacility() {
GlobalProperty gp = Context.getAdministrationService().getGlobalPropertyObject(EmrConstants.GP_DEFAULT_LOCATION);
if (gp == null) {
return new ResponseEntity<Object>("Default facility not configured!", new HttpHeaders(), HttpStatus.NOT_FOUND);
}
Location location = (Location) gp.getValue();
ObjectNode locationNode = JsonNodeFactory.instance.objectNode();
locationNode.put("locationId", location.getLocationId());
locationNode.put("uuid", location.getUuid());
locationNode.put("display", location.getName());
return locationNode.toString();
}
/**
* ARV drugs
*
* @return custom ARV drugs object for non standard regimen
*/
@RequestMapping(method = RequestMethod.GET, value = "/arvDrugs")
@ResponseBody
public Object getArvDrugs() {
ConceptService concService = Context.getConceptService();
ArrayNode drugs = JsonNodeFactory.instance.arrayNode();
ObjectNode drugsObj = JsonNodeFactory.instance.objectNode();
List<Concept> arvDrugs = Arrays.asList(
concService.getConcept(84309),
concService.getConcept(86663),
concService.getConcept(84795),
concService.getConcept(78643),
concService.getConcept(70057),
concService.getConcept(75628),
concService.getConcept(74807),
concService.getConcept(80586),
concService.getConcept(75523),
concService.getConcept(79040),
concService.getConcept(83412),
concService.getConcept(71648),
concService.getConcept(159810),
concService.getConcept(154378),
concService.getConcept(74258),
concService.getConcept(164967)
);
for (Concept con: arvDrugs) {
ObjectNode node = JsonNodeFactory.instance.objectNode();
node.put("name", con.getName() != null ? con.getName().toString() : "");
node.put("uuid", con.getUuid() != null ? con.getUuid().toString() : "");
drugs.add(node);
}
drugsObj.put("results", drugs);
return drugsObj.toString();
}
/**
* Gets the facility name given the facility code
* @return
*/
@RequestMapping(method = RequestMethod.GET, value = "/facilityName")
@ResponseBody
public Object getFacilityName(@RequestParam("facilityCode") String facilityCode) {
SimpleObject locationResponseObj = new SimpleObject();
Location facility = Context.getService(KenyaEmrService.class).getLocationByMflCode(facilityCode);
locationResponseObj.put("name", facility.getName());
return locationResponseObj;
}
/**
* Get a list of programs a patient is eligible for
* @param request
* @param patientUuid
* @return
*/
@RequestMapping(method = RequestMethod.GET, value = "/eligiblePrograms") // gets all programs a patient is eligible for
@ResponseBody
public Object getEligiblePrograms(HttpServletRequest request, @RequestParam("patientUuid") String patientUuid) {
if (StringUtils.isBlank(patientUuid)) {
return new ResponseEntity<Object>("You must specify patientUuid in the request!",
new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
Patient patient = Context.getPatientService().getPatientByUuid(patientUuid);
if (patient == null) {
return new ResponseEntity<Object>("The provided patient was not found in the system!",
new HttpHeaders(), HttpStatus.NOT_FOUND);
}
ProgramManager programManager = CoreContext.getInstance().getManager(ProgramManager.class);
ArrayNode programList = JsonNodeFactory.instance.arrayNode();
if (!patient.isVoided()) {
Collection<ProgramDescriptor> activePrograms = programManager.getPatientActivePrograms(patient);
Collection<ProgramDescriptor> eligiblePrograms = programManager.getPatientEligiblePrograms(patient);
/**
* ProgramEndPoint {
* uuid: string;
* display: string;
* enrollmentFormUuid: string;
* discontinuationFormUuid: string;
* enrollmentStatus: string;
* }
*/
for (ProgramDescriptor descriptor : eligiblePrograms) {
ObjectNode programObj = JsonNodeFactory.instance.objectNode();
programObj.put("uuid", descriptor.getTargetUuid());
programObj.put("display", descriptor.getTarget().getName());
programObj.put("enrollmentFormUuid", descriptor.getDefaultEnrollmentForm().getTargetUuid());
programObj.put("discontinuationFormUuid", descriptor.getDefaultCompletionForm().getTargetUuid());
programObj.put("enrollmentStatus", activePrograms.contains(descriptor) ? "active" : "eligible");
programList.add(programObj);
}
}
return programList.toString();
}
/**
* Gets the last regimen encounter uuid by category
* @return
*/
@RequestMapping(method = RequestMethod.GET, value = "/lastRegimenEncounter")
@ResponseBody
public Object getLastRegimenEncounterUuid(@RequestParam("category") String category, @RequestParam("patientUuid") String patientUuid) {
ObjectNode encObj = JsonNodeFactory.instance.objectNode();
ObjectNode node = JsonNodeFactory.instance.objectNode();
Patient patient = Context.getPatientService().getPatientByUuid(patientUuid);
String event = null;
Encounter enc = EncounterBasedRegimenUtils.getLastEncounterForCategory(patient, category);
String ARV_TREATMENT_PLAN_EVENT = "1255AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
String DATE_REGIMEN_STOPPED = "1191AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
String endDate = null;
if (enc != null) {
Date latest = null;
List<Date> dates = new ArrayList<Date>();
for(Obs obs:enc.getObs()) {
dates.add(obs.getObsDatetime());
latest = Collections.max(dates);
}
for(Obs obs:enc.getObs()) {
if(obs.getConcept().getUuid().equals(ARV_TREATMENT_PLAN_EVENT) && obs.getObsDatetime().equals(latest)) {
event =obs.getValueCoded() != null ? obs.getValueCoded().getName().getName() : "";
}
if (obs.getConcept() != null && obs.getConcept().getUuid().equals(DATE_REGIMEN_STOPPED)) {
if(obs.getValueDatetime() != null){
endDate = DATE_FORMAT.format(obs.getValueDatetime());
}
}
}
}
node.put("uuid", enc != null ? enc.getUuid() : "");
node.put("startDate", enc != null ? DATE_FORMAT.format(enc.getEncounterDatetime()): "");
node.put("endDate", endDate);
node.put("event", event);
encObj.put("results", node);
return encObj.toString();
}
/**
* Get a list of standard regimen
* @param
* @return
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
*/
@RequestMapping(method = RequestMethod.GET, value = "/standardRegimen")
@ResponseBody
public Object getStandardRegimen() throws SAXException, IOException, ParserConfigurationException {
ArrayNode standardRegimenCategories = JsonNodeFactory.instance.arrayNode();
ObjectNode resultsObj = JsonNodeFactory.instance.objectNode();
for (RegimenConfiguration configuration : Context.getRegisteredComponents(RegimenConfiguration.class)) {
InputStream stream = null;
try {
ClassLoader loader = configuration.getClassLoader();
stream = loader.getResourceAsStream(configuration.getDefinitionsPath());
if (stream == null || stream.available() == 0) {
throw new RuntimeException("Empty or unavailable stream for " + configuration.getDefinitionsPath());
}
// XML parsing logic
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dbFactory.newDocumentBuilder();
Document document = builder.parse(stream);
Element root = document.getDocumentElement();
// Category section i.e ARV, TB etc
NodeList categoryNodes = root.getElementsByTagName("category");
for (int c = 0; c < categoryNodes.getLength(); c++) {
ObjectNode categoryObj = JsonNodeFactory.instance.objectNode();
Element categoryElement = (Element) categoryNodes.item(c);
String categoryCode = categoryElement.getAttribute("code");
categoryObj.put("categoryCode", categoryCode);
NodeList groupNodes = categoryElement.getElementsByTagName("group");
ArrayNode standardRegimen = JsonNodeFactory.instance.arrayNode();
for (int g = 0; g < groupNodes.getLength(); g++) {
ObjectNode standardRegimenObj = JsonNodeFactory.instance.objectNode();
Element groupElement = (Element) groupNodes.item(g);
String groupName = groupElement.getAttribute("name");
String regimenLineValue = "";
if (groupName.equalsIgnoreCase("Adult (first line)")) {
regimenLineValue = "AF";
}else if (groupName.equalsIgnoreCase("Adult (second line)")) {
regimenLineValue = "AS";
}else if (groupName.equalsIgnoreCase("Adult (third line)")) {
regimenLineValue = "AT";
}else if (groupName.equalsIgnoreCase("Child (First Line)")) {
regimenLineValue = "CF";
}else if (groupName.equalsIgnoreCase("Child (Second Line)")) {
regimenLineValue = "CS";
}else if (groupName.equalsIgnoreCase("Child (Third Line)")) {
regimenLineValue = "CT";
}else if (groupName.equalsIgnoreCase("Intensive Phase (Adult)")) {
regimenLineValue = "Intensive Phase (Adult)";
}else if (groupName.equalsIgnoreCase("Intensive Phase (Child)")) {
regimenLineValue = "Intensive Phase (Child)";
}else if (groupName.equalsIgnoreCase("Continuation Phase (Adult)")) {
regimenLineValue = "Continuation Phase (Adult)";
}
standardRegimenObj.put("regimenline", groupName);
standardRegimenObj.put("regimenLineValue", regimenLineValue);
ArrayNode regimen = JsonNodeFactory.instance.arrayNode();
NodeList regimenNodes = groupElement.getElementsByTagName("regimen");
for (int r = 0; r < regimenNodes.getLength(); r++) {
ObjectNode regimenObj = JsonNodeFactory.instance.objectNode();
Element regimenElement = (Element) regimenNodes.item(r);
String name = regimenElement.getAttribute("name");
String conceptRef = regimenElement.getAttribute("conceptRef");
regimenObj.put("name", name);
regimenObj.put("conceptRef", conceptRef);
regimen.add(regimenObj);
}
standardRegimenObj.put("regimen", regimen);
standardRegimen.add(standardRegimenObj);
}
categoryObj.put("category", standardRegimen);
standardRegimenCategories.add(categoryObj);
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Unable to load " + configuration.getModuleId() + ":" + configuration.getDefinitionsPath(), e);
} finally {
try {
if (stream != null) {
stream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
resultsObj.put("results", standardRegimenCategories);
return resultsObj.toString();
}
/**
* Returns regimen change/stop reasons
* @return
*/
@RequestMapping(method = RequestMethod.GET, value = "/regimenReason")
@ResponseBody
public Object getRegimenReason() {
ObjectNode regimenReasonObj = JsonNodeFactory.instance.objectNode();
ArrayNode reasons = JsonNodeFactory.instance.arrayNode();
ObjectNode arvReasonsObj = JsonNodeFactory.instance.objectNode();
ObjectNode tbReasonsObj = JsonNodeFactory.instance.objectNode();
Map<String, String> arvReasonOptionsMap = new HashMap<String, String>();
Map<String, String> tbReasonOptionsMap = new HashMap<String, String>();
arvReasonOptionsMap.put("Toxicity / side effects", "102AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
arvReasonOptionsMap.put("Pregnancy", "1434AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
arvReasonOptionsMap.put("Risk of pregnancy", "160559AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
arvReasonOptionsMap.put("New diagnosis of TB", "160567AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
arvReasonOptionsMap.put("New drug available", "160561AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
arvReasonOptionsMap.put("Drugs out of stock", "1754AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
arvReasonOptionsMap.put("Clinical treatment failure", "843AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
arvReasonOptionsMap.put("Immunological failure", "160566AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
arvReasonOptionsMap.put("Virological Failure", "160569AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
arvReasonOptionsMap.put("Poor Adherence", "159598AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
arvReasonOptionsMap.put("Inpatient care or hospitalization", "5485AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
arvReasonOptionsMap.put("Refusal / patient decision", "127750AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
arvReasonOptionsMap.put("Planned treatment interruption", "160016AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
arvReasonOptionsMap.put("Completed total PMTCT", "1253AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
arvReasonOptionsMap.put("Tuberculosis treatment started", "1270AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
arvReasonOptionsMap.put("Patient lacks finance", "819AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
ArrayNode arvReasons = JsonNodeFactory.instance.arrayNode();
for (Map.Entry<String, String> entry : arvReasonOptionsMap.entrySet()) {
ObjectNode arvCategoryReasonObj = JsonNodeFactory.instance.objectNode();
arvCategoryReasonObj.put("label", entry.getKey());
arvCategoryReasonObj.put("value", entry.getValue());
arvReasons.add(arvCategoryReasonObj);
}
arvReasonsObj.put("category", "ARV");
arvReasonsObj.put("reason", arvReasons);
reasons.add(arvReasonsObj);
tbReasonOptionsMap.put("Toxicity / side effects", "102AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
tbReasonOptionsMap.put("Pregnancy", "1434AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
tbReasonOptionsMap.put("Clinical treatment failure", "843AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
tbReasonOptionsMap.put("Poor Adherence", "159598AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
tbReasonOptionsMap.put("Inpatient care or hospitalization", "5485AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
tbReasonOptionsMap.put("Drugs out of stock", "1754AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
tbReasonOptionsMap.put("Planned treatment interruption", "160016AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
tbReasonOptionsMap.put("Refusal / patient decision", "127750AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
tbReasonOptionsMap.put("Drug formulation changed", "1258AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
tbReasonOptionsMap.put("Patient lacks finance", "819AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
ArrayNode tbReasons = JsonNodeFactory.instance.arrayNode();
for (Map.Entry<String, String> entry : tbReasonOptionsMap.entrySet()) {
ObjectNode tbCategoryReasonObj = JsonNodeFactory.instance.objectNode();
tbCategoryReasonObj.put("label", entry.getKey());
tbCategoryReasonObj.put("value", entry.getValue());
tbReasons.add(tbCategoryReasonObj);
}
tbReasonsObj.put("category", "TB");
tbReasonsObj.put("reason", tbReasons);
reasons.add(tbReasonsObj);
regimenReasonObj.put("results", reasons);
return regimenReasonObj.toString();
}
/**
* Calculate z-score based on a client's sex, weight, and height
* @param sex
* @param weight
* @param height
* @return
*/
@RequestMapping(method = RequestMethod.GET, value = "/zscore")
@ResponseBody
public Object calculateZScore(@RequestParam("sex") String sex, @RequestParam("weight") Double weight, @RequestParam("height") Double height) {
ObjectNode resultNode = JsonNodeFactory.instance.objectNode();
Integer result = ZScoreUtil.calculateZScore(height, weight, sex);
if (result < -4) { // this is an indication of an error. We can break it down further for appropriate messages
return new ResponseEntity<Object>("Could not compute the zscore for the patient!",
new HttpHeaders(), HttpStatus.NOT_FOUND);
}
resultNode.put("wfl_score", result);
return resultNode.toString();
}
/**
* Fetches Patient's hiv care panel data
*
* @return custom hiv data
*/
@RequestMapping(method = RequestMethod.GET, value = "/currentProgramDetails")
@ResponseBody
public Object getPatientHivCarePanel(@RequestParam("patientUuid") String patientUuid) {
Patient patient = Context.getPatientService().getPatientByUuid(patientUuid);
Map<String, SimpleObject> carePanelObj = new HashMap<String, SimpleObject>();
SimpleObject mchMotherResponseObj = new SimpleObject();
SimpleObject mchChildResponseObj = new SimpleObject();
SimpleObject hivResponseObj = new SimpleObject();
SimpleObject tbResponseObj = new SimpleObject();
SimpleObject firstEncDetails = null;
CalculationResult enrolledInHiv = EmrCalculationUtils.evaluateForPatient(HIVEnrollment.class, null, patient);
if((Boolean) enrolledInHiv.getValue() == false) {
CalculationResult lastWhoStage = EmrCalculationUtils.evaluateForPatient(LastWhoStageCalculation.class, null, patient);
if(lastWhoStage != null && lastWhoStage.getValue() != null) {
hivResponseObj.put("whoStage", EmrUtils.whoStage(((Obs) lastWhoStage.getValue()).getValueCoded()));
hivResponseObj.put("whoStageDate", formatDate(((Obs) lastWhoStage.getValue()).getObsDatetime()));
} else {
hivResponseObj.put("whoStage", "");
hivResponseObj.put("whoStageDate", "");
}
CalculationResult lastCd4 = EmrCalculationUtils.evaluateForPatient(LastCd4CountDateCalculation.class, null, patient);
if(lastCd4 != null && lastCd4.getValue() != null) {
hivResponseObj.put("cd4", ((Obs) lastCd4.getValue()).getValueNumeric().toString());
hivResponseObj.put("cd4Date", formatDate(((Obs) lastCd4.getValue()).getObsDatetime()));
} else {
hivResponseObj.put("cd4", "None");
hivResponseObj.put("cd4Date", "");
}
CalculationResult lastCd4Percent = EmrCalculationUtils.evaluateForPatient(LastCd4PercentageCalculation.class, null, patient);
if(lastCd4Percent != null && lastCd4Percent.getValue() != null) {
hivResponseObj.put("cd4Percent", ((Obs) lastCd4Percent.getValue()).getValueNumeric().toString());
hivResponseObj.put("cd4PercentDate", formatDate(((Obs) lastCd4Percent.getValue()).getObsDatetime()));
} else {
hivResponseObj.put("cd4Percent", "None");
hivResponseObj.put("cd4PercentDate", "");
}
CalculationResult lastViralLoad = EmrCalculationUtils.evaluateForPatient(ViralLoadAndLdlCalculation.class, null, patient);
String valuesRequired = "None";
Date datesRequired = null;
if(!lastViralLoad.isEmpty()){
String values = lastViralLoad.getValue().toString();
//split by brace
String value = values.replaceAll("\\{", "").replaceAll("\\}","");
//split by equal sign
if(!value.isEmpty()) {
String[] splitByEqualSign = value.split("=");
valuesRequired = splitByEqualSign[0];
//for a date from a string
String dateSplitedBySpace = splitByEqualSign[1].split(" ")[0].trim();
String yearPart = dateSplitedBySpace.split("-")[0].trim();
String monthPart = dateSplitedBySpace.split("-")[1].trim();
String dayPart = dateSplitedBySpace.split("-")[2].trim();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, Integer.parseInt(yearPart));
calendar.set(Calendar.MONTH, Integer.parseInt(monthPart) - 1);
calendar.set(Calendar.DATE, Integer.parseInt(dayPart));
datesRequired = calendar.getTime();
}
}
// get default LDL value
AdministrationService as = Context.getAdministrationService();
hivResponseObj.put("ldlValue", valuesRequired);
hivResponseObj.put("ldlDate", formatDate(datesRequired));
hivResponseObj.put("enrolledInHiv", (Boolean) enrolledInHiv.getValue());
Encounter lastEnc = EncounterBasedRegimenUtils.getLastEncounterForCategory(patient, "ARV");
SimpleObject lastEncDetails = null;
if (lastEnc != null) {
lastEncDetails = EncounterBasedRegimenUtils.buildRegimenChangeObject(lastEnc.getObs(), lastEnc);
}
hivResponseObj.put("lastEncDetails", lastEncDetails);
carePanelObj.put("HIV", hivResponseObj);
}
// tb details
CalculationResult patientEnrolledInTbProgram = EmrCalculationUtils.evaluateForPatient(PatientInTbProgramCalculation.class, null,patient);
if((Boolean) patientEnrolledInTbProgram.getValue() == true) {
CalculationResult tbDiseaseClassification = EmrCalculationUtils.evaluateForPatient(TbDiseaseClassificationCalculation.class, null, patient);
if(tbDiseaseClassification != null && tbDiseaseClassification.getValue() != null) {
tbResponseObj.put("tbDiseaseClassification", ((Obs) tbDiseaseClassification.getValue()).getValueCoded().getName().getName());
tbResponseObj.put("tbDiseaseClassificationDate", formatDate(((Obs) tbDiseaseClassification.getValue()).getObsDatetime()));
} else {
tbResponseObj.put("tbDiseaseClassification", "None");
tbResponseObj.put("tbDiseaseClassificationDate", "");
}
CalculationResult tbPatientClassification = EmrCalculationUtils.evaluateForPatient(TbPatientClassificationCalculation.class, null, patient);
if(tbPatientClassification != null){
Obs obs = (Obs) tbPatientClassification.getValue();
if(obs.getValueCoded().equals(Dictionary.getConcept(Dictionary.SMEAR_POSITIVE_NEW_TUBERCULOSIS_PATIENT))) {
tbResponseObj.put("tbPatientClassification", "New tuberculosis patient");
}
else {
tbResponseObj.put("tbPatientClassification", obs.getValueCoded().getName().getName());
}
}
CalculationResult tbTreatmentNo = EmrCalculationUtils.evaluateForPatient(TbTreatmentNumberCalculation.class, null, patient);
if(tbTreatmentNo != null && tbTreatmentNo.getValue() != null) {
tbResponseObj.put("tbTreatmentNumber", ((Obs) tbTreatmentNo.getValue()));
} else {
tbResponseObj.put("tbTreatmentNumber", "None");
}
Encounter lastTBEnc = EncounterBasedRegimenUtils.getLastEncounterForCategory(patient, "TB");
SimpleObject lastTBEncDetails = null;
if (lastTBEnc != null) {
lastTBEncDetails = EncounterBasedRegimenUtils.buildRegimenChangeObject(lastTBEnc.getObs(), lastTBEnc);
}
tbResponseObj.put("lastTbEncounter", lastTBEncDetails);
carePanelObj.put("TB", tbResponseObj);
}
//mch mother details
PatientCalculationContext context = Context.getService(PatientCalculationService.class).createCalculationContext();
Program hivProgram = MetadataUtils.existing(Program.class, HivMetadata._Program.HIV);
PatientWrapper patientWrapper = new PatientWrapper(patient);
Encounter lastMchEnrollment = patientWrapper.lastEncounter(MetadataUtils.existing(EncounterType.class, MchMetadata._EncounterType.MCHMS_ENROLLMENT));
Encounter lastMchFollowup = patientWrapper.lastEncounter(MetadataUtils.existing(EncounterType.class, MchMetadata._EncounterType.MCHMS_CONSULTATION));
if(lastMchEnrollment != null ) {
EncounterWrapper lastMchEnrollmentWrapped = null;
EncounterWrapper lastMchFollowUpWrapped = null;
//Check whether already in hiv program
CalculationResultMap enrolled = Calculations.firstEnrollments(hivProgram, Arrays.asList(patient.getPatientId()), context);
PatientProgram program = EmrCalculationUtils.resultForPatient(enrolled, patient.getPatientId());
if (lastMchEnrollment != null) {
lastMchEnrollmentWrapped = new EncounterWrapper(lastMchEnrollment);
}
if (lastMchFollowup != null) {
lastMchFollowUpWrapped = new EncounterWrapper(lastMchFollowup);
}
Obs hivEnrollmentStatusObs = null;
Obs hivFollowUpStatusObs = null;
if (lastMchEnrollmentWrapped != null) {
hivEnrollmentStatusObs = lastMchEnrollmentWrapped.firstObs(Dictionary.getConcept(Dictionary.HIV_STATUS));
}
if (lastMchFollowUpWrapped != null) {
hivFollowUpStatusObs = lastMchFollowUpWrapped.firstObs(Dictionary.getConcept(Dictionary.HIV_STATUS));
}
//Check if already enrolled in HIV, add regimen
if(program != null) {
String regimenName = null;
String regimenStartDate = null;
Encounter lastDrugRegimenEditorEncounter = EncounterBasedRegimenUtils.getLastEncounterForCategory(patient, "ARV"); //last DRUG_REGIMEN_EDITOR encounter
if (lastDrugRegimenEditorEncounter != null) {
SimpleObject o = EncounterBasedRegimenUtils.buildRegimenChangeObject(lastDrugRegimenEditorEncounter.getAllObs(), lastDrugRegimenEditorEncounter);
regimenName = o.get("regimenShortDisplay").toString();
regimenStartDate = o.get("startDate").toString();
if (regimenName != null) {
mchMotherResponseObj.put("hivStatus", "Positive");
mchMotherResponseObj.put("hivStatusDate", regimenStartDate);
mchMotherResponseObj.put("onHaart", "Yes (" + regimenName + ")");
mchMotherResponseObj.put("onHaartDate", regimenStartDate);
} else {
mchMotherResponseObj.put("hivStatus", "Positive");
mchMotherResponseObj.put("hivStatusDate", regimenStartDate);
mchMotherResponseObj.put("onHaart", "Not specified");
mchMotherResponseObj.put("onHaartDate", regimenStartDate);
}
}
//Check mch enrollment and followup forms
} else if(hivEnrollmentStatusObs != null || hivFollowUpStatusObs != null) {
String regimenName = null;
if(hivFollowUpStatusObs != null){
mchMotherResponseObj.put("hivStatus", hivFollowUpStatusObs.getValueCoded().getName().getName());
mchMotherResponseObj.put("hivStatusDate", hivFollowUpStatusObs.getValueDatetime());
}else {
mchMotherResponseObj.put("hivStatus", hivEnrollmentStatusObs.getValueCoded().getName().getName());
mchMotherResponseObj.put("hivStatusDate", hivEnrollmentStatusObs.getValueDatetime());
}
Encounter lastDrugRegimenEditorEncounter = EncounterBasedRegimenUtils.getLastEncounterForCategory(patient, "ARV"); //last DRUG_REGIMEN_EDITOR encounter
mchMotherResponseObj.put("onHaart", hivEnrollmentStatusObs.getValueDatetime());
if (lastDrugRegimenEditorEncounter != null) {
SimpleObject o = EncounterBasedRegimenUtils.buildRegimenChangeObject(lastDrugRegimenEditorEncounter.getAllObs(), lastDrugRegimenEditorEncounter);
regimenName = o.get("regimenShortDisplay").toString();
if (regimenName != null) {
if (hivEnrollmentStatusObs.getValueCoded().getName().getName().equalsIgnoreCase("positive")) {
mchMotherResponseObj.put("onHaart", "Yes (" + regimenName + ")");
} else {
mchMotherResponseObj.put("onHaart", "Not specified");
}
} else {
mchMotherResponseObj.put("onHaart", "Not specified");
}
} else {
if (hivEnrollmentStatusObs.getValueCoded().getName().getName().equalsIgnoreCase("negative")) {
mchMotherResponseObj.put("onHaart", "Not applicable");
}
if (hivEnrollmentStatusObs.getValueCoded().getName().getName().equalsIgnoreCase("unknown")) {
mchMotherResponseObj.put("onHaart", "Not applicable");
}
if (hivEnrollmentStatusObs.getValueCoded().getName().getName().equalsIgnoreCase("positive")) {
mchMotherResponseObj.put("onHaart", "Not specified");
}
}
}
carePanelObj.put("mchMother", mchMotherResponseObj);
}
//mch child details
Encounter lastHeiEnrollmentEncounter = Utils.lastEncounter(patient, Context.getEncounterService().getEncounterTypeByUuid(MchMetadata._EncounterType.MCHCS_ENROLLMENT));
if(lastHeiEnrollmentEncounter != null) {
List<Obs> milestones = new ArrayList<Obs>();
String prophylaxis;
String feeding;
List<Obs> remarks = new ArrayList<Obs>();
String heiOutcomes;
Integer prophylaxisQuestion = 1282;
Integer feedingMethodQuestion = 1151;
Integer heiOutcomesQuestion = 159427;