use of org.hl7.fhir.dstu2.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();
}
use of org.hl7.fhir.dstu2.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());
}
use of org.hl7.fhir.dstu2.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;
}
use of org.hl7.fhir.dstu2.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;
}
use of org.hl7.fhir.dstu2.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);
}
Aggregations