use of org.hl7.fhir.r4.model.MedicationRequest in project cqf-ruler by DBCG.
the class ActivityDefinitionApplyProvider method resolveMedicationRequest.
private MedicationRequest resolveMedicationRequest(ActivityDefinition activityDefinition, String patientId) throws ActivityDefinitionApplyException {
// intent, medication, and subject are required
MedicationRequest medicationRequest = new MedicationRequest();
medicationRequest.setIntent(MedicationRequest.MedicationRequestIntent.ORDER);
medicationRequest.setSubject(new Reference(patientId));
if (activityDefinition.hasProduct()) {
medicationRequest.setMedication(activityDefinition.getProduct());
} else {
throw new ActivityDefinitionApplyException("Missing required product property");
}
if (activityDefinition.hasDosage()) {
medicationRequest.setDosageInstruction(activityDefinition.getDosage());
}
if (activityDefinition.hasBodySite()) {
throw new ActivityDefinitionApplyException("BodySite does not map to " + activityDefinition.getKind());
}
if (activityDefinition.hasCode()) {
throw new ActivityDefinitionApplyException("Code does not map to " + activityDefinition.getKind());
}
if (activityDefinition.hasQuantity()) {
throw new ActivityDefinitionApplyException("Quantity does not map to " + activityDefinition.getKind());
}
return medicationRequest;
}
use of org.hl7.fhir.r4.model.MedicationRequest in project cqf-ruler by DBCG.
the class ActivityDefinitionApplyProvider method resolveActivityDefinition.
// For library use
public Resource resolveActivityDefinition(ActivityDefinition activityDefinition, String patientId, String practitionerId, String organizationId, RequestDetails theRequest) throws FHIRException {
Resource result = newResource(activityDefinition.getKind().toCode());
switch(result.fhirType()) {
case "ServiceRequest":
result = resolveServiceRequest(activityDefinition, patientId, practitionerId, organizationId);
break;
case "MedicationRequest":
result = resolveMedicationRequest(activityDefinition, patientId);
break;
case "SupplyRequest":
result = resolveSupplyRequest(activityDefinition, practitionerId, organizationId);
break;
case "Procedure":
result = resolveProcedure(activityDefinition, patientId);
break;
case "DiagnosticReport":
result = resolveDiagnosticReport(activityDefinition, patientId);
break;
case "Communication":
result = resolveCommunication(activityDefinition, patientId);
break;
case "CommunicationRequest":
result = resolveCommunicationRequest(activityDefinition, patientId);
break;
case "Task":
result = resolveTask(activityDefinition, patientId);
break;
}
for (ActivityDefinition.ActivityDefinitionDynamicValueComponent dynamicValue : activityDefinition.getDynamicValue()) {
// ActivityDefinition apply operation does not fail.
try {
if (dynamicValue.getExpression() != null) {
// Special case for setting a Patient reference
if ("Patient".equals(dynamicValue.getExpression().getExpression())) {
this.modelResolver.setValue(result, dynamicValue.getPath(), new Reference(patientId));
} else {
/*
* TODO: Passing the activityDefinition as context here because that's what will
* have the libraries, but perhaps the "context" here should be the result
* resource?
*/
Object value = expressionEvaluation.evaluateInContext(activityDefinition, dynamicValue.getExpression().getExpression(), patientId, theRequest);
if (value != null) {
logger.debug("dynamicValue value: {}", value);
if (value instanceof Boolean) {
value = new BooleanType((Boolean) value);
} else if (value instanceof DateTime) {
value = Date.from(((DateTime) value).getDateTime().toInstant());
} else if (value instanceof String) {
value = new StringType((String) value);
}
this.modelResolver.setValue(result, dynamicValue.getPath(), value);
} else {
logger.warn("WARNING: ActivityDefinition has null value for path: {}", dynamicValue.getPath());
}
}
}
} catch (Exception e) {
logger.error("ERROR: ActivityDefinition dynamicValue {} could not be applied and threw exception {}", dynamicValue.getPath(), e.toString());
logger.error(e.toString());
}
}
return result;
}
use of org.hl7.fhir.r4.model.MedicationRequest in project bunsen by cerner.
the class TestData method newMedicationRequest.
/**
* Returns a new MedicationRequest for testing.
*
* @return a FHIR MedicationRequest for testing.
*/
public static MedicationRequest newMedicationRequest() {
MedicationRequest medicationRequest = new MedicationRequest();
medicationRequest.setId("test-medication-request");
CodeableConcept itemCodeableConcept = new CodeableConcept();
itemCodeableConcept.addCoding().setSystem("http://www.nlm.nih.gov/research/umls/rxnorm").setCode("103109").setDisplay("Vitamin E 3 MG Oral Tablet [Ephynal]").setUserSelected(true);
medicationRequest.setMedication(itemCodeableConcept);
medicationRequest.setSubject(new Reference("Patient/12345").setDisplay("Here is a display for you."));
medicationRequest.setDosageInstruction(ImmutableList.of(new Dosage().setTiming(new Timing().setRepeat(new TimingRepeatComponent().setCount(10)))));
medicationRequest.setSubstitution(new MedicationRequestSubstitutionComponent().setAllowed(true));
return medicationRequest;
}
use of org.hl7.fhir.r4.model.MedicationRequest in project synthea by synthetichealth.
the class FhirR4 method convertToFHIR.
/**
* Convert the given Person into a FHIR Bundle of the Patient and the
* associated entries from their health record.
*
* @param person Person to generate the FHIR JSON for
* @param stopTime Time the simulation ended
* @return FHIR Bundle containing the Person's health record
*/
public static Bundle convertToFHIR(Person person, long stopTime) {
Bundle bundle = new Bundle();
if (TRANSACTION_BUNDLE) {
bundle.setType(BundleType.TRANSACTION);
} else {
bundle.setType(BundleType.COLLECTION);
}
BundleEntryComponent personEntry = basicInfo(person, bundle, stopTime);
for (Encounter encounter : person.record.encounters) {
BundleEntryComponent encounterEntry = encounter(person, personEntry, bundle, encounter);
for (HealthRecord.Entry condition : encounter.conditions) {
condition(person, personEntry, bundle, encounterEntry, condition);
}
for (HealthRecord.Allergy allergy : encounter.allergies) {
allergy(person, personEntry, bundle, encounterEntry, allergy);
}
for (Observation observation : encounter.observations) {
// Observation resources in v4 don't support Attachments
if (observation.value instanceof Attachment) {
media(person, personEntry, bundle, encounterEntry, observation);
} else {
observation(person, personEntry, bundle, encounterEntry, observation);
}
}
for (Procedure procedure : encounter.procedures) {
procedure(person, personEntry, bundle, encounterEntry, procedure);
}
for (HealthRecord.Device device : encounter.devices) {
device(person, personEntry, bundle, device);
}
for (HealthRecord.Supply supply : encounter.supplies) {
supplyDelivery(person, personEntry, bundle, supply, encounter);
}
for (Medication medication : encounter.medications) {
medicationRequest(person, personEntry, bundle, encounterEntry, medication);
}
for (HealthRecord.Entry immunization : encounter.immunizations) {
immunization(person, personEntry, bundle, encounterEntry, immunization);
}
for (Report report : encounter.reports) {
report(person, personEntry, bundle, encounterEntry, report);
}
for (CarePlan careplan : encounter.careplans) {
BundleEntryComponent careTeamEntry = careTeam(person, personEntry, bundle, encounterEntry, careplan);
carePlan(person, personEntry, bundle, encounterEntry, encounter.provider, careTeamEntry, careplan);
}
for (ImagingStudy imagingStudy : encounter.imagingStudies) {
imagingStudy(person, personEntry, bundle, encounterEntry, imagingStudy);
}
if (USE_US_CORE_IG) {
String clinicalNoteText = ClinicalNoteExporter.export(person, encounter);
boolean lastNote = (encounter == person.record.encounters.get(person.record.encounters.size() - 1));
clinicalNote(person, personEntry, bundle, encounterEntry, clinicalNoteText, lastNote);
}
// one claim per encounter
BundleEntryComponent encounterClaim = encounterClaim(person, personEntry, bundle, encounterEntry, encounter.claim);
explanationOfBenefit(personEntry, bundle, encounterEntry, person, encounterClaim, encounter);
}
if (USE_US_CORE_IG) {
// Add Provenance to the Bundle
provenance(bundle, person, stopTime);
}
return bundle;
}
use of org.hl7.fhir.r4.model.MedicationRequest in project synthea by synthetichealth.
the class FHIRSTU3ExporterTest method testFHIRSTU3Export.
@Test
public void testFHIRSTU3Export() throws Exception {
TestHelper.loadTestProperties();
Generator.DEFAULT_STATE = Config.get("test_state.default", "Massachusetts");
Config.set("exporter.baseDirectory", tempFolder.newFolder().toString());
FhirContext ctx = FhirStu3.getContext();
IParser parser = ctx.newJsonParser().setPrettyPrint(true);
FhirValidator validator = ctx.newValidator();
validator.setValidateAgainstStandardSchema(true);
validator.setValidateAgainstStandardSchematron(true);
ValidationResources validationResources = new ValidationResources();
List<String> errors = ParallelTestingService.runInParallel((person) -> {
List<String> validationErrors = new ArrayList<String>();
TestHelper.exportOff();
Config.set("exporter.fhir_stu3.export", "true");
Config.set("exporter.fhir.use_shr_extensions", "true");
FhirStu3.TRANSACTION_BUNDLE = person.randBoolean();
String fhirJson = FhirStu3.convertToFHIRJson(person, System.currentTimeMillis());
// (these should have been converted into URIs)
if (fhirJson.contains("SNOMED-CT")) {
validationErrors.add("JSON contains unconverted references to 'SNOMED-CT' (should be URIs)");
}
// let's crack open the Bundle and validate
// each individual entry.resource to get context-sensitive error
// messages...
Bundle bundle = parser.parseResource(Bundle.class, fhirJson);
for (BundleEntryComponent entry : bundle.getEntry()) {
ValidationResult eresult = validator.validateWithResult(entry.getResource());
if (!eresult.isSuccessful()) {
for (SingleValidationMessage emessage : eresult.getMessages()) {
boolean valid = false;
if (emessage.getMessage().contains("@ Observation obs-7")) {
/*
* The obs-7 invariant basically says that Observations should have values, unless
* they are made of components. This test replaces an invalid XPath expression
* that was causing correct instances to fail validation.
*/
valid = validateObs7((Observation) entry.getResource());
} else if (emessage.getMessage().contains("@ Condition con-4")) {
/*
* The con-4 invariant says "If condition is abated, then clinicalStatus must be
* either inactive, resolved, or remission" which is very clear and sensical.
* However, the XPath expression does not evaluate correctly for valid instances,
* so we must manually validate.
*/
valid = validateCon4((Condition) entry.getResource());
} else if (emessage.getMessage().contains("@ MedicationRequest mps-1")) {
/*
* The mps-1 invariant says MedicationRequest.requester.onBehalfOf can only be
* specified if MedicationRequest.requester.agent is practitioner or device.
* But the invariant is poorly written and does not correctly handle references
* starting with "urn:uuid"
*/
// ignore this error
valid = true;
} else if (emessage.getMessage().contains("per-1: If present, start SHALL have a lower value than end")) {
/*
* The per-1 invariant does not account for daylight savings time... so, if the
* daylight savings switch happens between the start and end, the validation
* fails, even if it is valid.
*/
// ignore this error
valid = true;
}
if (!valid) {
System.out.println(parser.encodeResourceToString(entry.getResource()));
System.out.println("ERROR: " + emessage.getMessage());
validationErrors.add(emessage.getMessage());
}
}
}
// Check ExplanationOfBenefit Resources against BlueButton
if (entry.getResource().fhirType().equals("ExplanationOfBenefit")) {
ValidationResult bbResult = validationResources.validateSTU3(entry.getResource());
for (SingleValidationMessage message : bbResult.getMessages()) {
if (message.getMessage().contains("extension https://bluebutton.cms.gov/assets")) {
/*
* The instance validator complains about the BlueButton extensions, ignore
*/
continue;
} else if (message.getSeverity() == ResultSeverityEnum.ERROR) {
if (!(message.getMessage().contains("Element 'ExplanationOfBenefit.id': minimum required = 1, but only found 0") || message.getMessage().contains("Could not verify slice for profile"))) {
// For some reason the validator is not detecting the IDs on the resources,
// even though they appear to be present while debugging and during normal
// operations.
System.out.println(message.getSeverity() + ": " + message.getMessage());
Assert.fail(message.getSeverity() + ": " + message.getMessage());
}
}
}
}
}
if (!validationErrors.isEmpty()) {
Exporter.export(person, System.currentTimeMillis());
}
return validationErrors;
});
assertTrue("Validation of exported FHIR bundle failed: " + String.join("|", errors), errors.size() == 0);
}
Aggregations