Search in sources :

Example 21 with COMPLETED

use of org.hl7.fhir.r4.model.Procedure.ProcedureStatus.COMPLETED in project dpc-app by CMSgov.

the class JobBatchProcessor method processJobBatchPartial.

/**
 * Processes a partial of a job batch. Marks the partial as completed upon processing
 *
 * @param aggregatorID the current aggregatorID
 * @param queue        the queue
 * @param job          the job to process
 * @param patientID    the current patient id to process
 * @return A list of batch files {@link JobQueueBatchFile}
 */
public List<JobQueueBatchFile> processJobBatchPartial(UUID aggregatorID, IJobQueue queue, JobQueueBatch job, String patientID) {
    StopWatch stopWatch = StopWatch.createStarted();
    OutcomeReason failReason = null;
    final Pair<Optional<List<ConsentResult>>, Optional<OperationOutcome>> consentResult = getConsent(patientID);
    Flowable<Resource> flowable;
    if (consentResult.getRight().isPresent()) {
        flowable = Flowable.just(consentResult.getRight().get());
        failReason = OutcomeReason.INTERNAL_ERROR;
    } else if (isOptedOut(consentResult.getLeft())) {
        failReason = OutcomeReason.CONSENT_OPTED_OUT;
        flowable = Flowable.just(AggregationUtils.toOperationOutcome(OutcomeReason.CONSENT_OPTED_OUT, patientID));
    } else if (isLookBackExempt(job.getOrgID())) {
        logger.info("Skipping lookBack for org: {}", job.getOrgID().toString());
        MDC.put(MDCConstants.IS_SMOKE_TEST_ORG, "true");
        flowable = Flowable.fromIterable(job.getResourceTypes()).flatMap(r -> fetchResource(job, patientID, r, job.getSince().orElse(null)));
    } else {
        List<LookBackAnswer> answers = getLookBackAnswers(job, patientID);
        if (passesLookBack(answers)) {
            flowable = Flowable.fromIterable(job.getResourceTypes()).flatMap(r -> fetchResource(job, patientID, r, job.getSince().orElse(null)));
        } else {
            failReason = LookBackAnalyzer.analyze(answers);
            flowable = Flowable.just(AggregationUtils.toOperationOutcome(failReason, patientID));
        }
    }
    final var results = writeResource(job, flowable).toList().blockingGet();
    queue.completePartialBatch(job, aggregatorID);
    final String resourcesRequested = job.getResourceTypes().stream().map(DPCResourceType::getPath).filter(Objects::nonNull).collect(Collectors.joining(";"));
    final String failReasonLabel = failReason == null ? "NA" : failReason.name();
    stopWatch.stop();
    logger.info("dpcMetric=DataExportResult,dataRetrieved={},failReason={},resourcesRequested={},duration={}", failReason == null, failReasonLabel, resourcesRequested, stopWatch.getTime());
    return results;
}
Also used : java.util(java.util) DPCResourceType(gov.cms.dpc.fhir.DPCResourceType) LoggerFactory(org.slf4j.LoggerFactory) Inject(javax.inject.Inject) Meter(com.codahale.metrics.Meter) FhirContext(ca.uhn.fhir.context.FhirContext) HttpHeaders(com.google.common.net.HttpHeaders) Flowable(io.reactivex.Flowable) Pair(org.apache.commons.lang3.tuple.Pair) Constants(gov.cms.dpc.common.Constants) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) OperationOutcome(org.hl7.fhir.dstu3.model.OperationOutcome) MetricRegistry(com.codahale.metrics.MetricRegistry) ExplanationOfBenefit(org.hl7.fhir.dstu3.model.ExplanationOfBenefit) Logger(org.slf4j.Logger) gov.cms.dpc.aggregation.service(gov.cms.dpc.aggregation.service) Resource(org.hl7.fhir.dstu3.model.Resource) JobQueueBatchFile(gov.cms.dpc.queue.models.JobQueueBatchFile) Publisher(org.reactivestreams.Publisher) BlueButtonClient(gov.cms.dpc.bluebutton.client.BlueButtonClient) StopWatch(org.apache.commons.lang3.time.StopWatch) Collectors(java.util.stream.Collectors) OffsetDateTime(java.time.OffsetDateTime) AggregationUtils(gov.cms.dpc.aggregation.util.AggregationUtils) MDCConstants(gov.cms.dpc.common.MDCConstants) IJobQueue(gov.cms.dpc.queue.IJobQueue) MDC(org.slf4j.MDC) MetricMaker(gov.cms.dpc.common.utils.MetricMaker) JobQueueBatch(gov.cms.dpc.queue.models.JobQueueBatch) Resource(org.hl7.fhir.dstu3.model.Resource) StopWatch(org.apache.commons.lang3.time.StopWatch) DPCResourceType(gov.cms.dpc.fhir.DPCResourceType)

Example 22 with COMPLETED

use of org.hl7.fhir.r4.model.Procedure.ProcedureStatus.COMPLETED in project gpconnect-demonstrator by nhsconnect.

the class MedicationDispenseResourceProvider method getMedicationDispensesForPatientId.

@Search
public List<MedicationDispense> getMedicationDispensesForPatientId(@RequiredParam(name = "patient") String patientId) {
    ArrayList<MedicationDispense> medicationDispenses = new ArrayList<>();
    List<MedicationDispenseDetail> medicationDispenseDetailList = medicationDispenseSearch.findMedicationDispenseForPatient(Long.parseLong(patientId));
    if (medicationDispenseDetailList != null && !medicationDispenseDetailList.isEmpty()) {
        for (MedicationDispenseDetail medicationDispenseDetail : medicationDispenseDetailList) {
            MedicationDispense medicationDispense = new MedicationDispense();
            medicationDispense.setId(String.valueOf(medicationDispenseDetail.getId()));
            medicationDispense.getMeta().setLastUpdated(medicationDispenseDetail.getLastUpdated());
            medicationDispense.getMeta().setVersionId(String.valueOf(medicationDispenseDetail.getLastUpdated().getTime()));
            switch(medicationDispenseDetail.getStatus().toLowerCase(Locale.UK)) {
                case "completed":
                    medicationDispense.setStatus(MedicationDispenseStatus.COMPLETED);
                    break;
                case "entered_in_error":
                    medicationDispense.setStatus(MedicationDispenseStatus.ENTEREDINERROR);
                    break;
                case "in_progress":
                    medicationDispense.setStatus(MedicationDispenseStatus.INPROGRESS);
                    break;
                case "on_hold":
                    medicationDispense.setStatus(MedicationDispenseStatus.ONHOLD);
                    break;
                case "stopped":
                    medicationDispense.setStatus(MedicationDispenseStatus.STOPPED);
                    break;
            }
            medicationDispense.setSubject(new Reference("Patient/" + patientId));
            medicationDispense.setAuthorizingPrescription(Collections.singletonList(new Reference("MedicationOrder/" + medicationDispenseDetail.getMedicationOrderId())));
            Medication medication = new Medication();
            Coding coding = new Coding();
            coding.setCode(String.valueOf(medicationDispenseDetail.getMedicationId()));
            coding.setDisplay(medicationDispenseDetail.getMedicationName());
            CodeableConcept codeableConcept = new CodeableConcept();
            codeableConcept.setCoding(Collections.singletonList(coding));
            medication.setCode(codeableConcept);
            medicationDispense.addDosageInstruction().setText(medicationDispenseDetail.getDosageText());
            medicationDispenses.add(medicationDispense);
        }
    }
    return medicationDispenses;
}
Also used : Coding(org.hl7.fhir.dstu3.model.Coding) MedicationDispense(org.hl7.fhir.dstu3.model.MedicationDispense) Reference(org.hl7.fhir.dstu3.model.Reference) ArrayList(java.util.ArrayList) Medication(org.hl7.fhir.dstu3.model.Medication) MedicationDispenseDetail(uk.gov.hscic.model.medication.MedicationDispenseDetail) CodeableConcept(org.hl7.fhir.dstu3.model.CodeableConcept) MedicationDispenseSearch(uk.gov.hscic.medication.dispense.MedicationDispenseSearch) Search(ca.uhn.fhir.rest.annotation.Search)

Example 23 with COMPLETED

use of org.hl7.fhir.r4.model.Procedure.ProcedureStatus.COMPLETED in project dpc-app by CMSgov.

the class JobBatchProcessorV2 method processJobBatchPartial.

/**
 * Processes a partial of a job batch. Marks the partial as completed upon processing
 *
 * @param aggregatorID the current aggregatorID
 * @param queue        the queue
 * @param job          the job to process
 * @param patientID    the current patient id to process
 * @return A list of batch files {@link JobQueueBatchFile}
 */
public List<JobQueueBatchFile> processJobBatchPartial(UUID aggregatorID, IJobQueue queue, JobQueueBatch job, String patientID) {
    StopWatch stopWatch = StopWatch.createStarted();
    OutcomeReason failReason = null;
    final Pair<Optional<List<ConsentResult>>, Optional<OperationOutcome>> consentResult = getConsent(patientID);
    Flowable<Resource> flowable;
    if (consentResult.getRight().isPresent()) {
        flowable = Flowable.just(consentResult.getRight().get());
        failReason = OutcomeReason.INTERNAL_ERROR;
    } else if (isOptedOut(consentResult.getLeft())) {
        failReason = OutcomeReason.CONSENT_OPTED_OUT;
        flowable = Flowable.just(AggregationUtils.toOperationOutcomeV2(OutcomeReason.CONSENT_OPTED_OUT, patientID));
    } else {
        logger.info("Skipping lookBack for V2 job: {}", job.getOrgID().toString());
        flowable = Flowable.fromIterable(job.getResourceTypes()).flatMap(r -> fetchResource(job, patientID, r, job.getSince().orElse(null)));
    }
    final var results = writeResource(job, flowable).toList().blockingGet();
    queue.completePartialBatch(job, aggregatorID);
    final String resourcesRequested = job.getResourceTypes().stream().map(DPCResourceType::getPath).filter(Objects::nonNull).collect(Collectors.joining(";"));
    final String failReasonLabel = failReason == null ? "NA" : failReason.name();
    stopWatch.stop();
    logger.info("dpcMetric=DataExportResult,dataRetrieved={},failReason={},resourcesRequested={},duration={}", failReason == null, failReasonLabel, resourcesRequested, stopWatch.getTime());
    return results;
}
Also used : Resource(org.hl7.fhir.r4.model.Resource) DPCResourceType(gov.cms.dpc.fhir.DPCResourceType) ConsentResult(gov.cms.dpc.aggregation.service.ConsentResult) StopWatch(org.apache.commons.lang3.time.StopWatch)

Example 24 with COMPLETED

use of org.hl7.fhir.r4.model.Procedure.ProcedureStatus.COMPLETED in project synthea by synthetichealth.

the class FhirR4 method procedure.

/**
 * Map the given Procedure into a FHIR Procedure resource, and add it to the given Bundle.
 *
 * @param rand           Source of randomness to use when generating ids etc
 * @param personEntry    The Person entry
 * @param bundle         Bundle to add to
 * @param encounterEntry The current Encounter entry
 * @param procedure      The Procedure
 * @return The added Entry
 */
private static BundleEntryComponent procedure(RandomNumberGenerator rand, BundleEntryComponent personEntry, Bundle bundle, BundleEntryComponent encounterEntry, Procedure procedure) {
    org.hl7.fhir.r4.model.Procedure procedureResource = new org.hl7.fhir.r4.model.Procedure();
    if (USE_US_CORE_IG) {
        Meta meta = new Meta();
        meta.addProfile("http://hl7.org/fhir/us/core/StructureDefinition/us-core-procedure");
        procedureResource.setMeta(meta);
    }
    procedureResource.setStatus(ProcedureStatus.COMPLETED);
    procedureResource.setSubject(new Reference(personEntry.getFullUrl()));
    procedureResource.setEncounter(new Reference(encounterEntry.getFullUrl()));
    if (USE_US_CORE_IG) {
        org.hl7.fhir.r4.model.Encounter encounterResource = (org.hl7.fhir.r4.model.Encounter) encounterEntry.getResource();
        procedureResource.setLocation(encounterResource.getLocationFirstRep().getLocation());
    }
    Code code = procedure.codes.get(0);
    CodeableConcept procCode = mapCodeToCodeableConcept(code, SNOMED_URI);
    procedureResource.setCode(procCode);
    if (procedure.stop != 0L) {
        Date startDate = new Date(procedure.start);
        Date endDate = new Date(procedure.stop);
        procedureResource.setPerformed(new Period().setStart(startDate).setEnd(endDate));
    } else {
        procedureResource.setPerformed(convertFhirDateTime(procedure.start, true));
    }
    if (!procedure.reasons.isEmpty()) {
        // Only one element in list
        Code reason = procedure.reasons.get(0);
        for (BundleEntryComponent entry : bundle.getEntry()) {
            if (entry.getResource().fhirType().equals("Condition")) {
                Condition condition = (Condition) entry.getResource();
                // Only one element in list
                Coding coding = condition.getCode().getCoding().get(0);
                if (reason.code.equals(coding.getCode())) {
                    procedureResource.addReasonReference().setReference(entry.getFullUrl()).setDisplay(reason.display);
                }
            }
        }
    }
    if (USE_SHR_EXTENSIONS) {
        procedureResource.setMeta(new Meta().addProfile(SHR_EXT + "shr-procedure-ProcedurePerformed"));
        // required fields for this profile are action-PerformedContext-extension,
        // status, code, subject, performed[x]
        Extension performedContext = new Extension();
        performedContext.setUrl(SHR_EXT + "shr-action-PerformedContext-extension");
        performedContext.addExtension(SHR_EXT + "shr-action-Status-extension", new CodeType("completed"));
        procedureResource.addExtension(performedContext);
    }
    BundleEntryComponent procedureEntry = newEntry(rand, bundle, procedureResource);
    procedure.fullUrl = procedureEntry.getFullUrl();
    return procedureEntry;
}
Also used : Condition(org.hl7.fhir.r4.model.Condition) Meta(org.hl7.fhir.r4.model.Meta) Reference(org.hl7.fhir.r4.model.Reference) DocumentReference(org.hl7.fhir.r4.model.DocumentReference) Period(org.hl7.fhir.r4.model.Period) Code(org.mitre.synthea.world.concepts.HealthRecord.Code) Date(java.util.Date) Extension(org.hl7.fhir.r4.model.Extension) BundleEntryComponent(org.hl7.fhir.r4.model.Bundle.BundleEntryComponent) Coding(org.hl7.fhir.r4.model.Coding) Procedure(org.mitre.synthea.world.concepts.HealthRecord.Procedure) Encounter(org.mitre.synthea.world.concepts.HealthRecord.Encounter) CodeType(org.hl7.fhir.r4.model.CodeType) CodeableConcept(org.hl7.fhir.r4.model.CodeableConcept)

Example 25 with COMPLETED

use of org.hl7.fhir.r4.model.Procedure.ProcedureStatus.COMPLETED in project synthea by synthetichealth.

the class FhirR4 method medicationRequest.

/**
 * Map the given Medication to a FHIR MedicationRequest resource, and add it to the given Bundle.
 *
 * @param person         The person being prescribed medication
 * @param personEntry    The Entry for the Person
 * @param bundle         Bundle to add the Medication to
 * @param encounterEntry Current Encounter entry
 * @param medication     The Medication
 * @return The added Entry
 */
private static BundleEntryComponent medicationRequest(Person person, BundleEntryComponent personEntry, Bundle bundle, BundleEntryComponent encounterEntry, Medication medication) {
    MedicationRequest medicationResource = new MedicationRequest();
    if (USE_US_CORE_IG) {
        Meta meta = new Meta();
        meta.addProfile("http://hl7.org/fhir/us/core/StructureDefinition/us-core-medicationrequest");
        medicationResource.setMeta(meta);
    } else if (USE_SHR_EXTENSIONS) {
        medicationResource.addExtension().setUrl(SHR_EXT + "shr-base-ActionCode-extension").setValue(PRESCRIPTION_OF_DRUG_CC);
        medicationResource.setMeta(new Meta().addProfile(SHR_EXT + "shr-medication-MedicationRequested"));
        Extension requestedContext = new Extension();
        requestedContext.setUrl(SHR_EXT + "shr-action-RequestedContext-extension");
        requestedContext.addExtension(SHR_EXT + "shr-action-Status-extension", new CodeType("completed"));
        requestedContext.addExtension(SHR_EXT + "shr-action-RequestIntent-extension", new CodeType("original-order"));
        medicationResource.addExtension(requestedContext);
    }
    medicationResource.setSubject(new Reference(personEntry.getFullUrl()));
    medicationResource.setEncounter(new Reference(encounterEntry.getFullUrl()));
    Code code = medication.codes.get(0);
    String system = code.system.equals("SNOMED-CT") ? SNOMED_URI : RXNORM_URI;
    medicationResource.setMedication(mapCodeToCodeableConcept(code, system));
    if (USE_US_CORE_IG && medication.administration) {
        // Occasionally, rather than use medication codes, we want to use a Medication
        // Resource. We only want to do this when we use US Core, to make sure we
        // sometimes produce a resource for the us-core-medication profile, and the
        // 'administration' flag is an arbitrary way to decide without flipping a coin.
        org.hl7.fhir.r4.model.Medication drugResource = new org.hl7.fhir.r4.model.Medication();
        Meta meta = new Meta();
        meta.addProfile("http://hl7.org/fhir/us/core/StructureDefinition/us-core-medication");
        drugResource.setMeta(meta);
        drugResource.setCode(mapCodeToCodeableConcept(code, system));
        drugResource.setStatus(MedicationStatus.ACTIVE);
        BundleEntryComponent drugEntry = newEntry(person, bundle, drugResource);
        medicationResource.setMedication(new Reference(drugEntry.getFullUrl()));
    }
    medicationResource.setAuthoredOn(new Date(medication.start));
    medicationResource.setIntent(MedicationRequestIntent.ORDER);
    org.hl7.fhir.r4.model.Encounter encounter = (org.hl7.fhir.r4.model.Encounter) encounterEntry.getResource();
    medicationResource.setRequester(encounter.getParticipantFirstRep().getIndividual());
    if (medication.stop != 0L) {
        medicationResource.setStatus(MedicationRequestStatus.STOPPED);
    } else {
        medicationResource.setStatus(MedicationRequestStatus.ACTIVE);
    }
    if (!medication.reasons.isEmpty()) {
        // Only one element in list
        Code reason = medication.reasons.get(0);
        for (BundleEntryComponent entry : bundle.getEntry()) {
            if (entry.getResource().fhirType().equals("Condition")) {
                Condition condition = (Condition) entry.getResource();
                // Only one element in list
                Coding coding = condition.getCode().getCoding().get(0);
                if (reason.code.equals(coding.getCode())) {
                    medicationResource.addReasonReference().setReference(entry.getFullUrl());
                }
            }
        }
    }
    if (medication.prescriptionDetails != null) {
        JsonObject rxInfo = medication.prescriptionDetails;
        Dosage dosage = new Dosage();
        dosage.setSequence(1);
        // as_needed is true if present
        dosage.setAsNeeded(new BooleanType(rxInfo.has("as_needed")));
        if (rxInfo.has("as_needed")) {
            dosage.setText("Take as needed.");
        }
        // as_needed is false
        if ((rxInfo.has("dosage")) && (!rxInfo.has("as_needed"))) {
            Timing timing = new Timing();
            TimingRepeatComponent timingRepeatComponent = new TimingRepeatComponent();
            timingRepeatComponent.setFrequency(rxInfo.get("dosage").getAsJsonObject().get("frequency").getAsInt());
            timingRepeatComponent.setPeriod(rxInfo.get("dosage").getAsJsonObject().get("period").getAsDouble());
            timingRepeatComponent.setPeriodUnit(convertUcumCode(rxInfo.get("dosage").getAsJsonObject().get("unit").getAsString()));
            timing.setRepeat(timingRepeatComponent);
            dosage.setTiming(timing);
            Quantity dose = new SimpleQuantity().setValue(rxInfo.get("dosage").getAsJsonObject().get("amount").getAsDouble());
            DosageDoseAndRateComponent dosageDetails = new DosageDoseAndRateComponent();
            dosageDetails.setType(new CodeableConcept().addCoding(new Coding().setCode(DoseRateType.ORDERED.toCode()).setSystem(DoseRateType.ORDERED.getSystem()).setDisplay(DoseRateType.ORDERED.getDisplay())));
            dosageDetails.setDose(dose);
            List<DosageDoseAndRateComponent> details = new ArrayList<DosageDoseAndRateComponent>();
            details.add(dosageDetails);
            dosage.setDoseAndRate(details);
            if (rxInfo.has("instructions")) {
                String text = "";
                for (JsonElement instructionElement : rxInfo.get("instructions").getAsJsonArray()) {
                    JsonObject instruction = instructionElement.getAsJsonObject();
                    Code instructionCode = new Code(SNOMED_URI, instruction.get("code").getAsString(), instruction.get("display").getAsString());
                    text += instructionCode.display + "\n";
                    dosage.addAdditionalInstruction(mapCodeToCodeableConcept(instructionCode, SNOMED_URI));
                }
                dosage.setText(text);
            }
        }
        List<Dosage> dosageInstruction = new ArrayList<Dosage>();
        dosageInstruction.add(dosage);
        medicationResource.setDosageInstruction(dosageInstruction);
    }
    BundleEntryComponent medicationEntry = newEntry(person, bundle, medicationResource);
    // create new claim for medication
    medicationClaim(person, personEntry, bundle, encounterEntry, medication.claim, medicationEntry);
    // Create new administration for medication, if needed
    if (medication.administration) {
        medicationAdministration(person, personEntry, bundle, encounterEntry, medication, medicationResource);
    }
    return medicationEntry;
}
Also used : Meta(org.hl7.fhir.r4.model.Meta) DosageDoseAndRateComponent(org.hl7.fhir.r4.model.Dosage.DosageDoseAndRateComponent) ArrayList(java.util.ArrayList) JsonObject(com.google.gson.JsonObject) Dosage(org.hl7.fhir.r4.model.Dosage) Coding(org.hl7.fhir.r4.model.Coding) Medication(org.mitre.synthea.world.concepts.HealthRecord.Medication) Encounter(org.mitre.synthea.world.concepts.HealthRecord.Encounter) TimingRepeatComponent(org.hl7.fhir.r4.model.Timing.TimingRepeatComponent) Condition(org.hl7.fhir.r4.model.Condition) MedicationRequest(org.hl7.fhir.r4.model.MedicationRequest) Reference(org.hl7.fhir.r4.model.Reference) DocumentReference(org.hl7.fhir.r4.model.DocumentReference) BooleanType(org.hl7.fhir.r4.model.BooleanType) SimpleQuantity(org.hl7.fhir.r4.model.SimpleQuantity) SimpleQuantity(org.hl7.fhir.r4.model.SimpleQuantity) Quantity(org.hl7.fhir.r4.model.Quantity) Code(org.mitre.synthea.world.concepts.HealthRecord.Code) Date(java.util.Date) Extension(org.hl7.fhir.r4.model.Extension) BundleEntryComponent(org.hl7.fhir.r4.model.Bundle.BundleEntryComponent) JsonElement(com.google.gson.JsonElement) CodeType(org.hl7.fhir.r4.model.CodeType) Timing(org.hl7.fhir.r4.model.Timing) CodeableConcept(org.hl7.fhir.r4.model.CodeableConcept)

Aggregations

Immunization (org.hl7.fhir.r4.model.Immunization)13 Date (java.util.Date)9 ArrayList (java.util.ArrayList)8 InputStream (java.io.InputStream)7 Reference (org.hl7.fhir.dstu3.model.Reference)7 Test (org.junit.jupiter.api.Test)7 CodeableConcept (org.hl7.fhir.r4.model.CodeableConcept)6 Collectors (java.util.stream.Collectors)5 BundleEntryComponent (org.hl7.fhir.r4.model.Bundle.BundleEntryComponent)5 Reference (org.hl7.fhir.r4.model.Reference)5 Code (org.mitre.synthea.world.concepts.HealthRecord.Code)5 FhirContext (ca.uhn.fhir.context.FhirContext)4 Search (ca.uhn.fhir.rest.annotation.Search)4 Trace (com.newrelic.api.agent.Trace)4 File (java.io.File)4 List (java.util.List)4 BundleEntryComponent (org.hl7.fhir.dstu3.model.Bundle.BundleEntryComponent)4 Coding (org.hl7.fhir.dstu3.model.Coding)4 Bundle (org.hl7.fhir.r4.model.Bundle)4 CodeType (org.hl7.fhir.r4.model.CodeType)4