/** @see java.lang.Object#toString() */
  public String toString() {
    StringBuilder ret = new StringBuilder();
    ret.append("Patients ");
    if (enrolledOnOrAfter != null) {
      ret.append("who enrolled on or after " + enrolledOnOrAfter + " ");
    }
    if (enrolledOnOrBefore != null) {
      ret.append("who enrolled on or before " + enrolledOnOrBefore + " ");
    }
    if (completedOnOrAfter != null) {
      ret.append("who completed on or after " + completedOnOrAfter + " ");
    }
    if (completedOnOrBefore != null) {
      ret.append("who completed on or before " + completedOnOrBefore + " ");
    }

    if (programs != null && programs.size() > 0) {
      ret.append(" in ");
      for (Program p : programs) {
        ret.append(p.getName() + " ");
      }
    }

    if (locationList != null && locationList.size() > 0) {
      ret.append(" at ");
      for (Location l : locationList) {
        ret.append(l.getName() + " ");
      }
    }
    return ret.toString();
  }
 @Override
 public List<Object> getPriorityDependencies(Location object) {
   List<Object> result = new ArrayList<Object>();
   if (object.getTags() != null) {
     result.addAll(object.getTags());
   }
   return result;
 }
 /**
  * @param locationAndDepths
  * @param locations
  * @param i counter
  */
 private void populateLocationAndDepthList(
     List<LocationAndDepth> locationAndDepths, Collection<Location> locations, int depth) {
   for (Location location : locations) {
     locationAndDepths.add(new LocationAndDepth(depth, location));
     if (location.getChildLocations() != null && location.getChildLocations().size() > 0) {
       populateLocationAndDepthList(locationAndDepths, location.getChildLocations(), depth + 1);
     }
   }
 }
 /**
  * Auto generated method comment
  *
  * @param locationId
  * @return
  */
 public static String getLocationName(Integer locationId) {
   try {
     if (null == locationId) return "";
     Location loc = Context.getLocationService().getLocation(locationId);
     return (loc != null) ? loc.getDisplayString() : "";
   } catch (Exception e) {
     log.info(e.getMessage());
     return "";
   }
 }
 /**
  * Looks at location, and if necessary its ancestors in the location hierarchy, until it finds one
  * tagged with "Visit Location"
  *
  * @param location
  * @return location, or an ancestor
  * @throws IllegalArgumentException if neither location nor its ancestors support visits
  */
 @Override
 public Location getLocationThatSupportsVisits(Location location) {
   if (location == null) {
     throw new IllegalArgumentException("Location does not support visits");
   } else if (location.hasTag(EmrApiConstants.LOCATION_TAG_SUPPORTS_VISITS)) {
     return location;
   } else {
     return getLocationThatSupportsVisits(location.getParentLocation());
   }
 }
  /** @see org.openmrs.api.db.LocationDAO#saveLocation(org.openmrs.Location) */
  public Location saveLocation(Location location) {
    if (location.getChildLocations() != null && location.getLocationId() != null) {
      // hibernate has a problem updating child collections
      // if the parent object was already saved so we do it
      // explicitly here
      for (Location child : location.getChildLocations())
        if (child.getLocationId() == null) saveLocation(child);
    }

    sessionFactory.getCurrentSession().saveOrUpdate(location);
    return location;
  }
Exemple #7
0
 /** Gets a Location entity by its exact name. */
 public static Location getLocationByName(String locationName, Location parent) {
   LocationService locationService = Context.getLocationService();
   Location location = locationService.getLocation(locationName);
   if (location == null) {
     location = new Location();
     location.setName(locationName);
     location.setDescription(locationName);
     if (parent != null) {
       location.setParentLocation(parent);
     }
     locationService.saveLocation(location);
   }
   return location;
 }
  /**
   * This method is synchronized to prevent multiple check-ins in a row at the same location and
   * during the same visit. See #579.
   *
   * @see org.openmrs.module.emrapi.adt.AdtService#checkInPatient(org.openmrs.Patient,
   *     org.openmrs.Location, org.openmrs.Provider, java.util.List, java.util.List, boolean)
   */
  @Override
  @Transactional
  public synchronized Encounter checkInPatient(
      Patient patient,
      Location where,
      Provider checkInClerk,
      List<Obs> obsForCheckInEncounter,
      List<Order> ordersForCheckInEncounter,
      boolean newVisit) {
    if (checkInClerk == null) {
      checkInClerk = getProvider(Context.getAuthenticatedUser());
    }

    Visit activeVisit = getActiveVisitHelper(patient, where);

    if (activeVisit != null && newVisit) {
      closeAndSaveVisit(activeVisit);
      activeVisit = null;
    }

    if (activeVisit == null) {
      activeVisit = ensureActiveVisit(patient, where);
    }

    Encounter lastEncounter = getLastEncounter(patient);
    if (lastEncounter != null
        && activeVisit.equals(lastEncounter.getVisit())
        && emrApiProperties.getCheckInEncounterType().equals(lastEncounter.getEncounterType())
        && where.equals(lastEncounter.getLocation())) {
      log.warn(
          "Patient id:{} tried to check-in twice in a row at id:{} during the same visit",
          patient.getId(),
          where.getId());
      return lastEncounter;
    }

    Encounter encounter =
        buildEncounter(
            emrApiProperties.getCheckInEncounterType(),
            patient,
            where,
            null,
            new Date(),
            obsForCheckInEncounter,
            ordersForCheckInEncounter);
    encounter.addProvider(emrApiProperties.getCheckInClerkEncounterRole(), checkInClerk);
    activeVisit.addEncounter(encounter);
    encounterService.saveEncounter(encounter);
    return encounter;
  }
  @Test
  public void shouldReturnBedAssignmentDetailsByPatient() {
    PatientService patientService = Context.getPatientService();
    Patient patient = patientService.getPatient(3);

    LocationService locationService = Context.getLocationService();
    Location ward = locationService.getLocation(123452);
    String bedNumFromDataSetup = "307-a";

    BedDetails bedDetails = bedManagementService.getBedAssignmentDetailsByPatient(patient);
    assertEquals(ward.getId(), bedDetails.getPhysicalLocation().getId());
    assertEquals(bedIdFromDataSetup, bedDetails.getBedId());
    assertEquals(bedNumFromDataSetup, bedDetails.getBedNumber());
  }
  /**
   * The onSubmit function receives the form/command object that was modified by the input form and
   * saves it to the db
   *
   * @see
   *     org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
   *     javax.servlet.http.HttpServletResponse, java.lang.Object,
   *     org.springframework.validation.BindException)
   * @should retire location
   * @should not retire location if reason is empty
   */
  protected ModelAndView onSubmit(
      HttpServletRequest request, HttpServletResponse response, Object obj, BindException errors)
      throws Exception {

    HttpSession httpSession = request.getSession();

    String view = getFormView();
    if (Context.isAuthenticated()) {
      try {
        Location location = (Location) obj;
        WebAttributeUtil.handleSubmittedAttributesForType(
            location,
            errors,
            LocationAttribute.class,
            request,
            Context.getLocationService().getAllLocationAttributeTypes());

        if (errors.hasErrors()) {
          return showForm(request, response, errors);
        }

        LocationService locationService = Context.getLocationService();

        // if the user was editing the location
        if (request.getParameter("saveLocation") != null) {
          locationService.saveLocation(location);
          httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Location.saved");
        }
        // the 'retire this location' button was clicked
        else if (request.getParameter("retireLocation") != null) {
          locationService.retireLocation(location, location.getRetireReason());
          httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Location.retired");
        }
        // the 'unretire this location' button was clicked
        else if (request.getParameter("unretireLocation") != null) {
          locationService.unretireLocation(location);
          httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Location.unretired");
        }
      } catch (APIException e) {
        log.error("Error while saving location: " + obj, e);
        httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, e.getMessage());
        return showForm(request, response, errors);
      }

      view = getSuccessView();
    }

    return new ModelAndView(new RedirectView(view));
  }
  @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));
  }
  /**
   * Utility method that returns all child locations and children of its child locations recursively
   *
   * @param location
   * @param foundLocations
   * @return
   */
  private Set<Location> getChildLocationsRecursively(
      Location location, Set<Location> foundLocations) {
    if (foundLocations == null) foundLocations = new LinkedHashSet<Location>();

    foundLocations.add(location);

    if (location.getChildLocations() != null) {
      for (Location l : location.getChildLocations()) {
        foundLocations.add(l);
        getChildLocationsRecursively(l, foundLocations);
      }
    }

    return foundLocations;
  }
  @Test
  public void testEstimatedBirthDate() {

    visitLocation.setName("Hôpital Universitaire de Mirebalais");

    Patient patient = new Patient();
    patient.setGender("M");
    patient.setBirthdate(new DateTime(1940, 7, 7, 5, 5, 5).toDate());
    patient.setBirthdateEstimated(true);

    PatientIdentifier primaryIdentifier = new PatientIdentifier();
    primaryIdentifier.setIdentifier("ZL1234");
    primaryIdentifier.setIdentifierType(primaryIdentifierType);
    primaryIdentifier.setVoided(false);
    patient.addIdentifier(primaryIdentifier);

    PatientIdentifier paperRecordIdentifier = new PatientIdentifier();
    paperRecordIdentifier.setIdentifier("A00005");
    paperRecordIdentifier.setIdentifierType(paperRecordIdentifierType);
    paperRecordIdentifier.setVoided(false);
    patient.addIdentifier(paperRecordIdentifier);

    PersonName name = new PersonName();
    name.setGivenName("Ringo");
    name.setFamilyName("Starr");
    patient.addName(name);

    String output = wristbandTemplate.generateWristband(patient, new Location());

    assertThat(output, containsString("^FO160,200^FB2150,1,0,L,0^AU^FD1940^FS"));
  }
  @Override
  public List<VisitDomainWrapper> getInpatientVisits(Location visitLocation, Location ward) {

    if (visitLocation == null) {
      throw new IllegalArgumentException("Location is required");
    }
    Set<Location> locations = getChildLocationsRecursively(visitLocation, null);
    List<Visit> candidates =
        visitService.getVisits(
            null, null, locations, null, null, null, null, null, null, false, false);

    List<VisitDomainWrapper> inpatientVisits = new ArrayList<VisitDomainWrapper>();
    for (Visit candidate : candidates) {
      VisitDomainWrapper visitDomainWrapper = wrap(candidate);
      if (itBelongsToARealPatient(candidate) && visitDomainWrapper.isAdmitted()) {
        if (ward != null) {
          Encounter latestAdtEncounter = visitDomainWrapper.getLatestAdtEncounter();
          if (latestAdtEncounter != null
              && (latestAdtEncounter.getLocation().getId().compareTo(ward.getId()) == 0)) {
            inpatientVisits.add(visitDomainWrapper);
          }
        } else {
          inpatientVisits.add(visitDomainWrapper);
        }
      }
    }

    return inpatientVisits;
  }
  /** @see CohortDefinitionEvaluator#evaluate(CohortDefinition, EvaluationContext) */
  public EvaluatedCohort evaluate(CohortDefinition cohortDefinition, EvaluationContext context) {

    PersonAttributeCohortDefinition pacd = (PersonAttributeCohortDefinition) cohortDefinition;
    List<String> values = new ArrayList<String>();

    if (pacd.getValues() != null) {
      values.addAll(pacd.getValues());
    }
    if (pacd.getValueConcepts() != null) {
      for (Concept c : pacd.getValueConcepts()) {
        values.add(c.serialize());
      }
    }
    if (pacd.getValueLocations() != null) {
      for (Location l : pacd.getValueLocations()) {
        values.add(l.serialize());
      }
    }

    CohortQueryService cqs = Context.getService(CohortQueryService.class);
    Cohort c = cqs.getPatientsHavingPersonAttributes(pacd.getAttributeType(), values);
    return new EvaluatedCohort(c, cohortDefinition, context);
  }
  @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"));
  }
Exemple #17
0
 /**
  * Get locations
  *
  * @param limit
  * @return
  */
 public List<Location> getLocations(String limit) {
   String query = "location?" + "limit=" + limit;
   ObjectMapper m = new ObjectMapper();
   List<Location> locations = new ArrayList<Location>();
   Location location;
   try {
     JsonNode rootNode = m.readTree(RestCall.getRequestGet(query));
     JsonNode results = rootNode.get("results");
     for (JsonNode result : results) {
       String uuid = result.path("uuid").textValue();
       String name = result.path("display").textValue();
       location = new Location();
       location.setName(name);
       location.setUuid(uuid);
       locations.add(location);
     }
     return locations;
   } catch (Exception ex) {
     logger.info("Some Error occured while getting locations.");
     logger.error("\n ERROR Caused by\n", ex);
     ex.printStackTrace();
     return locations;
   }
 }
 /**
  * @param a
  * @param b
  * @return true if a.equals(b) or a is an ancestor of b.
  */
 private boolean isSameOrAncestor(Location a, Location b) {
   if (a == null || b == null) {
     return a == null && b == null;
   }
   return a.equals(b) || isSameOrAncestor(a, b.getParentLocation());
 }
  /**
   * Construct a new EncounterDetailSubmissionElement
   *
   * @param context
   * @param parameters
   * @should display 'Enter' option if 'type' is set to Autocomplete
   */
  public EncounterDetailSubmissionElement(
      FormEntryContext context, Map<String, Object> parameters) {

    // Register Date and Time widgets, if appropriate
    if (Boolean.TRUE.equals(parameters.get("date"))) {

      dateWidget = new DateWidget();
      dateErrorWidget = new ErrorWidget();

      if (context.getExistingEncounter() != null) {
        dateWidget.setInitialValue(context.getExistingEncounter().getEncounterDatetime());
      } else if (parameters.get("defaultDate") != null) {
        dateWidget.setInitialValue(parameters.get("defaultDate"));
      }

      if (parameters.get("disallowMultipleEncountersOnDate") != null
          && StringUtils.hasText((String) parameters.get("disallowMultipleEncountersOnDate"))) {
        dateWidget.setOnChangeFunction(
            "existingEncounterOnDate(this, '"
                + parameters.get("disallowMultipleEncountersOnDate")
                + "') ");
      }

      if ("true".equals(parameters.get("showTime"))) {
        timeWidget = new TimeWidget();
        timeErrorWidget = new ErrorWidget();
        if (context.getExistingEncounter() != null) {
          timeWidget.setInitialValue(context.getExistingEncounter().getEncounterDatetime());
        } else if (parameters.get("defaultDate") != null) {
          timeWidget.setInitialValue(parameters.get("defaultDate"));
        }
        context.registerWidget(timeWidget);
        context.registerErrorWidget(timeWidget, timeErrorWidget);
      }
      context.registerWidget(dateWidget);
      context.registerErrorWidget(dateWidget, dateErrorWidget);
    }

    // Register Provider widgets, if appropriate
    if (Boolean.TRUE.equals(parameters.get("provider"))) {

      if ("autocomplete".equals(parameters.get("type"))) {
        providerWidget = new AutocompleteWidget(Person.class);
      } else {
        providerWidget = new DropdownWidget();
      }
      providerErrorWidget = new ErrorWidget();

      List<Option> providerOptions = new ArrayList<Option>();
      // If specific persons are specified, display only those persons in order
      String personsParam = (String) parameters.get("persons");
      if (personsParam != null) {
        for (String s : personsParam.split(",")) {
          Person p = HtmlFormEntryUtil.getPerson(s);
          if (p == null) {
            throw new RuntimeException("Cannot find Person: " + s);
          }
          String label = p.getPersonName().getFullName();
          providerOptions.add(new Option(label, p.getId().toString(), false));
        }
        removeNonProviders(providerOptions);
      }

      // Only if specific person ids are not passed in do we get by user Role
      if (providerOptions.isEmpty()) {

        List<PersonStub> users = new ArrayList<PersonStub>();
        List<Option> providerUsers = new ArrayList<Option>();

        // If the "role" attribute is passed in, limit to users with this role
        if (parameters.get("role") != null) {
          Role role = Context.getUserService().getRole((String) parameters.get("role"));
          if (role == null) {
            throw new RuntimeException("Cannot find role: " + parameters.get("role"));
          } else {
            users =
                Context.getService(HtmlFormEntryService.class)
                    .getUsersAsPersonStubs(role.getRole());
          }
        }

        // Otherwise, use default options appropriate to the underlying OpenMRS version
        else {
          if (openmrsVersionDoesNotSupportProviders()) {
            // limit to users with the default OpenMRS PROVIDER role,
            String defaultRole = OpenmrsConstants.PROVIDER_ROLE;
            Role role = Context.getUserService().getRole(defaultRole);
            if (role != null) {
              users =
                  Context.getService(HtmlFormEntryService.class)
                      .getUsersAsPersonStubs(role.getRole());
            }
            // If this role isn't used, default to all Users
            if (users.isEmpty()) {
              users = Context.getService(HtmlFormEntryService.class).getUsersAsPersonStubs(null);
            }
          } else {
            // in OpenMRS 1.9+, get all suitable providers
            users = getAllProvidersThatArePersonsAsPersonStubs();
          }
        }

        for (PersonStub personStub : users) {

          Option option = new Option(personStub.toString(), personStub.getId().toString(), false);
          providerUsers.add(option);
        }
        providerOptions.addAll(providerUsers);
      }

      // Set default values as appropriate
      Person defaultProvider = null;
      Option defProviderOption;
      if (context.getExistingEncounter() != null) {
        defaultProvider = context.getExistingEncounter().getProvider();
        // this is done to avoid default provider being added twice due to that it can be added from
        // the
        // users = getAllProvidersThatArePersonsAsPersonStubs(); section with selected="false",
        // therefore this can't be caught when
        // searching whether the options list contains the 'defaultProvider'
        boolean defaultOptionPresent = false;
        if (defaultProvider != null) {
          for (Option option : providerOptions) {
            if (option.getValue().equals(defaultProvider.getId().toString())) {
              defaultOptionPresent = true;
              providerOptions.remove(option);
              break;
            }
          }
        }
        if (defaultOptionPresent) {
          defProviderOption =
              new Option(
                  defaultProvider.getPersonName().getFullName(),
                  defaultProvider.getId().toString(),
                  true);
          providerOptions.add(defProviderOption);
        }

      } else {
        String defParam = (String) parameters.get("default");
        if (StringUtils.hasText(defParam)) {
          if ("currentuser".equalsIgnoreCase(defParam)) {
            defaultProvider = Context.getAuthenticatedUser().getPerson();
          } else {
            defaultProvider = HtmlFormEntryUtil.getPerson(defParam);
          }
          if (defaultProvider == null) {
            throw new IllegalArgumentException(
                "Invalid default provider specified for encounter: " + defParam);
          } else {
            defProviderOption =
                new Option(
                    defaultProvider.getPersonName().getFullName(),
                    defaultProvider.getId().toString(),
                    true);
            for (Option option : providerOptions) {
              if (option.getValue().equals(defProviderOption.getValue())) {
                providerOptions.remove(option);
                break;
              }
            }
            providerOptions.add(defProviderOption);
          }
        }
      }
      if (defaultProvider != null) {
        providerWidget.setInitialValue(new PersonStub(defaultProvider));
      }
      Collections.sort(providerOptions, new OptionComparator());

      if (("autocomplete").equals(parameters.get("type"))) {
        providerWidget.addOption(new Option());
        if (!providerOptions.isEmpty()) {
          providerWidget.setOptions(providerOptions);
        }

      } else {
        // if initialValueIsSet=false, no initial/default provider, hence this shows the 'select
        // input' field as first option
        boolean initialValueIsSet = !(providerWidget.getInitialValue() == null);
        providerWidget.addOption(
            new Option(
                Context.getMessageSourceService().getMessage("htmlformentry.chooseAProvider"),
                "",
                !initialValueIsSet)); // if no initial or default value

        if (!providerOptions.isEmpty()) {
          for (Option option : providerOptions) {
            providerWidget.addOption(option);
          }
        }
      }
      context.registerWidget(providerWidget);
      context.registerErrorWidget(providerWidget, providerErrorWidget);
    }

    if (Boolean.TRUE.equals(parameters.get("encounterType"))) {
      encounterTypeWidget = new EncounterTypeWidget();
      encounterTypeErrorWidget = new ErrorWidget();
      if (parameters.get("types") != null) {
        List<EncounterType> encounterTypes = new ArrayList<EncounterType>();
        String[] temp = ((String) parameters.get("types")).split(",");
        for (String s : temp) {
          EncounterType type = HtmlFormEntryUtil.getEncounterType(s);
          if (type == null) {
            throw new RuntimeException("Cannot find encounter type: " + s);
          }
          encounterTypes.add(type);
        }

        encounterTypeWidget.setOptions(encounterTypes);
      }
      // Set default values

      EncounterType defaultEncounterType = null;
      if (context.getExistingEncounter() != null) {
        defaultEncounterType = context.getExistingEncounter().getEncounterType();
      } else {
        String defaultTypeId = (String) parameters.get("default");
        if (StringUtils.hasText(defaultTypeId)) {
          defaultEncounterType = HtmlFormEntryUtil.getEncounterType(defaultTypeId);
        }
      }

      encounterTypeWidget.setInitialValue(defaultEncounterType);
      context.registerWidget(encounterTypeWidget);
      context.registerErrorWidget(encounterTypeWidget, encounterTypeErrorWidget);
    }

    // Register Location widgets, if appropriate
    if (Boolean.TRUE.equals(parameters.get("location"))) {

      locationErrorWidget = new ErrorWidget();
      List<Location> locations = new ArrayList<Location>();
      List<Option> locationOptions = new ArrayList<Option>();

      if ("autocomplete".equals(parameters.get("type"))) {
        locationWidget = new AutocompleteWidget(Location.class);
      } else {
        locationWidget = new DropdownWidget();
      }

      // If the "order" attribute is passed in, limit to the specified locations in order
      if (parameters.get("order") != null) {

        String[] temp = ((String) parameters.get("order")).split(",");
        for (String s : temp) {
          Location loc = HtmlFormEntryUtil.getLocation(s);
          if (loc == null) {
            throw new RuntimeException("Cannot find location: " + loc);
          }
          locations.add(loc);
        }
      }

      // Set default values
      Location defaultLocation = null;
      if (context.getExistingEncounter() != null) {
        defaultLocation = context.getExistingEncounter().getLocation();
      } else {
        String defaultLocId = (String) parameters.get("default");
        if (StringUtils.hasText(defaultLocId)) {
          defaultLocation = HtmlFormEntryUtil.getLocation(defaultLocId);
        }
      }
      defaultLocation = defaultLocation == null ? context.getDefaultLocation() : defaultLocation;
      locationWidget.setInitialValue(defaultLocation);

      if (!locations.isEmpty()) {
        for (Location location : locations) {
          String label = location.getName();
          Option option =
              new Option(label, location.getId().toString(), location.equals(defaultLocation));
          locationOptions.add(option);
        }
      } else {
        locations = Context.getLocationService().getAllLocations();
        for (Location location : locations) {
          String label = location.getName();
          Option option =
              new Option(label, location.getId().toString(), location.equals(defaultLocation));
          locationOptions.add(option);
        }
        Collections.sort(locationOptions, new OptionComparator());
      }

      if ("autocomplete".equals(parameters.get("type"))) {
        locationWidget.addOption(new Option());
        if (!locationOptions.isEmpty()) {
          locationWidget.setOptions(locationOptions);
        }
      } else {
        boolean initialValueIsSet = !(locationWidget.getInitialValue() == null);
        locationWidget.addOption(
            new Option(
                Context.getMessageSourceService().getMessage("htmlformentry.chooseALocation"),
                "",
                !initialValueIsSet));
        if (!locationOptions.isEmpty()) {
          for (Option option : locationOptions) locationWidget.addOption(option);
        }
      }
      context.registerWidget(locationWidget);
      context.registerErrorWidget(locationWidget, locationErrorWidget);
    }

    if (Boolean.TRUE.equals(parameters.get("showVoidEncounter"))
        && context.getMode()
            == Mode
                .EDIT) { // only show void option if the encounter already exists.  And VIEW implies
                         // not voided.
      if (parameters.get("toggle") != null) {
        ToggleWidget toggleWidget = new ToggleWidget((String) parameters.get("toggle"));
        voidWidget =
            new CheckboxWidget(
                " " + Context.getMessageSourceService().getMessage("general.voided"),
                (context.getExistingEncounter() != null
                        && context.getExistingEncounter().isVoided().equals(true))
                    ? "true"
                    : "false",
                toggleWidget.getTargetId(),
                toggleWidget.isToggleDim());
      } else {
        voidWidget = new CheckboxWidget();
      }
      voidWidget.setLabel(" " + Context.getMessageSourceService().getMessage("general.voided"));
      voidErrorWidget = new ErrorWidget();
      if (context.getExistingEncounter() != null
          && context.getExistingEncounter().isVoided().equals(true))
        voidWidget.setInitialValue("true");
      context.registerWidget(voidWidget);
      context.registerErrorWidget(voidWidget, voidErrorWidget);
    }

    // set the id, if it has been specified
    if (parameters.get("id") != null) {
      id = (String) parameters.get("id");
    }
  }
  private static String replaceIdsWithUuidsHelper(
      String formXmlData, String attribute, String objectType) {
    // pattern to find the specified attribute and pull out its values; regex matches any characters
    // within quotes after an equals, i.e. ="a2-32" would match a232
    Pattern substitutionPattern =
        Pattern.compile(attribute + "=\"(.*?)\"", Pattern.CASE_INSENSITIVE);
    Matcher matcher = substitutionPattern.matcher(formXmlData);

    // list to keep track of any "repeat" keys we are going to have to substitute out as well
    Set<String> keysToReplace = new HashSet<String>();

    StringBuffer buffer = new StringBuffer();

    while (matcher.find()) {
      // split the group into the various ids
      String[] ids = matcher.group(1).split(",");

      StringBuffer idBuffer = new StringBuffer();
      // now loop through each id
      for (String id : ids) {
        // see if this is a concept id (i.e., is made up of one or more digits), as opposed to a
        // mapping id or a uuid, or a key used in a repeat template)
        if (id.matches("^\\d+$")) {
          // now we need to fetch the appropriate object for this id, and append the uuid to the
          // buffer
          if ("concept".equalsIgnoreCase(objectType)) {
            Concept concept = Context.getConceptService().getConcept(Integer.valueOf(id));
            idBuffer.append(concept.getUuid() + ",");
          } else if ("location".equalsIgnoreCase(objectType)) {
            Location location = Context.getLocationService().getLocation(Integer.valueOf(id));
            idBuffer.append(location.getUuid() + ",");
          } else if ("program".equalsIgnoreCase(objectType)) {
            Program program = Context.getProgramWorkflowService().getProgram(Integer.valueOf(id));
            idBuffer.append(program.getUuid() + ",");
          } else if ("person".equalsIgnoreCase(objectType)) {
            Person person = Context.getPersonService().getPerson(Integer.valueOf(id));
            idBuffer.append(person.getUuid() + ",");
          }
        } else {
          // otherwise, leave the id only
          idBuffer.append(id + ",");

          // also, if this id is a key (i.e., something in curly braces) we need to keep track of it
          // so that we can perform key substitutions
          // pattern matches one or more characters of any type within curly braces
          Matcher keyMatcher = Pattern.compile("\\{(.+)\\}").matcher(id);
          if (keyMatcher.find()) {
            keysToReplace.add(keyMatcher.group(1));
          }
        }
      }

      // trim off the trailing comma
      idBuffer.deleteCharAt(idBuffer.length() - 1);

      // now do the replacement
      // append to the buffer the matched sequence, substituting out group(1) with the updated ids
      matcher.appendReplacement(
          buffer,
          matcher.group().substring(0, matcher.start(1) - matcher.start())
              + idBuffer.toString()
              + "\"");
    }

    // append the rest of htmlform
    matcher.appendTail(buffer);

    formXmlData = buffer.toString();

    // now recursively handle any keys we have discovered during this substitution
    for (String key : keysToReplace) {
      formXmlData = replaceIdsWithUuidsHelper(formXmlData, key);
    }

    return formXmlData;
  }
  public void controller(
      @RequestParam(value = "patientId", required = false) Patient patient,
      @RequestParam(value = "headerForm") String headerForm,
      @RequestParam(value = "flowsheets") String[] flowsheets,
      @RequestParam(value = "viewOnly", required = false) Boolean viewOnly,
      @RequestParam(value = "requireEncounter", required = false) Boolean requireEncounter,
      UiUtils ui,
      PageModel model,
      @SpringBean("htmlFormEntryService") HtmlFormEntryService htmlFormEntryService,
      @SpringBean("formService") FormService formService,
      @SpringBean("locationService") LocationService locationService,
      @SpringBean("coreResourceFactory") ResourceFactory resourceFactory,
      @InjectBeans PatientDomainWrapper patientDomainWrapper,
      PageRequest pageRequest) {

    patientDomainWrapper.setPatient(patient);
    model.addAttribute("patient", patientDomainWrapper);
    model.addAttribute("headerForm", headerForm);
    model.addAttribute("flowsheets", flowsheets);
    model.addAttribute("requireEncounter", (requireEncounter == null || requireEncounter));

    Location defaultLocation = null;
    Integer locationId =
        pageRequest
            .getSession()
            .getAttribute(PihMalawiWebConstants.SESSION_LOCATION_ID, Integer.TYPE);
    if (locationId != null) {
      defaultLocation = locationService.getLocation(locationId);
    }

    List<Encounter> allEncounters = new ArrayList<Encounter>();

    List<String> alerts = new ArrayList<String>();

    String headerFormResource = "pihmalawi:htmlforms/" + headerForm + ".xml";

    HtmlForm headerHtmlForm =
        getHtmlFormFromResource(
            headerFormResource, resourceFactory, formService, htmlFormEntryService);
    model.addAttribute("headerForm", headerForm);

    Encounter headerEncounter = null;
    List<Encounter> headerEncounters = getEncountersForForm(patient, headerHtmlForm);
    if (headerEncounters.size() > 0) {
      headerEncounter = headerEncounters.get(headerEncounters.size() - 1); // Most recent
      if (headerEncounters.size() > 1) {
        alerts.add(
            "WARNING:  More than one "
                + headerHtmlForm.getName()
                + " encounters exist for this patient.  Displaying the most recent only.");
      }
      allEncounters.add(headerEncounter);
    }
    model.addAttribute("headerEncounter", headerEncounter);

    Map<String, HtmlForm> flowsheetForms = new LinkedHashMap<String, HtmlForm>();
    Map<String, List<Integer>> flowsheetEncounters = new LinkedHashMap<String, List<Integer>>();
    if (flowsheets != null) {
      for (String flowsheet : flowsheets) {
        String flowsheetResource = "pihmalawi:htmlforms/" + flowsheet + ".xml";
        HtmlForm htmlForm =
            getHtmlFormFromResource(
                flowsheetResource, resourceFactory, formService, htmlFormEntryService);
        flowsheetForms.put(flowsheet, htmlForm);
        List<Integer> encIds = new ArrayList<Integer>();
        List<Encounter> encounters = getEncountersForForm(patient, htmlForm);
        for (Encounter e : encounters) {
          encIds.add(e.getEncounterId());
          allEncounters.add(e);
        }
        flowsheetEncounters.put(flowsheet, encIds);
      }
    }
    model.addAttribute("flowsheetForms", flowsheetForms);
    model.addAttribute("flowsheetEncounters", flowsheetEncounters);

    model.addAttribute("alerts", alerts);

    if (defaultLocation == null) {
      Date maxDate = null;
      if (allEncounters.size() > 0) {
        for (Encounter e : allEncounters) {
          if (maxDate == null || maxDate.compareTo(e.getEncounterDatetime()) < 0) {
            maxDate = e.getEncounterDatetime();
            defaultLocation = e.getLocation();
          }
        }
      }
    }
    model.addAttribute(
        "defaultLocationId", defaultLocation == null ? null : defaultLocation.getLocationId());
    model.addAttribute("viewOnly", viewOnly == Boolean.TRUE);

    model.addAttribute(
        "returnUrl",
        ui.pageLink(
            "pihmalawi",
            "mastercard",
            SimpleObject.create(
                "patientId",
                patient.getId(),
                "headerForm",
                headerForm,
                "flowsheets",
                flowsheets,
                "viewOnly",
                viewOnly)));
  }
 public LocationMock(Location loc) {
   setAddress1(loc.getAddress1());
   setAddress2(loc.getAddress2());
   setChangedBy(loc.getChangedBy());
   setChildLocations(loc.getChildLocations(true));
   setCityVillage(loc.getCityVillage());
   setCountry(loc.getCountry());
   setCountyDistrict(loc.getCountyDistrict());
   setCreator(loc.getCreator());
   setDateChanged(loc.getDateChanged());
   setDateCreated(loc.getDateCreated());
   setDateRetired(loc.getDateRetired());
   setDescription(loc.getDescription());
   setId(loc.getId());
   setLatitude(loc.getLatitude());
   setLongitude(loc.getLongitude());
   setName(loc.getName());
   setNeighborhoodCell(loc.getNeighborhoodCell());
   setParentLocation(loc.getParentLocation());
   setPostalCode(loc.getPostalCode());
   setRegion(loc.getRegion());
   setRetired(loc.getRetired());
   setRetiredBy(loc.getRetiredBy());
   setRetireReason(loc.getRetireReason());
   setStateProvince(loc.getStateProvince());
   setSubregion(loc.getSubregion());
   setTags(loc.getTags());
   setTownshipDivision(loc.getTownshipDivision());
   setUuid(loc.getUuid());
 }
  @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);
  }
 public boolean isInRegion(String region) {
   return location != null && location.getRegion().trim().equals(region);
 }
 public String name() {
   return location.getName();
 }
  @Test
  public void testWristBandTemplate() {

    Date today = new Date();

    visitLocation.setName("Hôpital Universitaire de Mirebalais");

    Patient patient = new Patient();
    patient.setGender("M");
    patient.setBirthdate(new DateTime(1940, 7, 7, 5, 5, 5).toDate());

    PatientIdentifier primaryIdentifier = new PatientIdentifier();
    primaryIdentifier.setIdentifier("ZL1234");
    primaryIdentifier.setIdentifierType(primaryIdentifierType);
    primaryIdentifier.setVoided(false);
    patient.addIdentifier(primaryIdentifier);

    PatientIdentifier paperRecordIdentifier = new PatientIdentifier();
    paperRecordIdentifier.setIdentifier("A000005");
    paperRecordIdentifier.setIdentifierType(paperRecordIdentifierType);
    paperRecordIdentifier.setVoided(false);
    paperRecordIdentifier.setLocation(visitLocation);
    patient.addIdentifier(paperRecordIdentifier);

    PersonAddress address = new PersonAddress();
    address.setAddress2("Avant Eglise Chretienne des perlerlerin de la siant tete de moliere");
    address.setAddress1("Saut D'Eau");
    address.setAddress3("1ere Riviere Canot");
    address.setCityVillage("Saut d'Eau");
    address.setStateProvince("Centre");
    patient.addAddress(address);

    PersonName name = new PersonName();
    name.setGivenName("Ringo");
    name.setFamilyName("Starr");
    patient.addName(name);

    when(messageSourceService.getMessage(
            "coreapps.ageYears", Collections.singletonList(patient.getAge()).toArray(), locale))
        .thenReturn("75 an(s)");

    String output = wristbandTemplate.generateWristband(patient, visitLocation);

    assertThat(output, containsString("^XA^CI28^MTD^FWB"));
    assertThat(
        output,
        containsString(
            "^FO050,200^FB2150,1,0,L,0^AS^FDHôpital Universitaire de Mirebalais "
                + df.format(today)
                + "^FS"));
    assertThat(output, containsString("^FO100,200^FB2150,1,0,L,0^AU^FDRingo Starr^FS"));
    assertThat(output, containsString("^FO160,200^FB2150,1,0,L,0^AU^FD07 juil. 1940^FS"));
    assertThat(
        output, containsString("^FO160,200^FB1850,1,0,L,0^AT^FD" + patient.getAge() + " an(s)^FS"));
    assertThat(output, containsString("^FO160,200^FB1650,1,0,L,0^AU^FDMasculin  A 000005^FS"));
    assertThat(
        output,
        containsString(
            "^FO220,200^FB2150,1,0,L,0^AS^FDAvant Eglise Chretienne des perlerlerin de la siant tete de moliere^FS"));
    assertThat(
        output,
        containsString(
            "^FO270,200^FB2150,1,0,L,0^AS^FDSaut D'Eau, 1ere Riviere Canot, Saut d'Eau, Centre^FS"));
    assertThat(output, containsString("^FO100,2400^AT^BY4^BC,150,N^FDZL1234^XZ"));
  }
  /**
   * @see CohortDefinitionEvaluator#evaluateCohort(CohortDefinition, EvaluationContext)
   * @should return patients who have identifiers of the passed types
   * @should return patients who have identifiers matching the passed locations
   * @should return patients who have identifiers matching the passed text
   * @should return patients who have identifiers matching the passed regular expression
   */
  public EvaluatedCohort evaluate(CohortDefinition cohortDefinition, EvaluationContext context) {

    PatientIdentifierCohortDefinition picd = (PatientIdentifierCohortDefinition) cohortDefinition;

    StringBuilder hql = new StringBuilder();
    Map<String, Object> params = new HashMap<String, Object>();

    hql.append("select 	patient.patientId");

    hql.append(ObjectUtil.notNull(picd.getRegexToMatch()) ? ", identifier " : " ");

    hql.append("from	PatientIdentifier ");
    hql.append("where	voided = false ");

    if (picd.getTypesToMatch() != null) {
      Set<Integer> typeIds = new HashSet<Integer>();
      for (PatientIdentifierType t : picd.getTypesToMatch()) {
        typeIds.add(t.getPatientIdentifierTypeId());
      }
      hql.append("and identifierType.patientIdentifierTypeId in (:idTypes) ");
      params.put("idTypes", typeIds);
    }

    if (picd.getLocationsToMatch() != null) {
      Set<Integer> locationIds = new HashSet<Integer>();
      for (Location l : picd.getLocationsToMatch()) {
        locationIds.add(l.getLocationId());
      }
      hql.append("and location.locationId in (:locationIds) ");
      params.put("locationIds", locationIds);
    }

    if (ObjectUtil.notNull(picd.getTextToMatch())) {
      if (picd.getTextToMatch().contains("%")) {
        hql.append("and identifier like :textToMatch ");
      } else {
        hql.append("and identifier = :textToMatch ");
      }
      params.put("textToMatch", picd.getTextToMatch());
    }

    List<Object> results =
        Context.getService(DataSetQueryService.class).executeHqlQuery(hql.toString(), params);
    EvaluatedCohort ret = new EvaluatedCohort(null, picd, context);

    if (ObjectUtil.notNull(
        picd.getRegexToMatch())) { // Query will return an array containing patientId and identifier
      for (Object o : results) {
        Object[] row = (Object[]) o;
        if (row.length == 2
            && row[1] != null
            && row[1].toString().matches(picd.getRegexToMatch())) {
          ret.addMember((Integer) row[0]);
        }
      }
    } else { // Query returns only a patientId
      for (Object o : results) {
        ret.addMember((Integer) o);
      }
    }

    return ret;
  }
  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;
  }