@Test
  public void testParsingDispositions() throws Exception {
    Concept admit =
        new ConceptBuilder(
                null,
                conceptService.getConceptDatatypeByName("N/A"),
                conceptService.getConceptClassByName("Misc"))
            .addName("Admit")
            .get();
    when(emrConceptService.getConcept("test:admit")).thenReturn(admit);
    Obs dispositionObs =
        dispositionDescriptor.buildObsGroup(
            new Disposition(
                "emrapi.admit",
                "Admit",
                "test:admit",
                Collections.<String>emptyList(),
                Collections.<DispositionObs>emptyList()),
            emrConceptService);
    encounter.addObs(doNotGoToServiceToFormatMembers(dispositionObs));
    ParsedObs parsed = parser.parseObservations(Locale.ENGLISH);

    assertThat(parsed.getDiagnoses().size(), is(0));
    assertThat(parsed.getDispositions().size(), is(1));
    assertThat(parsed.getObs().size(), is(0));
    assertThat(path(parsed.getDispositions(), 0, "disposition"), is((Object) "Admit"));
    assertThat(
        path(parsed.getDispositions(), 0, "additionalObs"), is((Object) Collections.emptyList()));
  }
 private Encounter buildEncounter(
     EncounterType encounterType,
     Patient patient,
     Location location,
     Form form,
     Date when,
     List<Obs> obsToCreate,
     List<Order> ordersToCreate) {
   Encounter encounter = new Encounter();
   encounter.setPatient(patient);
   encounter.setEncounterType(encounterType);
   encounter.setLocation(location);
   encounter.setForm(form);
   encounter.setEncounterDatetime(when);
   if (obsToCreate != null) {
     for (Obs obs : obsToCreate) {
       obs.setObsDatetime(new Date());
       encounter.addObs(obs);
     }
   }
   if (ordersToCreate != null) {
     for (Order order : ordersToCreate) {
       encounter.addOrder(order);
     }
   }
   return encounter;
 }
Ejemplo n.º 3
0
  /**
   * Adds a new encounter with the given observations and orders.
   *
   * @param observations a list of observations
   * @param orderUuids a list of order UUIDs
   * @param patient the patient for whom to add the encounter
   * @param encounterTime the time of the encounter
   * @param changeMessage a message to be recorded with the observation
   * @param encounterTypeName the OpenMRS name for the encounter type, configured in OpenMRS
   * @param locationUuid the UUID of the location where the encounter happened
   */
  public static Encounter addEncounter(
      List observations,
      List orderUuids,
      Patient patient,
      Date encounterTime,
      String changeMessage,
      String encounterTypeName,
      String locationUuid) {
    // OpenMRS will reject the encounter if the time is in the past, even if
    // the client's clock is off by only one millisecond; work around this.
    encounterTime = Utils.fixEncounterDateTime(encounterTime);

    EncounterService encounterService = Context.getEncounterService();
    final Location location = Context.getLocationService().getLocationByUuid(locationUuid);
    if (location == null) {
      throw new InvalidObjectDataException("Location not found: " + locationUuid);
    }
    EncounterType encounterType = encounterService.getEncounterType(encounterTypeName);
    if (encounterType == null) {
      throw new InvalidObjectDataException("Encounter type not found: " + encounterTypeName);
    }

    List<Obs> obsList = new ArrayList<>();
    if (observations != null) {
      for (Object observation : observations) {
        obsList.add(jsonObservationToObs(observation, patient, encounterTime, location));
      }
    }

    if (orderUuids != null) {
      for (Object item : orderUuids) {
        obsList.add(orderUuidToObs((String) item, patient, encounterTime, location));
      }
    }

    // Write the encounter and all the observations to the database.
    Encounter encounter = new Encounter();
    encounter.setEncounterDatetime(encounterTime);
    encounter.setPatient(patient);
    encounter.setLocation(location);
    encounter.setEncounterType(encounterType);
    encounter = encounterService.saveEncounter(encounter);

    ObsService obsService = Context.getObsService();
    for (Obs obs : obsList) {
      if (obs != null) {
        encounter.addObs(obs);
        obsService.saveObs(obs, changeMessage);
      }
    }
    return encounter;
  }
  @Test
  public void testParsingDispositionWithTransferLocation() throws Exception {
    Concept admit =
        new ConceptBuilder(
                null,
                conceptService.getConceptDatatypeByName("N/A"),
                conceptService.getConceptClassByName("Misc"))
            .addName("Transfer")
            .get();
    when(emrConceptService.getConcept("test:transfer")).thenReturn(admit);

    Obs dispositionObs =
        dispositionDescriptor.buildObsGroup(
            new Disposition(
                "emrapi.transfer",
                "Transfer",
                "test:transfer",
                Collections.<String>emptyList(),
                Collections.<DispositionObs>emptyList()),
            emrConceptService);

    Obs transferLocationObs = new Obs();
    transferLocationObs.setObsId(100);
    transferLocationObs.setConcept(dispositionDescriptor.getInternalTransferLocationConcept());
    transferLocationObs.setValueText("3");
    dispositionObs.addGroupMember(transferLocationObs);

    Location transferLocation = new Location();
    transferLocation.setName("Outpatient clinic");
    when(locationService.getLocation(3)).thenReturn(transferLocation);

    encounter.addObs(doNotGoToServiceToFormatMembers(dispositionObs));
    ParsedObs parsed = parser.parseObservations(Locale.ENGLISH);

    SimpleObject expectedTransferLocationObject =
        SimpleObject.create("obsId", transferLocationObs.getObsId());
    expectedTransferLocationObject.put("question", "Transfer location");
    expectedTransferLocationObject.put("answer", "Outpatient clinic");

    List<SimpleObject> expectedAdditionalObsList = new ArrayList<SimpleObject>();
    expectedAdditionalObsList.add(expectedTransferLocationObject);

    assertThat(parsed.getDiagnoses().size(), is(0));
    assertThat(parsed.getDispositions().size(), is(1));
    assertThat(parsed.getObs().size(), is(0));
    assertThat(path(parsed.getDispositions(), 0, "disposition"), is((Object) "Transfer"));
    assertThat(
        path(parsed.getDispositions(), 0, "additionalObs"), is((Object) expectedAdditionalObsList));
  }
  @Test
  public void testParsingDispositionWithDateOfDeath() throws Exception {
    Concept admit =
        new ConceptBuilder(
                null,
                conceptService.getConceptDatatypeByName("N/A"),
                conceptService.getConceptClassByName("Misc"))
            .addName("Death")
            .get();
    when(emrConceptService.getConcept("test:death")).thenReturn(admit);

    Obs dispositionObs =
        dispositionDescriptor.buildObsGroup(
            new Disposition(
                "emrapi.death",
                "Death",
                "test:death",
                Collections.<String>emptyList(),
                Collections.<DispositionObs>emptyList()),
            emrConceptService);

    Date dateOfDeath = new DateTime(2012, 2, 20, 10, 10, 10).toDate();
    Obs dateOfDeathObs = new Obs();
    dateOfDeathObs.setObsId(100);
    dateOfDeathObs.setConcept(dispositionDescriptor.getDateOfDeathConcept());
    dateOfDeathObs.setValueDate(dateOfDeath);
    dispositionObs.addGroupMember(dateOfDeathObs);

    encounter.addObs(doNotGoToServiceToFormatMembers(dispositionObs));
    ParsedObs parsed = parser.parseObservations(Locale.ENGLISH);

    SimpleObject expectedAdmissionLocationObject =
        SimpleObject.create("obsId", dateOfDeathObs.getObsId());
    expectedAdmissionLocationObject.put("question", "Date of death");
    expectedAdmissionLocationObject.put("answer", "20 Feb 2012 10:10 AM");

    List<SimpleObject> expectedAdditionalObsList = new ArrayList<SimpleObject>();
    expectedAdditionalObsList.add(expectedAdmissionLocationObject);

    assertThat(parsed.getDiagnoses().size(), is(0));
    assertThat(parsed.getDispositions().size(), is(1));
    assertThat(parsed.getObs().size(), is(0));
    assertThat(path(parsed.getDispositions(), 0, "disposition"), is((Object) "Death"));
    assertThat(
        path(parsed.getDispositions(), 0, "additionalObs"), is((Object) expectedAdditionalObsList));
  }
  @Test
  public void testParsingDiagnoses() throws Exception {
    encounter.addObs(
        diagnosisMetadata.buildDiagnosisObsGroup(
            new Diagnosis(new CodedOrFreeTextAnswer("Random Disease"), Diagnosis.Order.PRIMARY)));
    ParsedObs parsed = parser.parseObservations(Locale.ENGLISH);

    assertThat(parsed.getDiagnoses().size(), is(1));
    assertThat(parsed.getDispositions().size(), is(0));
    assertThat(parsed.getObs().size(), is(0));
    assertThat(
        path(parsed.getDiagnoses(), 0, "question"),
        is((Object) "coreapps.patientDashBoard.diagnosisQuestion.PRIMARY"));
    assertThat(
        path(parsed.getDiagnoses(), 0, "answer"),
        is((Object) "(coreapps.Diagnosis.Certainty.PRESUMED) \"Random Disease\""));
    assertThat(path(parsed.getDiagnoses(), 0, "order"), is((Object) 0));
  }
  @Test
  public void testParsingSimpleObs() throws Exception {
    ConceptDatatype textDatatype = conceptService.getConceptDatatypeByName("Text");
    ConceptClass misc = conceptService.getConceptClassByName("Misc");

    String consultNote =
        "Consult note"; // intentionally the same as what will result from
                        // capitalizeFirstLetter(consultNote)
    String valueText = "Patient is here for blah blah blah.";

    Concept consultComments =
        new ConceptBuilder(conceptService, textDatatype, misc).addName(consultNote).get();

    encounter.addObs(new ObsBuilder().setConcept(consultComments).setValue(valueText).get());
    ParsedObs parsed = parser.parseObservations(Locale.ENGLISH);

    assertThat(parsed.getDiagnoses().size(), is(0));
    assertThat(parsed.getDispositions().size(), is(0));
    assertThat(parsed.getObs().size(), is(1));
    assertThat(path(parsed.getObs(), 0, "question"), is((Object) consultNote));
    assertThat(path(parsed.getObs(), 0, "answer"), is((Object) valueText));
  }
  @Test
  public void testParsingObsWithLocationAnswer() throws Exception {
    ConceptDatatype textDatatype = conceptService.getConceptDatatypeByName("Text");
    ConceptClass misc = conceptService.getConceptClassByName("Misc");

    Location xanadu = new Location();
    xanadu.setName("Xanadu");
    when(locationService.getLocation(2)).thenReturn(xanadu);

    Concept someLocation =
        new ConceptBuilder(conceptService, textDatatype, misc).addName("Some location").get();

    encounter.addObs(
        new ObsBuilder()
            .setConcept(someLocation)
            .setValue("2")
            .setComment("org.openmrs.Location")
            .get());
    ParsedObs parsed = parser.parseObservations(Locale.ENGLISH);
    ;
    assertThat(parsed.getObs().size(), is(1));
    assertThat(path(parsed.getObs(), 0, "question"), is((Object) "Some location"));
    assertThat(path(parsed.getObs(), 0, "answer"), is((Object) "Xanadu"));
  }
  @Test
  public void shouldEvaluateOBRORUR01TemplateForOBSGroup() throws Exception {
    // given
    Encounter encounter = new Encounter();

    Date date = new Date();
    encounter.setEncounterDatetime(date);
    encounter.setUuid("ENCOUNTER UUID");

    EncounterType encounterType = new EncounterType();
    encounterType.setName("ENCOUNTER TYPE NAME");
    encounter.setEncounterType(encounterType);

    Location location = new Location(1);
    location.setUuid("LOCATION UUID");
    location.setName("LOCATION NAME");
    encounter.setLocation(location);

    Person provider = new Person(1);
    provider.setUuid("PROVIDER UUID");
    provider.addName(
        new PersonName("PROVIDER GIVENNAME", "PROVIDER MIDDLENAME", "PROVIDER FAMILYNAME"));
    encounter.setProvider(provider);

    ConceptSource source = new ConceptSource();
    source.setName("AMPATH");

    ConceptMap map = new ConceptMap();
    map.setSourceCode("200");
    map.setSource(source);

    ConceptDatatype datatype = new ConceptDatatype();
    datatype.setUuid(ConceptDatatype.NUMERIC_UUID);
    datatype.setHl7Abbreviation(ConceptDatatype.NUMERIC);

    ConceptNumeric concept = new ConceptNumeric();
    concept.setDatatype(datatype);
    concept.addConceptMapping(map);
    concept.addName(new ConceptName("NumericConcept", Locale.ENGLISH));
    concept.setUnits("mg");

    Date dateCreated = new Date(213231421890234L);

    Obs obs = new Obs(2);
    obs.setConcept(concept);
    obs.setDateCreated(dateCreated);
    obs.setValueNumeric(10d);

    obs.setObsGroup(getObsGroup());
    obs.getObsGroup().addGroupMember(obs);

    encounter.addObs(obs);

    obs = new Obs(3);
    obs.setConcept(concept);
    obs.setDateCreated(dateCreated);
    obs.setValueNumeric(23d);
    encounter.addObs(obs);

    Map<String, Object> bindings = new HashMap<String, Object>();
    bindings.put("encounter", encounter);
    bindings.put("implementationId", "MVP");

    // when
    HL7Template hl7Template = hl7QueryService.getHL7TemplateByName("Generic Obs Group");
    String evaluatedTemplate = hl7QueryService.evaluateTemplate(hl7Template, bindings);

    // then
    evaluatedTemplate = StringUtils.deleteWhitespace(evaluatedTemplate);
    Assert.assertEquals(
        "<ORU_R01.ORDER_OBSERVATION><OBR><OBR.1>0</OBR.1><OBR.4><CE.1>100</CE.1>"
            + "<CE.2>MEDICALRECORDOBSERVATIONS</CE.2><CE.3>LOCAL</CE.3></OBR.4><OBR.18>0</OBR.18>"
            + "<OBR.29><EIP.2><EI.3>ENCOUNTERUUID</EI.3></EIP.2></OBR.29></OBR><ORU_R01.OBSERVATION>"
            + "<OBX><OBX.1>1</OBX.1><OBX.2>NM</OBX.2><OBX.3><CE.1>200</CE.1><CE.2>NumericConcept</CE.2>"
            + "<CE.3>AMPATH</CE.3></OBX.3><OBX.5>23.0</OBX.5><OBX.6><CE.1>mg</CE.1><CE.3>UCUM</CE.3></OBX.6>"
            + "<OBX.14><TS.1>"
            + new HL7TemplateFunctions().formatDate(dateCreated, null)
            + "</TS.1>"
            + "</OBX.14></OBX></ORU_R01.OBSERVATION></ORU_R01.ORDER_OBSERVATION>"
            + "<ORU_R01.ORDER_OBSERVATION><OBR><OBR.1>2</OBR.1><OBR.4><CE.1>100</CE.1><CE.2>MedSet</CE.2>"
            + "<CE.3>LOCAL</CE.3></OBR.4><OBR.18>0</OBR.18><OBR.29><EIP.2><EI.3>ENCOUNTERUUID</EI.3></EIP.2></OBR.29"
            + "></OBR><ORU_R01.OBSERVATION><OBX><OBX.1>2</OBX.1><OBX.2>NM</OBX.2><OBX.3><CE.1>200</CE.1>"
            + "<CE.2>NumericConcept</CE.2><CE.3>AMPATH</CE.3></OBX.3><OBX.5>10.0</OBX.5><OBX.6><CE.1>mg</CE.1>"
            + "<CE.3>UCUM</CE.3></OBX.6><OBX.14><TS.1>"
            + new HL7TemplateFunctions().formatDate(dateCreated, null)
            + "</TS.1></OBX.14></OBX></ORU_R01.OBSERVATION></ORU_R01.ORDER_OBSERVATION>",
        evaluatedTemplate);
  }
    /**
     *
     * Returns the encounter with the obs that aren't used when populating form are removed.
     * This *doesn't* save the encounter.
     * TODO: handle Orders?
     *
     * @param e
     * @param htmlform
     * @return
     * @throws Exception
     */
    public static Encounter trimEncounterToMatchForm(Encounter e, HtmlForm htmlform) throws Exception {

       //this should move existing obs from session to tag handlers.
        FormEntrySession session = new FormEntrySession(e.getPatient(), e, FormEntryContext.Mode.VIEW, htmlform, null); // session gets a null HttpSession
        session.getHtmlToDisplay();

        if (log.isDebugEnabled()){
            Map<Concept, List<Obs>>  map = session.getContext().getExistingObs();
            if (map != null){
                for (Map.Entry<Concept, List<Obs>> existingObs : map.entrySet()){
                    List<Obs> oList = existingObs.getValue();
                    for (Obs oInner : oList)
                        log.debug("Obs in existingObs " + existingObs.getKey() + " " + oInner.getConcept());
                }
            }
            Map<Obs, Set<Obs>> map2 = session.getContext().getExistingObsInGroups();
            if (map2 != null){
                for (Map.Entry<Obs, Set<Obs>> existingObsInGroups : map2.entrySet()){
                    Set<Obs> oList = existingObsInGroups.getValue();
                    for (Obs oInner : oList)
                        log.debug("Obs in existingObsInGroups " + existingObsInGroups.getKey().getConcept() + " " + oInner.getConcept());
                }
            }
        }
        Encounter ret = new Encounter();
        ret.setCreator(e.getCreator());
        ret.setEncounterDatetime(e.getEncounterDatetime());
        EncounterCompatibility.setProvider(ret, EncounterCompatibility.getProvider(e));
        ret.setLocation(e.getLocation());
        ret.setDateCreated(e.getDateCreated());
        ret.setPatient(e.getPatient());
        //renders new encounter unsave-able:
        ret.setEncounterId(e.getEncounterId());

        for (Obs oTest : e.getAllObs()){
            boolean found = false;
            if (session.getContext().getExistingObs() != null && !oTest.isObsGrouping()){
                List<Obs> obsList = session.getContext().getExistingObs().get(oTest.getConcept());
                if (obsList != null && obsList.size() > 0){
                    for (Obs o : obsList){
                        if (o.getObsId().equals(oTest.getObsId())){
                            found = true;
                            continue;
                        }
                    }
                }
            }
            if (!found && session.getContext().getExistingObsInGroups() != null){
                for (Map.Entry<Obs, Set<Obs>> mapEntry : session.getContext().getExistingObsInGroups().entrySet()){
                    if (mapEntry.getKey().equals(oTest)){
                        found = true;
                        continue;
                    } else {
                        Set<Obs> oSet = mapEntry.getValue();
                        //note: oSet.contains fails for some reason
                        for (Obs o:oSet){
                              if (o.getObsId().equals(oTest.getObsId())){
                                  found = true;
                                  continue;
                              }
                        }
                    }
                }
            }
            if (!found)
                ret.addObs(oTest);
        }
        session = null;
        return ret;
    }
  @RequestMapping(method = RequestMethod.POST)
  public void savePatientInfo(
      @RequestParam("patientId") Integer patientId,
      @RequestParam(value = "encounterId", required = false) Integer encounterId,
      HttpServletRequest request,
      HttpServletResponse response)
      throws ParseException, IOException {

    Map<String, String> parameters = RegistrationWebUtils.optimizeParameters(request);

    // get patient
    Patient patient = Context.getPatientService().getPatient(patientId);

    /*
     * SAVE ENCOUNTER
     */
    Encounter encounter = null;
    if (encounterId != null) {
      encounter = Context.getEncounterService().getEncounter(encounterId);
    } else {
      encounter = RegistrationWebUtils.createEncounter(patient, true);

      // create OPD obs
      Concept opdWardConcept =
          Context.getConceptService().getConcept(RegistrationConstants.CONCEPT_NAME_OPD_WARD);
      Concept selectedOPDConcept =
          Context.getConceptService()
              .getConcept(
                  Integer.parseInt(
                      parameters.get(RegistrationConstants.FORM_FIELD_PATIENT_OPD_WARD)));
      Obs opd = new Obs();
      opd.setConcept(opdWardConcept);
      opd.setValueCoded(selectedOPDConcept);
      encounter.addObs(opd);

      // send patient to opd room/bloodbank

      // harsh 5/10/2012 changed the way to get blood bank concept->shifted hardcoded dependency
      // from id to name
      //			Concept bloodbankConcept = Context.getConceptService().getConcept(
      //			    GlobalPropertyUtil.getInteger(RegistrationConstants.PROPERTY_BLOODBANK_CONCEPT_ID,
      // 6425));
      String bloodBankWardName =
          GlobalPropertyUtil.getString(
              RegistrationConstants.PROPERTY_BLOODBANK_OPDWARD_NAME, "Blood Bank Room");

      // ghanshyam 03-sept-2013 Bug #394 [Blood bank]queue
      String socn = new String(selectedOPDConcept.getName().toString());
      String substringofsocn = socn.substring(0, 15);

      if (!substringofsocn.equalsIgnoreCase(bloodBankWardName)) {
        RegistrationWebUtils.sendPatientToOPDQueue(patient, selectedOPDConcept, true);
      } else {
        OrderType orderType = null;
        String orderTypeName =
            Context.getAdministrationService().getGlobalProperty("bloodbank.orderTypeName");
        orderType = OrderUtil.getOrderTypeByName(orderTypeName);

        Order order = new Order();
        order.setConcept(selectedOPDConcept);
        order.setCreator(Context.getAuthenticatedUser());
        order.setDateCreated(new Date());
        order.setOrderer(Context.getAuthenticatedUser());
        order.setPatient(patient);
        order.setStartDate(new Date());
        order.setAccessionNumber("0");
        order.setOrderType(orderType);
        order.setEncounter(encounter);
        encounter.addOrder(order);
      }
    }

    // create temporary attributes
    for (String name : parameters.keySet()) {
      if ((name.contains(".attribute.")) && (!StringUtils.isBlank(parameters.get(name)))) {
        String[] parts = name.split("\\.");
        String idText = parts[parts.length - 1];
        Integer id = Integer.parseInt(idText);
        Concept tempCatConcept = Context.getConceptService().getConceptByName("TEMPORARY CATEGORY");

        Concept temporaryAttributeConcept =
            Context.getConceptService().getConcept(tempCatConcept.getConceptId());
        Obs temporaryAttribute = new Obs();
        temporaryAttribute.setConcept(temporaryAttributeConcept);
        logger.info("concept: " + temporaryAttributeConcept);
        logger.info("value: " + parameters.get(name));
        temporaryAttribute.setValueAsString(parameters.get(name));
        encounter.addObs(temporaryAttribute);
      }
    }

    // save encounter
    Context.getEncounterService().saveEncounter(encounter);
    logger.info(
        String.format(
            "Save encounter for the visit of patient [encounterId=%s, patientId=%s]",
            encounter.getId(), patient.getId()));

    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.print("success");
  }