Search in sources :

Example 1 with BOOKED

use of org.hl7.fhir.dstu3.model.Appointment.AppointmentStatus.BOOKED in project BridgeServer2 by Sage-Bionetworks.

the class CRCControllerTest method postAppointmentCreated.

@Test
public void postAppointmentCreated() throws Exception {
    when(mockRequest.getHeader(AUTHORIZATION)).thenReturn(AUTHORIZATION_HEADER_VALUE);
    when(mockAccountService.authenticate(any(), any())).thenReturn(account);
    when(mockAccountService.getAccount(ACCOUNT_ID)).thenReturn(Optional.of(account));
    mockGetLocation(LOCATION_JSON);
    // mockGetGeocoding();
    DateRangeResourceList<? extends ReportData> results = new DateRangeResourceList<>(ImmutableList.of());
    doReturn(results).when(mockReportService).getParticipantReport(APP_ID, TEST_USER_ID, APPOINTMENT_REPORT, HEALTH_CODE, JAN1, JAN2);
    Appointment appointment = new Appointment();
    appointment.setStatus(BOOKED);
    // add a wrong participant to verify we go through them all and look for ours
    addAppointmentParticipantComponent(appointment, "Location/foo");
    addAppointmentSageId(appointment, TEST_USER_ID);
    String json = FHIR_CONTEXT.newJsonParser().encodeResourceToString(appointment);
    mockRequestBody(mockRequest, json);
    ResponseEntity<StatusMessage> retValue = controller.postAppointment();
    assertEquals(retValue.getBody().getMessage(), "Appointment created (status = booked).");
    assertEquals(retValue.getStatusCodeValue(), 201);
    verify(mockAccountService).authenticate(eq(app), signInCaptor.capture());
    SignIn capturedSignIn = signInCaptor.getValue();
    assertEquals(capturedSignIn.getAppId(), APP_ID);
    assertEquals(capturedSignIn.getExternalId(), CUIMC_USERNAME);
    assertEquals(capturedSignIn.getPassword(), "dummy-password");
    verify(mockReportService).saveParticipantReport(eq(APP_ID), eq(TEST_USER_ID), eq(APPOINTMENT_REPORT), eq(HEALTH_CODE), reportCaptor.capture());
    ReportData capturedReport = reportCaptor.getValue();
    assertEquals(capturedReport.getDate(), "1970-01-01");
    verifyParticipant(capturedReport.getData());
    assertEquals(capturedReport.getStudyIds(), USER_STUDY_IDS);
    verify(mockAccountService).updateAccount(accountCaptor.capture());
    Account capturedAcct = accountCaptor.getValue();
    assertEquals(capturedAcct.getDataGroups(), makeSetOf(CRCController.AccountStates.TESTS_SCHEDULED, "group1"));
    assertEquals(capturedAcct.getAttributes().get(TIMESTAMP_FIELD), TIMESTAMP.toString());
    verify(mockHealthDataService).submitHealthData(eq(APP_ID), participantCaptor.capture(), dataCaptor.capture());
    HealthDataSubmission healthData = dataCaptor.getValue();
    assertEquals(healthData.getAppVersion(), "v1");
    assertEquals(healthData.getCreatedOn(), TIMESTAMP);
    assertEquals(healthData.getMetadata().toString(), "{\"type\":\"" + APPOINTMENT_REPORT + "\"}");
    assertEquals(healthData.getData().toString(), APPOINTMENT_JSON_FULLY_RESOLVED);
}
Also used : Appointment(org.hl7.fhir.dstu3.model.Appointment) Account(org.sagebionetworks.bridge.models.accounts.Account) HealthDataSubmission(org.sagebionetworks.bridge.models.healthdata.HealthDataSubmission) ReportData(org.sagebionetworks.bridge.models.reports.ReportData) SignIn(org.sagebionetworks.bridge.models.accounts.SignIn) DateRangeResourceList(org.sagebionetworks.bridge.models.DateRangeResourceList) StatusMessage(org.sagebionetworks.bridge.models.StatusMessage) Test(org.testng.annotations.Test)

Example 2 with BOOKED

use of org.hl7.fhir.dstu3.model.Appointment.AppointmentStatus.BOOKED in project BridgeServer2 by Sage-Bionetworks.

the class CRCControllerTest method postAppointmentSkipsLocationIfNotPresent.

@Test
public void postAppointmentSkipsLocationIfNotPresent() throws Exception {
    when(mockRequest.getHeader(AUTHORIZATION)).thenReturn(AUTHORIZATION_HEADER_VALUE);
    when(mockAccountService.authenticate(any(), any())).thenReturn(account);
    when(mockAccountService.getAccount(ACCOUNT_ID)).thenReturn(Optional.of(account));
    DateRangeResourceList<? extends ReportData> results = new DateRangeResourceList<>(ImmutableList.of());
    doReturn(results).when(mockReportService).getParticipantReport(APP_ID, TEST_USER_ID, APPOINTMENT_REPORT, HEALTH_CODE, JAN1, JAN2);
    Appointment appointment = new Appointment();
    appointment.setStatus(BOOKED);
    addAppointmentSageId(appointment, TEST_USER_ID);
    String json = FHIR_CONTEXT.newJsonParser().encodeResourceToString(appointment);
    mockRequestBody(mockRequest, json);
    controller.postAppointment();
    verify(controller, never()).post(any(), any(), any());
    verify(mockHealthDataService).submitHealthData(any(), any(), any());
}
Also used : Appointment(org.hl7.fhir.dstu3.model.Appointment) DateRangeResourceList(org.sagebionetworks.bridge.models.DateRangeResourceList) Test(org.testng.annotations.Test)

Example 3 with BOOKED

use of org.hl7.fhir.dstu3.model.Appointment.AppointmentStatus.BOOKED in project gpconnect-demonstrator by nhsconnect.

the class AppointmentResourceProvider method updateAppointment.

/**
 * amend or cancel an existing appointment
 *
 * @param appointmentId
 * @param appointment Resource
 * @param theRequest required to access the interaction id
 * @return MethodOutcome
 */
@Update
public MethodOutcome updateAppointment(@IdParam IdType appointmentId, @ResourceParam Appointment appointment, HttpServletRequest theRequest) {
    MethodOutcome methodOutcome = new MethodOutcome();
    OperationOutcome operationalOutcome = new OperationOutcome();
    AppointmentDetail appointmentDetail = appointmentResourceConverterToAppointmentDetail(appointment);
    Meta meta = appointment.getMeta();
    final List<UriType> profiles = meta.getProfile();
    // #203 validations
    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), // what to do if > 1 meta profile element?
    () -> "Meta.profile " + profiles.get(0).getValue() + " is not equal to " + SD_GPC_APPOINTMENT), // #203
    new VC(() -> !appointment.getReason().isEmpty(), () -> "Appointment reason shouldn't be provided!"), 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!") });
    // URL ID and Resource ID must be the same
    if (!Objects.equals(appointmentId.getIdPartAsLong(), appointmentDetail.getId())) {
        operationalOutcome.addIssue().setSeverity(IssueSeverity.ERROR).setDiagnostics("Id in URL (" + appointmentId.getIdPart() + ") should match Id in Resource (" + appointmentDetail.getId() + ")");
        methodOutcome.setOperationOutcome(operationalOutcome);
        return methodOutcome;
    }
    // Make sure there is an existing appointment to be amended
    AppointmentDetail oldAppointmentDetail = appointmentSearch.findAppointmentByID(appointmentId.getIdPartAsLong());
    if (oldAppointmentDetail == null) {
        operationalOutcome.addIssue().setSeverity(IssueSeverity.ERROR).setDiagnostics("No appointment details found for ID: " + appointmentId.getIdPart());
        methodOutcome.setOperationOutcome(operationalOutcome);
        return methodOutcome;
    }
    // 1.2.7 set the old service type and service category for comparison with incoming update/cancel content values
    SlotDetail slotDetail1 = slotSearch.findSlotByID(oldAppointmentDetail.getSlotIds().get(0));
    oldAppointmentDetail.setServiceType(slotDetail1.getTypeDisply());
    ScheduleDetail scheduleDetail = scheduleSearch.findScheduleByID(slotDetail1.getScheduleReference());
    oldAppointmentDetail.setServiceCategory(scheduleDetail.getTypeDescription());
    String oldAppointmentVersionId = String.valueOf(oldAppointmentDetail.getLastUpdated().getTime());
    String newAppointmentVersionId = appointmentId.getVersionIdPart();
    if (newAppointmentVersionId != null && !newAppointmentVersionId.equalsIgnoreCase(oldAppointmentVersionId)) {
        throw new ResourceVersionConflictException("The specified version (" + newAppointmentVersionId + ") did not match the current resource version (" + oldAppointmentVersionId + ")");
    }
    // check for absolute reference #200
    Iterator<AppointmentParticipantComponent> iter = appointment.getParticipant().iterator();
    while (iter.hasNext()) {
        AppointmentParticipantComponent participant = iter.next();
        if (participant.getActor() != null) {
            checkReferenceIsRelative(participant.getActor().getReference());
        }
    }
    String interactionId = theRequest.getHeader(SSP_INTERACTIONID);
    // Determine if it is a cancel or an amend. This was previously a check for the presence of a cancellation reason
    // but that is not sufficient. We can sefely assume that the interaction id is populated at this point.
    AppointmentOperation appointmentOperation = null;
    final AppointmentDetail fAppointmentDetail = appointmentDetail;
    switch(interactionId) {
        case REST_CANCEL_APPOINTMENT:
            appointmentOperation = AppointmentOperation.CANCEL;
            // added at 1.2.2
            VC.execute(new VC[] { new VC(() -> appointment.getStatus() != AppointmentStatus.CANCELLED, () -> "Status must be \"cancelled\""), // #203
            new VC(() -> isInThePast(fAppointmentDetail.getStartDateTime()), () -> "The cancellation start date cannot be in the past"), new VC(() -> fAppointmentDetail.getCancellationReason() == null, () -> "The cancellation reason must be provided"), // no point in this since fhir forbids empty elements
            new VC(() -> fAppointmentDetail.getCancellationReason().isEmpty(), () -> "The cancellation reason can not be blank") });
            validateAppointmentExtensions(appointment, profiles, appointmentOperation);
            // #172
            String appointmentType = appointment.getAppointmentType().getText();
            if (appointmentType != null) {
                throwUnprocessableEntity422_InvalidResourceException("The appointment type cannot be updated on a cancellation");
            }
            // This is a Cancellation - so copy across fields which can be
            // altered
            List cancelComparisonResult = compareAppointmentsForInvalidProperty(AppointmentOperation.CANCEL, oldAppointmentDetail, appointmentDetail);
            if (cancelComparisonResult.size() > 0) {
                throwUnprocessableEntity422_InvalidResourceException("Invalid Appointment property has been amended (cancellation) " + cancelComparisonResult);
            }
            oldAppointmentDetail.setCancellationReason(appointmentDetail.getCancellationReason());
            String oldStatus = oldAppointmentDetail.getStatus();
            appointmentDetail = oldAppointmentDetail;
            appointmentDetail.setStatus("cancelled");
            if (!"cancelled".equalsIgnoreCase(oldStatus)) {
                for (Long slotId : appointmentDetail.getSlotIds()) {
                    SlotDetail slotDetail = slotSearch.findSlotByID(slotId);
                    // slotDetail.setAppointmentId(null);
                    slotDetail.setFreeBusyType("FREE");
                    slotDetail.setLastUpdated(new Date());
                    slotStore.saveSlot(slotDetail);
                }
            }
            break;
        case REST_UPDATE_APPOINTMENT:
            appointmentOperation = AppointmentOperation.AMEND;
            VC.execute(new VC[] { new VC(() -> appointment.getStatus() != AppointmentStatus.BOOKED, () -> "Status must be \"booked\""), // this subsumes #161 which only inhibited amendment of the cancellation reason in an amend
            new VC(() -> fAppointmentDetail.getCancellationReason() != null, () -> "Cannot amend cancellation reason in appointment amend"), // added at 1.2.2
            new VC(() -> isInThePast(fAppointmentDetail.getStartDateTime()), () -> "The appointment amend start date cannot be in the past") });
            List amendComparisonResult = compareAppointmentsForInvalidProperty(AppointmentOperation.AMEND, oldAppointmentDetail, appointmentDetail);
            if (amendComparisonResult.size() > 0) {
                throwUnprocessableEntity422_InvalidResourceException("Invalid Appointment property has been amended " + amendComparisonResult);
            }
            validateAppointmentExtensions(appointment, profiles, appointmentOperation);
            // This is an Amend
            oldAppointmentDetail.setComment(appointmentDetail.getComment());
            oldAppointmentDetail.setDescription(appointmentDetail.getDescription());
            appointmentDetail = oldAppointmentDetail;
            break;
        default:
            System.err.println("AppointmentResourceProvider.updateAppointment Unhandled interaction id  " + interactionId);
    }
    // we'll get the delivery channel from the slot
    String deliveryChannel = null;
    String practitionerRoleCode = null;
    String practitionerRoleDisplay = null;
    ScheduleDetail schedule = null;
    // Common to both Update and cancel
    // slots valid?
    List<SlotDetail> slots = new ArrayList<>();
    for (Long slotId : appointmentDetail.getSlotIds()) {
        SlotDetail slotDetail = slotSearch.findSlotByID(slotId);
        if (slotDetail == null) {
            throwUnprocessableEntity422_InvalidResourceException("Slot resource reference is not a valid resource");
        }
        if (deliveryChannel == null) {
            deliveryChannel = slotDetail.getDeliveryChannelCode();
        }
        if (schedule == null) {
            // load the schedule so we can get the Practitioner ID
            schedule = scheduleSearch.findScheduleByID(slotDetail.getScheduleReference());
        }
        if (practitionerRoleDisplay == null) {
            practitionerRoleDisplay = schedule.getPractitionerRoleDisplay();
            practitionerRoleCode = schedule.getPractitionerRoleCode();
        }
        slots.add(slotDetail);
    }
    validateUpdateExtensions(deliveryChannel, practitionerRoleDisplay, practitionerRoleCode, appointment.getExtension());
    // dates valid?
    // #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)), new VC(() -> appointment.getSlot().size() != slots.size(), () -> String.format("Slot count mismatch %d provided appointment has %d", appointment.getSlot().size(), slots.size())) });
    // check the slots match
    HashSet<String> hs = new HashSet<>();
    for (SlotDetail slotDetail : slots) {
        hs.add("Slot/" + slotDetail.getId());
    }
    for (Reference reference : appointment.getSlot()) {
        if (!hs.contains(reference.getReference())) {
            throwUnprocessableEntity422_InvalidResourceException(String.format("Provided slot id %s does not exist in booked appointment", reference.getReference()));
        }
    }
    // Update version and
    appointmentDetail.setLastUpdated(new Date());
    // lastUpdated timestamp
    appointmentDetail = appointmentStore.saveAppointment(appointmentDetail, slots);
    methodOutcome.setId(new IdDt("Appointment", appointmentDetail.getId()));
    methodOutcome.setResource(appointmentDetailToAppointmentResourceConverter(appointmentDetail));
    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) MethodOutcome(ca.uhn.fhir.rest.api.MethodOutcome) VC(uk.gov.hscic.common.validators.VC) ScheduleDetail(uk.gov.hscic.model.appointment.ScheduleDetail) SlotDetail(uk.gov.hscic.model.appointment.SlotDetail)

Example 4 with BOOKED

use of org.hl7.fhir.dstu3.model.Appointment.AppointmentStatus.BOOKED in project gpconnect-demonstrator by nhsconnect.

the class AppointmentResourceProvider method appointmentDetailToAppointmentResourceConverter.

/**
 * AppointmentDetail to fhir resource Appointment
 *
 * @param appointmentDetail
 * @return Appointment Resource
 */
private Appointment appointmentDetailToAppointmentResourceConverter(AppointmentDetail appointmentDetail) {
    Appointment appointment = new Appointment();
    String appointmentId = String.valueOf(appointmentDetail.getId());
    String versionId = String.valueOf(appointmentDetail.getLastUpdated().getTime());
    String resourceType = appointment.getResourceType().toString();
    IdType id = new IdType(resourceType, appointmentId, versionId);
    appointment.setId(id);
    appointment.getMeta().setVersionId(versionId);
    appointment.getMeta().setLastUpdated(appointmentDetail.getLastUpdated());
    appointment.getMeta().addProfile(SystemURL.SD_GPC_APPOINTMENT);
    Extension extension = new Extension(SystemURL.SD_EXTENSION_GPC_APPOINTMENT_CANCELLATION_REASON, new StringType(appointmentDetail.getCancellationReason()));
    appointment.addExtension(extension);
    // #157 derive delivery channel from slot
    List<Long> sids = appointmentDetail.getSlotIds();
    ScheduleDetail scheduleDetail = null;
    if (sids.size() > 0) {
        // get the first slot but it should not matter because for multi slot appts the deliveryChannel is always the same
        SlotDetail slotDetail = slotSearch.findSlotByID(sids.get(0));
        String deliveryChannel = slotDetail.getDeliveryChannelCode();
        if (deliveryChannel != null && !deliveryChannel.trim().isEmpty()) {
            Extension deliveryChannelExtension = new Extension(SystemURL.SD_EXTENSION_GPC_DELIVERY_CHANNEL, new CodeType(deliveryChannel));
            appointment.addExtension(deliveryChannelExtension);
        }
        scheduleDetail = scheduleSearch.findScheduleByID(slotDetail.getScheduleReference());
    }
    // practitioner role extension here
    // lookup the practitioner
    Long practitionerID = appointmentDetail.getPractitionerId();
    if (practitionerID != null) {
        // #195 we need to get this detail from the schedule not the practitioner table
        if (scheduleDetail != null) {
            Coding roleCoding = new Coding(SystemURL.VS_GPC_PRACTITIONER_ROLE, scheduleDetail.getPractitionerRoleCode(), scheduleDetail.getPractitionerRoleDisplay());
            Extension practitionerRoleExtension = new Extension(SystemURL.SD_EXTENSION_GPC_PRACTITIONER_ROLE, new CodeableConcept().addCoding(roleCoding));
            appointment.addExtension(practitionerRoleExtension);
        }
    }
    switch(appointmentDetail.getStatus().toLowerCase(Locale.UK)) {
        case "pending":
            appointment.setStatus(AppointmentStatus.PENDING);
            break;
        case "booked":
            appointment.setStatus(AppointmentStatus.BOOKED);
            break;
        case "arrived":
            appointment.setStatus(AppointmentStatus.ARRIVED);
            break;
        case "fulfilled":
            appointment.setStatus(AppointmentStatus.FULFILLED);
            break;
        case "cancelled":
            appointment.setStatus(AppointmentStatus.CANCELLED);
            break;
        case "noshow":
            appointment.setStatus(AppointmentStatus.NOSHOW);
            break;
        default:
            appointment.setStatus(AppointmentStatus.PENDING);
            break;
    }
    appointment.setStart(appointmentDetail.getStartDateTime());
    appointment.setEnd(appointmentDetail.getEndDateTime());
    // #218 Date time formats
    appointment.getStartElement().setPrecision(TemporalPrecisionEnum.SECOND);
    appointment.getEndElement().setPrecision(TemporalPrecisionEnum.SECOND);
    List<Reference> slotResources = new ArrayList<>();
    for (Long slotId : appointmentDetail.getSlotIds()) {
        slotResources.add(new Reference("Slot/" + slotId));
    }
    appointment.setSlot(slotResources);
    if (appointmentDetail.getPriority() != null) {
        appointment.setPriority(appointmentDetail.getPriority());
    }
    appointment.setComment(appointmentDetail.getComment());
    appointment.setDescription(appointmentDetail.getDescription());
    appointment.addParticipant().setActor(new Reference("Patient/" + appointmentDetail.getPatientId())).setStatus(ParticipationStatus.ACCEPTED);
    appointment.addParticipant().setActor(new Reference("Location/" + appointmentDetail.getLocationId())).setStatus(ParticipationStatus.ACCEPTED);
    if (null != appointmentDetail.getPractitionerId()) {
        appointment.addParticipant().setActor(new Reference("Practitioner/" + appointmentDetail.getPractitionerId())).setStatus(ParticipationStatus.ACCEPTED);
    }
    if (null != appointmentDetail.getCreated()) {
        appointment.setCreated(appointmentDetail.getCreated());
    }
    if (null != appointmentDetail.getBookingOrganization()) {
        // add extension with reference to contained item
        String reference = "#1";
        Reference orgRef = new Reference(reference);
        Extension bookingOrgExt = new Extension(SystemURL.SD_CC_APPOINTMENT_BOOKINGORG, orgRef);
        appointment.addExtension(bookingOrgExt);
        BookingOrgDetail bookingOrgDetail = appointmentDetail.getBookingOrganization();
        Organization bookingOrg = new Organization();
        bookingOrg.setId(reference);
        bookingOrg.getNameElement().setValue(bookingOrgDetail.getName());
        // #198 org phone now persists usetype and system
        ContactPoint orgTelecom = bookingOrg.getTelecomFirstRep();
        orgTelecom.setValue(bookingOrgDetail.getTelephone());
        try {
            orgTelecom.setSystem(ContactPointSystem.fromCode(bookingOrgDetail.getSystem().toLowerCase()));
            if (bookingOrgDetail.getUsetype() != null && !bookingOrgDetail.getUsetype().trim().isEmpty()) {
                orgTelecom.setUse(ContactPointUse.fromCode(bookingOrgDetail.getUsetype().toLowerCase()));
            }
        } catch (FHIRException ex) {
        // Logger.getLogger(AppointmentResourceProvider.class.getName()).log(Level.SEVERE, null, ex);
        }
        bookingOrg.getMeta().addProfile(SystemURL.SD_GPC_ORGANIZATION);
        if (null != bookingOrgDetail.getOrgCode()) {
            bookingOrg.getIdentifierFirstRep().setSystem(SystemURL.ID_ODS_ORGANIZATION_CODE).setValue(bookingOrgDetail.getOrgCode());
        }
        // add contained booking organization resource
        appointment.getContained().add(bookingOrg);
    }
    // if bookingOrganization
    appointment.setMinutesDuration(appointmentDetail.getMinutesDuration());
    // 1.2.7 set service category from schedule type description
    appointment.setServiceCategory(new CodeableConcept().setText(scheduleDetail.getTypeDescription()));
    // 1.2.7 set service type from slot type description
    appointment.addServiceType(new CodeableConcept().setText(slotSearch.findSlotByID(sids.get(0)).getTypeDisply()));
    return appointment;
}
Also used : FHIRException(org.hl7.fhir.exceptions.FHIRException) BookingOrgDetail(uk.gov.hscic.model.appointment.BookingOrgDetail) ScheduleDetail(uk.gov.hscic.model.appointment.ScheduleDetail) SlotDetail(uk.gov.hscic.model.appointment.SlotDetail)

Example 5 with BOOKED

use of org.hl7.fhir.dstu3.model.Appointment.AppointmentStatus.BOOKED 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

Appointment (org.hl7.fhir.dstu3.model.Appointment)7 DateRangeResourceList (org.sagebionetworks.bridge.models.DateRangeResourceList)4 StatusMessage (org.sagebionetworks.bridge.models.StatusMessage)4 Test (org.testng.annotations.Test)4 AppointmentParticipantComponent (org.hl7.fhir.dstu3.model.Appointment.AppointmentParticipantComponent)3 ScheduleDetail (uk.gov.hscic.model.appointment.ScheduleDetail)3 SlotDetail (uk.gov.hscic.model.appointment.SlotDetail)3 IdDt (ca.uhn.fhir.model.primitive.IdDt)2 MethodOutcome (ca.uhn.fhir.rest.api.MethodOutcome)2 Account (org.sagebionetworks.bridge.models.accounts.Account)2 HealthDataSubmission (org.sagebionetworks.bridge.models.healthdata.HealthDataSubmission)2 VC (uk.gov.hscic.common.validators.VC)2 AppointmentDetail (uk.gov.hscic.model.appointment.AppointmentDetail)2 IParser (ca.uhn.fhir.parser.IParser)1 ILoggingEvent (ch.qos.logback.classic.spi.ILoggingEvent)1 LoggingEvent (ch.qos.logback.classic.spi.LoggingEvent)1 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 HttpEntity (org.apache.http.HttpEntity)1 HttpResponse (org.apache.http.HttpResponse)1 StatusLine (org.apache.http.StatusLine)1