private static boolean regimenComponentIsTheSameAsDrugOrderExcludingDates(
     DrugOrder rc, DrugOrder doTmp) {
   if (rc.getDrug() != null
       && doTmp.getDrug() != null
       && rc.getDrug().getDrugId().intValue() != doTmp.getDrug().getDrugId().intValue())
     return false;
   if (!OpenmrsUtil.nullSafeEquals(rc.getConcept(), doTmp.getConcept())) return false;
   if (!OpenmrsUtil.nullSafeEquals(rc.getDose(), doTmp.getDose())) return false;
   if (!OpenmrsUtil.nullSafeEquals(rc.getFrequency(), doTmp.getFrequency())) return false;
   if (!OpenmrsUtil.nullSafeEquals(rc.getUnits(), doTmp.getUnits())) return false;
   return true;
 }
  @Test
  public void shouldAddNewDrugOrderWhenPrnIsTrueWIthNoDosageFrequencyOrDosageInstruction() {

    EncounterTransaction.DrugOrder drugOrder =
        new DrugOrderBuilder()
            .withBasicValues("drug-uuid", "test-concept-uuid", today, today, 3, "", "")
            .withPrn(true)
            .build();
    Concept drugConcept = new Concept(3);
    OrderType drugOrderType = new OrderType("Drug Order", "this is a drug order type");

    when(orderService.getAllOrderTypes()).thenReturn(asList(drugOrderType));
    when(conceptService.getConceptByUuid("test-concept-uuid")).thenReturn(drugConcept);
    Drug drug = new Drug();
    drug.setName("test drug");
    when(conceptService.getDrugByUuid("drug-uuid")).thenReturn(drug);

    encounterDrugOrderServiceHelper.update(encounter, asList(drugOrder));

    assertThat(encounter.getOrders().size(), is(1));
    org.openmrs.DrugOrder order = (org.openmrs.DrugOrder) encounter.getOrders().iterator().next();
    assertEquals(drugConcept, order.getConcept());
    assertEquals(drugOrderType, order.getOrderType());
    assertEquals(patient, order.getPatient());
    assertEquals(encounter, order.getEncounter());
    assertEquals(today, order.getStartDate());
    assertEquals(today, order.getAutoExpireDate());
    assertEquals(drug.getDisplayName(), order.getDrug().getDisplayName());
    assertEquals(Double.valueOf(3), order.getDose());

    assertEquals(true, order.getPrn());
    assertEquals(null, order.getFrequency());
    assertEquals(null, order.getUnits());
  }
  @Test
  public void shouldAddNewDrugOrder() throws Exception {
    executeDataSet("shouldAddNewDrugOrder.xml");

    String json =
        "{ \"patientUuid\" : \"a76e8d23-0c38-408c-b2a8-ea5540f01b51\", "
            + "\"visitTypeUuid\" : \"b45ca846-c79a-11e2-b0c0-8e397087571c\", "
            + "\"encounterTypeUuid\": \"2b377dba-62c3-4e53-91ef-b51c68899890\", "
            + "\"encounterDateTime\" : \"2005-01-02T00:00:00.000+0000\", "
            + "\"testOrders\":["
            + "{\"concept\":{ \"uuid\": \"d102c80f-1yz9-4da3-bb88-8122ce8868dd\"}, "
            + "\"instructions\":\"do it\", \"orderTypeUuid\": \"1a61ef2a-250c-11e3-b832-0800271c1b75\" }],"
            + "\"drugOrders\":["
            + "{\"uuid\": \"4d6fb6e0-4950-426c-9a9b-1f97e6037893\","
            + "\"concept\": {\"uuid\": \"29dc4a20-507f-40ed-9545-d47e932483fa\"},"
            + "\"notes\": \"Take as needed\","
            + "\"startDate\": \"2013-09-30T09:26:09.717Z\","
            + "\"endDate\": \"2013-10-02T09:26:09.717Z\","
            + "\"numberPerDosage\": 1,"
            + "\"dosageInstruction\": {\"uuid\": \"632aa422-2696-11e3-895c-0800271c1b75\"},"
            + "\"dosageFrequency\": {\"uuid\": \"6302096d-2696-11e3-895c-0800271c1b75\"},"
            + "\"prn\": true}"
            + "]}";

    EncounterTransaction response =
        deserialize(
            handle(newPostRequest("/rest/emrapi/encounter", json)), EncounterTransaction.class);

    Visit visit = visitService.getVisitByUuid(response.getVisitUuid());
    Encounter encounter = visit.getEncounters().iterator().next();
    assertEquals(2, encounter.getOrders().size());

    List<Order> orders = new ArrayList<Order>(encounter.getOrders());

    List<DrugOrder> drugOrders = getOrdersOfType(orders, DrugOrder.class);
    assertEquals(1, drugOrders.size());
    DrugOrder drugOrder = drugOrders.get(0);
    assertEquals("a76e8d23-0c38-408c-b2a8-ea5540f01b51", drugOrder.getPatient().getUuid());
    assertEquals("f13d6fae-baa9-4553-955d-920098bec08f", drugOrder.getEncounter().getUuid());
    assertEquals("29dc4a20-507f-40ed-9545-d47e932483fa", drugOrder.getConcept().getUuid());
    assertEquals("1a61ef2a-250c-11e3-b832-9876541c1b75", drugOrder.getOrderType().getUuid());
    assertEquals("Take as needed", drugOrder.getInstructions());
    assertEquals(new DateTime("2013-09-30T09:26:09.717Z").toDate(), drugOrder.getStartDate());
    assertEquals(new DateTime("2013-10-02T09:26:09.717Z").toDate(), drugOrder.getAutoExpireDate());
    assertEquals("6302096d-2696-11e3-895c-0800271c1b75", drugOrder.getFrequency());
    assertEquals("632aa422-2696-11e3-895c-0800271c1b75", drugOrder.getUnits());
    assertEquals("test drug", drugOrder.getDrug().getDisplayName());
    assertEquals(Double.valueOf(1), drugOrder.getDose());
    assertEquals(true, drugOrder.getPrn());

    List<TestOrder> testOrders = getOrdersOfType(orders, TestOrder.class);
    assertEquals(1, testOrders.size());
    TestOrder testOrder = testOrders.get(0);
    assertEquals("d102c80f-1yz9-4da3-bb88-8122ce8868dd", testOrder.getConcept().getUuid());
    assertEquals("a76e8d23-0c38-408c-b2a8-ea5540f01b51", testOrder.getPatient().getUuid());
    assertEquals("f13d6fae-baa9-4553-955d-920098bec08f", testOrder.getEncounter().getUuid());
    assertEquals("1a61ef2a-250c-11e3-b832-0800271c1b75", testOrder.getOrderType().getUuid());
    assertEquals("do it", testOrder.getInstructions());
  }
 private static boolean drugOrderMatchesDrugConcept(DrugOrder rc, DrugOrder doTmp) {
   if (rc.getDrug() != null
       && (doTmp.getDrug() != null
               && rc.getDrug().getConcept().equals(doTmp.getDrug().getConcept())
           || (doTmp.getConcept() != null
               && rc.getDrug().getConcept().equals(doTmp.getConcept())))) return true;
   if (doTmp.getDrug() != null
       && (rc.getDrug() != null && doTmp.getDrug().getConcept().equals(rc.getDrug().getConcept())
           || (rc.getConcept() != null && doTmp.getDrug().getConcept().equals(rc.getConcept()))))
     return true;
   if (doTmp.getConcept() != null
       && rc.getConcept() != null
       && doTmp.getConcept().equals(rc.getConcept())) return true;
   return false;
 }
  /**
   * @verifies not require all fields for a discontinuation order
   * @see DrugOrderValidator#validate(Object, org.springframework.validation.Errors)
   */
  @Test
  public void validate_shouldNotRequireAllFieldsForADiscontinuationOrder() throws Exception {
    DrugOrder orderToDiscontinue = (DrugOrder) Context.getOrderService().getOrder(111);
    assertTrue(OrderUtilTest.isActiveOrder(orderToDiscontinue, null));
    DrugOrder discontinuationOrder = new DrugOrder();
    discontinuationOrder.setDosingType(null);
    discontinuationOrder.setCareSetting(orderToDiscontinue.getCareSetting());
    discontinuationOrder.setConcept(orderToDiscontinue.getConcept());
    discontinuationOrder.setAction(Order.Action.DISCONTINUE);
    discontinuationOrder.setPreviousOrder(orderToDiscontinue);
    discontinuationOrder.setPatient(orderToDiscontinue.getPatient());
    discontinuationOrder.setDrug(orderToDiscontinue.getDrug());
    discontinuationOrder.setOrderType(orderToDiscontinue.getOrderType());
    discontinuationOrder.setOrderer(Context.getProviderService().getProvider(1));
    discontinuationOrder.setEncounter(Context.getEncounterService().getEncounter(3));

    Errors errors = new BindException(discontinuationOrder, "order");
    new DrugOrderValidator().validate(discontinuationOrder, errors);
    Assert.assertFalse(errors.hasErrors());
  }
  /**
   * @param omrsPatient
   * @param omrsPerson
   * @throws APIException
   * @throws Exception
   */
  public void processDrugOrders(Patient omrsPatient) throws APIException, Exception {
    org.openmrs.Person omrsPerson = Context.getPersonService().getPerson(omrsPatient.getPersonId());
    @SuppressWarnings("deprecation")
    List<DrugOrder> drugOrders = Context.getOrderService().getDrugOrdersByPatient(omrsPatient);
    if (drugOrders != null) {
      /*
       * Check if the drug order fulfills the combination of 3 or more
       * drugs per regimen
       */
      if (drugOrders.size() >= MIN_DRUGS_IN_A_REGIMEN) {
        // Construct the regimen from drug orders
        String regimen = "";
        Date drugStartDate = null; // Capture the regimen start date
        for (DrugOrder drugOrder : drugOrders) {
          drugStartDate = drugOrder.getStartDate();
          regimen += drugOrder.getConcept().getShortNameInLocale(Locale.ENGLISH).getName() + "/";
        }
        // Truncate the trailing "/" from the regimen string
        regimen = regimen.substring(0, regimen.length() - 1);

        // check the ARV plan
        // 1255=> ARV Plan
        Concept arvPlanConcept = Context.getConceptService().getConcept(ARV_PLAN_CONCEPT_ID);

        // 1256 => start drugs
        Concept startDrugsConcept = Context.getConceptService().getConcept(START_DRUGS_CONCEPT_ID);
        // 1259 => Change Regimen
        Concept changeRegimenConcept =
            Context.getConceptService().getConcept(CHANGE_REGIMEN_CONCEPT_ID);

        List<Obs> lastArvPlanObsList =
            Context.getObsService()
                .getObservations(
                    Collections.singletonList(omrsPerson),
                    null,
                    Collections.singletonList(arvPlanConcept),
                    null,
                    null,
                    null,
                    null,
                    1,
                    null,
                    null,
                    null,
                    false);
        if (lastArvPlanObsList != null) {
          if (lastArvPlanObsList.size() > 0) {
            AppProperties appProperties =
                new AppPropertiesLoader(new AppProperties()).getAppProperties();
            Person oecPerson = new Person();
            List<OruFiller> fillers = new ArrayList<OruFiller>();
            OruFiller oruFiller = new OruFiller();
            Obs lastArvPlanObs = lastArvPlanObsList.get(0);
            OruFillerMapper oruFillerMapper = new OruFillerMapper(lastArvPlanObs, oruFiller);
            HashSet<PersonIdentifier> patientIds =
                new PatientIdsMapper(omrsPatient).getPatientIds();
            PersonMapper personMapper = new PersonMapper(omrsPatient, oecPerson);
            personMapper.mapPatient(patientIds);
            oruFiller.setCodingSystem(
                (String) appProperties.getProperty(CODING_SYSTEM_PROPERTY_NAME));
            Boolean proceed = true;
            if (lastArvPlanObs.getValueCoded().equals(startDrugsConcept)) {
              oruFillerMapper.setEvent(Event.FIRST_LINE_REGIMEN.getValue());
              fillers.add(oruFillerMapper.getOruFiller());
              oruFillerMapper.mapObs(regimen);

            } else if (lastArvPlanObs.getValueCoded().equals(changeRegimenConcept)) {
              oruFillerMapper.setEvent(Event.SECOND_LINE_REGIMEN.getValue());
              fillers.add(oruFillerMapper.getOruFiller());
              oruFillerMapper.mapObs(regimen);
            } else {
              proceed = false;
            }
            oruFillerMapper.getOruFiller().setDateTimeOfObservation(sdf.format(drugStartDate));
            if (proceed) {
              try {
                EventsHl7Service eventsHl7Service =
                    new EventsHl7Service(personMapper.getOecPerson(), fillers, appProperties);
                eventsHl7Service.doWork(Triggers.R01.getValue());
              } catch (Exception ex) {
                log.debug(ex);
                System.out.println("Unable to send HL7 message: " + ex.getMessage());
              }
            }
          }
        }
      }
    }
  }