Search in sources :

Example 11 with Period

use of org.hl7.fhir.dstu2016may.model.Period in project hl7v2-fhir-converter by LinuxForHealth.

the class HL7EventTypeFHIRConversionTest method validate_evn_segment.

@Test
void validate_evn_segment() {
    String hl7message = "MSH|^~\\&|||||||ADT^A01^ADT_A01|64322|P|2.6|123|456|ER|AL|USA|ASCII|en|2.6||||||\r" + // + "EVN||||851||20210319134735|\r"  // TODO, not working with this value
    "EVN||||O||20210319134735|\r" + "PV1|1|I||R|||||||||R|1||||||||||||||||||||||||||||||||||||||";
    String json = ftv.convert(hl7message, OPTIONS);
    assertThat(json).isNotBlank();
    FHIRContext context = new FHIRContext(true, false);
    IBaseResource bundleResource = context.getParser().parseResource(json);
    assertThat(bundleResource).isNotNull();
    Bundle b = (Bundle) bundleResource;
    List<BundleEntryComponent> e = b.getEntry();
    // Find the encounter from the FHIR bundle.
    List<Resource> encounterResource = e.stream().filter(v -> ResourceType.Encounter == v.getResource().getResourceType()).map(BundleEntryComponent::getResource).collect(Collectors.toList());
    assertThat(encounterResource).hasSize(1);
    Encounter encounter = (Encounter) encounterResource.get(0);
    // ENV.4 is used for reasonCode
    List<CodeableConcept> reasonCodes = encounter.getReasonCode();
    assertEquals(1, reasonCodes.size());
    CodeableConcept encounterReason = encounter.getReasonCodeFirstRep();
    Coding encounterReasonCoding = encounterReason.getCodingFirstRep();
    // assertThat(encounterReasonCoding.getCode()).isEqualTo("851");  // TODO, should be able to use user-defined values
    assertThat(encounterReasonCoding.getCode()).isEqualTo("O");
    // EVN.6 is used for start period (with no end) if there is no PV1.44
    Base period = encounter.getNamedProperty("period").getValues().get(0);
    String startPeriod = period.getNamedProperty("start").getValues().get(0).toString();
    int endPeriodSize = period.getNamedProperty("end").getValues().size();
    assertThat(startPeriod).isEqualTo("DateTimeType[2021-03-19T13:47:35+08:00]");
    assertThat(endPeriodSize).isZero();
}
Also used : FHIRContext(io.github.linuxforhealth.fhir.FHIRContext) Bundle(org.hl7.fhir.r4.model.Bundle) Resource(org.hl7.fhir.r4.model.Resource) IBaseResource(org.hl7.fhir.instance.model.api.IBaseResource) Base(org.hl7.fhir.r4.model.Base) BundleEntryComponent(org.hl7.fhir.r4.model.Bundle.BundleEntryComponent) Coding(org.hl7.fhir.r4.model.Coding) Encounter(org.hl7.fhir.r4.model.Encounter) IBaseResource(org.hl7.fhir.instance.model.api.IBaseResource) CodeableConcept(org.hl7.fhir.r4.model.CodeableConcept) Test(org.junit.jupiter.api.Test)

Example 12 with Period

use of org.hl7.fhir.dstu2016may.model.Period in project cqf-ruler by DBCG.

the class LibraryEvaluationProvider method evaluate.

@SuppressWarnings({ "unchecked" })
@Operation(name = "$evaluate", idempotent = true, type = Library.class)
public Bundle evaluate(@IdParam IdType theId, @OperationParam(name = "patientId") String patientId, @OperationParam(name = "periodStart") String periodStart, @OperationParam(name = "periodEnd") String periodEnd, @OperationParam(name = "productLine") String productLine, @OperationParam(name = "terminologyEndpoint") Endpoint terminologyEndpoint, @OperationParam(name = "dataEndpoint") Endpoint dataEndpoint, @OperationParam(name = "context") String contextParam, @OperationParam(name = "executionResults") String executionResults, @OperationParam(name = "parameters") Parameters parameters, @OperationParam(name = "additionalData") Bundle additionalData, RequestDetails theRequestDetails) {
    log.info("Library evaluation started..");
    if (patientId == null && contextParam != null && contextParam.equals("Patient")) {
        log.error("Patient id null");
        throw new IllegalArgumentException("Must specify a patientId when executing in Patient context.");
    }
    Bundle libraryBundle = new Bundle();
    Library theResource = null;
    if (additionalData != null) {
        for (Bundle.BundleEntryComponent entry : additionalData.getEntry()) {
            if (entry.getResource().fhirType().equals("Library")) {
                libraryBundle.addEntry(entry);
                if (entry.getResource().getIdElement().equals(theId)) {
                    theResource = (Library) entry.getResource();
                }
            }
        }
    }
    if (theResource == null) {
        theResource = read(theId, theRequestDetails);
    }
    VersionedIdentifier libraryIdentifier = new VersionedIdentifier().withId(theResource.getName()).withVersion(theResource.getVersion());
    TerminologyProvider terminologyProvider;
    if (terminologyEndpoint != null) {
        IGenericClient client = Clients.forEndpoint(getFhirContext(), terminologyEndpoint);
        terminologyProvider = new R4FhirTerminologyProvider(client);
    } else {
        terminologyProvider = myJpaTerminologyProviderFactory.create(new SystemRequestDetails());
    }
    DataProvider dataProvider;
    if (dataEndpoint != null) {
        List<RetrieveProvider> retrieveProviderList = new ArrayList<>();
        IGenericClient client = Clients.forEndpoint(dataEndpoint);
        RestFhirRetrieveProvider retriever = new RestFhirRetrieveProvider(new SearchParameterResolver(getFhirContext()), client);
        retriever.setTerminologyProvider(terminologyProvider);
        if (terminologyEndpoint == null || (terminologyEndpoint != null && !terminologyEndpoint.getAddress().equals(dataEndpoint.getAddress()))) {
            retriever.setExpandValueSets(true);
        }
        retrieveProviderList.add(retriever);
        if (additionalData != null) {
            BundleRetrieveProvider bundleProvider = new BundleRetrieveProvider(getFhirContext(), additionalData);
            bundleProvider.setTerminologyProvider(terminologyProvider);
            retrieveProviderList.add(bundleProvider);
            PriorityRetrieveProvider priorityProvider = new PriorityRetrieveProvider(retrieveProviderList);
            dataProvider = new CompositeDataProvider(myModelResolver, priorityProvider);
        } else {
            dataProvider = new CompositeDataProvider(myModelResolver, retriever);
        }
    } else {
        List<RetrieveProvider> retrieveProviderList = new ArrayList<>();
        JpaFhirRetrieveProvider retriever = new JpaFhirRetrieveProvider(getDaoRegistry(), new SearchParameterResolver(getFhirContext()));
        retriever.setTerminologyProvider(terminologyProvider);
        // Assume it's a different server, therefore need to expand.
        if (terminologyEndpoint != null) {
            retriever.setExpandValueSets(true);
        }
        retrieveProviderList.add(retriever);
        if (additionalData != null) {
            BundleRetrieveProvider bundleProvider = new BundleRetrieveProvider(getFhirContext(), additionalData);
            bundleProvider.setTerminologyProvider(terminologyProvider);
            retrieveProviderList.add(bundleProvider);
            PriorityRetrieveProvider priorityProvider = new PriorityRetrieveProvider(retrieveProviderList);
            dataProvider = new CompositeDataProvider(myModelResolver, priorityProvider);
        } else {
            dataProvider = new CompositeDataProvider(myModelResolver, retriever);
        }
    }
    LibraryContentProvider bundleLibraryProvider = new BundleFhirLibraryContentProvider(this.getFhirContext(), libraryBundle, adapterFactory, libraryVersionSelector);
    LibraryContentProvider jpaLibraryContentProvider = this.myJpaLibraryContentProviderFactory.create(theRequestDetails);
    List<LibraryContentProvider> sourceProviders = new ArrayList<LibraryContentProvider>(Arrays.asList(bundleLibraryProvider, jpaLibraryContentProvider));
    LibraryLoader libraryLoader = this.myLibraryLoaderFactory.create(sourceProviders);
    CqlEngine engine = new CqlEngine(libraryLoader, Collections.singletonMap("http://hl7.org/fhir", dataProvider), terminologyProvider);
    Map<String, Object> resolvedParameters = new HashMap<>();
    if (parameters != null) {
        for (Parameters.ParametersParameterComponent pc : parameters.getParameter()) {
            resolvedParameters.put(pc.getName(), pc.getValue());
        }
    }
    if (periodStart != null && periodEnd != null) {
        // resolve the measurement period
        Interval measurementPeriod = new Interval(Operations.resolveRequestDate(periodStart, true), true, Operations.resolveRequestDate(periodEnd, false), true);
        resolvedParameters.put("Measurement Period", new Interval(DateTime.fromJavaDate((Date) measurementPeriod.getStart()), true, DateTime.fromJavaDate((Date) measurementPeriod.getEnd()), true));
    }
    if (productLine != null) {
        resolvedParameters.put("Product Line", productLine);
    }
    EvaluationResult evalResult = engine.evaluate(libraryIdentifier, null, Pair.of(contextParam != null ? contextParam : "Unspecified", patientId == null ? "null" : patientId), resolvedParameters, this.getDebugMap());
    List<Resource> results = new ArrayList<>();
    FhirMeasureBundler bundler = new FhirMeasureBundler();
    if (evalResult != null && evalResult.expressionResults != null) {
        for (Map.Entry<String, Object> def : evalResult.expressionResults.entrySet()) {
            Parameters result = new Parameters();
            try {
                result.setId(def.getKey());
                Object res = def.getValue();
                if (res == null) {
                    result.addParameter().setName("value").setValue(new StringType("null"));
                } else if (res instanceof List<?>) {
                    if (((List<?>) res).size() > 0 && ((List<?>) res).get(0) instanceof Resource) {
                        if (executionResults != null && executionResults.equals("Summary")) {
                            result.addParameter().setName("value").setValue(new StringType(((Resource) ((List<?>) res).get(0)).getIdElement().getResourceType() + "/" + ((Resource) ((List<?>) res).get(0)).getIdElement().getIdPart()));
                        } else {
                            result.addParameter().setName("value").setResource(bundler.bundle((Iterable<Resource>) res, theRequestDetails.getFhirServerBase()));
                        }
                    } else {
                        result.addParameter().setName("value").setValue(new StringType(res.toString()));
                    }
                } else if (res instanceof Iterable) {
                    result.addParameter().setName("value").setResource(bundler.bundle((Iterable<Resource>) res, theRequestDetails.getFhirServerBase()));
                } else if (res instanceof Resource) {
                    if (executionResults != null && executionResults.equals("Summary")) {
                        result.addParameter().setName("value").setValue(new StringType(((Resource) res).getIdElement().getResourceType() + "/" + ((Resource) res).getIdElement().getIdPart()));
                    } else {
                        result.addParameter().setName("value").setResource((Resource) res);
                    }
                } else if (res instanceof Type) {
                    result.addParameter().setName("value").setValue((Type) res);
                } else {
                    result.addParameter().setName("value").setValue(new StringType(res.toString()));
                }
                result.addParameter().setName("resultType").setValue(new StringType(resolveType(res)));
            } catch (RuntimeException re) {
                re.printStackTrace();
                String message = re.getMessage() != null ? re.getMessage() : re.getClass().getName();
                result.addParameter().setName("error").setValue(new StringType(message));
            }
            results.add(result);
        }
    }
    return bundler.bundle(results, theRequestDetails.getFhirServerBase());
}
Also used : HashMap(java.util.HashMap) StringType(org.hl7.fhir.r4.model.StringType) IGenericClient(ca.uhn.fhir.rest.client.api.IGenericClient) ArrayList(java.util.ArrayList) LibraryLoader(org.opencds.cqf.cql.engine.execution.LibraryLoader) CompositeDataProvider(org.opencds.cqf.cql.engine.data.CompositeDataProvider) DataProvider(org.opencds.cqf.cql.engine.data.DataProvider) VersionedIdentifier(org.cqframework.cql.elm.execution.VersionedIdentifier) BundleRetrieveProvider(org.opencds.cqf.cql.evaluator.engine.retrieve.BundleRetrieveProvider) RestFhirRetrieveProvider(org.opencds.cqf.cql.engine.fhir.retrieve.RestFhirRetrieveProvider) SystemRequestDetails(ca.uhn.fhir.jpa.partition.SystemRequestDetails) PriorityRetrieveProvider(org.opencds.cqf.cql.evaluator.engine.retrieve.PriorityRetrieveProvider) List(java.util.List) ArrayList(java.util.ArrayList) R4FhirTerminologyProvider(org.opencds.cqf.cql.engine.fhir.terminology.R4FhirTerminologyProvider) FhirMeasureBundler(org.opencds.cqf.ruler.cpg.r4.util.FhirMeasureBundler) JpaFhirRetrieveProvider(org.opencds.cqf.ruler.cql.JpaFhirRetrieveProvider) LibraryContentProvider(org.opencds.cqf.cql.evaluator.cql2elm.content.LibraryContentProvider) BundleFhirLibraryContentProvider(org.opencds.cqf.cql.evaluator.cql2elm.content.fhir.BundleFhirLibraryContentProvider) Parameters(org.hl7.fhir.r4.model.Parameters) BundleFhirLibraryContentProvider(org.opencds.cqf.cql.evaluator.cql2elm.content.fhir.BundleFhirLibraryContentProvider) Bundle(org.hl7.fhir.r4.model.Bundle) Resource(org.hl7.fhir.r4.model.Resource) CqlEngine(org.opencds.cqf.cql.engine.execution.CqlEngine) EvaluationResult(org.opencds.cqf.cql.engine.execution.EvaluationResult) StringType(org.hl7.fhir.r4.model.StringType) Type(org.hl7.fhir.r4.model.Type) IdType(org.hl7.fhir.r4.model.IdType) SearchParameterResolver(org.opencds.cqf.cql.engine.fhir.searchparam.SearchParameterResolver) TerminologyProvider(org.opencds.cqf.cql.engine.terminology.TerminologyProvider) R4FhirTerminologyProvider(org.opencds.cqf.cql.engine.fhir.terminology.R4FhirTerminologyProvider) CompositeDataProvider(org.opencds.cqf.cql.engine.data.CompositeDataProvider) Library(org.hl7.fhir.r4.model.Library) RestFhirRetrieveProvider(org.opencds.cqf.cql.engine.fhir.retrieve.RestFhirRetrieveProvider) JpaFhirRetrieveProvider(org.opencds.cqf.ruler.cql.JpaFhirRetrieveProvider) RetrieveProvider(org.opencds.cqf.cql.engine.retrieve.RetrieveProvider) BundleRetrieveProvider(org.opencds.cqf.cql.evaluator.engine.retrieve.BundleRetrieveProvider) PriorityRetrieveProvider(org.opencds.cqf.cql.evaluator.engine.retrieve.PriorityRetrieveProvider) Map(java.util.Map) DebugMap(org.opencds.cqf.cql.engine.debug.DebugMap) HashMap(java.util.HashMap) Interval(org.opencds.cqf.cql.engine.runtime.Interval) Operation(ca.uhn.fhir.rest.annotation.Operation)

Example 13 with Period

use of org.hl7.fhir.dstu2016may.model.Period in project cqf-ruler by DBCG.

the class ReportProvider method report.

/**
 * Implements the <a href=
 * "https://build.fhir.org/ig/HL7/davinci-ra/OperationDefinition-report.html">$report</a>
 * operation found in the
 * <a href="https://build.fhir.org/ig/HL7/davinci-ra/index.html">Da Vinci Risk
 * Adjustment IG</a>.
 *
 * @param requestDetails metadata about the current request being processed.
 *                       Generally auto-populated by the HAPI FHIR server
 *                       framework.
 * @param periodStart    the start of the clinical evaluation period
 * @param periodEnd      the end of the clinical evaluation period
 * @param subject        a Patient or Patient Group
 * @return a Parameters with Bundles of MeasureReports and evaluatedResource
 *         Resources
 */
@Description(shortDefinition = "$report", value = "Implements the <a href=\"https://build.fhir.org/ig/HL7/davinci-ra/OperationDefinition-report.html\">$report</a> operation found in the <a href=\"https://build.fhir.org/ig/HL7/davinci-ra/index.html\">Da Vinci Risk Adjustment IG</a>.")
@Operation(name = "$report", idempotent = true, type = MeasureReport.class)
public Parameters report(RequestDetails requestDetails, @OperationParam(name = "periodStart", min = 1, max = 1) String periodStart, @OperationParam(name = "periodEnd", min = 1, max = 1) String periodEnd, @OperationParam(name = "subject", min = 1, max = 1) String subject) throws FHIRException {
    validateParameters(periodStart, periodEnd, subject);
    Parameters result = newResource(Parameters.class, subject.replace("/", "-") + "-report");
    Date periodStartDate = Operations.resolveRequestDate(periodStart, true);
    Date periodEndDate = Operations.resolveRequestDate(periodEnd, false);
    Period period = new Period().setStart(periodStartDate).setEnd(periodEndDate);
    List<Patient> patients = getPatientListFromSubject(subject);
    (patients).forEach(patient -> {
        Parameters.ParametersParameterComponent patientParameter = patientReport(patient, period, requestDetails.getFhirServerBase());
        result.addParameter(patientParameter);
    });
    return result;
}
Also used : Parameters(org.hl7.fhir.r4.model.Parameters) Period(org.hl7.fhir.r4.model.Period) Patient(org.hl7.fhir.r4.model.Patient) Date(java.util.Date) Description(ca.uhn.fhir.model.api.annotation.Description) Operation(ca.uhn.fhir.rest.annotation.Operation)

Example 14 with Period

use of org.hl7.fhir.dstu2016may.model.Period in project cqf-ruler by DBCG.

the class ReportProvider method patientReport.

private Parameters.ParametersParameterComponent patientReport(Patient thePatient, Period thePeriod, String serverBase) {
    String patientId = thePatient.getIdElement().getIdPart();
    final Map<IIdType, IAnyResource> bundleEntries = new HashMap<>();
    bundleEntries.put(thePatient.getIdElement(), thePatient);
    ReferenceParam subjectParam = new ReferenceParam(patientId);
    search(MeasureReport.class, Searches.byParam("subject", subjectParam)).getAllResourcesTyped().forEach(measureReport -> {
        if (measureReport.getPeriod().getEnd().before(thePeriod.getStart()) || measureReport.getPeriod().getStart().after(thePeriod.getEnd())) {
            return;
        }
        bundleEntries.putIfAbsent(measureReport.getIdElement(), measureReport);
        getEvaluatedResources(measureReport).values().forEach(resource -> bundleEntries.putIfAbsent(resource.getIdElement(), resource));
    });
    Bundle patientReportBundle = new Bundle();
    patientReportBundle.setMeta(new Meta().addProfile(PATIENT_REPORT_PROFILE_URL));
    patientReportBundle.setType(Bundle.BundleType.COLLECTION);
    patientReportBundle.setTimestamp(new Date());
    patientReportBundle.setId(patientId + "-report");
    patientReportBundle.setIdentifier(new Identifier().setSystem("urn:ietf:rfc:3986").setValue("urn:uuid:" + UUID.randomUUID().toString()));
    bundleEntries.entrySet().forEach(resource -> patientReportBundle.addEntry(new Bundle.BundleEntryComponent().setResource((Resource) resource.getValue()).setFullUrl(Operations.getFullUrl(serverBase, resource.getValue().fhirType(), resource.getValue().getIdElement().getIdPart()))));
    Parameters.ParametersParameterComponent patientParameter = new Parameters.ParametersParameterComponent();
    patientParameter.setResource(patientReportBundle);
    patientParameter.setId(thePatient.getIdElement().getIdPart() + "-report");
    patientParameter.setName("return");
    return patientParameter;
}
Also used : Meta(org.hl7.fhir.r4.model.Meta) Parameters(org.hl7.fhir.r4.model.Parameters) HashMap(java.util.HashMap) Bundle(org.hl7.fhir.r4.model.Bundle) IAnyResource(org.hl7.fhir.instance.model.api.IAnyResource) Resource(org.hl7.fhir.r4.model.Resource) ReferenceParam(ca.uhn.fhir.rest.param.ReferenceParam) Date(java.util.Date) Identifier(org.hl7.fhir.r4.model.Identifier) IAnyResource(org.hl7.fhir.instance.model.api.IAnyResource) IIdType(org.hl7.fhir.instance.model.api.IIdType)

Example 15 with Period

use of org.hl7.fhir.dstu2016may.model.Period in project cqf-ruler by DBCG.

the class ReportProvider method validateParameters.

private Period validateParameters(String periodStart, String periodEnd, String subject) {
    if (periodStart == null) {
        throw new IllegalArgumentException("Parameter 'periodStart' is required.");
    }
    if (periodEnd == null) {
        throw new IllegalArgumentException("Parameter 'periodEnd' is required.");
    }
    Date periodStartDate = Operations.resolveRequestDate(periodStart, true);
    Date periodEndDate = Operations.resolveRequestDate(periodEnd, false);
    if (periodStartDate.after(periodEndDate)) {
        throw new IllegalArgumentException("Parameter 'periodStart' must be before 'periodEnd'.");
    }
    if (subject == null) {
        throw new IllegalArgumentException("Parameter 'subject' is required.");
    }
    if (!subject.startsWith("Patient/") && !subject.startsWith("Group/")) {
        throw new IllegalArgumentException("Parameter 'subject' must be in the format 'Patient/[id]' or 'Group/[id]'.");
    }
    return new Period().setStart(periodStartDate).setEnd(periodEndDate);
}
Also used : Period(org.hl7.fhir.r4.model.Period) Date(java.util.Date)

Aggregations

Period (org.hl7.fhir.r4.model.Period)87 Complex (org.hl7.fhir.r4.utils.formats.Turtle.Complex)44 Date (java.util.Date)42 Test (org.junit.Test)42 Complex (org.hl7.fhir.dstu3.utils.formats.Turtle.Complex)40 Coding (org.hl7.fhir.r4.model.Coding)34 Test (org.junit.jupiter.api.Test)34 Complex (org.hl7.fhir.dstu2016may.formats.RdfGenerator.Complex)32 Period (org.hl7.fhir.dstu3.model.Period)30 ArrayList (java.util.ArrayList)29 CodeableConcept (org.hl7.fhir.r4.model.CodeableConcept)27 DateTimeType (org.hl7.fhir.r4.model.DateTimeType)20 Encounter (org.hl7.fhir.r4.model.Encounter)20 Reference (org.hl7.fhir.r4.model.Reference)20 Patient (org.hl7.fhir.r4.model.Patient)19 Reference (org.hl7.fhir.dstu3.model.Reference)18 HashMap (java.util.HashMap)17 Identifier (org.hl7.fhir.r4.model.Identifier)17 NotImplementedException (org.apache.commons.lang3.NotImplementedException)15 List (java.util.List)14