Search in sources :

Example 6 with AppointmentDetail

use of uk.gov.hscic.model.appointment.AppointmentDetail in project gpconnect-demonstrator by nhsconnect.

the class RefreshData method resetAppointments.

private void resetAppointments() {
    appointmentStore.clearAppointments();
    slotStore.clearSlots();
    try {
        List<String> lines = Files.readLines(new File(configPath + slotsFilename), StandardCharsets.UTF_8);
        for (String line : lines) {
            String[] element = line.split(",");
            Date currentDate = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(currentDate);
            calendar.add(Calendar.DAY_OF_YEAR, Integer.parseInt(element[SLOT_INDEX_DAY_OFFSET]));
            calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(element[SLOT_INDEX_START_H]));
            calendar.set(Calendar.MINUTE, Integer.parseInt(element[SLOT_INDEX_START_M]));
            calendar.set(Calendar.SECOND, Integer.parseInt(element[SLOT_INDEX_START_S]));
            calendar.set(Calendar.MILLISECOND, 0);
            Date startDate = calendar.getTime();
            calendar.setTime(currentDate);
            calendar.add(Calendar.DAY_OF_YEAR, Integer.parseInt(element[SLOT_INDEX_DAY_OFFSET]));
            calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(element[SLOT_INDEX_END_H]));
            calendar.set(Calendar.MINUTE, Integer.parseInt(element[SLOT_INDEX_END_M]));
            calendar.set(Calendar.SECOND, Integer.parseInt(element[SLOT_INDEX_END_S]));
            calendar.set(Calendar.MILLISECOND, 0);
            Date endDate = calendar.getTime();
            // handle trailing comma on last entry
            String deliveryChannelCode = element.length >= SLOT_FIELDS ? element[SLOT_FIELDS - 1] : "";
            // 0 number of days to add to today
            // 1 start hours
            // 2 start minutes
            // 3 start seconds
            // 4 end hours
            // 5 end minutes
            // 6 end seconds
            // 7 Slot type code long eg 408443003
            // 8 Slot type description/display string eg General Medical Practice
            // 9 Practitioner internal id /schedule reference eg 2
            // 10 Slot Status FREE/BUSY string
            // 11 boolean gp connect bookable boolean
            // 12 organization id int 1 or 2
            // 13 organization type String eg Urgent care
            // 14 sequence of PVT delivery channel codes String P In-person, T Telephone, V Video eg TVP
            // The Collections.singletonList idiom is a way of converting a single item into a list containing one item
            // 1.2.7 allow null service type and code
            Long slotType = null;
            try {
                slotType = Long.parseLong(element[SLOT_INDEX_SLOT_TYPE_CODE]);
            } catch (NumberFormatException ex) {
            }
            slotStore.saveSlot(createSlot(slotType, element[SLOT_INDEX_DESCRIPTION], Long.parseLong(element[SLOT_INDEX_PRACTITIONER_ID]), element[SLOT_INDEX_FREE_BUSY], startDate, endDate, currentDate, Boolean.parseBoolean(element[SLOT_INDEX_BOOKABLE]), element[SLOT_INDEX_ORG_ID].isEmpty() ? Collections.EMPTY_LIST : Collections.singletonList(Long.parseLong(element[SLOT_INDEX_ORG_ID])), element[SLOT_INDEX_ORG_TYPE].trim().isEmpty() ? Collections.EMPTY_LIST : Collections.singletonList(element[SLOT_INDEX_ORG_TYPE].trim()), deliveryChannelCode));
        }
    } catch (IOException e) {
        LOG.error("Error reading slots file", e);
    }
    try {
        List<SlotDetail> slots = slotStore.findAllSlots();
        if (slots.size() > 2) {
            AppointmentDetail appointment = createAppointment(slots.get(0), "A appointment to discuss test data");
            appointmentStore.saveAppointment(appointment, Collections.singletonList(slots.get(0)));
            AppointmentDetail appointment2 = createAppointment(slots.get(1), "A follow-up appointment for tests.");
            appointmentStore.saveAppointment(appointment2, Collections.singletonList(slots.get(1)));
        }
    } catch (Exception e) {
        LOG.error("Error booking test appointments", e);
    }
}
Also used : Calendar(java.util.Calendar) AppointmentDetail(uk.gov.hscic.model.appointment.AppointmentDetail) IOException(java.io.IOException) Date(java.util.Date) IOException(java.io.IOException) File(java.io.File) SlotDetail(uk.gov.hscic.model.appointment.SlotDetail)

Example 7 with AppointmentDetail

use of uk.gov.hscic.model.appointment.AppointmentDetail in project gpconnect-demonstrator by nhsconnect.

the class AppointmentEntityToAppointmentDetailTransformer method transform.

@Override
public AppointmentDetail transform(AppointmentEntity item) {
    AppointmentDetail appointmentDetail = new AppointmentDetail();
    appointmentDetail.setId(item.getId());
    appointmentDetail.setCancellationReason(item.getCancellationReason());
    appointmentDetail.setStatus(item.getStatus());
    appointmentDetail.setDescription(item.getDescription());
    appointmentDetail.setStartDateTime(item.getStartDateTime());
    appointmentDetail.setEndDateTime(item.getEndDateTime());
    appointmentDetail.setSlotIds(item.getSlots().stream().map(SlotEntity::getId).collect(Collectors.toList()));
    appointmentDetail.setComment(item.getComment());
    appointmentDetail.setPatientId(item.getPatientId());
    appointmentDetail.setPractitionerId(item.getPractitionerId());
    appointmentDetail.setLocationId(item.getLocationId());
    appointmentDetail.setLastUpdated(item.getLastUpdated());
    appointmentDetail.setMinutesDuration(item.getMinutesDuration());
    appointmentDetail.setPriority(item.getPriority());
    appointmentDetail.setBookingOrganization(bookingOrgTransformer.transform(item.getBookingOrganization()));
    appointmentDetail.setCreated(item.getCreated());
    return appointmentDetail;
}
Also used : AppointmentDetail(uk.gov.hscic.model.appointment.AppointmentDetail) SlotEntity(uk.gov.hscic.appointment.slot.SlotEntity)

Example 8 with AppointmentDetail

use of uk.gov.hscic.model.appointment.AppointmentDetail 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

AppointmentDetail (uk.gov.hscic.model.appointment.AppointmentDetail)8 SlotDetail (uk.gov.hscic.model.appointment.SlotDetail)4 IdDt (ca.uhn.fhir.model.primitive.IdDt)3 MethodOutcome (ca.uhn.fhir.rest.api.MethodOutcome)3 Date (java.util.Date)3 AppointmentParticipantComponent (org.hl7.fhir.dstu3.model.Appointment.AppointmentParticipantComponent)3 ScheduleDetail (uk.gov.hscic.model.appointment.ScheduleDetail)3 VC (uk.gov.hscic.common.validators.VC)2 BookingOrgDetail (uk.gov.hscic.model.appointment.BookingOrgDetail)2 Update (ca.uhn.fhir.rest.annotation.Update)1 ResourceVersionConflictException (ca.uhn.fhir.rest.server.exceptions.ResourceVersionConflictException)1 UnclassifiedServerFailureException (ca.uhn.fhir.rest.server.exceptions.UnclassifiedServerFailureException)1 UnprocessableEntityException (ca.uhn.fhir.rest.server.exceptions.UnprocessableEntityException)1 File (java.io.File)1 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 Calendar (java.util.Calendar)1 OperationOutcome (org.hl7.fhir.dstu3.model.OperationOutcome)1 IBaseDatatype (org.hl7.fhir.instance.model.api.IBaseDatatype)1 SlotEntity (uk.gov.hscic.appointment.slot.SlotEntity)1