Search in sources :

Example 26 with EncounterType

use of org.openmrs.EncounterType in project openmrs-module-coreapps by openmrs.

the class VisitDetailsFragmentControllerTest method shouldReturnEncountersForVisit.

@Test
public void shouldReturnEncountersForVisit() throws ParseException {
    CoreAppsProperties coreAppsProperties = mock(CoreAppsProperties.class);
    when(coreAppsProperties.getPatientDashboardEncounterCount()).thenReturn(100);
    UiSessionContext sessionContext = mock(UiSessionContext.class);
    User authenticatedUser = new User();
    when(sessionContext.getCurrentUser()).thenReturn(authenticatedUser);
    AppContextModel appContextModel = new AppContextModel();
    when(sessionContext.generateAppContextModel()).thenReturn(appContextModel);
    authenticatedUser.addRole(createRoleForUser());
    AdministrationService administrationService = mock(AdministrationService.class);
    when(administrationService.getGlobalProperty(UiFrameworkConstants.GP_FORMATTER_DATETIME_FORMAT)).thenReturn("dd.MMM.yyyy, HH:mm:ss");
    AppFrameworkService appFrameworkService = mock(AppFrameworkService.class);
    when(appFrameworkService.getExtensionsForCurrentUser(CoreAppsConstants.ENCOUNTER_TEMPLATE_EXTENSION)).thenReturn(generateMockEncounterTemplateExtensions());
    EncounterService encounterService = mock(EncounterService.class);
    Patient patient = mock(Patient.class);
    when(patient.getPatientId()).thenReturn(1);
    when(patient.isDead()).thenReturn(false);
    Visit visit = new Visit();
    Location visitLocation = new Location();
    visitLocation.setName("Visit Location");
    visit.setVisitId(1);
    visit.setLocation(visitLocation);
    visit.setStartDatetime(new Date());
    visit.setStopDatetime(new Date());
    visit.setCreator(authenticatedUser);
    visit.setPatient(patient);
    Location encounterLocation = new Location();
    encounterLocation.setName("Location");
    EncounterType encounterType = new EncounterType();
    encounterType.setName("Encounter Type");
    encounterType.setUuid(encounterTypeUuid);
    Provider primaryProvider = new Provider();
    primaryProvider.setName("Primary Provider");
    EncounterProvider primaryEncounterProvider = new EncounterProvider();
    primaryEncounterProvider.setProvider(primaryProvider);
    EncounterRole primaryEncounterRole = new EncounterRole();
    primaryEncounterRole.setUuid(primaryEncounterRoleUuid);
    primaryEncounterProvider.setEncounterRole(primaryEncounterRole);
    when(encounterService.getEncounterRoleByUuid(primaryEncounterRoleUuid)).thenReturn(primaryEncounterRole);
    Provider secondaryProvider = new Provider();
    secondaryProvider.setName("Secondary Provider");
    EncounterProvider secondaryEncounterProvider = new EncounterProvider();
    secondaryEncounterProvider.setProvider(secondaryProvider);
    secondaryEncounterProvider.setEncounterRole(new EncounterRole());
    Encounter encounter = new Encounter();
    encounter.setEncounterId(7);
    encounter.setEncounterDatetime(new Date());
    encounter.setLocation(encounterLocation);
    encounter.setEncounterType(encounterType);
    encounter.setEncounterProviders(new LinkedHashSet<EncounterProvider>());
    // add secondary provider so that it is the one that is "arbitrarily" returned first
    encounter.getEncounterProviders().add(secondaryEncounterProvider);
    encounter.getEncounterProviders().add(primaryEncounterProvider);
    encounter.setCreator(authenticatedUser);
    encounter.setDateCreated(new Date());
    visit.addEncounter(encounter);
    UiUtils uiUtils = new TestUiUtils(administrationService);
    VisitDetailsFragmentController controller = new VisitDetailsFragmentController();
    SimpleObject response = controller.getVisitDetails(mock(EmrApiProperties.class), coreAppsProperties, appFrameworkService, encounterService, visit, null, null, uiUtils, sessionContext);
    List<SimpleObject> actualEncounters = (List<SimpleObject>) response.get("encounters");
    SimpleObject actualEncounter = actualEncounters.get(0);
    assertThat(response.get("startDatetime"), notNullValue());
    assertThat(response.get("stopDatetime"), notNullValue());
    assertThat((String) response.get("location"), is("Visit Location"));
    assertThat(actualEncounters.size(), is(1));
    assertThat((Integer) actualEncounter.get("encounterId"), is(7));
    assertThat((String) actualEncounter.get("location"), is("Location"));
    assertThat((SimpleObject) actualEncounter.get("encounterType"), isSimpleObjectWith("uuid", encounterType.getUuid(), "name", encounterType.getName()));
    assertThat(actualEncounter.get("encounterDatetime"), notNullValue());
    assertThat(actualEncounter.get("encounterDate"), notNullValue());
    assertThat(actualEncounter.get("encounterTime"), notNullValue());
    assertTrue((Boolean) actualEncounter.get("canEdit"));
    assertThat((String) actualEncounter.get("primaryProvider"), is("Primary Provider"));
    List<SimpleObject> actualProviders = (List<SimpleObject>) actualEncounter.get("encounterProviders");
    assertThat(actualProviders.size(), is(2));
}
Also used : UiSessionContext(org.openmrs.module.appui.UiSessionContext) EncounterProvider(org.openmrs.EncounterProvider) User(org.openmrs.User) SimpleObject(org.openmrs.ui.framework.SimpleObject) Visit(org.openmrs.Visit) TestUiUtils(org.openmrs.module.appui.TestUiUtils) Patient(org.openmrs.Patient) EmrApiProperties(org.openmrs.module.emrapi.EmrApiProperties) EncounterService(org.openmrs.api.EncounterService) Date(java.util.Date) EncounterProvider(org.openmrs.EncounterProvider) Provider(org.openmrs.Provider) AppContextModel(org.openmrs.module.appframework.context.AppContextModel) AdministrationService(org.openmrs.api.AdministrationService) CoreAppsProperties(org.openmrs.module.coreapps.CoreAppsProperties) EncounterRole(org.openmrs.EncounterRole) Encounter(org.openmrs.Encounter) AppFrameworkService(org.openmrs.module.appframework.service.AppFrameworkService) ArrayList(java.util.ArrayList) List(java.util.List) EncounterType(org.openmrs.EncounterType) Location(org.openmrs.Location) TestUiUtils(org.openmrs.module.appui.TestUiUtils) UiUtils(org.openmrs.ui.framework.UiUtils) Test(org.junit.Test)

Example 27 with EncounterType

use of org.openmrs.EncounterType in project openmrs-module-coreapps by openmrs.

the class ParseEncounterToJson method createEncounterJSON.

public SimpleObject createEncounterJSON(User authenticatedUser, Encounter encounter) {
    boolean canDelete = authenticatedUser.hasPrivilege(EmrApiConstants.PRIVILEGE_DELETE_ENCOUNTER);
    boolean canEdit = authenticatedUser.hasPrivilege(EmrApiConstants.PRIVILEGE_EDIT_ENCOUNTER);
    SimpleObject simpleEncounter = SimpleObject.fromObject(new EncounterDomainWrapper(encounter), uiUtils, "encounterId", "location", "encounterDatetime", "encounterProviders.provider", "voided", "form");
    // UUID is not provided by EncounterDomainWrapper, adding it here.
    simpleEncounter.put("uuid", encounter.getUuid());
    // manually set the date and time components so we can control how we format them
    simpleEncounter.put("encounterDate", DateFormatUtils.format(encounter.getEncounterDatetime(), "dd MMM yyyy", Context.getLocale()));
    simpleEncounter.put("encounterTime", DateFormatUtils.format(encounter.getEncounterDatetime(), "hh:mm a", Context.getLocale()));
    // do the same for other date fields
    simpleEncounter.put("dateCreated", DateFormatUtils.format(encounter.getDateCreated(), "dd MMM yyyy", Context.getLocale()));
    simpleEncounter.put("creator", uiUtils.format(encounter.getCreator()));
    if (encounter.getDateChanged() != null) {
        simpleEncounter.put("dateChanged", DateFormatUtils.format(encounter.getDateChanged(), "dd MMM yyyy", Context.getLocale()));
    }
    if (encounter.getChangedBy() != null) {
        simpleEncounter.put("changedBy", uiUtils.format(encounter.getChangedBy()));
    }
    EncounterType encounterType = encounter.getEncounterType();
    simpleEncounter.put("encounterType", SimpleObject.create("uuid", encounterType.getUuid(), "name", uiUtils.format(encounterType)));
    // determine the provider
    Provider primaryProvider = null;
    // if a primary encounter role has been specified, get the provider for that role
    EncounterRole primaryEncounterRole = getPrimaryEncounterRoleForEncounter(encounter);
    if (primaryEncounterRole != null) {
        Set<Provider> providers = encounter.getProvidersByRole(primaryEncounterRole);
        if (providers != null && !providers.isEmpty()) {
            // for now, if there are multiple providers with this role, return an arbitrary one
            primaryProvider = providers.iterator().next();
        }
    }
    // otherwise, just pick an arbitrary (non-voided) provider
    if (primaryProvider == null) {
        primaryProvider = getFirstNonVoidedProvider(encounter);
    }
    simpleEncounter.put("primaryProvider", uiUtils.format(primaryProvider));
    if (verifyIfUserHasPermissionToDeleteAnEncounter(encounter, authenticatedUser, canDelete)) {
        simpleEncounter.put("canDelete", true);
    }
    if (verifyIfUserHasPermissionToEditAnEncounter(encounter, authenticatedUser, canEdit)) {
        simpleEncounter.put("canEdit", true);
    } else {
        simpleEncounter.put("canEdit", false);
    }
    if (encounter.getVisit() != null) {
        simpleEncounter.put("visitId", encounter.getVisit().getId());
    }
    return simpleEncounter;
}
Also used : EncounterDomainWrapper(org.openmrs.module.emrapi.encounter.EncounterDomainWrapper) SimpleObject(org.openmrs.ui.framework.SimpleObject) EncounterRole(org.openmrs.EncounterRole) EncounterType(org.openmrs.EncounterType) EncounterProvider(org.openmrs.EncounterProvider) Provider(org.openmrs.Provider)

Example 28 with EncounterType

use of org.openmrs.EncounterType in project openmrs-module-coreapps by openmrs.

the class EncounterDiagnosesTagHandlerComponentTest method testHandleSubmissionHandlesValidSubmissionEditingForm.

@Test
public void testHandleSubmissionHandlesValidSubmissionEditingForm() throws Exception {
    final DiagnosisMetadata dmd = emrApiProperties.getDiagnosisMetadata();
    final Date date = new Date();
    // first, create an encounter
    final Concept malaria = conceptService.getConcept(11);
    final Patient patient = patientService.getPatient(8);
    final Encounter existingEncounter = new Encounter();
    existingEncounter.setEncounterType(new EncounterType(1));
    existingEncounter.setPatient(patient);
    existingEncounter.setEncounterDatetime(date);
    existingEncounter.setLocation(locationService.getLocation(2));
    Obs primaryDiagnosis = dmd.buildDiagnosisObsGroup(new Diagnosis(new CodedOrFreeTextAnswer(malaria), Diagnosis.Order.PRIMARY));
    Obs secondaryDiagnosis = dmd.buildDiagnosisObsGroup(new Diagnosis(new CodedOrFreeTextAnswer("Unknown disease"), Diagnosis.Order.SECONDARY));
    existingEncounter.addObs(primaryDiagnosis);
    existingEncounter.addObs(secondaryDiagnosis);
    encounterService.saveEncounter(existingEncounter);
    ObjectMapper jackson = new ObjectMapper();
    ArrayNode json = jackson.createArrayNode();
    {
        // change the existing primary diagnosis from PRESUMED to CONFIRMED
        ObjectNode diagnosisNode = json.addObject();
        diagnosisNode.put("certainty", "CONFIRMED");
        diagnosisNode.put("order", "PRIMARY");
        diagnosisNode.put("diagnosis", CodedOrFreeTextAnswer.CONCEPT_PREFIX + "11");
        diagnosisNode.put("existingObs", primaryDiagnosis.getObsId());
    }
    {
        // this is a new diagnosis
        ObjectNode diagnosisNode = json.addObject();
        diagnosisNode.put("certainty", "PRESUMED");
        diagnosisNode.put("order", "SECONDARY");
        diagnosisNode.put("diagnosis", CodedOrFreeTextAnswer.NON_CODED_PREFIX + "I had spelled it wrong before");
    }
    final String jsonToSubmit = jackson.writeValueAsString(json);
    new RegressionTestHelper() {

        @Override
        public String getXmlDatasetPath() {
            return "";
        }

        @Override
        public String getFormName() {
            return "encounterDiagnosesSimpleForm";
        }

        @Override
        public Map<String, Object> getFormEntrySessionAttributes() {
            Map<String, Object> attributes = new HashMap<String, Object>();
            attributes.put("uiUtils", new TestUiUtils() {

                @Override
                public String includeFragment(String providerName, String fragmentId, Map<String, Object> config) throws PageAction {
                    return "[[ included fragment " + providerName + "." + fragmentId + " here ]]";
                }
            });
            return attributes;
        }

        @Override
        public Patient getPatientToView() throws Exception {
            return patient;
        }

        @Override
        public Encounter getEncounterToEdit() {
            return existingEncounter;
        }

        @Override
        public String[] widgetLabelsForEdit() {
            return new String[] { "Date:", "Location:", "Provider:", "Encounter Type:" };
        }

        @Override
        public void setupEditRequest(MockHttpServletRequest request, Map<String, String> widgets) {
            request.setParameter(widgets.get("Date:"), dateAsString(date));
            request.setParameter(widgets.get("Location:"), "2");
            request.setParameter(widgets.get("Provider:"), "1");
            request.setParameter(widgets.get("Encounter Type:"), "1");
            request.setParameter("encounterDiagnoses", jsonToSubmit);
        }

        @Override
        public void testEditFormHtml(String html) {
            System.out.println(html);
        }

        @Override
        public void testEditedResults(SubmissionResults results) {
            results.assertNoErrors();
            results.assertEncounterEdited();
            List<Obs> diagnoses = new ArrayList<Obs>();
            for (Obs obs : results.getEncounterCreated().getObsAtTopLevel(true)) {
                if (dmd.isDiagnosis(obs)) {
                    diagnoses.add(obs);
                }
            }
            Matcher<Obs> newPrimary = new ObsGroupMatcher().withGroupingConcept(dmd.getDiagnosisSetConcept()).withNonVoidedObs(dmd.getDiagnosisCertaintyConcept(), dmd.getConceptFor(Diagnosis.Certainty.CONFIRMED)).withVoidedObs(dmd.getDiagnosisCertaintyConcept(), dmd.getConceptFor(Diagnosis.Certainty.PRESUMED)).withNonVoidedObs(dmd.getDiagnosisOrderConcept(), dmd.getConceptFor(Diagnosis.Order.PRIMARY)).withNonVoidedObs(dmd.getCodedDiagnosisConcept(), malaria);
            Matcher<Obs> newSecondary = new ObsGroupMatcher().withGroupingConcept(dmd.getDiagnosisSetConcept()).withNonVoidedObs(dmd.getDiagnosisCertaintyConcept(), dmd.getConceptFor(Diagnosis.Certainty.PRESUMED)).withNonVoidedObs(dmd.getDiagnosisOrderConcept(), dmd.getConceptFor(Diagnosis.Order.SECONDARY)).withNonVoidedObs(dmd.getNonCodedDiagnosisConcept(), "I had spelled it wrong before");
            Matcher<Obs> oldSecondary = new ObsGroupMatcher().withGroupingConcept(dmd.getDiagnosisSetConcept()).withVoidedObs(dmd.getDiagnosisCertaintyConcept(), dmd.getConceptFor(Diagnosis.Certainty.PRESUMED)).withVoidedObs(dmd.getDiagnosisOrderConcept(), dmd.getConceptFor(Diagnosis.Order.SECONDARY)).withVoidedObs(dmd.getNonCodedDiagnosisConcept(), "Unknown disease").thatIsVoided();
            assertThat(diagnoses.size(), is(3));
            assertThat(diagnoses, containsInAnyOrder(newPrimary, newSecondary, oldSecondary));
        }
    }.run();
}
Also used : ObsGroupMatcher(org.openmrs.module.emrapi.matcher.ObsGroupMatcher) Matcher(org.hamcrest.Matcher) Encounter(org.openmrs.Encounter) ArrayList(java.util.ArrayList) List(java.util.List) Diagnosis(org.openmrs.module.emrapi.diagnosis.Diagnosis) ArrayNode(org.codehaus.jackson.node.ArrayNode) ObjectMapper(org.codehaus.jackson.map.ObjectMapper) Concept(org.openmrs.Concept) Obs(org.openmrs.Obs) ObjectNode(org.codehaus.jackson.node.ObjectNode) TestUiUtils(org.openmrs.module.appui.TestUiUtils) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) DiagnosisMetadata(org.openmrs.module.emrapi.diagnosis.DiagnosisMetadata) Patient(org.openmrs.Patient) CodedOrFreeTextAnswer(org.openmrs.module.emrapi.diagnosis.CodedOrFreeTextAnswer) Date(java.util.Date) EncounterType(org.openmrs.EncounterType) HashMap(java.util.HashMap) Map(java.util.Map) ObsGroupMatcher(org.openmrs.module.emrapi.matcher.ObsGroupMatcher) RegressionTestHelper(org.openmrs.module.htmlformentry.RegressionTestHelper) Test(org.junit.Test) BaseModuleWebContextSensitiveTest(org.openmrs.web.test.BaseModuleWebContextSensitiveTest)

Example 29 with EncounterType

use of org.openmrs.EncounterType in project openmrs-module-coreapps by openmrs.

the class VisitTypeHelper method setTransferEncounter.

/**
 * Creates a transfer encounter when visit type is changed
 *
 * @param visit
 * @param vs
 * @param es
 * @param encounter
 * @param patient
 * @param person
 * @param loginLocation
 * @param previousType
 * @param isTransferType
 */
protected void setTransferEncounter(Visit visit, VisitService vs, EncounterService es, Encounter encounter, Patient patient, Person person, Location loginLocation, VisitType previousType, boolean isTransferType) {
    AdministrationService adminService = Context.getAdministrationService();
    String transferEncounterUuid = adminService.getGlobalProperty(CoreAppsConstants.TRANSFER_ENCOUNTER_TYPE_UUID);
    EncounterType transferEncounterType = es.getEncounterTypeByUuid(transferEncounterUuid);
    if (previousType != null && isTransferType) {
        // add Transfer encounter
        encounter.setEncounterType(transferEncounterType);
        encounter.setPatient(patient);
        encounter.setEncounterDatetime(new Date());
        encounter.setProvider(person);
        encounter.setLocation(loginLocation);
        es.saveEncounter(encounter);
        visit.addEncounter(encounter);
        vs.saveVisit(visit);
    }
}
Also used : AdministrationService(org.openmrs.api.AdministrationService) EncounterType(org.openmrs.EncounterType) Date(java.util.Date)

Example 30 with EncounterType

use of org.openmrs.EncounterType in project openmrs-module-coreapps by openmrs.

the class MostRecentEncounterFragmentController method controller.

public void controller(FragmentConfiguration config, FragmentModel model, UiUtils ui, @FragmentParam("patientId") Patient patient, @FragmentParam("app") AppDescriptor app, @SpringBean("encounterService") EncounterService encounterService) {
    if (app.getConfig().path("encounterTypeUuid").isMissingNode()) {
        throw new IllegalStateException("encounterTypeUuid app config parameter required");
    }
    if (app.getConfig().path("encounterDateLabel").isMissingNode()) {
        throw new IllegalStateException("encounterDateLabel app config parameter required");
    }
    List<EncounterType> encounterTypes = new ArrayList<EncounterType>();
    EncounterType encounterType = encounterService.getEncounterTypeByUuid((app.getConfig().get("encounterTypeUuid").getTextValue()));
    if (encounterType == null) {
        throw new IllegalStateException("No encounter type with uuid " + app.getConfig().get("encounterTypeUuid").getTextValue());
    }
    encounterTypes.add(encounterType);
    EncounterServiceCompatibility service = Context.getRegisteredComponent("coreapps.EncounterServiceCompatibility", EncounterServiceCompatibility.class);
    List<Encounter> encounters = service.getEncounters(Context.getEncounterService(), patient, null, null, null, null, encounterTypes, null, null, null, false);
    model.addAttribute("app", app);
    model.addAttribute("patient", patient);
    String definitionUiResource = "";
    if (!app.getConfig().path("definitionUiResource").isMissingNode()) {
        definitionUiResource = app.getConfig().get("definitionUiResource").getTextValue();
    }
    model.addAttribute("definitionUiResource", definitionUiResource);
    if (encounters.size() > 0) {
        model.addAttribute("encounter", encounters.get(encounters.size() - 1));
    } else {
        model.addAttribute("encounter", null);
    }
    model.addAttribute("creatable", app.getConfig().get("creatable") != null ? app.getConfig().get("creatable").getBooleanValue() : false);
    model.addAttribute("createIcon", app.getConfig().get("create-icon") != null ? app.getConfig().get("create-icon").getTextValue() : null);
    model.addAttribute("createProvider", app.getConfig().get("create-provider") != null ? app.getConfig().get("create-provider").getTextValue() : null);
    model.addAttribute("createFragment", app.getConfig().get("create-fragment") != null ? app.getConfig().get("create-fragment").getTextValue() : null);
    model.addAttribute("editable", app.getConfig().get("editable") != null ? app.getConfig().get("editable").getBooleanValue() : false);
    model.addAttribute("editIcon", app.getConfig().get("edit-icon") != null ? app.getConfig().get("edit-icon").getTextValue() : null);
    model.addAttribute("editProvider", app.getConfig().get("edit-provider") != null ? app.getConfig().get("edit-provider").getTextValue() : null);
    model.addAttribute("editFragment", app.getConfig().get("edit-fragment") != null ? app.getConfig().get("edit-fragment").getTextValue() : null);
    String returnUrl = config.getAttribute("returnUrl") != null ? config.getAttribute("returnUrl").toString() : null;
    if (StringUtils.isBlank(returnUrl)) {
        returnUrl = getNodeValue(app.getConfig(), "returnUrl", null);
    }
    if (StringUtils.isBlank(returnUrl)) {
        String returnProvider = getNodeValue(app.getConfig(), "returnProvider", null);
        String returnPage = getNodeValue(app.getConfig(), "returnPage", null);
        if (StringUtils.isNotBlank(returnProvider) && StringUtils.isNotBlank(returnPage)) {
            returnUrl = ui.pageLink(returnProvider, returnPage, SimpleObject.create("patientId", patient.getId()));
        }
    }
    model.addAttribute("returnUrl", returnUrl);
}
Also used : ArrayList(java.util.ArrayList) Encounter(org.openmrs.Encounter) EncounterServiceCompatibility(org.openmrs.module.coreapps.EncounterServiceCompatibility) EncounterType(org.openmrs.EncounterType)

Aggregations

EncounterType (org.openmrs.EncounterType)60 Test (org.junit.Test)44 BaseContextSensitiveTest (org.openmrs.test.BaseContextSensitiveTest)42 Encounter (org.openmrs.Encounter)19 Date (java.util.Date)17 Location (org.openmrs.Location)12 Patient (org.openmrs.Patient)10 User (org.openmrs.User)10 EncounterRole (org.openmrs.EncounterRole)9 Provider (org.openmrs.Provider)8 BindException (org.springframework.validation.BindException)7 Errors (org.springframework.validation.Errors)7 ArrayList (java.util.ArrayList)5 GlobalProperty (org.openmrs.GlobalProperty)5 List (java.util.List)4 Privilege (org.openmrs.Privilege)4 Concept (org.openmrs.Concept)3 Visit (org.openmrs.Visit)3 HashMap (java.util.HashMap)2 SQLQuery (org.hibernate.SQLQuery)2