Search in sources :

Example 1 with DateParam

use of ca.uhn.fhir.rest.param.DateParam in project gpconnect-demonstrator by nhsconnect.

the class AppointmentResourceProvider method getAppointmentsForPatientIdAndDates.

@Search
public List<Appointment> getAppointmentsForPatientIdAndDates(@RequiredParam(name = "patient") IdType patientLocalId, @Sort SortSpec sort, @Count Integer count, @RequiredParam(name = "start") DateAndListParam startDates) {
    Date startLowerDate = null;
    Date startUpperDate = null;
    List<DateOrListParam> startDateList = startDates.getValuesAsQueryTokens();
    if (startDateList.size() != 2) {
        throwUnprocessableEntityInvalid422_ParameterException("Appointment search must have both 'le' and 'ge' start date parameters.");
    }
    Pattern dateOnlyPattern = Pattern.compile("[0-9]{4}(-(0[1-9]|1[0-2])(-(0[0-9]|[1-2][0-9]|3[0-1])))");
    boolean lePrefix = false;
    boolean gePrefix = false;
    for (DateOrListParam filter : startDateList) {
        DateParam token = filter.getValuesAsQueryTokens().get(0);
        if (!dateOnlyPattern.matcher(token.getValueAsString()).matches()) {
            throwUnprocessableEntityInvalid422_ParameterException("Search dates must be of the format: yyyy-MM-dd and should not include time or timezone.");
        }
        if (null != token.getPrefix()) {
            switch(token.getPrefix()) {
                case GREATERTHAN_OR_EQUALS:
                    startLowerDate = token.getValue();
                    gePrefix = true;
                    break;
                case LESSTHAN_OR_EQUALS:
                    Calendar upper = Calendar.getInstance();
                    upper.setTime(token.getValue());
                    upper.add(Calendar.HOUR, 23);
                    upper.add(Calendar.MINUTE, 59);
                    upper.add(Calendar.SECOND, 59);
                    startUpperDate = upper.getTime();
                    lePrefix = true;
                    break;
                default:
                    throwUnprocessableEntityInvalid422_ParameterException("Unknown prefix on start date parameter: only le and ge prefixes are allowed.");
            }
        }
    }
    if (!gePrefix || !lePrefix) {
        throwUnprocessableEntityInvalid422_ParameterException("Parameters must contain two start parameters, one with prefix 'ge' and one with prefix 'le'.");
    } else if (startLowerDate.before(getYesterday())) {
        throwUnprocessableEntityInvalid422_ParameterException("Search dates from the past: " + startLowerDate.toString() + " are not allowed in appointment search.");
    } else if (startUpperDate.before(getYesterday())) {
        throwUnprocessableEntityInvalid422_ParameterException("Search dates from the past: " + startUpperDate.toString() + " are not allowed in appointment search.");
    } else if (startUpperDate.before(startLowerDate)) {
        throwUnprocessableEntityInvalid422_ParameterException("Upper search date must be after the lower search date.");
    }
    List<Appointment> appointment = appointmentSearch.searchAppointments(patientLocalId.getIdPartAsLong(), startLowerDate, startUpperDate).stream().map(this::appointmentDetailToAppointmentResourceConverter).collect(Collectors.toList());
    List<Appointment> futureAppointments = appointmentValidation.filterToReturnFutureAppointments(appointment);
    if (futureAppointments.isEmpty()) {
        return null;
    }
    // Update startIndex if we do paging
    return count != null ? futureAppointments.subList(0, count) : futureAppointments;
}
Also used : DateOrListParam(ca.uhn.fhir.rest.param.DateOrListParam) Pattern(java.util.regex.Pattern) DateParam(ca.uhn.fhir.rest.param.DateParam) AppointmentSearch(uk.gov.hscic.appointment.appointment.AppointmentSearch) ScheduleSearch(uk.gov.hscic.appointment.schedule.ScheduleSearch) SlotSearch(uk.gov.hscic.appointment.slot.SlotSearch)

Example 2 with DateParam

use of ca.uhn.fhir.rest.param.DateParam in project beneficiary-fhir-data by CMSgov.

the class ClaimDao method serviceDateRangePredicate.

@VisibleForTesting
Predicate serviceDateRangePredicate(Root<?> root, DateRangeParam serviceDate, CriteriaBuilder builder, String endDateAttributeName) {
    Path<LocalDate> serviceDateEndPath = root.get(endDateAttributeName);
    List<Predicate> predicates = new ArrayList<>();
    DateParam lowerBound = serviceDate.getLowerBound();
    if (lowerBound != null) {
        LocalDate from = lowerBound.getValue().toInstant().atOffset(ZoneOffset.UTC).toLocalDate();
        if (ParamPrefixEnum.GREATERTHAN.equals(lowerBound.getPrefix())) {
            predicates.add(builder.greaterThan(serviceDateEndPath, from));
        } else if (ParamPrefixEnum.GREATERTHAN_OR_EQUALS.equals(lowerBound.getPrefix())) {
            predicates.add(builder.greaterThanOrEqualTo(serviceDateEndPath, from));
        } else {
            throw new IllegalArgumentException(String.format("Unsupported prefix supplied %s", lowerBound.getPrefix()));
        }
    }
    DateParam upperBound = serviceDate.getUpperBound();
    if (upperBound != null) {
        LocalDate to = upperBound.getValue().toInstant().atOffset(ZoneOffset.UTC).toLocalDate();
        if (ParamPrefixEnum.LESSTHAN_OR_EQUALS.equals(upperBound.getPrefix())) {
            predicates.add(builder.lessThanOrEqualTo(serviceDateEndPath, to));
        } else if (ParamPrefixEnum.LESSTHAN.equals(upperBound.getPrefix())) {
            predicates.add(builder.lessThan(serviceDateEndPath, to));
        } else {
            throw new IllegalArgumentException(String.format("Unsupported prefix supplied %s", upperBound.getPrefix()));
        }
    }
    return builder.and(predicates.toArray(new Predicate[0]));
}
Also used : ArrayList(java.util.ArrayList) LocalDate(java.time.LocalDate) Predicate(javax.persistence.criteria.Predicate) DateParam(ca.uhn.fhir.rest.param.DateParam) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 3 with DateParam

use of ca.uhn.fhir.rest.param.DateParam in project beneficiary-fhir-data by CMSgov.

the class R4ClaimResponseResourceProviderIT method shouldGetCorrectClaimResponseResourcesByMbiHash.

@Test
void shouldGetCorrectClaimResponseResourcesByMbiHash() {
    IGenericClient fhirClient = ServerTestUtils.get().createFhirClientV2();
    Bundle claimResult = fhirClient.search().forResource(ClaimResponse.class).where(ImmutableMap.of("mbi", Collections.singletonList(new ReferenceParam(RDATestUtils.MBI_OLD_HASH)), "service-date", Arrays.asList(new DateParam("gt1970-07-18"), new DateParam("lt1970-07-30")))).returnBundle(Bundle.class).execute();
    // Sort entries for consistent testing results
    claimResult.getEntry().sort(Comparator.comparing(a -> a.getResource().getId()));
    String expected = testUtils.expectedResponseFor("claimResponseSearch");
    String actual = FhirContext.forR4().newJsonParser().encodeResourceToString(claimResult);
    Set<String> ignorePatterns = new HashSet<>(IGNORE_PATTERNS);
    ignorePatterns.add("\"/id\"");
    ignorePatterns.add("\"/entry/[0-9]+/resource/created\"");
    AssertUtils.assertJsonEquals(expected, actual, ignorePatterns);
}
Also used : RDATestUtils(gov.cms.bfd.server.war.utils.RDATestUtils) Arrays(java.util.Arrays) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) Set(java.util.Set) AssertUtils(gov.cms.bfd.server.war.utils.AssertUtils) ClaimResponse(org.hl7.fhir.r4.model.ClaimResponse) HashSet(java.util.HashSet) AfterAll(org.junit.jupiter.api.AfterAll) Test(org.junit.jupiter.api.Test) FhirContext(ca.uhn.fhir.context.FhirContext) BeforeAll(org.junit.jupiter.api.BeforeAll) ReferenceParam(ca.uhn.fhir.rest.param.ReferenceParam) Bundle(org.hl7.fhir.r4.model.Bundle) IGenericClient(ca.uhn.fhir.rest.client.api.IGenericClient) ServerTestUtils(gov.cms.bfd.server.war.ServerTestUtils) Comparator(java.util.Comparator) Collections(java.util.Collections) DateParam(ca.uhn.fhir.rest.param.DateParam) ClaimResponse(org.hl7.fhir.r4.model.ClaimResponse) IGenericClient(ca.uhn.fhir.rest.client.api.IGenericClient) Bundle(org.hl7.fhir.r4.model.Bundle) ReferenceParam(ca.uhn.fhir.rest.param.ReferenceParam) DateParam(ca.uhn.fhir.rest.param.DateParam) HashSet(java.util.HashSet) Test(org.junit.jupiter.api.Test)

Example 4 with DateParam

use of ca.uhn.fhir.rest.param.DateParam in project MobileAccessGateway by i4mi.

the class Iti67RequestConverter method searchParameterIti67ToFindDocumentsQuery.

/**
 * convert ITI-67 request to ITI-18 request
 * @param searchParameter
 * @return
 */
public QueryRegistry searchParameterIti67ToFindDocumentsQuery(@Body Iti67SearchParameters searchParameter) {
    boolean getLeafClass = true;
    Query searchQuery = null;
    if (searchParameter.get_id() != null || searchParameter.getIdentifier() != null) {
        GetDocumentsQuery query = new GetDocumentsQuery();
        if (searchParameter.getIdentifier() != null) {
            String val = searchParameter.getIdentifier().getValue();
            if (val.startsWith("urn:oid:")) {
                query.setUniqueIds(Collections.singletonList(val.substring("urn:oid:".length())));
            } else if (val.startsWith("urn:uuid:")) {
                query.setUuids(Collections.singletonList(val.substring("urn:uuid:".length())));
            }
        } else {
            query.setUuids(Collections.singletonList(searchParameter.get_id().getValue()));
        }
        searchQuery = query;
    } else {
        FindDocumentsQuery query;
        // TODO   related Note 4                  -->  $XDSDocumentEntryReferenceIdList
        TokenOrListParam related = searchParameter.getRelated();
        if (related != null) {
            FindDocumentsByReferenceIdQuery referenceIdQuery = new FindDocumentsByReferenceIdQuery();
            ;
            QueryList<ReferenceId> outerReferences = new QueryList<ReferenceId>();
            List<ReferenceId> references = new ArrayList<ReferenceId>();
            for (TokenParam token : related.getValuesAsQueryTokens()) {
                references.add(new ReferenceId(token.getValue(), null, getScheme(token.getSystem())));
            }
            outerReferences.getOuterList().add(references);
            referenceIdQuery.setTypedReferenceIds(outerReferences);
            query = referenceIdQuery;
        } else
            query = new FindDocumentsQuery();
        // query.setMetadataLevel(metadataLevel);
        // status  -->  $XDSDocumentEntryStatus
        TokenOrListParam status = searchParameter.getStatus();
        if (status != null) {
            List<AvailabilityStatus> availabilites = new ArrayList<AvailabilityStatus>();
            for (TokenParam statusToken : status.getValuesAsQueryTokens()) {
                String tokenValue = statusToken.getValue();
                if (tokenValue.equals("current"))
                    availabilites.add(AvailabilityStatus.APPROVED);
                else if (tokenValue.equals("superseded"))
                    availabilites.add(AvailabilityStatus.DEPRECATED);
            }
            query.setStatus(availabilites);
        }
        // patient or patient.identifier  -->  $XDSDocumentEntryPatientId
        TokenParam tokenIdentifier = searchParameter.getPatientIdentifier();
        if (tokenIdentifier != null) {
            String system = getScheme(tokenIdentifier.getSystem());
            if (system == null)
                throw new InvalidRequestException("Missing OID for patient");
            query.setPatientId(new Identifiable(tokenIdentifier.getValue(), new AssigningAuthority(system)));
        }
        ReferenceParam patientRef = searchParameter.getPatientReference();
        if (patientRef != null) {
            Identifiable id = transformReference(patientRef.getValue());
            query.setPatientId(id);
        }
        // date Note 1 Note 5              -->  $DSDocumentEntryCreationTimeFrom
        // date Note 2 Note 5              -->  $XDSDocumentEntryCreationTimeTo
        DateRangeParam dateRange = searchParameter.getDate();
        if (dateRange != null) {
            DateParam creationTimeFrom = dateRange.getLowerBound();
            DateParam creationTimeTo = dateRange.getUpperBound();
            query.getCreationTime().setFrom(timestampFromDateParam(creationTimeFrom));
            query.getCreationTime().setTo(timestampFromDateParam(creationTimeTo));
        }
        // period Note 1                   -->  $XDSDocumentEntryServiceStartTimeFrom
        // period Note 2                   -->  $XDSDocumentEntryServiceStartTimeTo
        // period Note 1                   -->  $XDSDocumentEntryServiceStopTimeFrom
        // period Note 2                   -->  $XDSDocumentEntryServiceStopTimeTo
        DateRangeParam periodRange = searchParameter.getPeriod();
        if (periodRange != null) {
            DateParam periodFrom = periodRange.getLowerBound();
            DateParam periodTo = periodRange.getUpperBound();
            query.getServiceStopTime().setFrom(timestampFromDateParam(periodFrom));
            query.getServiceStartTime().setTo(timestampFromDateParam(periodTo));
        }
        // category                        -->  $XDSDocumentEntryClassCode
        TokenOrListParam categories = searchParameter.getCategory();
        query.setClassCodes(codesFromTokens(categories));
        // type                            -->  $XDSDocumentEntryTypeCode
        TokenOrListParam types = searchParameter.getType();
        query.setTypeCodes(codesFromTokens(types));
        // setting                         -->  $XDSDocumentEntryPracticeSettingCode
        TokenOrListParam settings = searchParameter.getSetting();
        query.setPracticeSettingCodes(codesFromTokens(settings));
        // facility                        -->  $XDSDocumentEntryHealthcareFacilityTypeCode
        TokenOrListParam facilities = searchParameter.getFacility();
        query.setHealthcareFacilityTypeCodes(codesFromTokens(facilities));
        // event                           -->  $XDSDocumentEntryEventCodeList
        TokenOrListParam events = searchParameter.getEvent();
        if (events != null) {
            QueryList<Code> eventCodeList = new QueryList<Code>();
            eventCodeList.getOuterList().add(codesFromTokens(events));
            query.setEventCodes(eventCodeList);
        }
        // security-label                  -->  $XDSDocumentEntryConfidentialityCode
        TokenOrListParam securityLabels = searchParameter.getSecurityLabel();
        if (securityLabels != null) {
            QueryList<Code> confidentialityCodes = new QueryList<Code>();
            confidentialityCodes.getOuterList().add(codesFromTokens(securityLabels));
            query.setConfidentialityCodes(confidentialityCodes);
        }
        // format                          -->  $XDSDocumentEntryFormatCode
        TokenOrListParam formats = searchParameter.getFormat();
        query.setFormatCodes(codesFromTokens(formats));
        // TODO   author.given / author.family    -->  $XDSDocumentEntryAuthorPerson
        StringParam authorGivenName = searchParameter.getAuthorGivenName();
        StringParam authorFamilyName = searchParameter.getAuthorFamilyName();
        if (authorGivenName != null || authorFamilyName != null) {
            Person person = new Person();
            XcnName name = new XcnName();
            if (authorFamilyName != null)
                name.setFamilyName(authorFamilyName.getValue());
            if (authorGivenName != null)
                name.setGivenName(authorGivenName.getValue());
            person.setName(name);
            // String author = (authorGivenName != null ? authorGivenName.getValue() : "%")+" "+(authorFamilyName != null ? authorFamilyName.getValue() : "%");
            List<Person> authorPersons = Collections.singletonList(person);
            query.setTypedAuthorPersons(authorPersons);
        }
        searchQuery = query;
    }
    final QueryRegistry queryRegistry = new QueryRegistry(searchQuery);
    queryRegistry.setReturnType((getLeafClass) ? QueryReturnType.LEAF_CLASS : QueryReturnType.OBJECT_REF);
    return queryRegistry;
}
Also used : FindDocumentsQuery(org.openehealth.ipf.commons.ihe.xds.core.requests.query.FindDocumentsQuery) FindDocumentsByReferenceIdQuery(org.openehealth.ipf.commons.ihe.xds.core.requests.query.FindDocumentsByReferenceIdQuery) Query(org.openehealth.ipf.commons.ihe.xds.core.requests.query.Query) GetDocumentsQuery(org.openehealth.ipf.commons.ihe.xds.core.requests.query.GetDocumentsQuery) ArrayList(java.util.ArrayList) ReferenceParam(ca.uhn.fhir.rest.param.ReferenceParam) FindDocumentsQuery(org.openehealth.ipf.commons.ihe.xds.core.requests.query.FindDocumentsQuery) GetDocumentsQuery(org.openehealth.ipf.commons.ihe.xds.core.requests.query.GetDocumentsQuery) ReferenceId(org.openehealth.ipf.commons.ihe.xds.core.metadata.ReferenceId) InvalidRequestException(ca.uhn.fhir.rest.server.exceptions.InvalidRequestException) StringParam(ca.uhn.fhir.rest.param.StringParam) QueryList(org.openehealth.ipf.commons.ihe.xds.core.requests.query.QueryList) DateParam(ca.uhn.fhir.rest.param.DateParam) QueryRegistry(org.openehealth.ipf.commons.ihe.xds.core.requests.QueryRegistry) FindDocumentsByReferenceIdQuery(org.openehealth.ipf.commons.ihe.xds.core.requests.query.FindDocumentsByReferenceIdQuery) XcnName(org.openehealth.ipf.commons.ihe.xds.core.metadata.XcnName) AssigningAuthority(org.openehealth.ipf.commons.ihe.xds.core.metadata.AssigningAuthority) Code(org.openehealth.ipf.commons.ihe.xds.core.metadata.Code) Identifiable(org.openehealth.ipf.commons.ihe.xds.core.metadata.Identifiable) DateRangeParam(ca.uhn.fhir.rest.param.DateRangeParam) TokenOrListParam(ca.uhn.fhir.rest.param.TokenOrListParam) AvailabilityStatus(org.openehealth.ipf.commons.ihe.xds.core.metadata.AvailabilityStatus) TokenParam(ca.uhn.fhir.rest.param.TokenParam) Person(org.openehealth.ipf.commons.ihe.xds.core.metadata.Person)

Example 5 with DateParam

use of ca.uhn.fhir.rest.param.DateParam in project openmrs-module-fhir2 by openmrs.

the class ConditionSearchQueryTest method searchForConditions_shouldReturnConditionByUnboundedOnsetDate.

@Test
public void searchForConditions_shouldReturnConditionByUnboundedOnsetDate() {
    DateRangeParam onsetDate = new DateRangeParam(new DateParam("gt" + ONSET_START_DATE));
    SearchParameterMap theParams = new SearchParameterMap().addParameter(FhirConstants.DATE_RANGE_SEARCH_HANDLER, "obsDatetime", onsetDate);
    IBundleProvider results = search(theParams);
    List<IBaseResource> resultList = get(results);
    assertThat(results, notNullValue());
    assertThat(resultList, not(empty()));
    assertThat(resultList.size(), equalTo(2));
}
Also used : DateRangeParam(ca.uhn.fhir.rest.param.DateRangeParam) IBundleProvider(ca.uhn.fhir.rest.api.server.IBundleProvider) IBaseResource(org.hl7.fhir.instance.model.api.IBaseResource) DateParam(ca.uhn.fhir.rest.param.DateParam) SearchParameterMap(org.openmrs.module.fhir2.api.search.param.SearchParameterMap) BaseModuleContextSensitiveTest(org.openmrs.test.BaseModuleContextSensitiveTest) Test(org.junit.Test)

Aggregations

DateParam (ca.uhn.fhir.rest.param.DateParam)31 DateRangeParam (ca.uhn.fhir.rest.param.DateRangeParam)24 IBundleProvider (ca.uhn.fhir.rest.api.server.IBundleProvider)21 Test (org.junit.Test)21 SearchParameterMap (org.openmrs.module.fhir2.api.search.param.SearchParameterMap)21 BaseModuleContextSensitiveTest (org.openmrs.test.BaseModuleContextSensitiveTest)20 IBaseResource (org.hl7.fhir.instance.model.api.IBaseResource)19 ReferenceParam (ca.uhn.fhir.rest.param.ReferenceParam)4 StringParam (ca.uhn.fhir.rest.param.StringParam)4 TokenParam (ca.uhn.fhir.rest.param.TokenParam)4 ArrayList (java.util.ArrayList)4 TokenOrListParam (ca.uhn.fhir.rest.param.TokenOrListParam)3 InvalidRequestException (ca.uhn.fhir.rest.server.exceptions.InvalidRequestException)3 Test (org.junit.jupiter.api.Test)3 FhirContext (ca.uhn.fhir.context.FhirContext)2 IGenericClient (ca.uhn.fhir.rest.client.api.IGenericClient)2 DateOrListParam (ca.uhn.fhir.rest.param.DateOrListParam)2 StringAndListParam (ca.uhn.fhir.rest.param.StringAndListParam)2 Date (java.util.Date)2 List (java.util.List)2