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(); } } } } }
private void validateDateActivated(Order order, Errors errors) { Date dateActivated = order.getDateActivated(); if (dateActivated != null) { if (dateActivated.after(new Date())) { errors.rejectValue("dateActivated", "Order.error.dateActivatedInFuture"); return; } Date dateStopped = order.getDateStopped(); if (dateStopped != null && dateActivated.after(dateStopped)) { errors.rejectValue("dateActivated", "Order.error.dateActivatedAfterDiscontinuedDate"); errors.rejectValue("dateStopped", "Order.error.dateActivatedAfterDiscontinuedDate"); } Date autoExpireDate = order.getAutoExpireDate(); if (autoExpireDate != null && dateActivated.after(autoExpireDate)) { errors.rejectValue("dateActivated", "Order.error.dateActivatedAfterAutoExpireDate"); errors.rejectValue("autoExpireDate", "Order.error.dateActivatedAfterAutoExpireDate"); } Encounter encounter = order.getEncounter(); if (encounter != null && encounter.getEncounterDatetime() != null && encounter.getEncounterDatetime().after(dateActivated)) { errors.rejectValue("dateActivated", "Order.error.dateActivatedAfterEncounterDatetime"); } } }
private Date guessVisitStopDatetime(Visit visit) { if (visit.getEncounters() == null || visit.getEncounters().size() == 0) { return visit.getStartDatetime(); } Iterator<Encounter> iterator = visit.getEncounters().iterator(); Encounter latest = iterator.next(); while (iterator.hasNext()) { Encounter candidate = iterator.next(); if (OpenmrsUtil.compare(candidate.getEncounterDatetime(), latest.getEncounterDatetime()) > 0) { latest = candidate; } } return latest.getEncounterDatetime(); }
public void printEncounterCreated() { if (encounterCreated == null) { System.out.println("No encounter created"); } else { System.out.println("=== Encounter created ==="); System.out.println( "Created: " + encounterCreated.getDateCreated() + " Edited: " + encounterCreated.getDateChanged()); System.out.println("Date: " + encounterCreated.getEncounterDatetime()); System.out.println("Location: " + encounterCreated.getLocation().getName()); System.out.println("Provider: " + encounterCreated.getProvider().getPersonName()); System.out.println(" (obs)"); Collection<Obs> obs = encounterCreated.getAllObs(false); if (obs == null) { System.out.println("None"); } else { for (Obs o : obs) { System.out.println( o.getConcept().getName() + " -> " + o.getValueAsString(Context.getLocale())); } } } }
/** @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()); }
/** * * Generates all of the data rows * * @param form * @param extraCols * @param sb * @return * @throws Exception */ public static String generateColumnDataFromHtmlForm(List<Encounter> encounters, HtmlForm form, List<String> extraCols, StringBuffer sb, Locale locale,List<PatientIdentifierType> pitList) throws Exception { for (Encounter e: encounters){ sb.append(DEFAULT_QUOTE).append(e.getEncounterId()).append(DEFAULT_QUOTE).append(DEFAULT_COLUMN_SEPARATOR); sb.append(DEFAULT_QUOTE).append(DATE_FORMATTER.format(e.getEncounterDatetime())).append(DEFAULT_QUOTE).append(DEFAULT_COLUMN_SEPARATOR); sb.append(DEFAULT_QUOTE).append(e.getLocation().getName()).append(DEFAULT_QUOTE).append(DEFAULT_COLUMN_SEPARATOR); sb.append(DEFAULT_QUOTE).append(EncounterCompatibility.getProvider(e).getGivenName()+ " " + EncounterCompatibility.getProvider(e).getFamilyName()).append(DEFAULT_QUOTE).append(DEFAULT_COLUMN_SEPARATOR); sb.append(DEFAULT_QUOTE).append((e.getPatient() != null ? e.getPatient().getPatientId() : EMPTY)).append(DEFAULT_QUOTE).append(DEFAULT_COLUMN_SEPARATOR); int index = 1; for (PatientIdentifierType pit : pitList){ sb.append(DEFAULT_QUOTE).append(e.getPatient().getPatientIdentifier(pit)).append(DEFAULT_QUOTE); if (index < pitList.size()) sb.append(DEFAULT_COLUMN_SEPARATOR); index ++; } FormEntrySession session = new FormEntrySession(e.getPatient(), e, Mode.VIEW, form, null); // session doesn't get HttpSession session.getHtmlToDisplay(); FormSubmissionController fsa = session.getSubmissionController(); List<FormSubmissionControllerAction> actions = fsa.getActions(); for (FormSubmissionControllerAction fsca : actions){ if (fsca instanceof ObsSubmissionElement){ ObsSubmissionElement ose = (ObsSubmissionElement) fsca; sb = appendObsToRow(ose, sb, extraCols, locale); } else { //TODO: add programs, orders, logic, etc... // just make sure these are in the headers too... } } session = null; sb.append(DEFAULT_LINE_SEPARATOR); } return sb.toString(); }
@Test public void shouldCreateNewEncounter() throws Exception { executeDataSet("shouldCreateMatchingEncounter.xml"); String encounterDateTimeString = "2011-05-01T12:10:06.000+0530"; Date encounterDateTime = new SimpleDateFormat(dateTimeFormat).parse(encounterDateTimeString); String json = "{ \"patientUuid\" : \"a76e8d23-0c38-408c-b2a8-ea5540f01b51\", " + "\"visitTypeUuid\" : \"b45ca846-c79a-11e2-b0c0-8e397087571c\", " + "\"encounterDateTime\" : \"" + encounterDateTimeString + "\", " + "\"encounterTypeUuid\": \"2b377dba-62c3-4e53-91ef-b51c68899890\" }"; EncounterTransaction response = deserialize( handle(newPostRequest("/rest/emrapi/encounter", json)), EncounterTransaction.class); assertEquals("1e5d5d48-6b78-11e0-93c3-18a905e044dc", response.getVisitUuid()); Visit visit = visitService.getVisitByUuid(response.getVisitUuid()); assertEquals(1, visit.getEncounters().size()); Encounter encounter = visit.getEncounters().iterator().next(); assertEquals("a76e8d23-0c38-408c-b2a8-ea5540f01b51", encounter.getPatient().getUuid()); assertEquals("2b377dba-62c3-4e53-91ef-b51c68899890", encounter.getEncounterType().getUuid()); assertEquals(encounterDateTime, encounter.getEncounterDatetime()); }
public QueueItem saveQueueItem(QueueItem queueItem) { log.debug("saveQueueItem(). Entering"); boolean isNew = false; Date newDate = queueItem.getEncounter().getEncounterDatetime(); log.debug("Encounter date: " + newDate); Date originalDate = null; if (queueItem.getQueueItemId() == null) { isNew = true; log.debug("Got a new queue item"); } // Not new we update some of the Encounter info if (!isNew) { log.info("Updating previously queued encounter!"); Encounter encounter = queueItem.getEncounter(); Patient p = encounter.getPatient(); originalDate = encounter.getEncounterDatetime(); if (OpenmrsUtil.compare(originalDate, newDate) != 0) { // if the obs datetime is the same as the // original encounter datetime, fix it if (OpenmrsUtil.compare(queueItem.getDateCreated(), originalDate) == 0) { encounter.setEncounterDatetime(newDate); } } // if the Person in the encounter doesn't match the Patient in the , // fix it if (!encounter.getPatient().getPersonId().equals(p.getPatientId())) { encounter.setPatient(p); } for (Obs obs : encounter.getAllObs(true)) { // if the date was changed if (OpenmrsUtil.compare(originalDate, newDate) != 0) { // if the obs datetime is the same as the // original encounter datetime, fix it if (OpenmrsUtil.compare(obs.getObsDatetime(), originalDate) == 0) { obs.setObsDatetime(newDate); } } // 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); } } } log.debug("Saving queu item."); dao.saveQueueItem(queueItem); return queueItem; }
/** @see FormSubmissionControllerAction#handleSubmission(FormEntrySession, HttpServletRequest) */ @Override public void handleSubmission(FormEntrySession session, HttpServletRequest submission) { if (dateWidget != null) { Date date = (Date) dateWidget.getValue(session.getContext(), submission); if (session.getSubmissionActions().getCurrentEncounter().getEncounterDatetime() != null && !session .getSubmissionActions() .getCurrentEncounter() .getEncounterDatetime() .equals(date)) { session .getContext() .setPreviousEncounterDate( new Date( session .getSubmissionActions() .getCurrentEncounter() .getEncounterDatetime() .getTime())); } session.getSubmissionActions().getCurrentEncounter().setEncounterDatetime(date); } if (timeWidget != null) { Date time = (Date) timeWidget.getValue(session.getContext(), submission); Encounter e = session.getSubmissionActions().getCurrentEncounter(); Date dateAndTime = HtmlFormEntryUtil.combineDateAndTime(e.getEncounterDatetime(), time); e.setEncounterDatetime(dateAndTime); } if (providerWidget != null) { Object value = providerWidget.getValue(session.getContext(), submission); Person person = (Person) convertValueToProvider(value); session.getSubmissionActions().getCurrentEncounter().setProvider(person); } if (locationWidget != null) { Object value = locationWidget.getValue(session.getContext(), submission); Location location = (Location) HtmlFormEntryUtil.convertToType(value.toString().trim(), Location.class); session.getSubmissionActions().getCurrentEncounter().setLocation(location); } if (encounterTypeWidget != null) { EncounterType encounterType = (EncounterType) encounterTypeWidget.getValue(session.getContext(), submission); session.getSubmissionActions().getCurrentEncounter().setEncounterType(encounterType); } if (voidWidget != null) { if ("true".equals(voidWidget.getValue(session.getContext(), submission))) { session.setVoidEncounter(true); } else if ("false".equals(voidWidget.getValue(session.getContext(), submission))) { // nothing.. the session.voidEncounter property will be false, and the encounter will be // un-voided if already voided // otherwise, nothing will happen. 99% of the time the encounter won't be voided to begin // with. } } }
/** * Validates the given Encounter. Currently checks if the patient has been set and also ensures * that the patient for an encounter and the visit it is associated to if any, are the same. * * @param obj The encounter to validate. * @param errors Errors * @see org.springframework.validation.Validator#validate(java.lang.Object, * org.springframework.validation.Errors) * @should fail if the patients for the visit and the encounter dont match * @should fail if patient is not set * @should fail if encounter dateTime is after current dateTime * @should fail if encounter dateTime is before visit startDateTime * @should fail if encounter dateTime is after visit stopDateTime */ public void validate(Object obj, Errors errors) throws APIException { if (log.isDebugEnabled()) { log.debug(this.getClass().getName() + ".validate..."); } if (obj == null || !(obj instanceof Encounter)) { throw new IllegalArgumentException( "The parameter obj should not be null and must be of type " + Encounter.class); } Encounter encounter = (Encounter) obj; ValidationUtils.rejectIfEmpty( errors, "patient", "Encounter.error.patient.required", "Patient is required"); if (encounter.getVisit() != null && !ObjectUtils.equals(encounter.getVisit().getPatient(), encounter.getPatient())) { errors.rejectValue( "visit", "Encounter.visit.patients.dontMatch", "The patient for the encounter and visit should be the same"); } Date encounterDateTime = encounter.getEncounterDatetime(); if (encounterDateTime != null && encounterDateTime.after(new Date())) { errors.rejectValue( "encounterDatetime", "Encounter.datetimeShouldBeBeforeCurrent", "The encounter datetime should be before the current date."); } Visit visit = encounter.getVisit(); if (visit != null && encounterDateTime != null) { if (visit.getStartDatetime() != null && encounterDateTime.before(visit.getStartDatetime())) { errors.rejectValue( "encounterDatetime", "Encounter.datetimeShouldBeInVisitDatesRange", "The encounter datetime should be between the visit start and stop dates."); } if (visit.getStopDatetime() != null && encounterDateTime.after(visit.getStopDatetime())) { errors.rejectValue( "encounterDatetime", "Encounter.datetimeShouldBeInVisitDatesRange", "The encounter datetime should be between the visit start and stop dates."); } } }
/** @see {@link ExistingVisitAssignmentHandler#beforeCreateEncounter(Encounter)} */ @Test @Verifies( value = "should assign new visit if no match found", method = "beforeCreateEncounter(Encounter)") public void beforeCreateEncounter_shouldAssignNewVisitIfNoMatchFound() 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()); new ExistingOrNewVisitAssignmentHandler().beforeCreateEncounter(encounter); Assert.assertNotNull(encounter.getVisit()); }
@Test public void shouldUseVisitStartTimeAsEncounterDateTimeForPreviousVisits() throws Exception { Date visitStartDate = getDateFromString("2010-09-22 00:00:00"); List<Document> documents = new ArrayList<>(); documents.add( new Document( "/radiology/foo-lalala.jpg", null, "3f596de5-5caa-11e3-a4c0-0800271c1b75", null, null, false)); VisitDocumentRequest visitDocumentRequest = new VisitDocumentRequest( patientUUID, firstVisitUuid, visitTypeUUID, null, null, firstEncounterTypeUUID, null, documents, secondProviderUuid, null, null); executeDataSet("visitDocumentData.xml"); // Date currentDate = new Date(System.currentTimeMillis() - 1000); visitDocumentService.upload(visitDocumentRequest); Context.flushSession(); Context.clearSession(); Visit visit = visitService.getVisit(1); Set<Encounter> encounters = visit.getEncounters(); Encounter encounter = getEncounterByTypeUuid(encounters, firstEncounterTypeUUID); boolean condition = encounter.getEncounterDatetime().compareTo(visitStartDate) >= 0; assertTrue(condition); Set<Obs> allObs = encounter.getAllObs(); Obs savedDocument = getSavedDocument(allObs, "3f596de5-5caa-11e3-a4c0-0800271c1b75"); assertTrue(savedDocument.getObsDatetime().compareTo(visitStartDate) == 0); }
/** @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()); }
@Test public void shouldUseNewDateAsEncounterDateTimeForActiveVisits() throws Exception { Date visitStartDate = getDateFromString("2014-06-22 00:00:00"); Date encounterDate = getDateFromString("2014-06-23 00:00:00"); Date obsDate = getDateFromString("2014-06-24 00:10:00"); List<Document> documents = new ArrayList<>(); documents.add(new Document("/radiology/fooo-bar.jpg", null, conceptUuid, null, obsDate, false)); visitDocumentRequest = new VisitDocumentRequest( patientUUID, secondVisitUuid, visitTypeUUID, visitStartDate, null, secondEncounterTypeUUID, encounterDate, documents, firstProviderUuid, null, null); Date currentDate = new Date(System.currentTimeMillis() - 1000); visitDocumentService.upload(visitDocumentRequest); Context.flushSession(); Context.clearSession(); Visit visit = visitService.getVisit(2); Set<Encounter> encounters = visit.getEncounters(); Encounter encounter = getEncounterByTypeUuid(encounters, secondEncounterTypeUUID); boolean condition = encounter.getEncounterDatetime().compareTo(currentDate) >= 0; assertTrue(condition); Set<Obs> allObs = encounter.getAllObs(); Obs savedDocument = getSavedDocument(allObs, conceptUuid); assertTrue(savedDocument.getObsDatetime().compareTo(currentDate) >= 0); }
private boolean shouldBeClosed(Visit visit) { if (visit.getStopDatetime() != null) { return false; // already closed } VisitDomainWrapper visitDomainWrapper = domainWrapperFactory.newVisitDomainWrapper(visit); if (visitDomainWrapper.isAdmitted() || visitDomainWrapper.isAwaitingAdmission()) { return false; // don't close the visit if patient is admitted or waiting admission } Disposition mostRecentDisposition = visitDomainWrapper.getMostRecentDisposition(); if (mostRecentDisposition != null && mostRecentDisposition.getKeepsVisitOpen() != null && mostRecentDisposition.getKeepsVisitOpen()) { return false; // don't close the visit if the most recent disposition is one that keeps visit // opens } Date now = new Date(); Date mustHaveSomethingAfter = DateUtils.addHours(now, -emrApiProperties.getVisitExpireHours()); if (OpenmrsUtil.compare(visit.getStartDatetime(), mustHaveSomethingAfter) >= 0) { return false; } if (visit.getEncounters() != null) { for (Encounter candidate : visit.getEncounters()) { if (OpenmrsUtil.compare(candidate.getEncounterDatetime(), mustHaveSomethingAfter) >= 0) { return false; } } } return true; }
/** @see org.openmrs.api.EncounterService#saveEncounter(org.openmrs.Encounter) */ public Encounter saveEncounter(Encounter encounter) throws APIException { // if authenticated user is not supposed to edit encounter of certain type if (!canEditEncounter(encounter, null)) { throw new APIException( "Encounter.error.privilege.required.edit", new Object[] {encounter.getEncounterType().getEditPrivilege()}); } // If new encounter, try to assign a visit using the registered visit assignment handler. if (encounter.getEncounterId() == null) { // Am using Context.getEncounterService().getActiveEncounterVisitHandler() instead of just // getActiveEncounterVisitHandler() for modules which may want to AOP around this call. EncounterVisitHandler encounterVisitHandler = Context.getEncounterService().getActiveEncounterVisitHandler(); if (encounterVisitHandler != null) { encounterVisitHandler.beforeCreateEncounter(encounter); // If we have been assigned a new visit, persist it. if (encounter.getVisit() != null && encounter.getVisit().getVisitId() == null) { Context.getVisitService().saveVisit(encounter.getVisit()); } } } boolean isNewEncounter = false; Date newDate = encounter.getEncounterDatetime(); Date originalDate = null; Location newLocation = encounter.getLocation(); Location originalLocation = null; // check permissions if (encounter.getEncounterId() == null) { isNewEncounter = true; Context.requirePrivilege(PrivilegeConstants.ADD_ENCOUNTERS); } else { Context.requirePrivilege(PrivilegeConstants.EDIT_ENCOUNTERS); } // This must be done after setting dateCreated etc on the obs because // of the way the ORM tools flush things and check for nullity // This also must be done before the save encounter so we can use the // orig date // after the save Patient p = encounter.getPatient(); if (!isNewEncounter) { // fetch the datetime from the database prior to saving for this // encounter // to see if it has changed and change all obs after saving if so originalDate = dao.getSavedEncounterDatetime(encounter); if (encounter.getLocation() != null) { originalLocation = dao.getSavedEncounterLocation(encounter); } // Our data model duplicates the patient column to allow for // observations to // not have to look up the parent Encounter to find the patient // Therefore, encounter.patient must always equal // encounter.observations[0-n].patient // If we are changing encounter.encounterDatetime, then we need to // also apply that // to Obs that inherited their obsDatetime from the encounter in the // first place for (Obs obs : encounter.getAllObs(true)) { // if the date was changed if (OpenmrsUtil.compare(originalDate, newDate) != 0 && OpenmrsUtil.compare(obs.getObsDatetime(), originalDate) == 0) { // if the obs datetime is the same as the // original encounter datetime, fix it obs.setObsDatetime(newDate); } if (!OpenmrsUtil.nullSafeEquals(newLocation, originalLocation) && obs.getLocation().equals(originalLocation)) { obs.setLocation(newLocation); } // if the Person in the obs doesn't match the Patient in the // encounter, fix it if (!obs.getPerson().getPersonId().equals(p.getPatientId())) { obs.setPerson(p); } } } // same goes for Orders for (Order o : encounter.getOrders()) { if (!p.equals(o.getPatient())) { o.setPatient(p); } } // do the actual saving to the database dao.saveEncounter(encounter); // save the new orders for (Order o : encounter.getOrders()) { if (o.getOrderId() == null) { Context.getOrderService().saveOrder(o, null); } } return encounter; }
public 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))); }
/** * * Returns the encounter with the obs that aren't used when populating form are removed. * This *doesn't* save the encounter. * TODO: handle Orders? * * @param e * @param htmlform * @return * @throws Exception */ public static Encounter trimEncounterToMatchForm(Encounter e, HtmlForm htmlform) throws Exception { //this should move existing obs from session to tag handlers. FormEntrySession session = new FormEntrySession(e.getPatient(), e, FormEntryContext.Mode.VIEW, htmlform, null); // session gets a null HttpSession session.getHtmlToDisplay(); if (log.isDebugEnabled()){ Map<Concept, List<Obs>> map = session.getContext().getExistingObs(); if (map != null){ for (Map.Entry<Concept, List<Obs>> existingObs : map.entrySet()){ List<Obs> oList = existingObs.getValue(); for (Obs oInner : oList) log.debug("Obs in existingObs " + existingObs.getKey() + " " + oInner.getConcept()); } } Map<Obs, Set<Obs>> map2 = session.getContext().getExistingObsInGroups(); if (map2 != null){ for (Map.Entry<Obs, Set<Obs>> existingObsInGroups : map2.entrySet()){ Set<Obs> oList = existingObsInGroups.getValue(); for (Obs oInner : oList) log.debug("Obs in existingObsInGroups " + existingObsInGroups.getKey().getConcept() + " " + oInner.getConcept()); } } } Encounter ret = new Encounter(); ret.setCreator(e.getCreator()); ret.setEncounterDatetime(e.getEncounterDatetime()); EncounterCompatibility.setProvider(ret, EncounterCompatibility.getProvider(e)); ret.setLocation(e.getLocation()); ret.setDateCreated(e.getDateCreated()); ret.setPatient(e.getPatient()); //renders new encounter unsave-able: ret.setEncounterId(e.getEncounterId()); for (Obs oTest : e.getAllObs()){ boolean found = false; if (session.getContext().getExistingObs() != null && !oTest.isObsGrouping()){ List<Obs> obsList = session.getContext().getExistingObs().get(oTest.getConcept()); if (obsList != null && obsList.size() > 0){ for (Obs o : obsList){ if (o.getObsId().equals(oTest.getObsId())){ found = true; continue; } } } } if (!found && session.getContext().getExistingObsInGroups() != null){ for (Map.Entry<Obs, Set<Obs>> mapEntry : session.getContext().getExistingObsInGroups().entrySet()){ if (mapEntry.getKey().equals(oTest)){ found = true; continue; } else { Set<Obs> oSet = mapEntry.getValue(); //note: oSet.contains fails for some reason for (Obs o:oSet){ if (o.getObsId().equals(oTest.getObsId())){ found = true; continue; } } } } } if (!found) ret.addObs(oTest); } session = null; return ret; }
/** * Adds the column headers and column data to the DataSet * * @param dataSet * @param encounters * @param patientIdentifierTypes * @param optionalColumns * @param columnDisplayFormat * @param maxColumnHeaderWidth * @param allColumns * @param fieldMap * @return */ public DataSet addData( SimpleDataSet dataSet, List<Encounter> encounters, List<PatientIdentifierType> patientIdentifierTypes, List<EncounterAndObsDataSetDefinition.ObsOptionalColumn> optionalColumns, List<EncounterAndObsDataSetDefinition.ColumnDisplayFormat> columnDisplayFormat, Integer maxColumnHeaderWidth, Set<ObsColumnDescriptor> allColumns, Map<Encounter, Map<ObsColumnDescriptor, Obs>> fieldMap) { for (Encounter encounter : encounters) { DataSetRow row = new DataSetRow(); List<String> providerNames = new ArrayList<String>(); for (EncounterProvider ep : encounter.getEncounterProviders()) { providerNames.add(ep.getProvider().getName()); } // Add the standard columns for encounters DataSetColumn c1 = new DataSetColumn( ObjectUtil.trimStringIfNeeded("ENCOUNTER_ID", maxColumnHeaderWidth), ObjectUtil.trimStringIfNeeded("ENCOUNTER_ID", maxColumnHeaderWidth), Integer.class); row.addColumnValue(c1, encounter.getEncounterId()); DataSetColumn c2 = new DataSetColumn( ObjectUtil.trimStringIfNeeded("ENCOUNTER_DATETIME", maxColumnHeaderWidth), ObjectUtil.trimStringIfNeeded("ENCOUNTER_DATETIME", maxColumnHeaderWidth), String.class); row.addColumnValue(c2, encounter.getEncounterDatetime().toString()); DataSetColumn c3 = new DataSetColumn( ObjectUtil.trimStringIfNeeded("LOCATION", maxColumnHeaderWidth), ObjectUtil.trimStringIfNeeded("LOCATION", maxColumnHeaderWidth), String.class); row.addColumnValue( c3, (encounter.getLocation() != null) ? encounter.getLocation().getName() : EMPTY); DataSetColumn c4 = new DataSetColumn( ObjectUtil.trimStringIfNeeded("PROVIDER", maxColumnHeaderWidth), ObjectUtil.trimStringIfNeeded("PROVIDER", maxColumnHeaderWidth), String.class); row.addColumnValue(c4, OpenmrsUtil.join(providerNames, ", ")); DataSetColumn c5 = new DataSetColumn( ObjectUtil.trimStringIfNeeded("INTERNAL_PATIENT_ID", maxColumnHeaderWidth), ObjectUtil.trimStringIfNeeded("INTERNAL_PATIENT_ID", maxColumnHeaderWidth), Integer.class); row.addColumnValue( c5, encounter.getPatient() != null ? encounter.getPatient().getPatientId() : EMPTY); if (patientIdentifierTypes != null) { for (PatientIdentifierType pit : patientIdentifierTypes) { List<PatientIdentifier> patientIdentifiers = encounter.getPatient().getPatientIdentifiers(pit); StringBuffer sbPatientIdentifiers = new StringBuffer(); int count = 0; for (PatientIdentifier patientIdentifier : patientIdentifiers) { if (count > 0) { sbPatientIdentifiers.append(", "); } sbPatientIdentifiers.append(patientIdentifier.toString()); count++; } DataSetColumn c6 = new DataSetColumn( pit.getName(), ObjectUtil.trimStringIfNeeded(pit.getName(), maxColumnHeaderWidth), String.class); row.addColumnValue(c6, sbPatientIdentifiers.toString()); } } Map<ObsColumnDescriptor, Obs> obsInEncounter = fieldMap.get(encounter); // Look up all obs for a given encounter based on column headers for all encounters for (ObsColumnDescriptor columnKey : allColumns) { Obs obs = obsInEncounter.get(columnKey); String columnName = columnKey.format(columnDisplayFormat, maxColumnHeaderWidth); DataSetColumn obsDsc = new DataSetColumn(columnName, columnName, String.class); StringBuffer columnValue = new StringBuffer(); if (obs != null && obs.getValueCoded() != null) { if (columnDisplayFormat.contains( EncounterAndObsDataSetDefinition.ColumnDisplayFormat.ID)) { columnValue.append(obs.getValueCoded()); } if (columnDisplayFormat.contains(EncounterAndObsDataSetDefinition.ColumnDisplayFormat.ID) && columnDisplayFormat.contains( EncounterAndObsDataSetDefinition.ColumnDisplayFormat.BEST_SHORT_NAME)) { columnValue.append("_"); } if (columnDisplayFormat.contains( EncounterAndObsDataSetDefinition.ColumnDisplayFormat.BEST_SHORT_NAME)) { String conceptName = obs.getValueAsString(Context.getLocale()); columnValue.append( maxColumnHeaderWidth != null && conceptName.length() > maxColumnHeaderWidth - columnValue.length() ? conceptName.substring(0, maxColumnHeaderWidth - columnValue.length() - 1) : conceptName); } row.addColumnValue(obsDsc, (obs != null) ? columnValue.toString() : EMPTY); } else { row.addColumnValue( obsDsc, (obs != null) ? obs.getValueAsString(Context.getLocale()) : EMPTY); } String dateColumnName = columnKey.format( columnDisplayFormat, maxColumnHeaderWidth != null ? maxColumnHeaderWidth - 5 : null); DataSetColumn obsDscDate = new DataSetColumn(dateColumnName + "_DATE", dateColumnName + "_DATE", String.class); row.addColumnValue(obsDscDate, (obs != null) ? obs.getObsDatetime().toString() : EMPTY); String parentColumnName = columnKey.format( columnDisplayFormat, maxColumnHeaderWidth != null ? maxColumnHeaderWidth - 7 : null); DataSetColumn obsDscParent = new DataSetColumn( parentColumnName + "_PARENT", parentColumnName + "_PARENT", String.class); row.addColumnValue( obsDscParent, (obs != null && obs.getObsGroup() != null) ? obs.getObsGroup().getId() : EMPTY); if (optionalColumns != null) { if (optionalColumns.contains( EncounterAndObsDataSetDefinition.ObsOptionalColumn.VALUE_MODIFIER)) { String valModColumnName = columnKey.format( columnDisplayFormat, maxColumnHeaderWidth != null ? maxColumnHeaderWidth - 10 : null); DataSetColumn obsDscValueModifier = new DataSetColumn( valModColumnName + "_VALUE_MOD", valModColumnName + "_VALUE_MOD", String.class); row.addColumnValue(obsDscValueModifier, (obs != null) ? obs.getValueModifier() : EMPTY); } if (optionalColumns.contains( EncounterAndObsDataSetDefinition.ObsOptionalColumn.ACCESSION_NUMBER)) { String accessionNumColumnName = columnKey.format( columnDisplayFormat, maxColumnHeaderWidth != null ? maxColumnHeaderWidth - 14 : null); DataSetColumn obsDscAccessionNumber = new DataSetColumn( accessionNumColumnName + "_ACCESSION_NUM", accessionNumColumnName + "_ACCESSION_NUM", String.class); row.addColumnValue( obsDscAccessionNumber, (obs != null) ? obs.getAccessionNumber() : EMPTY); } if (optionalColumns.contains( EncounterAndObsDataSetDefinition.ObsOptionalColumn.COMMENT)) { String commentColumnName = columnKey.format( columnDisplayFormat, maxColumnHeaderWidth != null ? maxColumnHeaderWidth - 8 : null); DataSetColumn obsDscComment = new DataSetColumn( commentColumnName + "_COMMENT", commentColumnName + "_COMMENT", String.class); row.addColumnValue(obsDscComment, (obs != null) ? obs.getComment() : EMPTY); } } } dataSet.addRow(row); } return dataSet; }
@Override public String getOverrideContent(String str) { if (!Context.isAuthenticated()) { return ""; } String gp = Context.getAdministrationService() .getGlobalProperty("htmlformflowsheet.patientChartFormIds"); if (StringUtils.isEmpty(gp)) { return ""; } StringBuilder sbExisting = new StringBuilder(""); StringBuilder sbNonExisting = new StringBuilder(""); try { String patientId = this.getParameterMap().get("patientId"); Patient p = Context.getPatientService().getPatient(Integer.valueOf(patientId)); for (StringTokenizer st = new StringTokenizer(gp, ","); st.hasMoreTokens(); ) { Map<Integer, Set<Integer>> progForms = new HashMap<Integer, Set<Integer>>(); Set<Integer> programIds = new HashSet<Integer>(); String formId = st.nextToken().trim(); if (formId.contains(":")) { String[] formIdSplit = formId.split(":"); formId = formIdSplit[0]; // check for required programs: String programInfo = formIdSplit[1]; if (programInfo.contains("|")) { for (StringTokenizer strTok = new StringTokenizer(programInfo, "|"); strTok.hasMoreTokens(); ) { String sTmp = strTok.nextToken().trim(); addFormToProgramList(progForms, Integer.valueOf(formId), Integer.valueOf(sTmp)); programIds.add(Integer.valueOf(sTmp)); } } else { // todo: support lookup programs by uuid and forms by uuid? addFormToProgramList(progForms, Integer.valueOf(formId), Integer.valueOf(programInfo)); programIds.add(Integer.valueOf(programInfo)); } } Form form = HtmlFormFlowsheetUtil.getFormFromString(formId); List<PatientProgram> pps = Context.getProgramWorkflowService() .getPatientPrograms(p, null, null, null, null, null, false); List<Encounter> encs = Context.getEncounterService() .getEncounters( p, null, null, null, Collections.singletonList(form), null, null, false); // for (Map.Entry<Integer, Set<Integer>> m : progForms.entrySet()){ // System.out.println(m.getKey()+ ":" + m.getValue()); // } // 1. no program association to form. always show. if (progForms.get(Integer.valueOf(formId)) == null || progForms.get(Integer.valueOf(formId)).size() == 0) { if (encs.size() == 0) { // if no encs, show add new sbNonExisting.append( " | <a href=\"/" + WebConstants.WEBAPP_NAME + "/module/htmlformentry/htmlFormEntry.form?personId=" + p.getPersonId() + "&patientId=" + p.getPatientId() + "&returnUrl=&formId=" + form.getFormId() + "\">" + form.getName() + "</a> | "); } else { // if encs, show existing flowsheet parent(s) for (Encounter e : encs) { sbExisting.append( " | <a href=\"/" + WebConstants.WEBAPP_NAME + "/module/htmlformentry/htmlFormEntry.form?encounterId=" + e.getEncounterId() + "&mode=EDIT\">" + form.getName() + " " + "(" + Context.getDateFormat().format(e.getEncounterDatetime()) + ")</a> | "); } } } else { // 2. program(s) specified for form // this builds a map of encounter corresponding to the parent form creation to the // patientProgram is was created in. Map<Encounter, PatientProgram> encounterToPatientProgram = new HashMap<Encounter, PatientProgram>(); for (Encounter e : encs) { for (PatientProgram pp : pps) { // if encounter is later than start date and less than end date or end date is null if (programIds.contains(pp.getProgram().getProgramId()) && e.getEncounterDatetime().getTime() >= pp.getDateEnrolled().getTime() && ((pp.getDateCompleted() == null || pp.getDateCompleted().getTime() >= e.getEncounterDatetime().getTime()))) { // encounter is in patientprogram encounterToPatientProgram.put(e, pp); } } } // show existing based on the map for (Map.Entry<Encounter, PatientProgram> m : encounterToPatientProgram.entrySet()) { sbExisting.append( " | <a href=\"/" + WebConstants.WEBAPP_NAME + "/module/htmlformentry/htmlFormEntry.form?encounterId=" + m.getKey().getEncounterId() + "&mode=EDIT\">" + form.getName()); if (m.getValue() != null) { sbExisting.append( " " + "(" + Context.getDateFormat().format(m.getValue().getDateEnrolled()) + " - "); if (m.getValue().getDateCompleted() != null) sbExisting.append(Context.getDateFormat().format(m.getValue().getDateCompleted())); sbExisting.append(")"); } sbExisting.append("</a> | "); } // show add new // if patient is in program currently, AND patient doesn't have an encounter for this // program PatientProgram ppActive = activePatientProgram(pps, programIds); boolean found = false; if (ppActive != null) { for (Map.Entry<Encounter, PatientProgram> m : encounterToPatientProgram.entrySet()) { if (m.getValue() != null && m.getValue().equals(ppActive)) found = true; } if (!found) sbNonExisting.append( " | <a href=\"/" + WebConstants.WEBAPP_NAME + "/module/htmlformentry/htmlFormEntry.form?personId=" + p.getPersonId() + "&patientId=" + p.getPatientId() + "&returnUrl=&formId=" + form.getFormId() + "\"> " + form.getName() + "</a> | "); } } } String retString = "<table><tr><td>"; if (!sbExisting.toString().equals("")) retString += "Existing Patient Chart(s): " + sbExisting.toString(); retString += "</td></tr><tr><td>"; if (!sbNonExisting.toString().equals("")) retString += "Create A New Patient Charts: " + sbNonExisting.toString(); retString += "</td></tr></table>"; return retString.replace("| |", " | "); } catch (Exception ex) { ex.printStackTrace(); return ""; } }