Search in sources :

Example 16 with FINAL

use of org.hl7.fhir.r4.model.Observation.ObservationStatus.FINAL in project quality-measure-and-cohort-service by Alvearie.

the class CohortEngineRestHandler method getMeasureParametersById.

@POST
@Path("/fhir/measure/{measure_id}/parameters")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@ApiOperation(value = "Get measure parameters by id", notes = CohortEngineRestHandler.MEASURE_API_NOTES, response = MeasureParameterInfoList.class, nickname = "get_measure_parameters_by_id", tags = { "FHIR Measures" })
@ApiImplicitParams({ @ApiImplicitParam(name = FHIR_DATA_SERVER_CONFIG_PART, value = CohortEngineRestHandler.EXAMPLE_DATA_SERVER_CONFIG_JSON, dataTypeClass = FhirServerConfig.class, required = true, paramType = "form", type = "file") })
@ApiResponses(value = { @ApiResponse(code = 200, message = "Successful Operation", response = MeasureParameterInfoList.class), @ApiResponse(code = 400, message = "Bad Request", response = ServiceErrorList.class), @ApiResponse(code = 500, message = "Server Error", response = ServiceErrorList.class) })
public Response getMeasureParametersById(@ApiParam(value = ServiceBaseConstants.MINOR_VERSION_DESCRIPTION, required = true, defaultValue = ServiceBuildConstants.DATE) @QueryParam(CohortEngineRestHandler.VERSION) String version, @ApiParam(hidden = true, type = "file", required = true) IMultipartBody multipartBody, @ApiParam(value = CohortEngineRestHandler.MEASURE_ID_DESC, required = true) @PathParam(CohortEngineRestHandler.MEASURE_ID) String measureId) {
    final String methodName = MethodNames.GET_MEASURE_PARAMETERS_BY_ID.getName();
    Response response = null;
    try {
        // Perform api setup
        Response errorResponse = ServiceBaseUtility.apiSetup(version, logger, methodName);
        if (errorResponse != null) {
            return errorResponse;
        }
        IAttachment dataSourceAttachment = multipartBody.getAttachment(FHIR_DATA_SERVER_CONFIG_PART);
        if (dataSourceAttachment == null) {
            throw new IllegalArgumentException(String.format("Missing '%s' MIME attachment", FHIR_DATA_SERVER_CONFIG_PART));
        }
        // deserialize the MeasuresEvaluation request
        ObjectMapper om = new ObjectMapper();
        FhirServerConfig fhirServerConfig = om.readValue(dataSourceAttachment.getDataHandler().getInputStream(), FhirServerConfig.class);
        // validate the contents of the fhirServerConfig
        validateBean(fhirServerConfig);
        // get the fhir client object used to call to FHIR
        FhirClientBuilder clientBuilder = FhirClientBuilderFactory.newInstance().newFhirClientBuilder();
        IGenericClient measureClient = clientBuilder.createFhirClient(fhirServerConfig);
        // resolve the measure, and return the parameter info for all the libraries linked to by the measure
        FhirResourceResolver<Measure> measureResolver = R4FhirServerResourceResolverFactory.createMeasureResolver(measureClient);
        List<MeasureParameterInfo> parameterInfoList = FHIRRestUtils.getParametersForMeasureId(measureResolver, measureId);
        // return the results
        MeasureParameterInfoList status = new MeasureParameterInfoList().measureParameterInfoList(parameterInfoList);
        response = Response.ok(status).build();
    } catch (Throwable e) {
        // map any exceptions caught into the proper REST error response objects
        return new CohortServiceExceptionMapper().toResponse(e);
    } finally {
        // Perform api cleanup
        Response errorResponse = ServiceBaseUtility.apiCleanup(logger, methodName);
        if (errorResponse != null) {
            response = errorResponse;
        }
    }
    return response;
}
Also used : MeasureParameterInfo(com.ibm.cohort.engine.api.service.model.MeasureParameterInfo) FhirClientBuilder(com.ibm.cohort.fhir.client.config.FhirClientBuilder) IGenericClient(ca.uhn.fhir.rest.client.api.IGenericClient) IAttachment(com.ibm.websphere.jaxrs20.multipart.IAttachment) Response(javax.ws.rs.core.Response) ApiResponse(io.swagger.annotations.ApiResponse) Measure(org.hl7.fhir.r4.model.Measure) MeasureParameterInfoList(com.ibm.cohort.engine.api.service.model.MeasureParameterInfoList) FhirServerConfig(com.ibm.cohort.fhir.client.config.FhirServerConfig) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Path(javax.ws.rs.Path) ApiImplicitParams(io.swagger.annotations.ApiImplicitParams) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) Consumes(javax.ws.rs.Consumes) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 17 with FINAL

use of org.hl7.fhir.r4.model.Observation.ObservationStatus.FINAL in project quality-measure-and-cohort-service by Alvearie.

the class CohortEngineRestHandler method evaluateMeasure.

@POST
@Path("/evaluation")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({ MediaType.APPLICATION_JSON })
@ApiOperation(value = "Evaluates a measure bundle for a single patient", notes = EVALUATION_API_NOTES, response = String.class, tags = { "Measure Evaluation" }, nickname = "evaluate_measure", extensions = { @Extension(properties = { @ExtensionProperty(name = DarkFeatureSwaggerFilter.DARK_FEATURE_NAME, value = CohortEngineRestConstants.DARK_LAUNCHED_MEASURE_EVALUATION) }) })
@ApiImplicitParams({ // This is necessary for the dark launch feature
@ApiImplicitParam(access = DarkFeatureSwaggerFilter.DARK_FEATURE_CONTROLLED, paramType = "header", dataType = "string"), // These are necessary to create a proper view of the request body that is all wrapped up in the Liberty IMultipartBody parameter
@ApiImplicitParam(name = REQUEST_DATA_PART, value = EXAMPLE_REQUEST_DATA_JSON, dataTypeClass = MeasureEvaluation.class, required = true, paramType = "form", type = "file"), @ApiImplicitParam(name = MEASURE_PART, value = EXAMPLE_MEASURE_ZIP, dataTypeClass = File.class, required = true, paramType = "form", type = "file") })
@ApiResponses(value = { @ApiResponse(code = 200, message = "Successful Operation: This API returns the JSON representation of a FHIR MeasureReport. A full example can be found at https://www.hl7.org/fhir/measurereport-cms146-cat1-example.html"), @ApiResponse(code = 400, message = "Bad Request", response = ServiceErrorList.class), @ApiResponse(code = 500, message = "Server Error", response = ServiceErrorList.class) })
public Response evaluateMeasure(@Context HttpServletRequest request, @ApiParam(value = ServiceBaseConstants.MINOR_VERSION_DESCRIPTION, required = true, defaultValue = ServiceBuildConstants.DATE) @QueryParam(CohortEngineRestHandler.VERSION) String version, @ApiParam(hidden = true, type = "file", required = true) IMultipartBody multipartBody) {
    final String methodName = MethodNames.EVALUATE_MEASURE.getName();
    Response response = null;
    // Error out if feature is not enabled
    ServiceBaseUtility.isDarkFeatureEnabled(CohortEngineRestConstants.DARK_LAUNCHED_MEASURE_EVALUATION);
    try {
        // Perform api setup
        Response errorResponse = ServiceBaseUtility.apiSetup(version, logger, methodName);
        if (errorResponse != null) {
            return errorResponse;
        }
        if (multipartBody == null) {
            throw new IllegalArgumentException("A multipart/form-data body is required");
        }
        IAttachment metadataAttachment = multipartBody.getAttachment(REQUEST_DATA_PART);
        if (metadataAttachment == null) {
            throw new IllegalArgumentException(String.format("Missing '%s' MIME attachment", REQUEST_DATA_PART));
        }
        IAttachment measureAttachment = multipartBody.getAttachment(MEASURE_PART);
        if (measureAttachment == null) {
            throw new IllegalArgumentException(String.format("Missing '%s' MIME attachment", MEASURE_PART));
        }
        // deserialize the MeasuresEvaluation request
        ObjectMapper om = new ObjectMapper();
        MeasureEvaluation evaluationRequest = om.readValue(metadataAttachment.getDataHandler().getInputStream(), MeasureEvaluation.class);
        // validate the contents of the evaluationRequest
        validateBean(evaluationRequest);
        FhirContext fhirContext = FhirContext.forR4();
        try (InputStream is = measureAttachment.getDataHandler().getInputStream();
            RetrieveCacheContext retrieveCacheContext = new DefaultRetrieveCacheContext()) {
            MeasureEvaluator evaluator = createMeasureEvaluator(is, evaluationRequest.getDataServerConfig(), evaluationRequest.getTerminologyServerConfig(), evaluationRequest.isExpandValueSets(), evaluationRequest.getSearchPageSize(), retrieveCacheContext, fhirContext);
            MeasureReport report = evaluator.evaluatePatientMeasure(evaluationRequest.getPatientId(), evaluationRequest.getMeasureContext(), evaluationRequest.getEvidenceOptions());
            // The default serializer gets into an infinite loop when trying to serialize MeasureReport, so we use the
            // HAPI encoder instead.
            IParser parser = fhirContext.newJsonParser();
            ResponseBuilder responseBuilder = Response.status(Response.Status.OK).header("Content-Type", "application/json").entity(parser.encodeResourceToString(report));
            response = responseBuilder.build();
        }
    } catch (Throwable e) {
        // map any exceptions caught into the proper REST error response objects
        response = new CohortServiceExceptionMapper().toResponse(e);
    } finally {
        // Perform api cleanup
        Response errorResponse = ServiceBaseUtility.apiCleanup(logger, methodName);
        if (errorResponse != null) {
            response = errorResponse;
        }
    }
    return response;
}
Also used : FhirContext(ca.uhn.fhir.context.FhirContext) MeasureEvaluation(com.ibm.cohort.engine.api.service.model.MeasureEvaluation) PatientListMeasureEvaluation(com.ibm.cohort.engine.api.service.model.PatientListMeasureEvaluation) ZipInputStream(java.util.zip.ZipInputStream) InputStream(java.io.InputStream) DefaultRetrieveCacheContext(com.ibm.cohort.engine.measure.cache.DefaultRetrieveCacheContext) RetrieveCacheContext(com.ibm.cohort.engine.measure.cache.RetrieveCacheContext) MeasureReport(org.hl7.fhir.r4.model.MeasureReport) DefaultRetrieveCacheContext(com.ibm.cohort.engine.measure.cache.DefaultRetrieveCacheContext) MeasureEvaluator(com.ibm.cohort.engine.measure.MeasureEvaluator) IAttachment(com.ibm.websphere.jaxrs20.multipart.IAttachment) Response(javax.ws.rs.core.Response) ApiResponse(io.swagger.annotations.ApiResponse) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IParser(ca.uhn.fhir.parser.IParser) Path(javax.ws.rs.Path) ApiImplicitParams(io.swagger.annotations.ApiImplicitParams) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 18 with FINAL

use of org.hl7.fhir.r4.model.Observation.ObservationStatus.FINAL in project quality-measure-and-cohort-service by Alvearie.

the class CohortEngineRestHandler method getMeasureParameters.

@POST
@Path("/fhir/measure/identifier/{measure_identifier_value}/parameters")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@ApiOperation(value = "Get measure parameters", notes = CohortEngineRestHandler.MEASURE_API_NOTES, response = MeasureParameterInfoList.class, authorizations = { @Authorization(value = "BasicAuth") }, responseContainer = "List", tags = { "FHIR Measures" })
@ApiImplicitParams({ @ApiImplicitParam(name = FHIR_DATA_SERVER_CONFIG_PART, value = CohortEngineRestHandler.EXAMPLE_DATA_SERVER_CONFIG_JSON, dataTypeClass = FhirServerConfig.class, required = true, paramType = "form", type = "file") })
@ApiResponses(value = { @ApiResponse(code = 200, message = "Successful Operation", response = MeasureParameterInfoList.class), @ApiResponse(code = 400, message = "Bad Request", response = ServiceErrorList.class), @ApiResponse(code = 500, message = "Server Error", response = ServiceErrorList.class) })
public Response getMeasureParameters(@ApiParam(value = ServiceBaseConstants.MINOR_VERSION_DESCRIPTION, required = true, defaultValue = ServiceBuildConstants.DATE) @QueryParam(CohortEngineRestHandler.VERSION) String version, @ApiParam(hidden = true, type = "file", required = true) IMultipartBody multipartBody, @ApiParam(value = CohortEngineRestHandler.MEASURE_IDENTIFIER_VALUE_DESC, required = true) @PathParam(CohortEngineRestHandler.MEASURE_IDENTIFIER_VALUE) String measureIdentifierValue, @ApiParam(value = CohortEngineRestHandler.MEASURE_IDENTIFIER_SYSTEM_DESC, required = false) @QueryParam(CohortEngineRestHandler.MEASURE_IDENTIFIER_SYSTEM) String measureIdentifierSystem, @ApiParam(value = CohortEngineRestHandler.MEASURE_VERSION_DESC, required = false) @QueryParam(CohortEngineRestHandler.MEASURE_VERSION) String measureVersion) {
    final String methodName = MethodNames.GET_MEASURE_PARAMETERS.getName();
    Response response = null;
    try {
        // Perform api setup
        Response errorResponse = ServiceBaseUtility.apiSetup(version, logger, methodName);
        if (errorResponse != null) {
            return errorResponse;
        }
        IAttachment dataSourceAttachment = multipartBody.getAttachment(FHIR_DATA_SERVER_CONFIG_PART);
        if (dataSourceAttachment == null) {
            throw new IllegalArgumentException(String.format("Missing '%s' MIME attachment", FHIR_DATA_SERVER_CONFIG_PART));
        }
        // deserialize the MeasuresEvaluation request
        ObjectMapper om = new ObjectMapper();
        FhirServerConfig fhirServerConfig = om.readValue(dataSourceAttachment.getDataHandler().getInputStream(), FhirServerConfig.class);
        // validate the contents of the fhirServerConfig
        validateBean(fhirServerConfig);
        // get the fhir client object used to call to FHIR
        FhirClientBuilder clientBuilder = FhirClientBuilderFactory.newInstance().newFhirClientBuilder();
        IGenericClient measureClient = clientBuilder.createFhirClient(fhirServerConfig);
        // build the identifier object which is used by the fhir client
        // to find the measure
        Identifier identifier = new Identifier().setValue(measureIdentifierValue).setSystem(measureIdentifierSystem);
        // resolve the measure, and return the parameter info for all the libraries linked to by the measure
        FhirResourceResolver<Measure> measureResolver = R4FhirServerResourceResolverFactory.createMeasureResolver(measureClient);
        List<MeasureParameterInfo> parameterInfoList = FHIRRestUtils.getParametersForMeasureIdentifier(measureResolver, identifier, measureVersion);
        // return the results
        MeasureParameterInfoList status = new MeasureParameterInfoList().measureParameterInfoList(parameterInfoList);
        response = Response.ok(status).build();
    } catch (Throwable e) {
        // map any exceptions caught into the proper REST error response objects
        return new CohortServiceExceptionMapper().toResponse(e);
    } finally {
        // Perform api cleanup
        Response errorResponse = ServiceBaseUtility.apiCleanup(logger, methodName);
        if (errorResponse != null) {
            response = errorResponse;
        }
    }
    return response;
}
Also used : MeasureParameterInfo(com.ibm.cohort.engine.api.service.model.MeasureParameterInfo) FhirClientBuilder(com.ibm.cohort.fhir.client.config.FhirClientBuilder) IGenericClient(ca.uhn.fhir.rest.client.api.IGenericClient) IAttachment(com.ibm.websphere.jaxrs20.multipart.IAttachment) Response(javax.ws.rs.core.Response) ApiResponse(io.swagger.annotations.ApiResponse) Identifier(org.hl7.fhir.r4.model.Identifier) Measure(org.hl7.fhir.r4.model.Measure) MeasureParameterInfoList(com.ibm.cohort.engine.api.service.model.MeasureParameterInfoList) FhirServerConfig(com.ibm.cohort.fhir.client.config.FhirServerConfig) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Path(javax.ws.rs.Path) ApiImplicitParams(io.swagger.annotations.ApiImplicitParams) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) Consumes(javax.ws.rs.Consumes) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 19 with FINAL

use of org.hl7.fhir.r4.model.Observation.ObservationStatus.FINAL in project quality-measure-and-cohort-service by Alvearie.

the class DefaultVT method testMeasureEvaluationByMeasureIdentifier.

// to tag a specific test to be part of DVT (deployment verification test)
@Category(DVT.class)
@Test
public /**
 * Test a successful measure evaluation using identifier and version as the lookup key
 */
void testMeasureEvaluationByMeasureIdentifier() throws Exception {
    // You want -Denabled.dark.features=all in your Liberty jvm.options
    Assume.assumeTrue(isServiceDarkFeatureEnabled(CohortEngineRestConstants.DARK_LAUNCHED_MEASURE_EVALUATION));
    final String RESOURCE = getUrlBase() + CohortServiceAPISpec.CREATE_DELETE_EVALUATION_PATH;
    FhirContext fhirContext = FhirContext.forR4();
    IParser parser = fhirContext.newJsonParser().setPrettyPrint(true);
    Library library = TestHelper.getTemplateLibrary();
    Identifier identifier = new Identifier().setValue("measure-identifier").setSystem("http://ibm.com/health/test");
    Measure measure = TestHelper.getTemplateMeasure(library);
    measure.setIdentifier(Arrays.asList(identifier));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    TestHelper.createMeasureArtifact(baos, parser, measure, library);
    // Files.write( baos.toByteArray(), new File("target/test_measure_v1_0_0.zip"));
    Map<String, Parameter> parameterOverrides = new HashMap<>();
    parameterOverrides.put("Measurement Period", new IntervalParameter(new DateParameter("2019-07-04"), true, new DateParameter("2020-07-04"), true));
    MeasureEvaluation requestData = new MeasureEvaluation();
    requestData.setDataServerConfig(dataServerConfig);
    requestData.setTerminologyServerConfig(termServerConfig);
    // This is a patient ID that is assumed to exist in the target FHIR server
    requestData.setPatientId(VALID_PATIENT_ID);
    requestData.setMeasureContext(new MeasureContext(null, parameterOverrides, new com.ibm.cohort.engine.measure.Identifier(identifier.getSystem(), identifier.getValue()), measure.getVersion()));
    requestData.setEvidenceOptions(new MeasureEvidenceOptions(false, MeasureEvidenceOptions.DefineReturnOptions.NONE));
    ObjectMapper om = new ObjectMapper();
    System.out.println(om.writeValueAsString(requestData));
    RequestSpecification request = buildBaseRequest(new Headers()).queryParam(CohortEngineRestHandler.VERSION, ServiceBuildConstants.DATE).multiPart(CohortEngineRestHandler.REQUEST_DATA_PART, requestData, "application/json").multiPart(CohortEngineRestHandler.MEASURE_PART, "test_measure_v1_0_0.zip", new ByteArrayInputStream(baos.toByteArray()));
    ValidatableResponse response = request.post(RESOURCE, getServiceVersion()).then();
    ValidatableResponse vr = runSuccessValidation(response, ContentType.JSON, HttpStatus.SC_OK);
    String expected = getJsonFromFile(ServiceAPIGlobalSpec.EXP_FOLDER_TYPE, "measure_evaluation_exp.json");
    String actual = vr.extract().asString();
    assertMeasureReportEquals(parser, expected, actual, false);
}
Also used : FhirContext(ca.uhn.fhir.context.FhirContext) ValidatableResponse(com.jayway.restassured.response.ValidatableResponse) HashMap(java.util.HashMap) MeasureEvaluation(com.ibm.cohort.engine.api.service.model.MeasureEvaluation) PatientListMeasureEvaluation(com.ibm.cohort.engine.api.service.model.PatientListMeasureEvaluation) Headers(com.jayway.restassured.response.Headers) RequestSpecification(com.jayway.restassured.specification.RequestSpecification) ByteArrayOutputStream(java.io.ByteArrayOutputStream) MeasureEvidenceOptions(com.ibm.cohort.engine.measure.evidence.MeasureEvidenceOptions) MeasureContext(com.ibm.cohort.engine.measure.MeasureContext) Identifier(org.hl7.fhir.r4.model.Identifier) DateParameter(com.ibm.cohort.cql.evaluation.parameters.DateParameter) ByteArrayInputStream(java.io.ByteArrayInputStream) Measure(org.hl7.fhir.r4.model.Measure) DateParameter(com.ibm.cohort.cql.evaluation.parameters.DateParameter) Parameter(com.ibm.cohort.cql.evaluation.parameters.Parameter) IntervalParameter(com.ibm.cohort.cql.evaluation.parameters.IntervalParameter) Library(org.hl7.fhir.r4.model.Library) IntervalParameter(com.ibm.cohort.cql.evaluation.parameters.IntervalParameter) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IParser(ca.uhn.fhir.parser.IParser) Category(org.junit.experimental.categories.Category) Test(org.junit.Test)

Example 20 with FINAL

use of org.hl7.fhir.r4.model.Observation.ObservationStatus.FINAL in project openmrs-module-fhir2 by openmrs.

the class ImmunizationTranslatorImpl method toOpenmrsType.

@Override
public Obs toOpenmrsType(@Nonnull Obs openmrsImmunization, @Nonnull Immunization fhirImmunization) {
    if (openmrsImmunization == null) {
        return null;
    }
    if (fhirImmunization == null) {
        return openmrsImmunization;
    }
    Patient patient = patientReferenceTranslator.toOpenmrsType(fhirImmunization.getPatient());
    if (patient == null) {
        final String errMsg;
        if (fhirImmunization.getPatient().hasReference()) {
            errMsg = "Could not find patient matching " + fhirImmunization.getPatient().getReference();
        } else {
            errMsg = "No patient was specified for this request";
        }
        throw createImmunizationRequestValidationError(errMsg);
    }
    List<ImmunizationPerformerComponent> performers = fhirImmunization.getPerformer();
    Provider provider = null;
    if (performers.size() > 1) {
        throw createImmunizationRequestValidationError("More than one performer was specified. Only a single performer is currently supported for each immunization.");
    } else if (performers.size() == 1) {
        ImmunizationPerformerComponent performer = performers.get(0);
        if (performer != null && performer.hasActor()) {
            provider = practitionerReferenceTranslator.toOpenmrsType(performer.getActor());
        }
    }
    final Visit visit;
    if (fhirImmunization.hasEncounter()) {
        visit = visitReferenceTranslator.toOpenmrsType(fhirImmunization.getEncounter());
    } else {
        visit = null;
    }
    if (visit == null) {
        final String errMsg;
        if (fhirImmunization.getEncounter().hasReference()) {
            errMsg = "Could not find visit matching " + fhirImmunization.getEncounter().getReference();
        } else {
            errMsg = "No encounter was specified for this request";
        }
        throw createImmunizationRequestValidationError(errMsg);
    }
    Location location = visit.getLocation();
    if (fhirImmunization.hasLocation()) {
        Location recordedLocation = locationReferenceTranslator.toOpenmrsType(fhirImmunization.getLocation());
        if (recordedLocation != null) {
            location = recordedLocation;
        }
    }
    if (!patient.equals(visit.getPatient())) {
        throw createImmunizationRequestValidationError("The visit '" + visit.getUuid() + "' does not belong to patient '" + patient.getUuid() + "'.");
    }
    EncounterType encounterType = helper.getImmunizationsEncounterType();
    // taking the visit's most recent immunization encounter
    Optional<Encounter> existingEncounter = visit.getEncounters().stream().filter(e -> encounterType.equals(e.getEncounterType())).max(Comparator.comparing(Encounter::getEncounterDatetime));
    final Provider encounterProvider = provider;
    final Location finalLocation = location;
    Encounter encounter = existingEncounter.orElseGet(() -> {
        final EncounterRole encounterRole = helper.getAdministeringEncounterRole();
        final Encounter newEncounter = new Encounter();
        newEncounter.setVisit(visit);
        newEncounter.setLocation(finalLocation);
        newEncounter.setEncounterType(encounterType);
        newEncounter.setPatient(patient);
        if (encounterProvider != null) {
            newEncounter.setProvider(encounterRole, encounterProvider);
        }
        if (visit.getStopDatetime() != null) {
            newEncounter.setEncounterDatetime(visit.getStopDatetime());
        } else {
            newEncounter.setEncounterDatetime(openmrsImmunization.getObsDatetime());
        }
        return newEncounter;
    });
    openmrsImmunization.setPerson(patient);
    openmrsImmunization.setLocation(location);
    openmrsImmunization.setEncounter(encounter);
    openmrsImmunization.getGroupMembers().forEach(obs -> {
        obs.setPerson(patient);
        obs.setLocation(finalLocation);
        obs.setEncounter(encounter);
    });
    Map<String, Obs> members = helper.getObsMembersMap(openmrsImmunization);
    Coding coding = fhirImmunization.getVaccineCode().getCoding().stream().filter(code -> StringUtils.isEmpty(code.getSystem())).reduce((code1, code2) -> {
        throw createImmunizationRequestValidationError("Multiple system-less coding found for the immunization's vaccine: " + code1.getCode() + " and " + code2.getCode() + ". No unique system concept could be identified as the coded answer.");
    }).orElseThrow(() -> createImmunizationRequestValidationError("Could not find a valid coding could be identified for this immunization."));
    {
        Obs obs = members.get(CIEL_984);
        if (obs == null) {
            obs = helper.addNewObs(openmrsImmunization, CIEL_984);
            members.put(CIEL_984, obs);
            obs.setValueCoded(conceptService.getConceptByUuid(coding.getCode()));
        } else if (obs.getId() == null) {
            obs.setValueCoded(conceptService.getConceptByUuid(coding.getCode()));
        } else {
            Concept newValue = conceptService.getConceptByUuid(coding.getCode());
            Concept prevValue = obs.getValueCoded();
            if (!newValue.equals(prevValue)) {
                obs = helper.replaceObs(openmrsImmunization, obs);
                obs.setValueCoded(newValue);
            }
        }
    }
    if (!fhirImmunization.hasOccurrenceDateTimeType() || !fhirImmunization.getOccurrenceDateTimeType().hasValue()) {
        throw createImmunizationRequestValidationError("An Immunization must have a valid occurrenceDateTime value");
    }
    {
        Obs obs = members.get(CIEL_1410);
        if (obs == null) {
            obs = helper.addNewObs(openmrsImmunization, CIEL_1410);
            members.put(CIEL_1410, obs);
            obs.setValueDatetime(fhirImmunization.getOccurrenceDateTimeType().getValue());
        } else if (obs.getId() == null) {
            obs.setValueDatetime(fhirImmunization.getOccurrenceDateTimeType().getValue());
        } else {
            Date newValue = fhirImmunization.getOccurrenceDateTimeType().getValue();
            Date prevValue = obs.getValueDatetime();
            if (!newValue.equals(prevValue)) {
                obs = helper.replaceObs(openmrsImmunization, obs);
                obs.setValueDatetime(newValue);
            }
        }
    }
    if (fhirImmunization.hasProtocolApplied()) {
        if (fhirImmunization.getProtocolApplied().size() != 1) {
            throw createImmunizationRequestValidationError("Either no protocol applied was found or multiple protocols applied were found. " + "Only one protocol is currently supported for each immunization.");
        }
        ImmunizationProtocolAppliedComponent protocolApplied = fhirImmunization.getProtocolApplied().get(0);
        if (protocolApplied.hasDoseNumber()) {
            {
                Obs obs = members.get(CIEL_1418);
                if (obs == null) {
                    obs = helper.addNewObs(openmrsImmunization, CIEL_1418);
                    members.put(CIEL_1418, obs);
                    obs.setValueNumeric(protocolApplied.getDoseNumberPositiveIntType().getValue().doubleValue());
                } else if (obs.getId() == null) {
                    obs.setValueNumeric(protocolApplied.getDoseNumberPositiveIntType().getValue().doubleValue());
                } else {
                    double newValue = protocolApplied.getDoseNumberPositiveIntType().getValue().doubleValue();
                    Double updatedValue = obs.getValueNumeric();
                    if (updatedValue != null && newValue != updatedValue) {
                        obs = helper.replaceObs(openmrsImmunization, obs);
                        obs.setValueNumeric(newValue);
                    }
                }
            }
        }
    } else {
        openmrsImmunization.removeGroupMember(members.get(CIEL_1418));
    }
    if (fhirImmunization.hasManufacturer() && fhirImmunization.getManufacturer().hasDisplay()) {
        {
            Obs obs = members.get(CIEL_1419);
            if (obs == null) {
                obs = helper.addNewObs(openmrsImmunization, CIEL_1419);
                members.put(CIEL_1419, obs);
                obs.setValueText(fhirImmunization.getManufacturer().getDisplay());
            } else if (obs.getId() == null) {
                obs.setValueText(fhirImmunization.getManufacturer().getDisplay());
            } else {
                String newValue = fhirImmunization.getManufacturer().getDisplay();
                String prevValue = obs.getValueText();
                if (!newValue.equals(prevValue)) {
                    obs = helper.replaceObs(openmrsImmunization, obs);
                    obs.setValueText(newValue);
                }
            }
        }
    } else {
        openmrsImmunization.removeGroupMember(members.get(CIEL_1419));
    }
    if (fhirImmunization.hasLotNumber()) {
        {
            Obs obs = members.get(CIEL_1420);
            if (obs == null) {
                obs = helper.addNewObs(openmrsImmunization, CIEL_1420);
                members.put(CIEL_1420, obs);
                obs.setValueText(fhirImmunization.getLotNumber());
            } else if (obs.getId() == null) {
                obs.setValueText(fhirImmunization.getLotNumber());
            } else {
                String newValue = fhirImmunization.getLotNumber();
                String prevValue = obs.getValueText();
                if (!newValue.equals(prevValue)) {
                    obs = helper.replaceObs(openmrsImmunization, obs);
                    obs.setValueText(newValue);
                }
            }
        }
    } else {
        openmrsImmunization.removeGroupMember(members.get(CIEL_1420));
    }
    if (fhirImmunization.hasExpirationDate()) {
        {
            Obs obs = members.get(CIEL_165907);
            if (obs == null) {
                obs = helper.addNewObs(openmrsImmunization, CIEL_165907);
                members.put(CIEL_165907, obs);
                obs.setValueDate(fhirImmunization.getExpirationDate());
            } else if (obs.getId() == null) {
                obs.setValueDate(fhirImmunization.getExpirationDate());
            } else {
                Date newValue = fhirImmunization.getExpirationDate();
                Date prevValue = obs.getValueDate();
                if (!newValue.equals(prevValue)) {
                    obs = helper.replaceObs(openmrsImmunization, obs);
                    obs.setValueDate(newValue);
                }
            }
        }
    } else {
        openmrsImmunization.removeGroupMember(members.get(CIEL_165907));
    }
    return openmrsImmunization;
}
Also used : Setter(lombok.Setter) ImmunizationObsGroupHelper.createImmunizationRequestValidationError(org.openmrs.module.fhir2.api.util.ImmunizationObsGroupHelper.createImmunizationRequestValidationError) Date(java.util.Date) Visit(org.openmrs.Visit) Autowired(org.springframework.beans.factory.annotation.Autowired) ImmunizationPerformerComponent(org.hl7.fhir.r4.model.Immunization.ImmunizationPerformerComponent) Reference(org.hl7.fhir.r4.model.Reference) StringUtils(org.apache.commons.lang3.StringUtils) AccessLevel(lombok.AccessLevel) ImmunizationProtocolAppliedComponent(org.hl7.fhir.r4.model.Immunization.ImmunizationProtocolAppliedComponent) Location(org.openmrs.Location) ImmunizationObsGroupHelper(org.openmrs.module.fhir2.api.util.ImmunizationObsGroupHelper) ImmunizationStatus(org.hl7.fhir.r4.model.Immunization.ImmunizationStatus) Map(java.util.Map) ConceptService(org.openmrs.api.ConceptService) Obs(org.openmrs.Obs) Nonnull(javax.annotation.Nonnull) PractitionerReferenceTranslator(org.openmrs.module.fhir2.api.translators.PractitionerReferenceTranslator) ImmunizationTranslator(org.openmrs.module.fhir2.api.translators.ImmunizationTranslator) ImmutableSet(com.google.common.collect.ImmutableSet) Encounter(org.openmrs.Encounter) Iterator(java.util.Iterator) EncounterReferenceTranslator(org.openmrs.module.fhir2.api.translators.EncounterReferenceTranslator) ConceptTranslator(org.openmrs.module.fhir2.api.translators.ConceptTranslator) Set(java.util.Set) LocationReferenceTranslator(org.openmrs.module.fhir2.api.translators.LocationReferenceTranslator) List(java.util.List) Immunization(org.hl7.fhir.r4.model.Immunization) Component(org.springframework.stereotype.Component) Concept(org.openmrs.Concept) Provider(org.openmrs.Provider) EncounterType(org.openmrs.EncounterType) Coding(org.hl7.fhir.r4.model.Coding) PatientReferenceTranslator(org.openmrs.module.fhir2.api.translators.PatientReferenceTranslator) Optional(java.util.Optional) ObservationValueTranslator(org.openmrs.module.fhir2.api.translators.ObservationValueTranslator) PositiveIntType(org.hl7.fhir.r4.model.PositiveIntType) Comparator(java.util.Comparator) Collections(java.util.Collections) Patient(org.openmrs.Patient) EncounterRole(org.openmrs.EncounterRole) Concept(org.openmrs.Concept) Obs(org.openmrs.Obs) ImmunizationPerformerComponent(org.hl7.fhir.r4.model.Immunization.ImmunizationPerformerComponent) Visit(org.openmrs.Visit) Patient(org.openmrs.Patient) Date(java.util.Date) Provider(org.openmrs.Provider) Coding(org.hl7.fhir.r4.model.Coding) Encounter(org.openmrs.Encounter) EncounterRole(org.openmrs.EncounterRole) ImmunizationProtocolAppliedComponent(org.hl7.fhir.r4.model.Immunization.ImmunizationProtocolAppliedComponent) EncounterType(org.openmrs.EncounterType) Location(org.openmrs.Location)

Aggregations

Test (org.junit.jupiter.api.Test)229 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)85 HashMap (java.util.HashMap)83 CamelSpringBootTest (org.apache.camel.test.spring.junit5.CamelSpringBootTest)59 List (java.util.List)53 Bundle (org.hl7.fhir.dstu3.model.Bundle)50 Nonnull (javax.annotation.Nonnull)48 Patient (org.hl7.fhir.dstu3.model.Patient)46 Organization (org.hl7.fhir.dstu3.model.Organization)45 ArrayList (java.util.ArrayList)44 Bundle (org.hl7.fhir.r4.model.Bundle)41 IBaseResource (org.hl7.fhir.instance.model.api.IBaseResource)39 UUID (java.util.UUID)38 Collectors (java.util.stream.Collectors)38 Coding (org.hl7.fhir.r4.model.Coding)34 FhirContext (ca.uhn.fhir.context.FhirContext)33 IGenericClient (ca.uhn.fhir.rest.client.api.IGenericClient)32 IParser (ca.uhn.fhir.parser.IParser)31 IOException (java.io.IOException)29 IdType (org.hl7.fhir.dstu3.model.IdType)28