Search in sources :

Example 81 with Meta

use of org.hl7.fhir.r4.model.Meta in project camel-spring-boot by apache.

the class FhirMetaIT method testDelete.

@Test
public void testDelete() throws Exception {
    // assert no meta
    Meta meta = fhirClient.meta().get(Meta.class).fromResource(this.patient.getIdElement()).execute();
    assertEquals(0, meta.getTag().size());
    Meta inMeta = new Meta();
    inMeta.addTag().setSystem("urn:system1").setCode("urn:code1");
    // add meta
    meta = fhirClient.meta().add().onResource(this.patient.getIdElement()).meta(inMeta).execute();
    assertEquals(1, meta.getTag().size());
    // delete meta
    final Map<String, Object> headers = new HashMap<>();
    // parameter type is org.hl7.fhir.instance.model.api.IBaseMetaType
    headers.put("CamelFhir.meta", meta);
    // parameter type is org.hl7.fhir.instance.model.api.IIdType
    headers.put("CamelFhir.id", this.patient.getIdElement());
    IBaseMetaType result = requestBodyAndHeaders("direct://DELETE", null, headers);
    LOG.debug("delete: " + result);
    assertNotNull(result, "delete result");
    assertEquals(0, result.getTag().size());
}
Also used : Meta(org.hl7.fhir.r4.model.Meta) HashMap(java.util.HashMap) IBaseMetaType(org.hl7.fhir.instance.model.api.IBaseMetaType) Test(org.junit.jupiter.api.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) CamelSpringBootTest(org.apache.camel.test.spring.junit5.CamelSpringBootTest)

Example 82 with Meta

use of org.hl7.fhir.r4.model.Meta in project camel-spring-boot by apache.

the class FhirMetaIT method testGetFromTypePreferResponseType.

@Test
public void testGetFromTypePreferResponseType() throws Exception {
    final Map<String, Object> headers = new HashMap<>();
    // parameter type is Class
    headers.put("CamelFhir.metaType", Meta.class);
    // parameter type is String
    headers.put("CamelFhir.resourceType", "Patient");
    headers.put(ExtraParameters.PREFER_RESPONSE_TYPE.getHeaderName(), Patient.class);
    Meta result = requestBodyAndHeaders("direct://GET_FROM_TYPE", null, headers);
    LOG.debug("getFromType: " + result);
    assertNotNull(result, "getFromType result");
}
Also used : Meta(org.hl7.fhir.r4.model.Meta) HashMap(java.util.HashMap) Test(org.junit.jupiter.api.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) CamelSpringBootTest(org.apache.camel.test.spring.junit5.CamelSpringBootTest)

Example 83 with Meta

use of org.hl7.fhir.r4.model.Meta in project gpconnect-demonstrator by nhsconnect.

the class MedicationStatementResourceProvider method getMedicationStatementResource.

public MedicationStatement getMedicationStatementResource(MedicationStatementDetail statementDetail) {
    MedicationStatement medicationStatement = new MedicationStatement();
    medicationStatement.setId(statementDetail.getId().toString());
    List<Identifier> identifiers = new ArrayList<>();
    Identifier identifier = new Identifier().setSystem("https://fhir.nhs.uk/Id/cross-care-setting-identifier").setValue(statementDetail.getGuid());
    identifiers.add(identifier);
    medicationStatement.setIdentifier(identifiers);
    medicationStatement.setMeta(new Meta().addProfile(SystemURL.SD_GPC_MEDICATION_STATEMENT));
    medicationStatement.addExtension(new Extension(SystemURL.SD_CC_EXT_MEDICATION_STATEMENT_LAST_ISSUE, new DateTimeType(statementDetail.getLastIssueDate(), TemporalPrecisionEnum.DAY)));
    if (statementDetail.getMedicationRequestPlanId() != null) {
        medicationStatement.addBasedOn(new Reference(new IdType("MedicationRequest", statementDetail.getMedicationRequestPlanId())));
    }
    try {
        medicationStatement.setStatus(MedicationStatementStatus.fromCode(statementDetail.getStatusCode()));
    } catch (FHIRException e) {
        throw new UnprocessableEntityException(e.getMessage());
    }
    if (statementDetail.getMedicationId() != null) {
        medicationStatement.setMedication(new Reference(new IdType("Medication", statementDetail.getMedicationId())));
    }
    medicationStatement.setEffective(new Period().setStart(statementDetail.getStartDate()).setEnd(statementDetail.getEndDate()));
    medicationStatement.setDateAsserted(statementDetail.getDateAsserted());
    if (statementDetail.getPatientId() != null)
        medicationStatement.setSubject(new Reference(new IdType("Patient", statementDetail.getPatientId())));
    try {
        medicationStatement.setTaken(statementDetail.getTakenCode() != null ? MedicationStatementTaken.fromCode(statementDetail.getTakenCode()) : MedicationStatementTaken.UNK);
    } catch (FHIRException e) {
        throw new UnprocessableEntityException(e.getMessage());
    }
    setReasonCodes(medicationStatement, statementDetail);
    setNotes(medicationStatement, statementDetail);
    String dosageText = statementDetail.getDosageText();
    medicationStatement.addDosage(new Dosage().setText(dosageText == null || dosageText.trim().isEmpty() ? NO_INFORMATION_AVAILABLE : dosageText).setPatientInstruction(statementDetail.getDosagePatientInstruction()));
    String prescribingAgency = statementDetail.getPrescribingAgency();
    if (prescribingAgency != null && !prescribingAgency.trim().isEmpty()) {
        String prescribingAgencyDisplay = "";
        if (prescribingAgency.equalsIgnoreCase("prescribed-at-gp-practice")) {
            prescribingAgencyDisplay = "Prescribed at GP practice";
        } else if (prescribingAgency.equalsIgnoreCase("prescribed-by-another-organisation")) {
            prescribingAgencyDisplay = "Prescribed by another organisation";
        }
        Coding coding = new Coding(SystemURL.CS_CC_PRESCRIBING_AGENCY_STU3, prescribingAgency, prescribingAgencyDisplay);
        CodeableConcept codeableConcept = new CodeableConcept().addCoding(coding);
        medicationStatement.addExtension(new Extension(SystemURL.SD_EXTENSION_CC_PRESCRIBING_AGENCY, codeableConcept));
    }
    // #281 1.2.5 add dosageLastChanged
    Date dosageLastChanged = statementDetail.getDosageLastChanged();
    if (dosageLastChanged != null) {
        medicationStatement.addExtension(new Extension(SystemURL.SD_EXTENSION_CC_DOSAGE_LAST_CHANGED, new DateTimeType(dosageLastChanged)));
    }
    return medicationStatement;
}
Also used : UnprocessableEntityException(ca.uhn.fhir.rest.server.exceptions.UnprocessableEntityException) ArrayList(java.util.ArrayList) FHIRException(org.hl7.fhir.exceptions.FHIRException) Date(java.util.Date)

Example 84 with Meta

use of org.hl7.fhir.r4.model.Meta in project gpconnect-demonstrator by nhsconnect.

the class PopulateMedicationBundle method createListEntry.

private ListResource createListEntry(List<MedicationStatementDetail> medicationStatements, String nhsNumber) {
    ListResource medicationStatementsList = new ListResource();
    // #179 dont populate List.id
    // medicationStatementsList.setId(new IdType(1));
    medicationStatementsList.setMeta(new Meta().addProfile(SystemURL.SD_GPC_LIST));
    medicationStatementsList.setStatus(ListStatus.CURRENT);
    // #179 dont populate List.id
    // medicationStatementsList.setId(new IdDt(1));
    medicationStatementsList.setMode(ListMode.SNAPSHOT);
    medicationStatementsList.setTitle(SystemConstants.MEDICATION_LIST);
    medicationStatementsList.setCode(new CodeableConcept().addCoding(new Coding(SystemURL.VS_SNOMED, "933361000000108", MEDICATION_LIST)));
    medicationStatementsList.setSubject(new Reference(new IdType("Patient", 1L)).setIdentifier(new Identifier().setValue(nhsNumber).setSystem(SystemURL.ID_NHS_NUMBER)));
    medicationStatementsList.setDate(new Date());
    medicationStatementsList.setOrderedBy(new CodeableConcept().addCoding(new Coding(SystemURL.CS_LIST_ORDER, "event-date", "Sorted by Event Date")));
    medicationStatementsList.addExtension(setClinicalSetting());
    if (medicationStatements.isEmpty()) {
        medicationStatementsList.setEmptyReason(new CodeableConcept().setText(SystemConstants.NO_CONTENT));
        medicationStatementsList.setNote(Arrays.asList(new Annotation(new StringType(SystemConstants.INFORMATION_NOT_AVAILABLE))));
    }
    Set<String> warningCodes = new HashSet<>();
    medicationStatements.forEach(statement -> {
        Reference statementRef = new Reference(new IdType("MedicationStatement", statement.getId()));
        ListEntryComponent listEntryComponent = new ListEntryComponent(statementRef);
        medicationStatementsList.addEntry(listEntryComponent);
        if (statement.getWarningCode() != null) {
            warningCodes.add(statement.getWarningCode());
        }
    });
    WarningCodeExtHelper.addWarningCodeExtensions(warningCodes, medicationStatementsList, patientRepository, medicationStatementRepository, structuredAllergySearch);
    return medicationStatementsList;
}
Also used : IIdType(org.hl7.fhir.instance.model.api.IIdType) ListEntryComponent(org.hl7.fhir.dstu3.model.ListResource.ListEntryComponent)

Example 85 with Meta

use of org.hl7.fhir.r4.model.Meta in project gpconnect-demonstrator by nhsconnect.

the class AppointmentResourceProvider method createAppointment.

/**
 * Create a new appointment
 *
 * @param appointment Resource
 * @return MethodOutcome
 */
@Create
public MethodOutcome createAppointment(@ResourceParam Appointment appointment) {
    Meta meta = appointment.getMeta();
    final List<UriType> profiles = meta.getProfile();
    // #203 validations
    // Uses VC class and lamda functions for brevity and to avoid masses of duplicated code
    // first lamda takes no params and returns a Boolean representing the fail condition ie true for fail
    // second lamda takes no params and returns a String describing the error condition
    // VC.execute evaluates the first lamda and if true theows an InvalidResource exception containg the string from the second lambda
    VC.execute(new VC[] { new VC(() -> profiles.isEmpty(), () -> "Meta element must be present in Appointment"), new VC(() -> !profiles.get(0).getValue().equalsIgnoreCase(SD_GPC_APPOINTMENT), () -> "Meta.profile " + profiles.get(0).getValue() + " is not equal to " + SD_GPC_APPOINTMENT), // what to do if > 1 meta profile element?
    new VC(() -> appointment.getStatus() == null, () -> "No status supplied"), new VC(() -> appointment.getStatus() != AppointmentStatus.BOOKED, () -> "Status must be \"booked\""), new VC(() -> appointment.getStart() == null || appointment.getEnd() == null, () -> "Both start and end date are required"), new VC(() -> appointment.getSlot().isEmpty(), () -> "At least one slot is required"), new VC(() -> appointment.getCreated() == null, () -> "Created must be populated"), new VC(() -> appointment.getParticipant().isEmpty(), () -> "At least one participant is required"), new VC(() -> !appointment.getIdentifierFirstRep().isEmpty() && appointment.getIdentifierFirstRep().getValue() == null, () -> "Appointment identifier value is required"), new VC(() -> appointment.getId() != null, () -> "Appointment id shouldn't be provided!"), new VC(() -> !appointment.getReason().isEmpty(), () -> "Appointment reason shouldn't be provided!"), // #157 refers to typeCode but means specialty  (name was changed)
    new VC(() -> !appointment.getSpecialty().isEmpty(), () -> "Appointment speciality shouldn't be provided!"), // new VC(() -> !appointment.getServiceType().isEmpty(), () -> "Appointment service type shouldn't be provided!"),
    new VC(() -> !appointment.getAppointmentType().isEmpty(), () -> "Appointment type shouldn't be provided!"), new VC(() -> !appointment.getIndication().isEmpty(), () -> "Appointment indication shouldn't be provided!"), new VC(() -> !appointment.getSupportingInformation().isEmpty(), () -> "Appointment supporting information shouldn't be provided!"), new VC(() -> !appointment.getIncomingReferral().isEmpty(), () -> "Appointment incoming referral shouldn't be provided!") });
    boolean patientFound = false;
    boolean locationFound = false;
    for (AppointmentParticipantComponent participant : appointment.getParticipant()) {
        if (participant.getActor().getReference() != null) {
            String reference = participant.getActor().getReference();
            // check for absolute reference #200
            checkReferenceIsRelative(reference);
            if (reference.contains("Patient")) {
                patientFound = true;
            } else if (reference.contains("Location")) {
                locationFound = true;
            }
        } else {
            throwUnprocessableEntity422_InvalidResourceException("Appointment resource is not valid as it does not contain a Participant Actor reference");
        }
    }
    if (!patientFound || !locationFound) {
        throwUnprocessableEntity422_InvalidResourceException("Appointment resource is not a valid resource required valid Patient and Location");
    }
    // variable accessed in a lambda must be declared final
    final boolean fPatientFound = patientFound;
    final boolean fLocationFound = locationFound;
    VC.execute(new VC[] { new VC(() -> !fPatientFound, () -> "Appointment resource is not a valid resource required valid Patient"), new VC(() -> !fLocationFound, () -> "Appointment resource is not a valid resource required valid Location") });
    String locationId = null;
    String practitionerId = null;
    for (AppointmentParticipantComponent participant : appointment.getParticipant()) {
        Reference participantActor = participant.getActor();
        final Boolean searchParticipant = (participantActor != null);
        if (searchParticipant) {
            appointmentValidation.validateParticipantActor(participantActor);
        }
        CodeableConcept participantType = participant.getTypeFirstRep();
        final Boolean validParticipantType = appointmentValidation.validateParticipantType(participantType);
        VC.execute(new VC[] { new VC(() -> !searchParticipant, () -> "Supplied Participant is not valid. Must have an Actor."), new VC(() -> !validParticipantType, () -> "Supplied Participant is not valid. Must have a Type.") });
        // gets the logical id as a string
        if (participantActor.getReference().startsWith("Location")) {
            locationId = appointmentValidation.getId();
        } else if (participantActor.getReference().startsWith("Practitioner")) {
            practitionerId = appointmentValidation.getId();
        }
        appointmentValidation.validateParticipantStatus(participant.getStatus(), participant.getStatusElement(), participant.getStatusElement());
    }
    List<Extension> extensions = validateAppointmentExtensions(appointment, profiles, AppointmentOperation.BOOK);
    // Store New Appointment
    AppointmentDetail appointmentDetail = appointmentResourceConverterToAppointmentDetail(appointment);
    List<SlotDetail> slots = new ArrayList<>();
    // we'll get the delivery channel from the slot
    String deliveryChannel = null;
    String practitionerRoleCode = null;
    String practitionerRoleDisplay = null;
    ScheduleDetail schedule = null;
    String serviceType = null;
    for (Long slotId : appointmentDetail.getSlotIds()) {
        SlotDetail slotDetail = slotSearch.findSlotByID(slotId);
        new VC(() -> slotDetail == null, () -> String.format("Slot resource reference value %s is not a valid resource.", slotId)).execute();
        if (slotDetail.getFreeBusyType().equals("BUSY")) {
            throw OperationOutcomeFactory.buildOperationOutcomeException(new ResourceVersionConflictException(String.format("Slot is already in use.", slotId)), SystemCode.DUPLICATE_REJECTED, IssueType.CONFLICT);
        }
        if (deliveryChannel == null) {
            deliveryChannel = slotDetail.getDeliveryChannelCode();
        } else if (!deliveryChannel.equals(slotDetail.getDeliveryChannelCode())) {
            // added at 1.2.2
            throwUnprocessableEntity422_InvalidResourceException(String.format("Subsequent slot (Slot/%s) delivery channel (%s) is not equal to initial slot delivery channel (%s).", slotId, deliveryChannel, slotDetail.getDeliveryChannelCode()));
        }
        // 1.2.7 check service type is the same as initial service type
        if (serviceType == null) {
            serviceType = slotDetail.getTypeDisply();
        } else if (!serviceType.equals(slotDetail.getTypeDisply())) {
            // added at 1.2.2
            throwUnprocessableEntity422_InvalidResourceException(String.format("Subsequent slot (Slot/%s) service type (%s) is not equal to initial slot service type (%s).", slotId, serviceType, slotDetail.getTypeDisply()));
        }
        if (schedule == null) {
            // load the schedule so we can get the Practitioner ID
            schedule = scheduleSearch.findScheduleByID(slotDetail.getScheduleReference());
            // add practitioner id so we can get the practitioner role
            // practitioner is derived but needs to be stored fgr comparison if provided
            appointmentDetail.setPractitionerId(schedule.getPractitionerId());
        }
        if (practitionerRoleDisplay == null) {
            practitionerRoleDisplay = schedule.getPractitionerRoleDisplay();
            practitionerRoleCode = schedule.getPractitionerRoleCode();
        }
        slots.add(slotDetail);
    }
    // for slot
    validateUpdateExtensions(deliveryChannel, practitionerRoleDisplay, practitionerRoleCode, extensions);
    // #203 check location id matches the one in the schedule
    if (locationId != null && !locationId.equals(schedule.getLocationId().toString())) {
        throwUnprocessableEntity422_InvalidResourceException(String.format("Provided location id (%s) is not equal to Schedule location id (%s)", locationId, schedule.getLocationId().toString()));
    }
    // #203 check practitioner id matches the one in the schedule if there is one
    if (practitionerId != null) {
        if (!practitionerId.equals(schedule.getPractitionerId().toString())) {
            throwUnprocessableEntity422_InvalidResourceException(String.format("Provided practitioner id (%s) is not equal to Schedule practitioner id (%s)", practitionerId, schedule.getPractitionerId().toString()));
        }
    }
    // #203
    Date firstSlotStart = slots.get(0).getStartDateTime();
    Date lastSlotEnd = slots.get(slots.size() - 1).getEndDateTime();
    // need to insert a colon in the timezone string
    String firstSlotStartStr = TIMESTAMP_FORMAT.format(firstSlotStart).replaceFirst("([0-9]{2})([0-9]{2})$", "$1:$2");
    String lastSlotEndStr = TIMESTAMP_FORMAT.format(lastSlotEnd).replaceFirst("([0-9]{2})([0-9]{2})$", "$1:$2");
    VC.execute(new VC[] { new VC(() -> appointment.getStart().compareTo(firstSlotStart) != 0, () -> String.format("Start date '%s' must match start date of first slot '%s'", appointment.getStart(), firstSlotStart)), new VC(() -> appointment.getEnd().compareTo(lastSlotEnd) != 0, () -> String.format("End date '%s' must match end date of last slot '%s'", appointment.getEnd(), lastSlotEnd)), // #218 strings should match exactly
    new VC(() -> !appointment.getStartElement().getValueAsString().equals(firstSlotStartStr), () -> String.format("Start date '%s' must lexically match start date of first slot '%s'", appointment.getStartElement().getValueAsString(), firstSlotStartStr)), new VC(() -> !appointment.getEndElement().getValueAsString().equals(lastSlotEndStr), () -> String.format("End date '%s' must lexically match end date of last slot '%s'", appointment.getEndElement().getValueAsString(), lastSlotEndStr)), // This probably can never happen under fhir
    new VC(() -> appointment.getSlot().isEmpty(), () -> "Slot reference must be populated") });
    int durationFromSlots = (int) (lastSlotEnd.getTime() - firstSlotStart.getTime()) / (1000 * 60);
    // #203 validate optional minutes duration
    if (appointment.hasMinutesDuration()) {
        int providedDuration = appointment.getMinutesDuration();
        new VC(() -> durationFromSlots != providedDuration, () -> String.format("Provided duration (%d minutes) is not equal to actual appointment duration (%d minutes)", providedDuration, durationFromSlots)).execute();
    } else {
        // not provided so write the calculated value into the appointmentDetail object
        appointmentDetail.setMinutesDuration(durationFromSlots);
    }
    // add deliveryChannel #157 removed
    // appointmentDetail.setDeliveryChannel(deliveryChannel);
    appointmentDetail = appointmentStore.saveAppointment(appointmentDetail, slots);
    for (SlotDetail slot : slots) {
        // slot.setAppointmentId(appointmentDetail.getId());
        slot.setFreeBusyType("BUSY");
        slot.setLastUpdated(new Date());
        slotStore.saveSlot(slot);
    }
    // Build response containing the new resource id
    MethodOutcome methodOutcome = new MethodOutcome();
    methodOutcome.setId(new IdDt("Appointment", appointmentDetail.getId()));
    methodOutcome.setResource(appointmentDetailToAppointmentResourceConverter(appointmentDetail));
    methodOutcome.setCreated(Boolean.TRUE);
    return methodOutcome;
}
Also used : AppointmentParticipantComponent(org.hl7.fhir.dstu3.model.Appointment.AppointmentParticipantComponent) AppointmentDetail(uk.gov.hscic.model.appointment.AppointmentDetail) IdDt(ca.uhn.fhir.model.primitive.IdDt) VC(uk.gov.hscic.common.validators.VC) MethodOutcome(ca.uhn.fhir.rest.api.MethodOutcome) ScheduleDetail(uk.gov.hscic.model.appointment.ScheduleDetail) SlotDetail(uk.gov.hscic.model.appointment.SlotDetail)

Aggregations

Meta (org.hl7.fhir.r4.model.Meta)40 HashMap (java.util.HashMap)36 Date (java.util.Date)35 Meta (org.hl7.fhir.dstu3.model.Meta)31 IBaseMetaType (org.hl7.fhir.instance.model.api.IBaseMetaType)28 Reference (org.hl7.fhir.r4.model.Reference)26 JsonObject (javax.json.JsonObject)24 Path (javax.ws.rs.Path)24 Produces (javax.ws.rs.Produces)24 Code (org.mitre.synthea.world.concepts.HealthRecord.Code)20 BundleEntryComponent (org.hl7.fhir.r4.model.Bundle.BundleEntryComponent)18 CodeableConcept (org.hl7.fhir.r4.model.CodeableConcept)17 DocumentReference (org.hl7.fhir.r4.model.DocumentReference)17 ArrayList (java.util.ArrayList)16 Coding (org.hl7.fhir.r4.model.Coding)16 XhtmlNode (org.hl7.fhir.utilities.xhtml.XhtmlNode)15 Test (org.junit.jupiter.api.Test)15 Test (org.junit.Test)14 NotImplementedException (org.apache.commons.lang3.NotImplementedException)13 GET (javax.ws.rs.GET)12