/** @see {@link DrugOrderValidator#validate(Object,Errors)} */
  @Test
  @Verifies(
      value = "should pass validation if all fields are correct",
      method = "validate(Object,Errors)")
  public void validate_shouldPassValidationIfAllFieldsAreCorrect() throws Exception {
    DrugOrder order = new DrugOrder();
    Encounter encounter = new Encounter();
    Patient patient = Context.getPatientService().getPatient(2);
    order.setConcept(Context.getConceptService().getConcept(88));
    order.setOrderer(Context.getProviderService().getProvider(1));
    order.setDosingType(DrugOrder.DosingType.FREE_TEXT);
    order.setInstructions("Instructions");
    order.setDosingInstructions("Test Instruction");
    order.setPatient(patient);
    encounter.setPatient(patient);
    order.setEncounter(encounter);
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH) - 1);
    order.setStartDate(cal.getTime());
    order.setAutoExpireDate(new Date());
    order.setOrderType(Context.getOrderService().getOrderTypeByName("Drug order"));
    order.setDrug(Context.getConceptService().getDrug(3));
    order.setCareSetting(Context.getOrderService().getCareSetting(1));
    order.setQuantity(2.00);
    order.setQuantityUnits(Context.getConceptService().getConcept(51));
    order.setNumRefills(10);

    Errors errors = new BindException(order, "order");
    new DrugOrderValidator().validate(order, errors);
    Assert.assertFalse(errors.hasErrors());
  }
 /**
  * Discontinues an order given a date and a reason, and saves it to the database if anything has
  * changed.
  *
  * @param order
  * @param effectiveDate
  * @param reason
  * @should change discontinued metadata if order is set to be discontinued after date
  * @should have no effect if order is discontinued before date
  */
 public static void discontinueOrder(Order order, Date date, Concept reason) {
   if (!order.isDiscontinuedRightNow()) {
     order.setDiscontinued(true);
     order.setDiscontinuedDate(date);
     order.setDiscontinuedReason(reason);
     Context.getOrderService().saveOrder(order);
   } else if (OpenmrsUtil.compareWithNullAsLatest(date, order.getDiscontinuedDate()) < 0) {
     order.setDiscontinued(true); // should already be true
     order.setDiscontinuedDate(date);
     order.setDiscontinuedReason(reason);
     Context.getOrderService().saveOrder(order);
   }
 }
  /** @see org.openmrs.api.EncounterService#purgeEncounter(Encounter, boolean) */
  public void purgeEncounter(Encounter encounter, boolean cascade) throws APIException {

    // if authenticated user is not supposed to edit encounter of certain type
    if (!canEditEncounter(encounter, null)) {
      throw new APIException(
          "Encounter.error.privilege.required.purge",
          new Object[] {encounter.getEncounterType().getEditPrivilege()});
    }

    if (cascade) {
      ObsService obsService = Context.getObsService();
      List<Encounter> justThisEncounter = new ArrayList<Encounter>();
      justThisEncounter.add(encounter);
      List<Obs> observations = new Vector<Obs>();
      observations.addAll(
          obsService.getObservations(
              null, justThisEncounter, null, null, null, null, null, null, null, null, null, true));
      for (Obs o : observations) {
        obsService.purgeObs(o);
      }
      Set<Order> orders = encounter.getOrders();
      for (Order o : orders) {
        Context.getOrderService().purgeOrder(o);
      }
    }
    Context.getEncounterService().purgeEncounter(encounter);
  }
  /** @see {@link OrderValidator#validate(Object,Errors)} */
  @Test
  @Verifies(
      value = "should pass validation if all fields are correct",
      method = "validate(Object,Errors)")
  public void validate_shouldPassValidationIfAllFieldsAreCorrect() throws Exception {
    Order order = new DrugOrder();
    Encounter encounter = new Encounter();
    order.setConcept(Context.getConceptService().getConcept(88));
    order.setOrderer(Context.getProviderService().getProvider(1));
    Patient patient = Context.getPatientService().getPatient(2);
    encounter.setPatient(patient);
    order.setPatient(patient);
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH) - 1);
    order.setDateActivated(cal.getTime());
    order.setAutoExpireDate(new Date());
    order.setCareSetting(new CareSetting());
    order.setEncounter(encounter);
    order.setUrgency(Order.Urgency.ROUTINE);
    order.setAction(Order.Action.NEW);
    order.setOrderType(Context.getOrderService().getOrderTypeByName("Drug order"));

    Errors errors = new BindException(order, "order");
    new OrderValidator().validate(order, errors);

    Assert.assertFalse(errors.hasErrors());
  }
 /**
  * @see
  *     org.openmrs.module.webservices.rest.web.resource.impl.BaseDelegatingResource#purge(java.lang.Object,
  *     org.openmrs.module.webservices.rest.web.RequestContext)
  */
 @Override
 public void purge(OrderType delegate, RequestContext context) throws ResponseException {
   if (delegate.getOrderTypeId().equals(OpenmrsConstants.ORDERTYPE_DRUG)) {
     throw new IllegalArgumentException("You are not allowed to delete the Drug ordertype");
   }
   Context.getOrderService().purgeOrderType(delegate);
 }
  /** @see org.openmrs.api.EncounterService#unvoidEncounter(org.openmrs.Encounter) */
  public Encounter unvoidEncounter(Encounter encounter) throws APIException {

    // if authenticated user is not supposed to edit encounter of certain type
    if (!canEditEncounter(encounter, null)) {
      throw new APIException(
          "Encounter.error.privilege.required.unvoid",
          new Object[] {encounter.getEncounterType().getEditPrivilege()});
    }

    String voidReason = encounter.getVoidReason();
    if (voidReason == null) {
      voidReason = "";
    }

    ObsService os = Context.getObsService();
    for (Obs o : encounter.getObsAtTopLevel(true)) {
      if (voidReason.equals(o.getVoidReason())) {
        os.unvoidObs(o);
      }
    }

    OrderService orderService = Context.getOrderService();
    for (Order o : encounter.getOrders()) {
      if (voidReason.equals(o.getVoidReason())) {
        orderService.unvoidOrder(o);
      }
    }

    encounter.setVoided(false);
    encounter.setVoidedBy(null);
    encounter.setDateVoided(null);
    encounter.setVoidReason(null);
    Context.getEncounterService().saveEncounter(encounter);
    return encounter;
  }
  /**
   * @verifies fail validation if numberOfRefills is null for outpatient careSetting
   * @see DrugOrderValidator#validate(Object, org.springframework.validation.Errors)
   */
  @Test
  public void validate_shouldFailValidationIfNumberOfRefillsIsNullForOutpatientCareSetting()
      throws Exception {
    DrugOrder OutpatientOrder = new DrugOrder();
    OutpatientOrder.setCareSetting(Context.getOrderService().getCareSetting(1));
    OutpatientOrder.setNumRefills(null);
    Errors OutpatientOrderErrors = new BindException(OutpatientOrder, "order");
    new DrugOrderValidator().validate(OutpatientOrder, OutpatientOrderErrors);
    Assert.assertTrue(OutpatientOrderErrors.hasFieldErrors("numRefills"));

    DrugOrder inPatientOrder = new DrugOrder();
    inPatientOrder.setCareSetting(Context.getOrderService().getCareSetting(2));
    inPatientOrder.setNumRefills(null);
    Errors InpatientOrderErrors = new BindException(inPatientOrder, "order");
    new DrugOrderValidator().validate(inPatientOrder, InpatientOrderErrors);
    Assert.assertFalse(InpatientOrderErrors.hasFieldErrors("numRefills"));
  }
  @Test
  @Verifies(
      value = "should return encounter with all child objects voided according to schema",
      method = "voidEncounterByHtmlFormSchema")
  public void testVoidEncounterByHtmlFormSchema_shouldHandleDrugOrderCorrectly() throws Exception {
    executeDataSet(
        XML_DATASET_PATH + new TestUtil().getTestDatasetFilename(XML_REGRESSION_TEST_DATASET));
    Encounter e = new Encounter();
    e.setPatient(Context.getPatientService().getPatient(2));
    Date date = Context.getDateFormat().parse("01/02/2003");
    e.setDateCreated(new Date());
    e.setEncounterDatetime(date);
    e.setLocation(Context.getLocationService().getLocation(2));
    e.setProvider(Context.getPersonService().getPerson(502));
    TestUtil.addObs(e, 1, 5000, date); // a matching obs

    DrugOrder dor = new DrugOrder();
    dor.setVoided(false);
    dor.setConcept(Context.getConceptService().getConcept(792));
    dor.setCreator(Context.getUserService().getUser(1));
    dor.setDateCreated(new Date());
    dor.setDiscontinued(false);
    dor.setDrug(Context.getConceptService().getDrug(2));
    dor.setOrderType(Context.getOrderService().getOrderType(1));
    dor.setPatient(Context.getPatientService().getPatient(2));
    dor.setStartDate(new Date());
    e.addOrder(dor);

    Context.getEncounterService().saveEncounter(e);

    Form form = new Form();
    HtmlForm htmlform = new HtmlForm();
    htmlform.setForm(form);
    form.setEncounterType(new EncounterType());
    htmlform.setDateChanged(new Date());
    htmlform.setXmlData(
        new TestUtil()
            .loadXmlFromFile(
                XML_DATASET_PATH + "returnSectionsAndConceptsInSectionsTestFormWithGroups.xml"));

    HtmlFormEntryUtil.voidEncounterByHtmlFormSchema(e, htmlform, "test void reason");

    // this is going to test out the voided state of the obs in the encounter after processing:
    // order was matched, so order was voided, and because that's the only thing in the encounter,
    // encounter was voided too.
    Assert.assertTrue(e.isVoided());
    Assert.assertTrue(e.getVoidReason().equals("test void reason"));
    for (Order o : e.getOrders()) {
      Assert.assertTrue(o.isVoided());
      Assert.assertTrue(o.getVoidReason().equals("test void reason"));
    }
    for (Obs o : e.getAllObs(true)) {
      Assert.assertTrue(o.getVoidReason().equals("test void reason"));
    }
  }
  @Test
  @Verifies(value = "should delete encounter correctly", method = "voidEncounterByHtmlFormSchema")
  public void testVoidEncounterByHtmlFormSchema_shouldDeleteEncounter() throws Exception {
    executeDataSet(
        XML_DATASET_PATH + new TestUtil().getTestDatasetFilename(XML_REGRESSION_TEST_DATASET));
    Encounter e = new Encounter();
    e.setPatient(Context.getPatientService().getPatient(2));
    Date date = Context.getDateFormat().parse("01/02/2003");
    e.setDateCreated(new Date());
    e.setEncounterDatetime(date);
    e.setLocation(Context.getLocationService().getLocation(2));
    e.setProvider(Context.getPersonService().getPerson(502));
    TestUtil.addObs(e, 3, 5000, date); // adding an un-matched, voided Obs
    for (Obs o : e.getAllObs(true)) {
      o.setVoided(true);
      o.setVoidedBy(Context.getUserService().getUser(1));
      o.setVoidReason("blah");
      o.setDateVoided(new Date());
    }

    // and adding a voided drug order
    DrugOrder dor = new DrugOrder();
    dor.setVoided(false);
    dor.setConcept(Context.getConceptService().getConcept(792));
    dor.setCreator(Context.getUserService().getUser(1));
    dor.setDateCreated(new Date());
    dor.setDiscontinued(false);
    dor.setDrug(Context.getConceptService().getDrug(2));
    dor.setOrderType(Context.getOrderService().getOrderType(1));
    dor.setPatient(Context.getPatientService().getPatient(2));
    dor.setVoided(true);
    dor.setVoidedBy(Context.getUserService().getUser(1));
    dor.setVoidReason("blah");
    dor.setDateVoided(new Date());
    dor.setStartDate(new Date());
    e.addOrder(dor);

    Context.getEncounterService().saveEncounter(e);

    Form form = new Form();
    HtmlForm htmlform = new HtmlForm();
    htmlform.setForm(form);
    form.setEncounterType(new EncounterType());
    htmlform.setDateChanged(new Date());
    htmlform.setXmlData(
        new TestUtil()
            .loadXmlFromFile(
                XML_DATASET_PATH + "returnSectionsAndConceptsInSectionsTestFormWithGroups.xml"));

    HtmlFormEntryUtil.voidEncounterByHtmlFormSchema(e, htmlform, null);

    // encounter had no non-voided objects, should be voided
    Assert.assertTrue(e.isVoided());
  }
Пример #10
0
 static Obs orderUuidToObs(
     String orderUuid, Patient patient, Date encounterTime, Location location) {
   Order order = Context.getOrderService().getOrderByUuid(orderUuid);
   if (order == null) {
     log.warn("Order not found: " + orderUuid);
     return null;
   }
   Obs obs = new Obs(patient, DbUtil.getOrderExecutedConcept(), encounterTime, location);
   obs.setOrder(order);
   obs.setValueNumeric(1d);
   return obs;
 }
  @Test
  @Verifies(
      value = "should return encounter with all child objects voided according to schema",
      method = "voidEncounterByHtmlFormSchema")
  public void testVoidEncounterByHtmlFormSchema_shouldHandleDrugOrderAndObsCorrectly()
      throws Exception {
    executeDataSet(
        XML_DATASET_PATH + new TestUtil().getTestDatasetFilename(XML_REGRESSION_TEST_DATASET));
    Encounter e = new Encounter();
    e.setPatient(Context.getPatientService().getPatient(2));
    Date date = Context.getDateFormat().parse("01/02/2003");
    e.setDateCreated(new Date());
    e.setEncounterDatetime(date);
    e.setLocation(Context.getLocationService().getLocation(2));
    e.setProvider(Context.getPersonService().getPerson(502));
    TestUtil.addObs(e, 3, 5000, date); // adding an un-matched Obs

    DrugOrder dor = new DrugOrder();
    dor.setVoided(false);
    dor.setConcept(Context.getConceptService().getConcept(792));
    dor.setCreator(Context.getUserService().getUser(1));
    dor.setDateCreated(new Date());
    dor.setDiscontinued(false);
    dor.setDrug(Context.getConceptService().getDrug(2));
    dor.setOrderType(Context.getOrderService().getOrderType(1));
    dor.setPatient(Context.getPatientService().getPatient(2));
    dor.setStartDate(new Date());
    e.addOrder(dor);

    Context.getEncounterService().saveEncounter(e);

    Form form = new Form();
    HtmlForm htmlform = new HtmlForm();
    htmlform.setForm(form);
    form.setEncounterType(new EncounterType());
    htmlform.setDateChanged(new Date());
    htmlform.setXmlData(
        new TestUtil()
            .loadXmlFromFile(
                XML_DATASET_PATH + "returnSectionsAndConceptsInSectionsTestFormWithGroups.xml"));

    HtmlFormEntryUtil.voidEncounterByHtmlFormSchema(e, htmlform, null);

    // order was matched, obs was not, so order should be voided, obs not, encounter not.
    Assert.assertTrue(!e.isVoided());
    for (Order o : e.getOrders()) {
      Assert.assertTrue(o.isVoided());
    }
    for (Obs o : e.getObs()) {
      Assert.assertTrue(!o.isVoided());
    }
  }
  /**
   * @verifies pass validation if the class of the order is a subclass of orderType.javaClass
   * @see OrderValidator#validate(Object, org.springframework.validation.Errors)
   */
  @Test
  public void validate_shouldPassValidationIfTheClassOfTheOrderIsASubclassOfOrderTypejavaClass()
      throws Exception {
    SomeDrugOrder order = new SomeDrugOrder();
    order.setConcept(Context.getConceptService().getConcept(88));
    order.setPatient(Context.getPatientService().getPatient(2));
    order.setOrderer(Context.getProviderService().getProvider(1));
    order.setOrderType(Context.getOrderService().getOrderTypeByName("Drug order"));

    Errors errors = new BindException(order, "order");
    new OrderValidator().validate(order, errors);
    Assert.assertFalse(errors.hasFieldErrors("orderType"));
  }
  /**
   * @verifies fail validation if orderType.javaClass does not match order.class
   * @see OrderValidator#validate(Object, org.springframework.validation.Errors)
   */
  @Test
  public void validate_shouldFailValidationIfOrderTypejavaClassDoesNotMatchOrderclass()
      throws Exception {
    Order order = new DrugOrder();
    order.setConcept(Context.getConceptService().getConcept(88));
    order.setPatient(Context.getPatientService().getPatient(2));
    order.setOrderer(Context.getProviderService().getProvider(1));
    order.setOrderType(Context.getOrderService().getOrderTypeByName("Test order"));

    Errors errors = new BindException(order, "order");
    new OrderValidator().validate(order, errors);
    Assert.assertTrue(errors.hasFieldErrors("orderType"));
    Assert.assertTrue(
        Arrays.asList(errors.getFieldError("orderType").getCodes())
            .contains("Order.error.orderTypeClassMismatchesOrderClass"));
  }
  public PatientDataResult evaluate(RowPerPatientData patientData, EvaluationContext context) {

    DateResult par = new DateResult(patientData, context);
    DateOfFirstDrugOrderStartedRestrictedByConceptSet pd =
        (DateOfFirstDrugOrderStartedRestrictedByConceptSet) patientData;

    par.setFormat(pd.getDateFormat());

    List<DrugOrder> orders = Context.getOrderService().getDrugOrdersByPatient(pd.getPatient());

    if (orders != null) {
      if (pd.getDrugConceptSetConcept() != null) {
        List<Concept> drugConcepts =
            Context.getConceptService().getConceptsByConceptSet(pd.getDrugConceptSetConcept());
        if (drugConcepts != null) {
          DrugOrder startDrugOrder = null;
          for (DrugOrder order : orders) {
            Concept drug = null;
            try {
              drug = order.getDrug().getConcept();
            } catch (Exception e) {
              log.error("Unable to retrieve a drug from the drug order: " + e.getMessage());
            }
            if (drug != null) {
              if (drugConcepts.contains(drug)) {
                if (order.getStartDate() != null
                    && (pd.getStartDate() == null
                        || OpenmrsUtil.compare(order.getStartDate(), pd.getStartDate()) >= 0)
                    && (pd.getEndDate() == null
                        || OpenmrsUtil.compare(order.getStartDate(), pd.getEndDate()) <= 0)) {
                  if (startDrugOrder == null
                      || order.getStartDate().before(startDrugOrder.getStartDate())) {
                    startDrugOrder = order;
                  }
                }
              }
            }
          }
          if (startDrugOrder != null) {
            par.setValue(startDrugOrder.getStartDate());
          }
        }
      }
    }

    return par;
  }
  /**
   * @see DrugOrderValidator#validate(Object,Errors)
   * @verifies fail validation if doseUnits is not a dose unit concept
   */
  @Test
  public void validate_shouldFailValidationIfDoseUnitsIsNotADoseUnitConcept() throws Exception {
    Concept concept = Context.getConceptService().getConcept(3);
    assertThat(concept, not(isIn(Context.getOrderService().getDrugDosingUnits())));

    DrugOrder order = new DrugOrder();
    order.setDosingType(DrugOrder.DosingType.FREE_TEXT);
    order.setDuration(5.0);
    order.setDurationUnits(concept);
    order.setDose(1.0);
    order.setDoseUnits(concept);
    order.setQuantity(30.0);
    order.setQuantityUnits(concept);

    Errors errors = new BindException(order, "order");
    new DrugOrderValidator().validate(order, errors);
    Assert.assertTrue(errors.hasFieldErrors("doseUnits"));
  }
Пример #16
0
  /**
   * @see org.openmrs.api.EncounterService#voidEncounter(org.openmrs.Encounter, java.lang.String)
   */
  public Encounter voidEncounter(Encounter encounter, String reason) {

    // if authenticated user is not supposed to edit encounter of certain type
    if (!canEditEncounter(encounter, null)) {
      throw new APIException(
          String.format(
              "Privilege %s required to void encounters of this type",
              encounter.getEncounterType().getEditPrivilege()));
    }

    if (reason == null) {
      throw new IllegalArgumentException("The argument 'reason' is required and so cannot be null");
    }

    ObsService os = Context.getObsService();
    for (Obs o : encounter.getObsAtTopLevel(false)) {
      if (!o.isVoided()) {
        os.voidObs(o, reason);
      }
    }

    OrderService orderService = Context.getOrderService();
    for (Order o : encounter.getOrders()) {
      if (!o.isVoided()) {
        orderService.voidOrder(o, reason);
      }
    }

    encounter.setVoided(true);
    encounter.setVoidedBy(Context.getAuthenticatedUser());
    // we expect the dateVoided to be already set by AOP logic at this point unless this method was
    // called within the API,
    // this ensures that original ParentVoidedDate and the dateVoided of associated objects will
    // always match for the
    // unvoid handler to work
    if (encounter.getDateVoided() == null) {
      encounter.setDateVoided(new Date());
    }
    encounter.setVoidReason(reason);
    Context.getEncounterService().saveEncounter(encounter);
    return encounter;
  }
  /**
   * @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());
  }
  /**
   * @verifies fail if route is not a valid concept
   * @see DrugOrderValidator#validate(Object, org.springframework.validation.Errors)
   */
  @Test
  public void validate_shouldFailIfRouteIsNotAValidConcept() throws Exception {
    Concept concept = Context.getConceptService().getConcept(3);
    assertThat(concept, not(isIn(Context.getOrderService().getDrugRoutes())));

    DrugOrder order = new DrugOrder();
    order.setDosingType(DrugOrder.DosingType.FREE_TEXT);
    order.setDuration(5.0);
    order.setDurationUnits(concept);
    order.setDose(1.0);
    order.setDoseUnits(concept);
    order.setQuantity(30.0);
    order.setQuantityUnits(concept);
    order.setRoute(concept);

    Errors errors = new BindException(order, "order");
    new DrugOrderValidator().validate(order, errors);
    Assert.assertTrue(errors.hasFieldErrors("route"));
    Assert.assertEquals(
        "DrugOrder.error.routeNotAmongAllowedConcepts", errors.getFieldError("route").getCode());
  }
 /**
  * @see
  *     org.openmrs.module.webservices.rest.web.resource.impl.BaseDelegatingResource#getByUniqueId(java.lang.String)
  */
 @Override
 public OrderType getByUniqueId(String uniqueId) {
   return Context.getOrderService().getOrderTypeByUuid(uniqueId);
 }
 /**
  * @see
  *     org.openmrs.module.webservices.rest.web.resource.impl.DelegatingResourceHandler#save(java.lang.Object)
  */
 @Override
 public OrderType save(OrderType delegate) {
   return Context.getOrderService().saveOrderType(delegate);
 }
Пример #21
0
  /**
   * This method produces a model containing the following mappings:
   *
   * <pre>
   *     (always)
   *          (java.util.Date) now
   *          (String) size
   *          (Locale) locale
   *          (String) portletUUID // unique for each instance of any portlet
   *          (other parameters)
   *     (if there's currently an authenticated user)
   *          (User) authenticatedUser
   *     (if the request has a patientId attribute)
   *          (Integer) patientId
   *          (Patient) patient
   *          (List<Obs>) patientObs
   *          (List<Encounter>) patientEncounters
   *          (List<DrugOrder>) patientDrugOrders
   *          (List<DrugOrder>) currentDrugOrders
   *          (List<DrugOrder>) completedDrugOrders
   *          (Obs) patientWeight // most recent weight obs
   *          (Obs) patientHeight // most recent height obs
   *          (Double) patientBmi // BMI derived from most recent weight and most recent height
   *          (String) patientBmiAsString // BMI rounded to one decimal place, or "?" if unknown
   *          (Integer) personId
   *          (if the patient has any obs for the concept in the global property 'concept.reasonExitedCare')
   *              (Obs) patientReasonForExit
   *     (if the request has a personId or patientId attribute)
   *          (Person) person
   *          (List<Relationship>) personRelationships
   *          (Map<RelationshipType, List<Relationship>>) personRelationshipsByType
   *     (if the request has an encounterId attribute)
   *          (Integer) encounterId
   *          (Encounter) encounter
   *          (Set<Obs>) encounterObs
   *     (if the request has a userId attribute)
   *          (Integer) userId
   *          (User) user
   *     (if the request has a patientIds attribute, which should be a (String) comma-separated list of patientIds)
   *          (PatientSet) patientSet
   *          (String) patientIds
   *     (if the request has a conceptIds attribute, which should be a (String) commas-separated list of conceptIds)
   *          (Map<Integer, Concept>) conceptMap
   *          (Map<String, Concept>) conceptMapByStringIds
   * </pre>
   *
   * @should calculate bmi into patientBmiAsString
   * @should not fail with empty height and weight properties
   */
  @SuppressWarnings("unchecked")
  public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    AdministrationService as = Context.getAdministrationService();
    ConceptService cs = Context.getConceptService();

    // find the portlet that was identified in the openmrs:portlet taglib
    Object uri = request.getAttribute("javax.servlet.include.servlet_path");
    String portletPath = "";
    Map<String, Object> model = null;
    {
      HttpSession session = request.getSession();
      String uniqueRequestId = (String) request.getAttribute(WebConstants.INIT_REQ_UNIQUE_ID);
      String lastRequestId =
          (String) session.getAttribute(WebConstants.OPENMRS_PORTLET_LAST_REQ_ID);
      if (uniqueRequestId.equals(lastRequestId)) {
        model =
            (Map<String, Object>) session.getAttribute(WebConstants.OPENMRS_PORTLET_CACHED_MODEL);

        // remove cached parameters
        List<String> parameterKeys = (List<String>) model.get("parameterKeys");
        for (String key : parameterKeys) {
          model.remove(key);
        }
      }
      if (model == null) {
        log.debug("creating new portlet model");
        model = new HashMap<String, Object>();
        session.setAttribute(WebConstants.OPENMRS_PORTLET_LAST_REQ_ID, uniqueRequestId);
        session.setAttribute(WebConstants.OPENMRS_PORTLET_CACHED_MODEL, model);
      }
    }

    if (uri != null) {
      long timeAtStart = System.currentTimeMillis();
      portletPath = uri.toString();

      // Allowable extensions are '' (no extension) and '.portlet'
      if (portletPath.endsWith("portlet")) portletPath = portletPath.replace(".portlet", "");
      else if (portletPath.endsWith("jsp"))
        throw new ServletException(
            "Illegal extension used for portlet: '.jsp'. Allowable extensions are '' (no extension) and '.portlet'");

      log.debug("Loading portlet: " + portletPath);

      String id = (String) request.getAttribute("org.openmrs.portlet.id");
      String size = (String) request.getAttribute("org.openmrs.portlet.size");
      Map<String, Object> params =
          (Map<String, Object>) request.getAttribute("org.openmrs.portlet.parameters");
      Map<String, Object> moreParams =
          (Map<String, Object>) request.getAttribute("org.openmrs.portlet.parameterMap");

      model.put("now", new Date());
      model.put("id", id);
      model.put("size", size);
      model.put("locale", Context.getLocale());
      model.put("portletUUID", UUID.randomUUID().toString().replace("-", ""));
      List<String> parameterKeys = new ArrayList<String>(params.keySet());
      model.putAll(params);
      if (moreParams != null) {
        model.putAll(moreParams);
        parameterKeys.addAll(moreParams.keySet());
      }
      model.put("parameterKeys", parameterKeys); // so we can clean these up in the next request

      // if there's an authenticated user, put them, and their patient set, in the model
      if (Context.getAuthenticatedUser() != null) {
        model.put("authenticatedUser", Context.getAuthenticatedUser());
      }

      Integer personId = null;

      // if a patient id is available, put patient data documented above in the model
      Object o = request.getAttribute("org.openmrs.portlet.patientId");
      if (o != null) {
        String patientVariation = "";
        Integer patientId = (Integer) o;
        if (!model.containsKey("patient")) {
          // we can't continue if the user can't view patients
          if (Context.hasPrivilege(PrivilegeConstants.VIEW_PATIENTS)) {
            Patient p = Context.getPatientService().getPatient(patientId);
            model.put("patient", p);

            // add encounters if this user can view them
            if (Context.hasPrivilege(PrivilegeConstants.VIEW_ENCOUNTERS))
              model.put(
                  "patientEncounters", Context.getEncounterService().getEncountersByPatient(p));

            if (Context.hasPrivilege(PrivilegeConstants.VIEW_OBS)) {
              List<Obs> patientObs = Context.getObsService().getObservationsByPerson(p);
              model.put("patientObs", patientObs);
              Obs latestWeight = null;
              Obs latestHeight = null;
              String bmiAsString = "?";
              try {
                String weightString = as.getGlobalProperty("concept.weight");
                ConceptNumeric weightConcept = null;
                if (StringUtils.hasLength(weightString))
                  weightConcept =
                      cs.getConceptNumeric(
                          cs.getConcept(Integer.valueOf(weightString)).getConceptId());
                String heightString = as.getGlobalProperty("concept.height");
                ConceptNumeric heightConcept = null;
                if (StringUtils.hasLength(heightString))
                  heightConcept =
                      cs.getConceptNumeric(
                          cs.getConcept(Integer.valueOf(heightString)).getConceptId());
                for (Obs obs : patientObs) {
                  if (obs.getConcept().equals(weightConcept)) {
                    if (latestWeight == null
                        || obs.getObsDatetime().compareTo(latestWeight.getObsDatetime()) > 0)
                      latestWeight = obs;
                  } else if (obs.getConcept().equals(heightConcept)) {
                    if (latestHeight == null
                        || obs.getObsDatetime().compareTo(latestHeight.getObsDatetime()) > 0)
                      latestHeight = obs;
                  }
                }
                if (latestWeight != null) model.put("patientWeight", latestWeight);
                if (latestHeight != null) model.put("patientHeight", latestHeight);
                if (latestWeight != null && latestHeight != null) {
                  double weightInKg;
                  double heightInM;
                  if (weightConcept.getUnits().equals("kg"))
                    weightInKg = latestWeight.getValueNumeric();
                  else if (weightConcept.getUnits().equals("lb"))
                    weightInKg = latestWeight.getValueNumeric() * 0.45359237;
                  else
                    throw new IllegalArgumentException(
                        "Can't handle units of weight concept: " + weightConcept.getUnits());
                  if (heightConcept.getUnits().equals("cm"))
                    heightInM = latestHeight.getValueNumeric() / 100;
                  else if (heightConcept.getUnits().equals("m"))
                    heightInM = latestHeight.getValueNumeric();
                  else if (heightConcept.getUnits().equals("in"))
                    heightInM = latestHeight.getValueNumeric() * 0.0254;
                  else
                    throw new IllegalArgumentException(
                        "Can't handle units of height concept: " + heightConcept.getUnits());
                  double bmi = weightInKg / (heightInM * heightInM);
                  model.put("patientBmi", bmi);
                  String temp = "" + bmi;
                  bmiAsString = temp.substring(0, temp.indexOf('.') + 2);
                }
              } catch (Exception ex) {
                if (latestWeight != null && latestHeight != null)
                  log.error(
                      "Failed to calculate BMI even though a weight and height were found", ex);
              }
              model.put("patientBmiAsString", bmiAsString);
            } else {
              model.put("patientObs", new HashSet<Obs>());
            }

            // information about whether or not the patient has exited care
            Obs reasonForExitObs = null;
            String reasonForExitConceptString = as.getGlobalProperty("concept.reasonExitedCare");
            if (StringUtils.hasLength(reasonForExitConceptString)) {
              Concept reasonForExitConcept = cs.getConcept(reasonForExitConceptString);
              if (reasonForExitConcept != null) {
                List<Obs> patientExitObs =
                    Context.getObsService()
                        .getObservationsByPersonAndConcept(p, reasonForExitConcept);
                if (patientExitObs != null) {
                  log.debug("Exit obs is size " + patientExitObs.size());
                  if (patientExitObs.size() == 1) {
                    reasonForExitObs = patientExitObs.iterator().next();
                    Concept exitReason = reasonForExitObs.getValueCoded();
                    Date exitDate = reasonForExitObs.getObsDatetime();
                    if (exitReason != null && exitDate != null) {
                      patientVariation = "Exited";
                    }
                  } else {
                    if (patientExitObs.size() == 0) {
                      log.debug("Patient has no reason for exit");
                    } else {
                      log.error("Too many reasons for exit - not putting data into model");
                    }
                  }
                }
              }
            }
            model.put("patientReasonForExit", reasonForExitObs);

            if (Context.hasPrivilege(PrivilegeConstants.VIEW_ORDERS)) {
              List<DrugOrder> drugOrderList = Context.getOrderService().getDrugOrdersByPatient(p);
              model.put("patientDrugOrders", drugOrderList);
              List<DrugOrder> currentDrugOrders = new ArrayList<DrugOrder>();
              List<DrugOrder> discontinuedDrugOrders = new ArrayList<DrugOrder>();
              Date rightNow = new Date();
              for (Iterator<DrugOrder> iter = drugOrderList.iterator(); iter.hasNext(); ) {
                DrugOrder next = iter.next();
                if (next.isCurrent() || next.isFuture()) currentDrugOrders.add(next);
                if (next.isDiscontinued(rightNow)) discontinuedDrugOrders.add(next);
              }
              model.put("currentDrugOrders", currentDrugOrders);
              model.put("completedDrugOrders", discontinuedDrugOrders);

              List<RegimenSuggestion> standardRegimens =
                  Context.getOrderService().getStandardRegimens();
              if (standardRegimens != null) model.put("standardRegimens", standardRegimens);
            }

            if (Context.hasPrivilege(PrivilegeConstants.VIEW_PROGRAMS)
                && Context.hasPrivilege(PrivilegeConstants.VIEW_PATIENT_PROGRAMS)) {
              model.put(
                  "patientPrograms",
                  Context.getProgramWorkflowService()
                      .getPatientPrograms(p, null, null, null, null, null, false));
              model.put(
                  "patientCurrentPrograms",
                  Context.getProgramWorkflowService()
                      .getPatientPrograms(p, null, null, new Date(), new Date(), null, false));
            }

            model.put("patientId", patientId);
            if (p != null) {
              personId = p.getPatientId();
              model.put("personId", personId);
            }

            model.put("patientVariation", patientVariation);
          }
        }
      }

      // if a person id is available, put person and relationships in the model
      if (personId == null) {
        o = request.getAttribute("org.openmrs.portlet.personId");
        if (o != null) {
          personId = (Integer) o;
          model.put("personId", personId);
        }
      }
      if (personId != null) {
        if (!model.containsKey("person")) {
          Person p = (Person) model.get("patient");
          if (p == null) p = Context.getPersonService().getPerson(personId);
          model.put("person", p);

          if (Context.hasPrivilege(PrivilegeConstants.VIEW_RELATIONSHIPS)) {
            List<Relationship> relationships = new ArrayList<Relationship>();
            relationships.addAll(Context.getPersonService().getRelationshipsByPerson(p));
            Map<RelationshipType, List<Relationship>> relationshipsByType =
                new HashMap<RelationshipType, List<Relationship>>();
            for (Relationship rel : relationships) {
              List<Relationship> list = relationshipsByType.get(rel.getRelationshipType());
              if (list == null) {
                list = new ArrayList<Relationship>();
                relationshipsByType.put(rel.getRelationshipType(), list);
              }
              list.add(rel);
            }

            model.put("personRelationships", relationships);
            model.put("personRelationshipsByType", relationshipsByType);
          }
        }
      }

      // if an encounter id is available, put "encounter" and "encounterObs" in the model
      o = request.getAttribute("org.openmrs.portlet.encounterId");
      if (o != null && !model.containsKey("encounterId")) {
        if (!model.containsKey("encounter")) {
          if (Context.hasPrivilege(PrivilegeConstants.VIEW_ENCOUNTERS)) {
            Encounter e = Context.getEncounterService().getEncounter((Integer) o);
            model.put("encounter", e);
            if (Context.hasPrivilege(PrivilegeConstants.VIEW_OBS))
              model.put("encounterObs", e.getObs());
          }
          model.put("encounterId", (Integer) o);
        }
      }

      // if a user id is available, put "user" in the model
      o = request.getAttribute("org.openmrs.portlet.userId");
      if (o != null) {
        if (!model.containsKey("user")) {
          if (Context.hasPrivilege(PrivilegeConstants.VIEW_USERS)) {
            User u = Context.getUserService().getUser((Integer) o);
            model.put("user", u);
          }
          model.put("userId", (Integer) o);
        }
      }

      // if a list of patient ids is available, make a patientset out of it
      o = request.getAttribute("org.openmrs.portlet.patientIds");
      if (o != null && !"".equals(o) && !model.containsKey("patientIds")) {
        if (!model.containsKey("patientSet")) {
          Cohort ps = new Cohort((String) o);
          model.put("patientSet", ps);
          model.put("patientIds", (String) o);
        }
      }

      o = model.get("conceptIds");
      if (o != null && !"".equals(o)) {
        if (!model.containsKey("conceptMap")) {
          log.debug("Found conceptIds parameter: " + o);
          Map<Integer, Concept> concepts = new HashMap<Integer, Concept>();
          Map<String, Concept> conceptsByStringIds = new HashMap<String, Concept>();
          String conceptIds = (String) o;
          String[] ids = conceptIds.split(",");
          for (String cId : ids) {
            try {
              Integer i = Integer.valueOf(cId);
              Concept c = cs.getConcept(i);
              concepts.put(i, c);
              conceptsByStringIds.put(i.toString(), c);
            } catch (Exception ex) {
            }
          }
          model.put("conceptMap", concepts);
          model.put("conceptMapByStringIds", conceptsByStringIds);
        }
      }

      populateModel(request, model);
      log.debug(portletPath + " took " + (System.currentTimeMillis() - timeAtStart) + " ms");
    }

    return new ModelAndView(portletPath, "model", model);
  }
 @Before
 public void setup() {
   orderService = Context.getOrderService();
 }
  /**
   * @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());
              }
            }
          }
        }
      }
    }
  }
  /** @see org.openmrs.api.EncounterService#saveEncounter(org.openmrs.Encounter) */
  public Encounter saveEncounter(Encounter encounter) throws APIException {

    // if authenticated user is not supposed to edit encounter of certain type
    if (!canEditEncounter(encounter, null)) {
      throw new APIException(
          "Encounter.error.privilege.required.edit",
          new Object[] {encounter.getEncounterType().getEditPrivilege()});
    }

    // If new encounter, try to assign a visit using the registered visit assignment handler.
    if (encounter.getEncounterId() == null) {

      // Am using Context.getEncounterService().getActiveEncounterVisitHandler() instead of just
      // getActiveEncounterVisitHandler() for modules which may want to AOP around this call.
      EncounterVisitHandler encounterVisitHandler =
          Context.getEncounterService().getActiveEncounterVisitHandler();
      if (encounterVisitHandler != null) {
        encounterVisitHandler.beforeCreateEncounter(encounter);

        // If we have been assigned a new visit, persist it.
        if (encounter.getVisit() != null && encounter.getVisit().getVisitId() == null) {
          Context.getVisitService().saveVisit(encounter.getVisit());
        }
      }
    }

    boolean isNewEncounter = false;
    Date newDate = encounter.getEncounterDatetime();
    Date originalDate = null;
    Location newLocation = encounter.getLocation();
    Location originalLocation = null;
    // check permissions
    if (encounter.getEncounterId() == null) {
      isNewEncounter = true;
      Context.requirePrivilege(PrivilegeConstants.ADD_ENCOUNTERS);
    } else {
      Context.requirePrivilege(PrivilegeConstants.EDIT_ENCOUNTERS);
    }

    // This must be done after setting dateCreated etc on the obs because
    // of the way the ORM tools flush things and check for nullity
    // This also must be done before the save encounter so we can use the
    // orig date
    // after the save
    Patient p = encounter.getPatient();

    if (!isNewEncounter) {
      // fetch the datetime from the database prior to saving for this
      // encounter
      // to see if it has changed and change all obs after saving if so
      originalDate = dao.getSavedEncounterDatetime(encounter);
      if (encounter.getLocation() != null) {
        originalLocation = dao.getSavedEncounterLocation(encounter);
      }
      // Our data model duplicates the patient column to allow for
      // observations to
      // not have to look up the parent Encounter to find the patient
      // Therefore, encounter.patient must always equal
      // encounter.observations[0-n].patient

      // If we are changing encounter.encounterDatetime, then we need to
      // also apply that
      // to Obs that inherited their obsDatetime from the encounter in the
      // first place

      for (Obs obs : encounter.getAllObs(true)) {
        // if the date was changed
        if (OpenmrsUtil.compare(originalDate, newDate) != 0
            && OpenmrsUtil.compare(obs.getObsDatetime(), originalDate) == 0) {

          // if the obs datetime is the same as the
          // original encounter datetime, fix it
          obs.setObsDatetime(newDate);
        }

        if (!OpenmrsUtil.nullSafeEquals(newLocation, originalLocation)
            && obs.getLocation().equals(originalLocation)) {
          obs.setLocation(newLocation);
        }

        // if the Person in the obs doesn't match the Patient in the
        // encounter, fix it
        if (!obs.getPerson().getPersonId().equals(p.getPatientId())) {
          obs.setPerson(p);
        }
      }
    }
    // same goes for Orders
    for (Order o : encounter.getOrders()) {
      if (!p.equals(o.getPatient())) {
        o.setPatient(p);
      }
    }

    // do the actual saving to the database
    dao.saveEncounter(encounter);

    // save the new orders
    for (Order o : encounter.getOrders()) {
      if (o.getOrderId() == null) {
        Context.getOrderService().saveOrder(o, null);
      }
    }
    return encounter;
  }
 public static RegimenHistory getRegimenHistory(Patient patient) {
   return new RegimenHistory(Context.getOrderService().getDrugOrdersByPatient(patient));
 }
  /* here's the logic for what happens if there is a future regimen:
  *
  *
  *      //1.  if no drug order of a specific DrugOrder, (create the new order).  (OUTCOME1)

         //2.  if DrugOrder, for all DrugOrders:
             //a.  if new start is before old start
                 //NEW ORDER HAS STOP DATE -- create the older as is, and make adjustments:
                     //1.  if new end is before or equal to old start (create the new order)  (OUTCOME2)
                     //2.  if new end is after old start and ( before old end or old end is infinite)
                        //if order is different, adjust the start date of the old order to the end date of the new (create the new order) (OUTCOME3)
                        //if order is same void old order(doesn't matter if old order has infinite stop date or not) (create the new order) (OUTCOME4)
                     //3. if end date is greater than or equal to old end -- void old order   (create the new order)  (OUTCOME5)
                 //NEW ORDER DOESN'T HAVE STOP DATE
                     //4. orders are different
                          //set end date of new to beginning of old and stop iterating over existing drug orders time sequence (create the new order, modified) (OUTCOME6)
                     //5. orders are the same
                         //delete the old order (create the new order) (OUTCOME7)
             //b. if start is the same
                 // void existing (create the new order) (OUTCOME8)

             //c.  if start is after existing start
                 //1. if order is after old drug end  (create the new order) (OUTCOME9)
                 //2. if order is before old drug end or equal to old drug end or old drug end date is infinite
                     //if orders are the same update the old order with the new, taking the new end date value (Do not create new order) (OUTCOME10)
                     //if orders are different adjust the old to end on new start date (create the new order) (OUTCOME11)

  * */
  public static void setRegimen(
      Patient patient,
      Date effectiveDate,
      Collection<DrugOrder> drugOrders,
      Concept reasonForChange,
      Encounter encounterForChange) {
    RegimenHistory history = getRegimenHistory(patient);
    Regimen regOnDate = history.getRegimen(effectiveDate);
    List<Regimen> regAfterDate = history.getRegimensAfter(effectiveDate);
    OrderService os = Context.getOrderService();
    if (encounterForChange != null) {
      Context.getEncounterService().saveEncounter(encounterForChange);
      for (DrugOrder drugOrder : drugOrders) {
        drugOrder.setEncounter(encounterForChange);
      }
    }

    if (!anyRegimens(regAfterDate)) {
      if (regOnDate == null || regOnDate.getComponents().isEmpty()) {
        // case:  there is no existing regimen on the regimen start date, and there are no new
        // regimens after this date
        // go ahead and create the regimen:
        for (DrugOrder drugOrder : drugOrders) {
          Context.getOrderService().saveOrder(drugOrder);
        }
      } else {

        // case: there are still open orders and there are no new regimens after this date
        // first see what existing things we need to stop
        for (RegimenComponent before : regOnDate.getComponents()) {
          // stop the old order only if it isn't exactly identical to a new order (excluding
          // discontinued_date)
          for (DrugOrder newOrder : drugOrders) {
            // but either concept or drug is the same
            if (!before.getDrugOrder().getDiscontinued()
                && drugOrderMatchesDrugConcept(before.getDrugOrder(), newOrder)
                && !regimenComponentIsTheSameAsDrugOrderExcludingDates(
                    before.getDrugOrder(), newOrder)) {
              discontinueOrder(before.getDrugOrder(), effectiveDate, reasonForChange);
            }
          }
        }
        // now see what new things to start (or extend)
        for (DrugOrder newOrder : drugOrders) {

          // create a new order if there isn't already an existing match,
          // or if there is (excluding discontinued date) you need to extend, or null the stop date

          boolean alreadyExists = false;
          for (RegimenComponent before : regOnDate.getComponents()) {

            if (!before.getDrugOrder().getDiscontinued()
                && regimenComponentIsTheSameAsDrugOrderExcludingDates(
                    before.getDrugOrder(), newOrder)) {
              alreadyExists = true;
              before.getDrugOrder().setDiscontinuedDate(newOrder.getDiscontinuedDate());
              before.getDrugOrder().setAutoExpireDate(newOrder.getAutoExpireDate());
              before.getDrugOrder().setPrn(newOrder.getPrn());
              before.getDrugOrder().setInstructions(newOrder.getInstructions());
              os.saveOrder(before.getDrugOrder());
              newOrder.setOrderId(before.getDrugOrder().getOrderId());
              break;
            }
          }
          if (!alreadyExists) {
            os.saveOrder(newOrder);
          }
        }
      }
    } else { // there is a regimen change after the new drug order start date
      for (DrugOrder newOrder : drugOrders) {
        boolean saveOrder = false;
        boolean merged = false;
        history = getRegimenHistory(patient);
        List<DrugOrder> existingDrugOrders = getDrugOrdersInOrderByDrugOrConcept(history, newOrder);
        if (existingDrugOrders.size() == 0) {
          saveOrder = setSaveOrder(merged); // (OUTCOME1)
        } else {
          for (DrugOrder before : existingDrugOrders) {
            if (newOrder.getStartDate().before(before.getStartDate())) {
              if (newOrder.getDiscontinuedDate() != null) {
                if (newOrder.getDiscontinuedDate().before(before.getStartDate())
                    || newOrder.getDiscontinuedDate().equals(before.getStartDate())) {
                  saveOrder = setSaveOrder(merged); // (OUTCOME2)
                } else if (newOrder.getDiscontinuedDate().after(before.getStartDate())
                    && (before.getDiscontinuedDate() == null
                        || newOrder.getDiscontinuedDate().before(before.getDiscontinuedDate()))) {
                  if (!regimenComponentIsTheSameAsDrugOrderExcludingDates(before, newOrder)) {
                    // (OUTCOME3)
                    before.setStartDate(newOrder.getDiscontinuedDate());
                    os.saveOrder(before);
                    saveOrder = setSaveOrder(merged);
                  } else {
                    // (OUTCOME4)
                    os.voidOrder(before, "overwritten");
                    saveOrder = setSaveOrder(merged);
                  }
                } else if (before.getDiscontinuedDate() != null
                    && (newOrder.getDiscontinuedDate().after(before.getDiscontinuedDate())
                        || newOrder.getDiscontinuedDate().equals(before.getDiscontinuedDate()))) {
                  // (OUTCOME5)
                  os.voidOrder(before, "overwritten");
                  saveOrder = setSaveOrder(merged);
                }
              } else { // new order has infinite end date
                if (!regimenComponentIsTheSameAsDrugOrderExcludingDates(before, newOrder)) {
                  // (OUTCOME6)
                  newOrder.setDiscontinuedDate(before.getStartDate());
                  saveOrder = setSaveOrder(merged);
                  break;
                } else {
                  // (OUTCOME7)
                  os.voidOrder(before, "overwritten");
                  saveOrder = setSaveOrder(merged);
                }
              }
            } else if (newOrder.getStartDate().equals(before.getStartDate())) { // b
              // (OUTCOME8)
              os.voidOrder(before, "overwritten");
              saveOrder = setSaveOrder(merged);
            } else { // c -- start date is after or equal to old end date
              if (before.getDiscontinuedDate() != null
                  && newOrder.getStartDate().after(before.getDiscontinuedDate())) // 1
                // (OUTCOME9)
                saveOrder = setSaveOrder(merged);

              if (before.getDiscontinuedDate() == null
                  || newOrder.getStartDate().before(before.getDiscontinuedDate())
                  || newOrder.getStartDate().equals(before.getDiscontinuedDate())) { // 2
                if (regimenComponentIsTheSameAsDrugOrderExcludingDates(before, newOrder)) {
                  // (OUTCOME10)
                  before.setDiscontinuedDate(newOrder.getDiscontinuedDate());
                  before.setAutoExpireDate(newOrder.getAutoExpireDate());
                  before.setPrn(newOrder.getPrn());
                  before.setInstructions(newOrder.getInstructions());
                  os.saveOrder(before);
                  saveOrder = false;
                  newOrder.setOrderId(before.getOrderId());
                  merged = true;
                } else {
                  // (OUTCOME11)
                  before.setDiscontinuedDate(newOrder.getStartDate());
                  os.saveOrder(before);
                  saveOrder = setSaveOrder(merged);
                }
              }
            }
          }
        }
        if (saveOrder) os.saveOrder(newOrder);
      }
    }
  }
 /**
  * @see
  *     org.openmrs.module.webservices.rest.web.resource.impl.DelegatingResourceHandler#newDelegate()
  */
 @Override
 public HivDrugOrder newDelegate() {
   HivDrugOrder o = new HivDrugOrder();
   o.setOrderType(Context.getOrderService().getOrderType(OpenmrsConstants.ORDERTYPE_DRUG));
   return o;
 }
 public void controller(FragmentModel model, @FragmentParam(value = "patientId") Patient patient) {
   model.addAttribute("medications", Context.getOrderService().getDrugOrdersByPatient(patient));
 }
  protected ModelAndView handleRequestInternal(
      HttpServletRequest request, HttpServletResponse response) throws Exception {

    ModelAndView mav = new ModelAndView();

    Drug drug = null;
    Location dftLoc = null;
    LocationService locationService = Context.getLocationService();

    String locationStr =
        Context.getAuthenticatedUser()
            .getUserProperties()
            .get(OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCATION);

    try {
      dftLoc = locationService.getLocation(Integer.valueOf(locationStr));
    } catch (Exception e) {
      mav.addObject("msg", "pharmacymanagement.missingDftLoc");
    }
    @SuppressWarnings("unused")
    String pharmacyId = null;
    DrugLotDate dld = null;
    List<DrugLotDate> dlds = new ArrayList<DrugLotDate>();
    String patientIdStr = null;
    Patient patient = null;
    DrugOrderService service = Context.getService(DrugOrderService.class);
    List<Pharmacy> pharmacyList = service.getPharmacyByLocation(dftLoc);
    List<DrugOrder> drugOrders = new ArrayList<DrugOrder>();
    ConceptService conceptService = Context.getConceptService();
    Pharmacy pharmacy = null;

    List<DrugOrder> drugOrderList = new ArrayList<DrugOrder>();
    pharmacyId = pharmacyList.size() > 0 ? "not empty" : "";

    if (request.getParameter("patientId") != null
        && !request.getParameter("patientId").equals("")) {
      patientIdStr = request.getParameter("patientId");

      patient = Context.getPatientService().getPatient(Integer.valueOf(patientIdStr));
    }

    if (patient != null
        && request.getParameter("pharmacyId") != null
        && !request.getParameter("pharmacyId").equals("")) {

      drugOrders = Context.getOrderService().getDrugOrdersByPatient(patient);

      pharmacy = service.getPharmacyById(Integer.valueOf(request.getParameter("pharmacyId")));
      List<Integer> drugIdList = new ArrayList<Integer>();
      for (DrugOrder dor : drugOrders) {
        if (dor.getDiscontinued() == false) {
          drugOrderList.add(dor);
        }
      }

      Set<DrugProduct> lotNos = new HashSet<DrugProduct>();
      int solde = 0;

      List<Integer> drugIdss = new ArrayList<Integer>();
      List<DrugOrder> drugOrders1 = new ArrayList<DrugOrder>();
      for (DrugOrder drOr : drugOrderList) {
        if (!drugIdss.contains(drOr.getDrug().getDrugId()) && drOr.getAutoExpireDate() == null) {
          dld = new DrugLotDate();
          drugOrders1.add(drOr);
          drugIdList.add(drOr.getDrug().getDrugId());

          dld.setDrugOrder(drOr);
          drug = conceptService.getDrug(drOr.getDrug().getDrugId());
          dld.setDrug(drug);
          Map<String, String> dpMap = new HashMap<String, String>();
          lotNos =
              Utils.getLotsExpDp(
                  null, drOr.getDrug().getDrugId() + "", null, pharmacy.getPharmacyId() + "");

          /**
           * TO DO change this list of lotNos by the testLots in the Utils class remember to
           * retrieve a list of list instead of a unique set!!!!!!!!!!!!!!!!
           */
          if (lotNos.size() > 0) {
            for (DrugProduct drugproduct : lotNos) {
              if (drug != null)
                solde =
                    service.getCurrSoldeDisp(
                        drug.getDrugId() + "",
                        null,
                        pharmacy.getPharmacyId() + "",
                        drugproduct.getExpiryDate() + "",
                        drugproduct.getLotNo(),
                        null);

              if (solde != 0) {
                dpMap.put(
                    drugproduct.getLotNo()
                        + " / "
                        + solde
                        + " ("
                        + drugproduct.getExpiryDate()
                        + ") ",
                    drugproduct.getDrugproductId() + "");
                dld.setDpMap(dpMap);
              }
            }
            if (dpMap.size() > 0) dlds.add(dld);
          }
        }
        drugIdss.add(drOr.getDrug().getDrugId());
      }

      mav.addObject("patient", patient);
    }

    if (dlds.size() != 0) {
      mav.addObject("dlds", dlds);
    }

    List<Object[]> lots = null;
    DrugProduct drugproduct = null;
    if (request.getParameter("drugproductId") != null
        && !request.getParameter("drugproductId").equals("")) {
      drugproduct =
          service.getDrugProductById(Integer.valueOf(request.getParameter("drugproductId")));
      if (drugproduct != null) {
        if (drugproduct.getCmddrugId() != null) {
          if (drugproduct.getCmddrugId().getDestination().getLocationId()
              == dftLoc.getLocationId()) {
            if (drugproduct.getDrugId() != null)
              lots =
                  service.getLotNumbersExpirationDates(
                      drugproduct.getDrugId().getDrugId() + "",
                      null,
                      dftLoc.getLocationId() + "",
                      null);
            else
              lots =
                  service.getLotNumbersExpirationDates(
                      null,
                      drugproduct.getConceptId().getConceptId() + "",
                      dftLoc.getLocationId() + "",
                      null);
          }
        } else {
          if (service.getReturnStockByDP(drugproduct).get(0).getDestination().getLocationId()
              == dftLoc.getLocationId()) {
            if (drugproduct.getDrugId() != null)
              lots =
                  service.getLotNumbersExpirationDates(
                      drugproduct.getDrugId().getDrugId() + "",
                      null,
                      dftLoc.getLocationId() + "",
                      null);
            else
              lots =
                  service.getLotNumbersExpirationDates(
                      null,
                      drugproduct.getConceptId().getConceptId() + "",
                      dftLoc.getLocationId() + "",
                      null);
          }
        }
      }
      mav.addObject("lots", lots);
    }

    if (request.getParameter("dpFromGet") != null
        && !request.getParameter("dpFromGet").equals("")) {
      DrugProduct dp =
          service.getDrugProductById(Integer.valueOf(request.getParameter("dpFromGet")));
      String dateStr = dp.getExpiryDate().toString();
      String[] dateArr = dateStr.split("-");
      String date = dateArr[2] + "/" + dateArr[1] + "/" + dateArr[0];
      mav.addObject("date", date);
    }

    mav.setViewName(getViewName());
    return mav;
  }