Search in sources :

Example 11 with Patient

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

the class PatientResourceProvider method createContact.

// patientDetailsToMinimalPatient
/**
 * add a set of contact details into the patient record NB these are
 * Contacts (related people etc) not contactpoints (telecoms)
 *
 * @param patient fhirResource object
 */
private void createContact(Patient patient) {
    // relationships
    Patient.ContactComponent contact = new ContactComponent();
    for (String relationship : new String[] { "Emergency contact", "Next of kin", "Daughter" }) {
        CodeableConcept crelationship = new CodeableConcept();
        crelationship.setText(relationship);
        contact.addRelationship(crelationship);
    }
    // contact address
    Address address = new Address();
    address.addLine("Trevelyan Square");
    address.addLine("Boar Ln");
    address.setPostalCode("LS1 6AE");
    address.setType(AddressType.PHYSICAL);
    address.setUse(AddressUse.HOME);
    contact.setAddress(address);
    // gender
    contact.setGender(AdministrativeGender.FEMALE);
    // telecom
    ContactPoint telecom = new ContactPoint();
    telecom.setSystem(ContactPointSystem.PHONE);
    telecom.setUse(ContactPointUse.MOBILE);
    telecom.setValue("07777123123");
    contact.addTelecom(telecom);
    // Name
    HumanName name = new HumanName();
    name.addGiven("Jane");
    name.setFamily("Jackson");
    List<StringType> prefixList = new ArrayList<>();
    prefixList.add(new StringType("Miss"));
    name.setPrefix(prefixList);
    name.setText("JACKSON Jane (Miss)");
    name.setUse(NameUse.OFFICIAL);
    contact.setName(name);
    patient.addContact(contact);
}
Also used : ContactComponent(org.hl7.fhir.dstu3.model.Patient.ContactComponent) ContactComponent(org.hl7.fhir.dstu3.model.Patient.ContactComponent)

Example 12 with Patient

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

the class PatientResourceProvider method StructuredRecordOperation.

@Operation(name = GET_STRUCTURED_RECORD_OPERATION_NAME)
public Bundle StructuredRecordOperation(@ResourceParam Parameters params) throws FHIRException {
    Bundle structuredBundle = new Bundle();
    Boolean getAllergies = false;
    Boolean includeResolved = false;
    Boolean getMedications = false;
    Boolean includePrescriptionIssues = false;
    Period medicationPeriod = null;
    String NHS = getNhsNumber(params);
    PatientDetails patientDetails = patientSearch.findPatient(NHS);
    // see https://nhsconnect.github.io/gpconnect/accessrecord_structured_development_retrieve_patient_record.html#error-handling
    if (patientDetails == null || patientDetails.isSensitive() || patientDetails.isDeceased() || !patientDetails.isActive()) {
        throw OperationOutcomeFactory.buildOperationOutcomeException(new ResourceNotFoundException("No patient details found for patient ID: " + NHS), SystemCode.PATIENT_NOT_FOUND, IssueType.NOTFOUND);
    }
    if (NHS.equals(patientNoconsent)) {
        throw OperationOutcomeFactory.buildOperationOutcomeException(new ForbiddenOperationException("No patient consent to share for patient ID: " + NHS), SystemCode.NO_PATIENT_CONSENT, IssueType.FORBIDDEN);
    }
    operationOutcome = null;
    for (ParametersParameterComponent param : params.getParameter()) {
        if (validateParametersName(param.getName())) {
            if (param.getName().equals(SystemConstants.INCLUDE_ALLERGIES)) {
                getAllergies = true;
                if (param.getPart().isEmpty()) {
                    // addWarningIssue(param, IssueType.REQUIRED, "Miss parameter part : " + SystemConstants.INCLUDE_RESOLVED_ALLERGIES);
                    throw OperationOutcomeFactory.buildOperationOutcomeException(new UnprocessableEntityException("Miss parameter : " + SystemConstants.INCLUDE_RESOLVED_ALLERGIES), SystemCode.INVALID_PARAMETER, IssueType.REQUIRED);
                }
                boolean includeResolvedParameterPartPresent = false;
                for (ParametersParameterComponent paramPart : param.getPart()) {
                    if (paramPart.getName().equals(SystemConstants.INCLUDE_RESOLVED_ALLERGIES)) {
                        if (paramPart.getValue() instanceof BooleanType) {
                            includeResolved = Boolean.valueOf(paramPart.getValue().primitiveValue());
                            includeResolvedParameterPartPresent = true;
                        } else {
                            throw OperationOutcomeFactory.buildOperationOutcomeException(new UnprocessableEntityException("Miss parameter : " + SystemConstants.INCLUDE_RESOLVED_ALLERGIES), SystemCode.INVALID_PARAMETER, IssueType.REQUIRED);
                        }
                    } else {
                        addWarningIssue(param, paramPart, IssueType.NOTSUPPORTED);
                    // throw OperationOutcomeFactory.buildOperationOutcomeException(
                    // new UnprocessableEntityException("Incorrect parameter passed : " + paramPart.getName()),
                    // SystemCode.INVALID_PARAMETER, IssueType.INVALID);
                    }
                }
                if (!includeResolvedParameterPartPresent) {
                    throw OperationOutcomeFactory.buildOperationOutcomeException(new UnprocessableEntityException("Miss parameter : " + SystemConstants.INCLUDE_RESOLVED_ALLERGIES), SystemCode.INVALID_PARAMETER, IssueType.REQUIRED);
                }
            }
            if (param.getName().equals(SystemConstants.INCLUDE_MEDICATION)) {
                getMedications = true;
                boolean isIncludedPrescriptionIssuesExist = false;
                for (ParametersParameterComponent paramPart : param.getPart()) {
                    if (paramPart.getName().equals(SystemConstants.INCLUDE_PRESCRIPTION_ISSUES)) {
                        if (paramPart.getValue() instanceof BooleanType) {
                            includePrescriptionIssues = Boolean.valueOf(paramPart.getValue().primitiveValue());
                            isIncludedPrescriptionIssuesExist = true;
                        }
                    } else if (paramPart.getName().equals(SystemConstants.MEDICATION_SEARCH_FROM_DATE) && paramPart.getValue() instanceof DateType) {
                        DateType startDateDt = (DateType) paramPart.getValue();
                        medicationPeriod = new Period();
                        medicationPeriod.setStart(startDateDt.getValue());
                        medicationPeriod.setEnd(null);
                        String startDate = startDateDt.asStringValue();
                        if (!validateStartDateParamAndEndDateParam(startDate, null)) {
                        // addWarningIssue(param, paramPart, IssueType.INVALID, "Invalid date used");
                        }
                    } else {
                        addWarningIssue(param, paramPart, IssueType.NOTSUPPORTED);
                    // throw OperationOutcomeFactory.buildOperationOutcomeException(
                    // new UnprocessableEntityException("Incorrect parameter passed : " + paramPart.getName()),
                    // SystemCode.INVALID_PARAMETER, IssueType.INVALID);
                    }
                }
                if (!isIncludedPrescriptionIssuesExist) {
                    // # 1.2.6 now defaults to true if not provided
                    includePrescriptionIssues = true;
                }
            }
        } else {
            // invalid parameter
            addWarningIssue(param, IssueType.NOTSUPPORTED);
        }
    }
    // for parameter
    // Add Patient
    Patient patient = patientDetailsToPatientResourceConverter(patientDetails);
    if (patient.getIdentifierFirstRep().getValue().equals(NHS)) {
        structuredBundle.addEntry().setResource(patient);
    }
    // Organization from patient
    Set<String> orgIds = new HashSet<>();
    orgIds.add(patientDetails.getManagingOrganization());
    // Practitioner from patient
    Set<String> practitionerIds = new HashSet<>();
    List<Reference> practitionerReferenceList = patient.getGeneralPractitioner();
    practitionerReferenceList.forEach(practitionerReference -> {
        String[] pracRef = practitionerReference.getReference().split("/");
        if (pracRef.length > 1) {
            practitionerIds.add(pracRef[1]);
        }
    });
    if (getAllergies) {
        structuredBundle = structuredAllergyIntoleranceBuilder.buildStructuredAllergyIntolerence(NHS, practitionerIds, structuredBundle, includeResolved);
    }
    if (getMedications) {
        structuredBundle = populateMedicationBundle.addMedicationBundleEntries(structuredBundle, patientDetails, includePrescriptionIssues, medicationPeriod, practitionerIds, orgIds);
    }
    // Add all practitioners and practitioner roles
    for (String practitionerId : practitionerIds) {
        Practitioner pracResource = practitionerResourceProvider.getPractitionerById(new IdType(practitionerId));
        structuredBundle.addEntry().setResource(pracResource);
        List<PractitionerRole> practitionerRoleList = practitionerRoleResourceProvider.getPractitionerRoleByPracticionerId(new IdType(practitionerId));
        for (PractitionerRole role : practitionerRoleList) {
            String[] split = role.getOrganization().getReference().split("/");
            orgIds.add(split[1]);
            structuredBundle.addEntry().setResource(role);
        }
    }
    // Add all organizations
    for (String orgId : orgIds) {
        OrganizationDetails organizationDetails = organizationSearch.findOrganizationDetails(new Long(orgId));
        Organization organization = organizationResourceProvider.convertOrganizationDetailsToOrganization(organizationDetails);
        structuredBundle.addEntry().setResource(organization);
    }
    structuredBundle.setType(BundleType.COLLECTION);
    structuredBundle.getMeta().addProfile(SystemURL.SD_GPC_STRUCTURED_BUNDLE);
    if (operationOutcome != null) {
        structuredBundle.addEntry().setResource(operationOutcome);
    } else {
        removeDuplicateResources(structuredBundle);
    }
    return structuredBundle;
}
Also used : OrganizationDetails(uk.gov.hscic.model.organization.OrganizationDetails) ForbiddenOperationException(ca.uhn.fhir.rest.server.exceptions.ForbiddenOperationException) ResourceNotFoundException(ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException) UnprocessableEntityException(ca.uhn.fhir.rest.server.exceptions.UnprocessableEntityException) PopulateMedicationBundle(uk.gov.hscic.medications.PopulateMedicationBundle) PatientDetails(uk.gov.hscic.model.patient.PatientDetails) ParametersParameterComponent(org.hl7.fhir.dstu3.model.Parameters.ParametersParameterComponent)

Example 13 with Patient

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

the class PatientJwtValidator method getPatientResourceBinding.

private ResourceBinding getPatientResourceBinding(IRestfulServerDefaults defaultServer) {
    ResourceBinding resourceBinding = null;
    if (defaultServer instanceof RestfulServer) {
        RestfulServer restfulServer = (RestfulServer) defaultServer;
        // if we get more than one Patient binding then return null
        resourceBinding = restfulServer.getResourceBindings().stream().filter(currentResourceBinding -> "Patient".equalsIgnoreCase(currentResourceBinding.getResourceName())).collect(Collectors.reducing((a, b) -> null)).orElse(null);
    }
    return resourceBinding;
}
Also used : BaseMethodBinding(ca.uhn.fhir.rest.server.method.BaseMethodBinding) IParameter(ca.uhn.fhir.rest.server.method.IParameter) IdDt(ca.uhn.fhir.model.primitive.IdDt) RestfulServer(ca.uhn.fhir.rest.server.RestfulServer) InvalidRequestException(ca.uhn.fhir.rest.server.exceptions.InvalidRequestException) ResourceBinding(ca.uhn.fhir.rest.server.ResourceBinding) Autowired(org.springframework.beans.factory.annotation.Autowired) ParameterUtil(ca.uhn.fhir.rest.param.ParameterUtil) Collectors(java.util.stream.Collectors) IssueType(org.hl7.fhir.dstu3.model.OperationOutcome.IssueType) Value(org.springframework.beans.factory.annotation.Value) OperationOutcomeFactory(uk.gov.hscic.OperationOutcomeFactory) RuleBuilder(ca.uhn.fhir.rest.server.interceptor.auth.RuleBuilder) List(java.util.List) Component(org.springframework.stereotype.Component) RequestTypeEnum(ca.uhn.fhir.rest.api.RequestTypeEnum) RequestDetails(ca.uhn.fhir.rest.api.server.RequestDetails) PatientResourceProvider(uk.gov.hscic.patient.PatientResourceProvider) IRestfulServerDefaults(ca.uhn.fhir.rest.server.IRestfulServerDefaults) IAuthRule(ca.uhn.fhir.rest.server.interceptor.auth.IAuthRule) SystemCode(uk.gov.hscic.SystemCode) ResourceNotFoundException(ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException) AuthorizationInterceptor(ca.uhn.fhir.rest.server.interceptor.auth.AuthorizationInterceptor) RestfulServer(ca.uhn.fhir.rest.server.RestfulServer) ResourceBinding(ca.uhn.fhir.rest.server.ResourceBinding)

Example 14 with Patient

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

the class MedicationRequestResourceProvider method getMedicationRequestFromDetail.

private MedicationRequest getMedicationRequestFromDetail(MedicationRequestDetail requestDetail) {
    MedicationRequest medicationRequest = new MedicationRequest();
    medicationRequest.setId(requestDetail.getId().toString());
    List<Identifier> identifiers = new ArrayList<>();
    Identifier identifier = new Identifier().setSystem("https://fhir.nhs.uk/Id/cross-care-setting-identifier").setValue(requestDetail.getGuid());
    identifiers.add(identifier);
    medicationRequest.setIdentifier(identifiers);
    medicationRequest.setMeta(new Meta().addProfile(SystemURL.SD_GPC_MEDICATION_REQUEST));
    setBasedOnReferences(medicationRequest, requestDetail);
    if (requestDetail.getPrescriptionTypeCode().contains("repeat")) {
        medicationRequest.setGroupIdentifier(new Identifier().setValue(requestDetail.getGroupIdentifier()));
    }
    try {
        medicationRequest.setStatus(MedicationRequestStatus.fromCode(requestDetail.getStatusCode()));
    } catch (FHIRException e) {
        throw new UnprocessableEntityException(e.getMessage());
    }
    try {
        medicationRequest.setIntent(MedicationRequestIntent.fromCode(requestDetail.getIntentCode()));
    } catch (FHIRException e) {
        throw new UnprocessableEntityException(e.getMessage());
    }
    if (requestDetail.getMedicationId() != null) {
        medicationRequest.setMedication(new Reference(new IdType("Medication", requestDetail.getMedicationId())));
    }
    if (requestDetail.getPatientId() != null) {
        medicationRequest.setSubject(new Reference(new IdType("Patient", requestDetail.getPatientId())));
    }
    if (requestDetail.getAuthorisingPractitionerId() != null) {
        medicationRequest.setRecorder(new Reference(new IdType("Practitioner", requestDetail.getAuthorisingPractitionerId())));
    }
    if (requestDetail.getPriorMedicationRequestId() != null) {
        medicationRequest.setPriorPrescription(new Reference(new IdType("MedicationRequest", requestDetail.getPriorMedicationRequestId())));
    }
    medicationRequest.setAuthoredOn(requestDetail.getAuthoredOn());
    medicationRequest.setDispenseRequest(getDispenseRequestComponent(requestDetail));
    // medicationRequest.setRequester(getRequesterComponent(requestDetail)); //TODO - spec needs to clarify whether this should be populated or not
    setReasonCodes(medicationRequest, requestDetail);
    setNotes(medicationRequest, requestDetail);
    if (medicationRequest.getIntent() != MedicationRequestIntent.ORDER) {
        setRepeatInformation(medicationRequest, requestDetail);
    }
    setPrescriptionType(medicationRequest, requestDetail);
    setStatusReason(medicationRequest, requestDetail);
    String dosageInstructionText = requestDetail.getDosageText();
    medicationRequest.addDosageInstruction(new Dosage().setText(dosageInstructionText == null || dosageInstructionText.trim().isEmpty() ? NO_INFORMATION_AVAILABLE : dosageInstructionText).setPatientInstruction(requestDetail.getDosageInstructions()));
    return medicationRequest;
}
Also used : UnprocessableEntityException(ca.uhn.fhir.rest.server.exceptions.UnprocessableEntityException) ArrayList(java.util.ArrayList) FHIRException(org.hl7.fhir.exceptions.FHIRException)

Example 15 with Patient

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

the class WarningCodeExtHelper method addWarningCodeExtensions.

/**
 * confidential items are per record but the other two are global values per
 * patient
 *
 * @param warningCodes
 * @param list
 * @param patientRepository
 * @param medicationStatementRepository
 * @param structuredAllergySearch
 */
public static void addWarningCodeExtensions(Set<String> warningCodes, ListResource list, PatientRepository patientRepository, MedicationStatementRepository medicationStatementRepository, StructuredAllergySearch structuredAllergySearch) {
    String NHS = list.getSubject().getIdentifier().getValue();
    PatientEntity patientEntity = patientRepository.findByNhsNumber(NHS);
    List<MedicationStatementEntity> medicationStatements = medicationStatementRepository.findByPatientId(patientEntity.getId());
    for (MedicationStatementEntity medicationStatement : medicationStatements) {
        setFlags(medicationStatement.getWarningCode());
    }
    List<StructuredAllergyIntoleranceEntity> allergies = structuredAllergySearch.getAllergyIntollerence(NHS);
    for (StructuredAllergyIntoleranceEntity allergy : allergies) {
        setFlags(allergy.getWarningCode());
    }
    // check medication_statements for either of the global flags
    if (dataInTransit) {
        warningCodes.add(DATA_IN_TRANSIT);
    }
    if (dataAwaitingFiling) {
        warningCodes.add(DATA_AWAITING_FILING);
    }
    StringBuilder sb = new StringBuilder();
    warningCodes.forEach(warningCode -> {
        if (warningCode != null) {
            String warningCodeDisplay = "";
            Annotation annotation = new Annotation();
            switch(warningCode) {
                case CONFIDENTIAL_ITEMS:
                    warningCodeDisplay = "Confidential Items";
                    // #266
                    annotation.setText(CONFIDENTIAL_ITEMS_NOTE);
                    // list.addNote(annotation);
                    sb.append("\r\n").append(annotation.getText());
                    break;
                case DATA_IN_TRANSIT:
                    warningCodeDisplay = "Data in Transit";
                    Calendar cal = new GregorianCalendar();
                    Date now = new Date();
                    cal.setTime(now);
                    // a week before now
                    cal.add(Calendar.DAY_OF_YEAR, -7);
                    // #266
                    annotation.setText(String.format(DATA_IN_TRANSIT_NOTE, DATE_FORMAT.format(cal.getTime())));
                    // list.addNote(annotation);
                    sb.append("\r\n").append(annotation.getText());
                    break;
                case DATA_AWAITING_FILING:
                    warningCodeDisplay = "Data Awaiting Filing";
                    // #266
                    annotation.setText(DATA_AWAITING_FILING_NOTE);
                    // list.addNote(annotation);
                    sb.append("\r\n").append(annotation.getText());
                    break;
                default:
                    break;
            }
            // #182
            Extension warningExt = new Extension(SystemURL.WARNING_CODE, new CodeType(warningCode));
            list.addExtension(warningExt);
        }
    });
    // cardinality of note 0..1 #266
    if (sb.length() > 0) {
        Annotation annotation = null;
        if (list.getNote().size() > 0) {
            annotation = list.getNote().get(0);
            annotation.setText(annotation.getText());
            annotation.setText(annotation.getText() + sb.toString());
        } else {
            annotation = new Annotation();
            list.addNote(annotation);
            annotation.setText(sb.toString().replaceFirst("^\r\n", ""));
        }
    }
}
Also used : StructuredAllergyIntoleranceEntity(uk.gov.hscic.patient.structuredAllergyIntolerance.StructuredAllergyIntoleranceEntity) GregorianCalendar(java.util.GregorianCalendar) Calendar(java.util.Calendar) GregorianCalendar(java.util.GregorianCalendar) Annotation(org.hl7.fhir.dstu3.model.Annotation) Date(java.util.Date) PatientEntity(uk.gov.hscic.patient.details.PatientEntity) MedicationStatementEntity(uk.gov.hscic.medication.statement.MedicationStatementEntity) Extension(org.hl7.fhir.dstu3.model.Extension) CodeType(org.hl7.fhir.dstu3.model.CodeType)

Aggregations

Test (org.junit.Test)576 Patient (org.hl7.fhir.r4.model.Patient)366 Test (org.junit.jupiter.api.Test)356 IBaseResource (org.hl7.fhir.instance.model.api.IBaseResource)245 IBundleProvider (ca.uhn.fhir.rest.api.server.IBundleProvider)227 Patient (org.hl7.fhir.dstu3.model.Patient)199 Bundle (org.hl7.fhir.r4.model.Bundle)181 ArrayList (java.util.ArrayList)144 SearchParameterMap (org.openmrs.module.fhir2.api.search.param.SearchParameterMap)140 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)138 ReferenceParam (ca.uhn.fhir.rest.param.ReferenceParam)136 Date (java.util.Date)133 ReferenceAndListParam (ca.uhn.fhir.rest.param.ReferenceAndListParam)127 ReferenceOrListParam (ca.uhn.fhir.rest.param.ReferenceOrListParam)127 BaseModuleContextSensitiveTest (org.openmrs.test.BaseModuleContextSensitiveTest)125 Reference (org.hl7.fhir.r4.model.Reference)106 List (java.util.List)103 Resource (org.hl7.fhir.r4.model.Resource)102 Bundle (org.hl7.fhir.dstu3.model.Bundle)96 BundleEntryComponent (org.hl7.fhir.r4.model.Bundle.BundleEntryComponent)94