/**
  * Gets the specified visit type
  *
  * @param uuid the uuid
  * @return the visit type
  * @throws IllegalArgumentException if no such visit type exists
  */
 public static VisitType getVisitType(String uuid) {
   VisitType ret = Context.getVisitService().getVisitTypeByUuid(uuid);
   if (ret == null) {
     throw new IllegalArgumentException("No such visit type with identifier " + uuid);
   }
   return ret;
 }
  /** @see {@link ExistingOrNewVisitAssignmentHandler#beforeCreateEncounter(Encounter)} */
  @Test
  @Verifies(
      value = "should resolve encounter and visit type uuids as global property values",
      method = "beforeCreateEncounter(Encounter)")
  public void beforeCreateEncounter_shouldResolveEncounterAndVisitTypeUuidsAsGlobalPropertyValues()
      throws Exception {
    final String encounterTypeUuid = "759799ab-c9a5-435e-b671-77773ada74e4";
    final String visitTypeUuid = "c0c579b0-8e59-401d-8a4a-976a0b183519";
    Encounter encounter = Context.getEncounterService().getEncounter(1);
    Assert.assertNull(encounter.getVisit());
    Assert.assertEquals(encounterTypeUuid, encounter.getEncounterType().getUuid());

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(encounter.getEncounterDatetime());
    calendar.set(Calendar.YEAR, 1900);

    encounter.setEncounterDatetime(calendar.getTime());

    GlobalProperty gp =
        new GlobalProperty(
            OpenmrsConstants.GP_ENCOUNTER_TYPE_TO_VISIT_TYPE_MAPPING,
            encounterTypeUuid + ":" + visitTypeUuid);
    Context.getAdministrationService().saveGlobalProperty(gp);

    new ExistingOrNewVisitAssignmentHandler().beforeCreateEncounter(encounter);

    Assert.assertNotNull(encounter.getVisit());

    // should be set according toencounterTypeUuid:visitTypeUuid
    Assert.assertEquals(1, encounter.getEncounterType().getEncounterTypeId().intValue());
    Assert.assertEquals(
        Context.getVisitService().getVisitTypeByUuid(visitTypeUuid),
        encounter.getVisit().getVisitType());
  }
  /** @see {@link ExistingVisitAssignmentHandler#beforeCreateEncounter(Encounter)} */
  @Test
  @Verifies(
      value = "should assign mapping global property visit type",
      method = "beforeCreateEncounter(Encounter)")
  public void beforeCreateEncounter_shouldAssignMappingGlobalPropertyVisitType() throws Exception {
    Encounter encounter = Context.getEncounterService().getEncounter(1);
    Assert.assertNull(encounter.getVisit());

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(encounter.getEncounterDatetime());
    calendar.set(Calendar.YEAR, 1900);

    encounter.setEncounterDatetime(calendar.getTime());

    GlobalProperty gp =
        new GlobalProperty(
            OpenmrsConstants.GP_ENCOUNTER_TYPE_TO_VISIT_TYPE_MAPPING, "3:4, 5:2, 1:2, 2:2");
    Context.getAdministrationService().saveGlobalProperty(gp);

    new ExistingOrNewVisitAssignmentHandler().beforeCreateEncounter(encounter);

    Assert.assertNotNull(encounter.getVisit());

    // should be set according to: 1:2 encounterTypeId:visitTypeId
    Assert.assertEquals(1, encounter.getEncounterType().getEncounterTypeId().intValue());
    Assert.assertEquals(
        Context.getVisitService().getVisitType(2), encounter.getVisit().getVisitType());
  }
  @Override
  public Encounter transferEncounter(Encounter encounter, Patient patient) {
    Encounter encounterCopy = encounter.copyAndAssignToAnotherPatient(patient);

    voidEncounter(encounter, "transfer to patient: id = " + patient.getId());

    // void visit if voided encounter is the only one
    Visit visit = encounter.getVisit();
    if (visit != null && visit.getEncounters().size() == 1) {
      Context.getVisitService().voidVisit(visit, "Visit does not contain non-voided encounters");
    }

    return saveEncounter(encounterCopy);
  }
  /** @see {@link ExistingVisitAssignmentHandler#beforeCreateEncounter(Encounter)} */
  @Test
  @Verifies(
      value = "should assign first visit type if mapping global property is not set",
      method = "beforeCreateEncounter(Encounter)")
  public void beforeCreateEncounter_shouldAssignFirstVisitTypeIfMappingGlobalPropertyIsNotSet()
      throws Exception {
    VisitType visitType = Context.getVisitService().getAllVisitTypes().get(0);

    Encounter encounter = Context.getEncounterService().getEncounter(1);
    Assert.assertNull(encounter.getVisit());

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(encounter.getEncounterDatetime());
    calendar.set(Calendar.YEAR, 1900);

    encounter.setEncounterDatetime(calendar.getTime());

    new ExistingOrNewVisitAssignmentHandler().beforeCreateEncounter(encounter);

    Assert.assertNotNull(encounter.getVisit());
    Assert.assertEquals(visitType, encounter.getVisit().getVisitType());
  }
 public void addMetadata() {
   {
     EncounterType et = Context.getEncounterService().getEncounterType("Registration");
     if (et == null)
       et =
           Context.getEncounterService()
               .getEncounterTypeByUuid("cfe614d5-fa7e-4919-b76b-a66117f57e4c");
     if (et == null) {
       et = new EncounterType("Registration", "Patient seen at registration desk");
       et.setUuid("cfe614d5-fa7e-4919-b76b-a66117f57e4c");
       Context.getEncounterService().saveEncounterType(et);
       log.info("Created new Registration encounter type: " + et);
     }
     PrimaryCareConstants.ENCOUNTER_TYPE_REGISTRATION = et;
   }
   {
     EncounterType et = Context.getEncounterService().getEncounterType("Vitals");
     if (et == null)
       et =
           Context.getEncounterService()
               .getEncounterTypeByUuid("daf32375-d293-4e27-a68d-2a58494c96e1");
     if (et == null) {
       et = new EncounterType("Vitals", "Patient vital signs taken before seeing clinician");
       et.setUuid("daf32375-d293-4e27-a68d-2a58494c96e1");
       Context.getEncounterService().saveEncounterType(et);
       log.info("Created new Vitals encounter type: " + et);
     }
     PrimaryCareConstants.ENCOUNTER_TYPE_VITALS = et;
   }
   {
     EncounterType et = Context.getEncounterService().getEncounterType("Diagnosis");
     if (et == null)
       et =
           Context.getEncounterService()
               .getEncounterTypeByUuid("e9355a6e-b2df-44b4-911c-104c6a41ed24");
     if (et == null) {
       et = new EncounterType("Diagnosis", "Diagnosis recorded");
       et.setUuid("e9355a6e-b2df-44b4-911c-104c6a41ed24");
       Context.getEncounterService().saveEncounterType(et);
       log.info("Created new Diagnosis encounter type: " + et);
     }
     PrimaryCareConstants.ENCOUNTER_TYPE_DIAGNOSIS = et;
   }
   {
     Privilege p = Context.getUserService().getPrivilege("Print Registration Barcodes Offline");
     if (p == null) {
       p =
           new Privilege(
               "Print Registration Barcodes Offline",
               "Allows a user to print registration barcodes offline.");
       p.setRetired(false);
       p.setUuid("c733a17e-bf39-4aba-a1b4-06aa013b7c49");
       Context.getUserService().savePrivilege(p);
       log.info("Created new Privilege" + p.getPrivilege());
     }
     PrimaryCareConstants.PRINT_BARCODE_OFFLINE_PRIVILEGE = p;
   }
   {
     Privilege p =
         Context.getUserService().getPrivilege("Generate Bulk Primary Care Ids All Locations");
     if (p == null) {
       p =
           new Privilege(
               "Generate Bulk Primary Care Ids All Locations",
               "Allows a user to generate a csv of primary care ids for any registered location.");
       p.setRetired(false);
       p.setUuid("1149b78f-9964-4bf6-ac19-c01a4c268879");
       Context.getUserService().savePrivilege(p);
       log.info("Created new Privilege" + p.getPrivilege());
     }
     PrimaryCareConstants.GENERATE_BULK_PRIMARY_CARE_IDS = p;
   }
   {
     EncounterRole er =
         Context.getEncounterService()
             .getEncounterRoleByUuid("e8a0fb6a-aba5-11e1-b9e7-002713655c9f");
     if (er == null) {
       er = new EncounterRole();
       er.setDescription(
           "This role represents primrary care registration during a primary care registration encounter.");
       er.setName("Primary Care Registration Recorder");
       er.setUuid("e8a0fb6a-aba5-11e1-b9e7-002713655c9f");
       // this is for openmrs1.9.  Awful.
       er.setCreator(
           Context.getEncounterService()
               .getEncounterRoleByUuid(EncounterRole.UNKNOWN_ENCOUNTER_ROLE_UUID)
               .getCreator());
       er.setDateCreated(new Date());
       er.setRetired(false);
       Context.getEncounterService().saveEncounterRole(er);
       log.info("Created Encounter Role representing primary care registration");
     }
     PrimaryCareConstants.PRIMARY_CARE_ENCOUNTER_ROLE = er;
   }
   {
     VisitType vt =
         Context.getVisitService().getVisitTypeByUuid("3515b588-b1df-4110-991b-0d603686d8e6");
     if (vt == null) {
       vt = new VisitType();
       vt.setCreator(
           Context.getEncounterService()
               .getEncounterRoleByUuid(EncounterRole.UNKNOWN_ENCOUNTER_ROLE_UUID)
               .getCreator()); // hack
       vt.setDateCreated(new Date());
       vt.setDescription("Represents a single day primary care visit to a health center.");
       vt.setName("Primary Care Outpatient");
       vt.setRetired(false);
       vt.setUuid("3515b588-b1df-4110-991b-0d603686d8e6");
       vt = Context.getVisitService().saveVisitType(vt);
       log.info("Created primary care outpatient visit type");
     }
     PrimaryCareConstants.VISIT_TYPE_OUTPATIENT = vt;
   }
 }
  /** @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;
  }
 @Before
 public void before() throws Exception {
   service = Context.getVisitService();
   controller = new VisitAttributeTypeController();
   executeDataSet(Rest19ExtTestConstants.TEST_DATASET);
 }
  /**
   * @see
   *     org.springframework.web.servlet.mvc.SimpleFormController#referenceData(javax.servlet.http.HttpServletRequest,
   *     java.lang.Object, org.springframework.validation.Errors)
   */
  @Override
  protected Map<String, Object> referenceData(HttpServletRequest request, Object obj, Errors error)
      throws Exception {

    Encounter encounter = (Encounter) obj;

    // the generic returned key-value pair mapping
    Map<String, Object> map = new HashMap<String, Object>();

    // obsIds of obs that were edited
    List<Integer> editedObs = new Vector<Integer>();

    // the map returned to the form
    // This is a mapping between the formfield and a list of the Obs/ObsGroup in that field
    // This mapping is sorted according to the comparator in FormField.java
    SortedMap<FormField, List<Obs>> obsMapToReturn = null;
    String sortType =
        Context.getAdministrationService()
            .getGlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_ENCOUNTER_FORM_OBS_SORT_ORDER);
    if ("weight".equals(sortType)) {
      obsMapToReturn = new TreeMap<FormField, List<Obs>>(); // use FormField.compareTo
    } else {
      obsMapToReturn =
          new TreeMap<FormField, List<Obs>>(
              new NumberingFormFieldComparator()); // use custom comparator
    }

    // this maps the obs to form field objects for non top-level obs
    // it is keyed on obs so that when looping over an exploded obsGroup
    // the formfield can be fetched easily (in order to show the field numbers etc)
    Map<Obs, FormField> otherFormFields = new HashMap<Obs, FormField>();

    if (Context.isAuthenticated()) {
      EncounterService es = Context.getEncounterService();
      FormService fs = Context.getFormService();

      // used to restrict the form field lookup
      Form form = encounter.getForm();

      List<EncounterType> encTypes = es.getAllEncounterTypes();
      // Non-retired types first
      Collections.sort(encTypes, new MetadataComparator(Context.getLocale()));
      map.put("encounterTypes", encTypes);

      map.put("encounterRoles", es.getAllEncounterRoles(false));
      map.put("forms", Context.getFormService().getAllForms());
      // loop over the encounter's observations to find the edited obs
      for (Obs o : encounter.getObsAtTopLevel(true)) {

        // only edited obs has previous version
        if (o.hasPreviousVersion()) {
          editedObs.add(o.getObsId());
        }

        // get the formfield for this obs
        FormField ff = fs.getFormField(form, o.getConcept(), obsMapToReturn.keySet(), false);
        if (ff == null) {
          ff = new FormField();
        }

        // we only put the top-level obs in the obsMap.  Those would
        // be the obs that don't have an obs grouper
        if (o.getObsGroup() == null) {
          // populate the obs map with this formfield and obs
          List<Obs> list = obsMapToReturn.get(ff);
          if (list == null) {
            list = new Vector<Obs>();
            obsMapToReturn.put(ff, list);
          }
          list.add(o);
        } else {
          // this is not a top-level obs, just put the formField
          // in a separate list and be done with it
          otherFormFields.put(o, ff);
        }
      }
    }

    if (log.isDebugEnabled()) {
      log.debug("setting obsMap in page context (size: " + obsMapToReturn.size() + ")");
    }
    map.put("obsMap", obsMapToReturn);

    map.put("otherFormFields", otherFormFields);

    map.put("locale", Context.getLocale());
    map.put("editedObs", editedObs);
    if (encounter.getPatient() != null) {
      map.put(
          "patientVisits", Context.getVisitService().getVisitsByPatient(encounter.getPatient()));
    }

    return map;
  }