/** @see org.openmrs.module.web.extension.AdministrationSectionExt#getLinks() */
  @Override
  public Map<String, String> getLinks() {
    Map<String, String> map = new LinkedHashMap<String, String>();

    if (Context.hasPrivilege(ReportingConstants.PRIV_RUN_REPORTS)) {
      map.put("module/amrsreports/mohRender.form", "Run AMRS Reports");
    }

    if (Context.hasPrivilege(ReportingConstants.PRIV_VIEW_REPORTS)) {
      map.put("module/amrsreports/mohHistory.form", "View AMRS Reports");
    }

    if (Context.hasPrivilege(PrivilegeConstants.VIEW_LOCATIONS)) {
      map.put("module/amrsreports/facility.list", "View MOH Facilities");
    }

    if (Context.hasPrivilege(ReportingConstants.PRIV_RUN_REPORTS)) {
      map.put("/module/amrsreports/cohortCounts.list", "View Cohort Counts");
    }

    if (Context.hasPrivilege(ReportingConstants.PRIV_RUN_REPORTS)) {
      map.put("module/amrsreports/locationPrivileges.form", "Location Privileges");
    }

    map.put("module/amrsreports/settings.form", "Settings");

    return map;
  }
  /**
   * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
   *     javax.servlet.http.HttpServletResponse)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String obsId = request.getParameter("obsId");
    String view = request.getParameter("view");
    String viewType = request.getParameter("viewType");

    HttpSession session = request.getSession();

    if (obsId == null || obsId.length() == 0) {
      session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "error.null");
      return;
    }
    if (!Context.hasPrivilege(OpenmrsConstants.PRIV_VIEW_OBS)) {
      session.setAttribute(
          WebConstants.OPENMRS_ERROR_ATTR, "Privilege required: " + OpenmrsConstants.PRIV_VIEW_OBS);
      session.setAttribute(
          WebConstants.OPENMRS_LOGIN_REDIRECT_HTTPSESSION_ATTR,
          request.getRequestURI() + "?" + request.getQueryString());
      response.sendRedirect(request.getContextPath() + "/login.htm");
      return;
    }

    Obs complexObs = Context.getObsService().getComplexObs(Integer.valueOf(obsId), view);
    ComplexData cd = complexObs.getComplexData();
    Object data = cd.getData();

    if ("download".equals(viewType)) {
      response.setHeader("Content-Disposition", "attachment; filename=" + cd.getTitle());
      response.setHeader("Pragma", "no-cache");
    }

    if (data instanceof byte[]) {
      ByteArrayInputStream stream = new ByteArrayInputStream((byte[]) data);
      OpenmrsUtil.copyFile(stream, response.getOutputStream());
    } else if (RenderedImage.class.isAssignableFrom(data.getClass())) {
      RenderedImage img = (RenderedImage) data;
      String[] parts = cd.getTitle().split(".");
      String extension = "jpg"; // default extension
      if (parts.length > 0) {
        extension = parts[parts.length - 1];
      }

      ImageIO.write(img, extension, response.getOutputStream());
    } else if (InputStream.class.isAssignableFrom(data.getClass())) {
      InputStream stream = (InputStream) data;
      OpenmrsUtil.copyFile(stream, response.getOutputStream());
      stream.close();
    } else {
      throw new ServletException(
          "Couldn't serialize complex obs data for obsId=" + obsId + " of type " + data.getClass());
    }
  }
  public Map<String, String> getLinks() {

    Map<String, String> map = new LinkedHashMap<String, String>();

    if (Context.hasPrivilege(IntegrityWorkflowConstants.MANAGE_RECORD_ASSIGNEES)) {
      map.put("/module/dataintegrityworkflow/viewChecks.form", "dataintegrityworkflow.manage.link");
    }
    if (Context.hasPrivilege(IntegrityWorkflowConstants.MANAGE_RECORD_ASSIGNEES)) {
      map.put(
          "/module/dataintegrityworkflow/viewCheckKey.form", "dataintegrityworkflow.change.link");
    }
    if (Context.hasPrivilege(IntegrityWorkflowConstants.VIEW_RECORD_ASSIGNMENTS)) {
      map.put(
          "/module/dataintegrityworkflow/viewAssignedRecords.form",
          "dataintegrityworkflow.view.link");
    }
    if (Context.hasPrivilege(IntegrityWorkflowConstants.MANAGE_RECORD_ASSIGNEES)) {
      map.put(
          "/module/dataintegrityworkflow/addWorkflowStage.form",
          "dataintegrityworkflow.stage.link");
    }
    return map;
  }
Beispiel #4
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);
  }
  /**
   * @see
   *     org.springframework.web.servlet.mvc.SimpleFormController#processFormSubmission(javax.servlet.http.HttpServletRequest,
   *     javax.servlet.http.HttpServletResponse, java.lang.Object,
   *     org.springframework.validation.BindException)
   */
  protected ModelAndView processFormSubmission(
      HttpServletRequest request, HttpServletResponse reponse, Object obj, BindException errors)
      throws Exception {

    Alert alert = (Alert) obj;
    new AlertValidator().validate(obj, errors);

    try {
      // check that the user has the right privileges here because
      // we are giving them a proxy privilege in the line following this
      if (Context.hasPrivilege(PrivilegeConstants.MANAGE_ALERTS) == false)
        throw new APIAuthenticationException("Must be logged in as user with alerts privileges");

      Context.addProxyPrivilege(PrivilegeConstants.VIEW_USERS);

      UserService us = Context.getUserService();

      if (Context.isAuthenticated()) {
        String[] userIdValues = request.getParameter("userIds").split(" ");
        List<Integer> userIds = new Vector<Integer>();
        String[] roleValues = request.getParameter("newRoles").split(",");
        List<String> roles = new Vector<String>();

        // create user list
        if (userIdValues != null)
          for (String userId : userIdValues) {
            if (!userId.trim().equals("")) userIds.add(Integer.valueOf(userId.trim()));
          }

        // create role list
        if (roleValues != null)
          for (String role : roleValues) {
            if (!role.trim().equals("")) roles.add(role.trim());
          }

        // remove all recipients not in the userIds list
        List<AlertRecipient> recipientsToRemove = new Vector<AlertRecipient>();
        if (alert.getRecipients() != null) {
          for (AlertRecipient recipient : alert.getRecipients()) {
            Integer userId = recipient.getRecipient().getUserId();
            if (!userIds.contains(userId)) recipientsToRemove.add(recipient);
          }
        }
        for (AlertRecipient ar : recipientsToRemove) alert.removeRecipient(ar);

        // add all new users
        if (userIds != null) {
          for (Integer userId : userIds) {
            alert.addRecipient(new User(userId));
          }
        }

        // add all new users according to the role(s) selected
        if (roles != null) {
          for (String roleStr : roles) {
            List<User> users = us.getUsersByRole(new Role(roleStr));
            for (User user : users) alert.addRecipient(user);
          }
        }
      }

      if ((alert.getRecipients() == null || alert.getRecipients().size() == 0)) {
        errors.rejectValue("recipients", "Alert.recipientRequired");
      }

    } catch (Exception e) {
      log.error("Error while processing alert form", e);
      errors.reject(e.getMessage());
    } finally {
      Context.removeProxyPrivilege(PrivilegeConstants.VIEW_USERS);
    }

    return super.processFormSubmission(request, reponse, alert, errors);
  }
  public void controller(@FragmentParam("visit") Visit visit, FragmentModel model) {

    model.addAttribute("visit", visit);
    model.addAttribute("sourceForm", new VisitWrapper(visit).getSourceForm());
    model.addAttribute("allowVoid", Context.hasPrivilege(PrivilegeConstants.DELETE_VISITS));
  }
 public boolean hasPrivilege(String privilege) {
   return Context.hasPrivilege(privilege);
 }