@RequestMapping("/module/hirifxray/createParticipant.form")
  public String createParticipant(
      ModelMap model,
      @RequestParam(value = "identifier", required = true) String identifier,
      @RequestParam(value = "gender", required = true) String gender)
      throws Exception {

    Patient p = new Patient();

    PersonName pn = new PersonName();
    pn.setGivenName("XXXX");
    pn.setFamilyName("XXXX");
    p.addName(pn);

    p.setGender(gender);

    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    p.setBirthdate(df.parse("1900-01-01"));

    PatientIdentifier pi = new PatientIdentifier();
    pi.setPatient(p);
    pi.setLocation(HirifMetadata.getUnknownLocation());
    pi.setIdentifierType(HirifMetadata.getIdentifierType());
    pi.setIdentifier(identifier);
    p.addIdentifier(pi);

    p = Context.getPatientService().savePatient(p);

    return "redirect:/module/hirifxray/participant.form?id=" + p.getPatientId();
  }
  @Test
  public void testSimplify() throws Exception {
    PersonName name = new PersonName();
    name.setGivenName("Barack");
    name.setFamilyName("Obama");

    PatientIdentifierType pit = new PatientIdentifierType();
    pit.setName("US President Number");

    Patient patient = new Patient();
    patient.setPatientId(44);
    patient.addName(name);
    patient.setGender("M");
    patient.setBirthdate(new SimpleDateFormat("yyyy-MM-dd").parse("1961-08-04"));
    patient.addIdentifier(new PatientIdentifier("44", pit, new Location()));

    EmrApiProperties emrApiProperties = mock(EmrApiProperties.class);
    when(emrApiProperties.getPrimaryIdentifierType()).thenReturn(pit);

    TestUiUtils ui = new TestUiUtils();
    SimpleObject o = new FindPatientFragmentController().simplify(ui, emrApiProperties, patient);

    assertEquals("Barack", PropertyUtils.getProperty(o, "preferredName.givenName"));
    assertNull(PropertyUtils.getProperty(o, "preferredName.middleName"));
    assertEquals("Obama", PropertyUtils.getProperty(o, "preferredName.familyName"));
    assertEquals("Barack Obama", PropertyUtils.getProperty(o, "preferredName.fullName"));
    assertEquals("04.Aug.1961", PropertyUtils.getProperty(o, "birthdate"));
    assertEquals(Boolean.FALSE, PropertyUtils.getProperty(o, "birthdateEstimated"));
    assertEquals("M", PropertyUtils.getProperty(o, "gender"));

    Object primaryIdentifier = ((List) o.get("primaryIdentifiers")).get(0);
    assertThat((String) PropertyUtils.getProperty(primaryIdentifier, "identifier"), is("44"));
  }
 /**
  * Creates a new person stub.
  *
  * @param given
  * @param middle
  * @param family
  * @param birthdate
  * @param dateformat
  * @param age
  * @param gender
  * @return PersonListItem person stub created
  */
 public Object createPerson(
     String given,
     String middle,
     String family,
     String birthdate,
     String dateformat,
     String age,
     String gender) {
   log.error(
       given
           + " "
           + middle
           + " "
           + family
           + " "
           + birthdate
           + " "
           + dateformat
           + " "
           + age
           + " "
           + gender);
   User user = Context.getAuthenticatedUser();
   Person p = new Person();
   p.setPersonCreator(user);
   p.setPersonDateCreated(new Date());
   p.setPersonChangedBy(user);
   p.setPersonDateChanged(new Date());
   if (StringUtils.isEmpty(gender)) {
     log.error("Gender cannot be null.");
     return String.valueOf("Gender cannot be null.");
   } else if (gender.toUpperCase().contains("M")) {
     p.setGender("M");
   } else if (gender.toUpperCase().contains("F")) {
     p.setGender("F");
   } else {
     log.error("Gender must be 'M' or 'F'.");
     return new String("Gender must be 'M' or 'F'.");
   }
   if ("".equals(given) || "".equals(family)) {
     log.error("Given name and family name cannot be null.");
     return new String("Given name and family name cannot be null.");
   }
   PersonName name = new PersonName(given, middle, family);
   name.setCreator(user);
   name.setDateCreated(new Date());
   name.setChangedBy(user);
   name.setDateChanged(new Date());
   p.addName(name);
   try {
     Date d = updateAge(birthdate, dateformat, age);
     p.setBirthdate(d);
   } catch (java.text.ParseException pe) {
     log.error(pe);
     return new String("Birthdate cannot be parsed.");
   }
   p.setGender(gender);
   Person person = Context.getPersonService().savePerson(p);
   return PersonListItem.createBestMatch(person);
 }
  /**
   * Encodes a list of queue items into JSON text
   *
   * @param items
   * @return
   */
  public static StringBuffer encode(List items) {
    StringBuffer json = new StringBuffer();
    Iterator itr = items.iterator();
    Calendar current = Calendar.getInstance();
    current.get(Calendar.DATE);
    if (items.size() <= 0) json.append("{}");
    else {
      while (itr.hasNext()) {
        QueueItem it = (QueueItem) itr.next();
        PersonName name = it.patient.getPersonName();
        json.append("{");

        json.append("\"status\":\"").append(it.status).append("\",");
        json.append("\"patientIdentifier\":\"")
            .append(it.patient.getPatientIdentifier())
            .append("\",");
        json.append("\"Procedure\":\"").append(it.getProcedureTitle()).append("\",");
        json.append("\"age\":\"").append(it.patient.getAge(null)).append("\",");
        json.append("\"sex\":\"").append(it.patient.getGender()).append("\",");
        json.append("\"dateCreated\":\"").append(it.dateCreated).append("\",");
        json.append("\"name\":{");
        boolean hasContent = addOptionalElement(json, "prefix", name.getPrefix());
        hasContent |= addOptionalElement(json, "givenName", name.getGivenName());
        hasContent |= addOptionalElement(json, "familyName", name.getFamilyName());
        if (hasContent)
          json.deleteCharAt(json.length() - 1); // delete last comma if at least something was added
        json.append("}");
        json.append(",\"patientId\":\"").append(it.patient.getPatientId()).append("\",");
        json.append("\"encounterId\":\"").append(it.encounter.getEncounterId()).append("\"");
        json.append("},");
      }
      json.deleteCharAt(json.length() - 1);
    }
    return json;
  }
  @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"));
  }
 private void voidEarlierNames(Patient patient, int oldNumberOfNames, int newNumberOfNames) {
   if (newNumberOfNames > oldNumberOfNames) {
     for (PersonName name : patient.getNames()) {
       if (name.getId() != null) {
         name.setVoided(true);
       }
     }
   }
 }
 public PersonName getPersonName() {
   // normally the DAO layer returns these in the correct order, i.e. preferred and non-voided
   // first, but it's possible that someone
   // has fetched a Person, changed their names around, and then calls this method, so we have to
   // be careful.
   if (getNames() != null && getNames().size() > 0) {
     for (PersonName name : getNames()) {
       if (name.isPreferred() && !name.isVoided()) return name;
     }
     for (PersonName name : getNames()) {
       if (!name.isVoided()) return name;
     }
     return null;
   }
   return null;
 }
  /** @see ShortPatientFormValidator#validate(Object,Errors) */
  @Test
  @Verifies(value = "should reject a duplicate name", method = "validate(Object,Errors)")
  public void validate_shouldRejectADuplicateName() throws Exception {
    Patient patient = ps.getPatient(7);
    PersonName oldName = patient.getPersonName();
    Assert.assertEquals(1, patient.getNames().size()); // sanity check
    // add a name for testing purposes
    PersonName name = new PersonName("my", "duplicate", "name");
    patient.addName(name);
    Context.getPatientService().savePatient(patient);
    Assert.assertNotNull(name.getId()); // should have been added

    ShortPatientModel model = new ShortPatientModel(patient);
    // should still be the preferred name for the test to pass
    Assert.assertEquals(oldName.getId(), model.getPersonName().getId());
    // change to a duplicate name
    model.getPersonName().setGivenName("My"); // should be case insensitive
    model.getPersonName().setMiddleName("duplicate");
    model.getPersonName().setFamilyName("name");

    Errors errors = new BindException(model, "patientModel");
    validator.validate(model, errors);
    Assert.assertEquals(true, errors.hasErrors());
  }
 private Patient getMrsPatient(org.openmrs.Patient savedPatient) {
   final List<Attribute> attributes =
       project(
           savedPatient.getAttributes(),
           Attribute.class,
           on(PersonAttribute.class).getAttributeType().toString(),
           on(PersonAttribute.class).getValue());
   PersonName firstName = patientHelper.getFirstName(savedPatient);
   final PatientIdentifier patientIdentifier = savedPatient.getPatientIdentifier();
   return new Patient(
       String.valueOf(savedPatient.getId()),
       firstName.getGivenName(),
       firstName.getMiddleName(),
       firstName.getFamilyName(),
       patientHelper.getPreferredName(savedPatient),
       savedPatient.getBirthdate(),
       savedPatient.getBirthdateEstimated(),
       savedPatient.getGender(),
       patientHelper.getAddress(savedPatient),
       attributes,
       (patientIdentifier != null)
           ? facilityAdaptor.convertLocationToFacility(patientIdentifier.getLocation())
           : null);
 }
  /**
   * Validates the given Patient.
   *
   * @param obj The patient to validate.
   * @param errors The patient to validate.
   * @see org.springframework.validation.Validator#validate(java.lang.Object,
   *     org.springframework.validation.Errors)
   * @should pass if the minimum required fields are provided and are valid
   * @should fail validation if gender is blank
   * @should fail validation if birthdate is blank
   * @should fail validation if birthdate makes patient 120 years old or older
   * @should fail validation if birthdate is a future date
   * @should fail validation if causeOfDeath is blank when patient is dead
   * @should fail if all name fields are empty or white space characters
   * @should fail if no identifiers are added
   * @should fail if all identifiers have been voided
   * @should fail if any name has more than 50 characters
   * @should fail validation if deathdate is a future date
   * @should fail if the deathdate is before the birthdate incase the patient is dead
   * @should reject a duplicate name
   * @should reject a duplicate address
   */
  public void validate(Object obj, Errors errors) {
    if (log.isDebugEnabled()) {
      log.debug(
          this.getClass().getName() + ": Validating patient data from the short patient form....");
    }

    ShortPatientModel shortPatientModel = (ShortPatientModel) obj;
    PersonName personName = shortPatientModel.getPersonName();

    // TODO We should be able to let developers and implementations to specify which person name
    // fields should be used to determine uniqueness

    // check if this name has a unique givenName, middleName and familyName combination
    for (PersonName possibleDuplicate : shortPatientModel.getPatient().getNames()) {
      // don't compare the name to itself
      if (OpenmrsUtil.nullSafeEquals(possibleDuplicate.getId(), personName.getId())) {
        continue;
      }

      if (OpenmrsUtil.nullSafeEqualsIgnoreCase(
              possibleDuplicate.getGivenName(), personName.getGivenName())
          && OpenmrsUtil.nullSafeEqualsIgnoreCase(
              possibleDuplicate.getMiddleName(), personName.getMiddleName())
          && OpenmrsUtil.nullSafeEqualsIgnoreCase(
              possibleDuplicate.getFamilyName(), personName.getFamilyName())) {
        errors.reject(
            "Patient.duplicateName",
            new Object[] {personName.getFullName()},
            personName.getFullName() + " is a duplicate name for the same patient");
      }
    }

    Errors nameErrors = new BindException(personName, "personName");
    new PersonNameValidator().validatePersonName(personName, nameErrors, false, true);

    if (nameErrors.hasErrors()) {
      // pick all the personName errors and bind them to the formObject
      Iterator<ObjectError> it = nameErrors.getAllErrors().iterator();
      Set<String> errorCodesWithNoArguments = new HashSet<String>();
      while (it.hasNext()) {
        ObjectError error = it.next();
        // don't show similar error message multiple times in the view
        // unless they take in arguments which will make them atleast different
        if (error.getCode() != null
            && (!errorCodesWithNoArguments.contains(error.getCode())
                || (error.getArguments() != null && error.getArguments().length > 0))) {
          errors.reject(error.getCode(), error.getArguments(), "");
          if (error.getArguments() == null || error.getArguments().length == 0) {
            errorCodesWithNoArguments.add(error.getCode());
          }
        }
      }
      // drop the collection
      errorCodesWithNoArguments = null;
    }

    // TODO We should be able to let developers and implementations to specify which
    // person address fields should be used to determine uniqueness

    // check if this address is unique
    PersonAddress personAddress = shortPatientModel.getPersonAddress();
    for (PersonAddress possibleDuplicate : shortPatientModel.getPatient().getAddresses()) {
      // don't compare the address to itself
      if (OpenmrsUtil.nullSafeEquals(possibleDuplicate.getId(), personAddress.getId())) {
        continue;
      }

      if (!possibleDuplicate.isBlank()
          && !personAddress.isBlank()
          && possibleDuplicate.toString().equalsIgnoreCase(personAddress.toString())) {
        errors.reject(
            "Patient.duplicateAddress",
            new Object[] {personAddress.toString()},
            personAddress.toString() + " is a duplicate address for the same patient");
      }
    }

    if (CollectionUtils.isEmpty(shortPatientModel.getIdentifiers())) {
      errors.reject("PatientIdentifier.error.insufficientIdentifiers");
    } else {
      boolean nonVoidedIdentifierFound = false;
      for (PatientIdentifier pId : shortPatientModel.getIdentifiers()) {
        // no need to validate unsaved identifiers that have been removed
        if (pId.getPatientIdentifierId() == null && pId.isVoided()) {
          continue;
        }

        if (!pId.isVoided()) {
          nonVoidedIdentifierFound = true;
        }

        new PatientIdentifierValidator().validate(pId, errors);
      }
      // if all the names are voided
      if (!nonVoidedIdentifierFound) {
        errors.reject("PatientIdentifier.error.insufficientIdentifiers");
      }
    }

    // Make sure they chose a gender
    if (StringUtils.isBlank(shortPatientModel.getPatient().getGender())) {
      errors.rejectValue("patient.gender", "Person.gender.required");
    }

    // check patients birthdate against future dates and really old dates
    if (shortPatientModel.getPatient().getBirthdate() != null) {
      if (shortPatientModel.getPatient().getBirthdate().after(new Date())) {
        errors.rejectValue("patient.birthdate", "error.date.future");
      } else {
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.YEAR, -120); // patient cannot be older than 120
        // years old
        if (shortPatientModel.getPatient().getBirthdate().before(c.getTime())) {
          errors.rejectValue("patient.birthdate", "error.date.nonsensical");
        }
      }
    } else {
      errors.rejectValue(
          "patient.birthdate",
          "error.required",
          new Object[] {Context.getMessageSourceService().getMessage("Person.birthdate")},
          "");
    }

    // validate the personAddress
    if (shortPatientModel.getPersonAddress() != null) {
      try {
        errors.pushNestedPath("personAddress");
        ValidationUtils.invokeValidator(
            new PersonAddressValidator(), shortPatientModel.getPersonAddress(), errors);
      } finally {
        errors.popNestedPath();
      }
    }

    if (shortPatientModel.getPatient().getDead()) {
      if (shortPatientModel.getPatient().getCauseOfDeath() == null) {
        errors.rejectValue("patient.causeOfDeath", "Person.dead.causeOfDeathNull");
      }

      if (shortPatientModel.getPatient().getDeathDate() != null) {
        if (shortPatientModel.getPatient().getDeathDate().after(new Date())) {
          errors.rejectValue("patient.deathDate", "error.date.future");
        }
        // death date has to be after birthdate if both are specified
        if (shortPatientModel.getPatient().getBirthdate() != null
            && shortPatientModel
                .getPatient()
                .getDeathDate()
                .before(shortPatientModel.getPatient().getBirthdate())) {
          errors.rejectValue("patient.deathDate", "error.deathdate.before.birthdate");
        }
      }
    }
  }
  @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"));
  }
  public EncounterListItem(Encounter encounter) {

    if (encounter != null) {
      encounterId = encounter.getEncounterId();
      encounterDateTime = encounter.getEncounterDatetime();
      encounterDateString = Format.format(encounter.getEncounterDatetime());
      PersonName pn = encounter.getPatient().getPersonName();
      if (pn != null) {
        personName = "";
        if (pn.getGivenName() != null) {
          personName += pn.getGivenName();
        }
        if (pn.getMiddleName() != null) {
          personName += " " + pn.getMiddleName();
        }
        if (pn.getFamilyName() != null) {
          personName += " " + pn.getFamilyName();
        }
      }
      if (encounter.getProvider() != null) {
        providerName = encounter.getProvider().getPersonName().getFullName();
      }
      if (encounter.getLocation() != null) {
        location = encounter.getLocation().getName();
      }
      if (encounter.getEncounterType() != null) {
        encounterType = encounter.getEncounterType().getName();
      }
      if (encounter.getForm() != null) {
        formName = encounter.getForm().getName();
        formId = encounter.getForm().getFormId();
      }
      voided = encounter.isVoided();
      if (encounter.getCreator() != null) {
        PersonName entererPersonName = encounter.getCreator().getPersonName();
        if (entererPersonName != null) {
          entererName = "";
          if (entererPersonName.getGivenName() != null) {
            entererName += entererPersonName.getGivenName();
          }
          if (entererPersonName.getMiddleName() != null) {
            entererName += " " + entererPersonName.getMiddleName();
          }
          if (entererPersonName.getFamilyName() != null) {
            entererName += " " + entererPersonName.getFamilyName();
          }
        }
      }
    }
  }