Search in sources :

Example 86 with BooleanType

use of org.hl7.fhir.r5.model.BooleanType in project redmatch by aehrc.

the class FhirExporter method getValue.

/**
 * Resolves a value.
 *
 * @param value The value specified in the transformation rules.
 * @param fhirType The type of the FHIR attribute where this value will be set.
 * @param vertex A vertex with patient data.
 * @param recordId The id of this record. Used to create the references to FHIR ids.
 * @param enumFactory If the type is an enumeration, this is the factory to create an instance.
 * @param fhirPackage The target FHIR package.
 * @return The value or null if the value cannot be determined. This can also be a list.
 */
private Base getValue(Value value, Class<?> fhirType, JsonObject vertex, String recordId, Class<?> enumFactory, VersionedFhirPackage fhirPackage) throws IOException {
    // If this is a field-based value then make sure that there is a value and if not return null
    if (value instanceof FieldBasedValue) {
        FieldBasedValue fbv = (FieldBasedValue) value;
        // Account for field ids of the form xx___y
        String fieldId = fbv.getFieldId();
        String shortFieldId = null;
        String regex = "(?<fieldId>.*)___\\d+$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(fieldId);
        if (matcher.find()) {
            shortFieldId = matcher.group("fieldId");
            log.debug("Transformed fieldId into '" + fieldId + "'");
        }
        boolean hasValue = false;
        JsonElement jsonElement = vertex.get(fieldId);
        if (jsonElement != null) {
            String rawValue = jsonElement.getAsString();
            if (!rawValue.isEmpty()) {
                hasValue = true;
            }
        }
        if (!hasValue && shortFieldId != null) {
            jsonElement = vertex.get(shortFieldId);
            if (jsonElement != null) {
                String rawValue = jsonElement.getAsString();
                if (!rawValue.isEmpty()) {
                    hasValue = true;
                }
            }
        }
        if (!hasValue) {
            return null;
        }
    }
    if (value instanceof BooleanValue) {
        return new BooleanType(((BooleanValue) value).getValue());
    } else if (value instanceof CodeLiteralValue) {
        String code = ((CodeLiteralValue) value).getCode();
        return getCode(code, enumFactory);
    } else if (value instanceof ConceptLiteralValue) {
        ConceptLiteralValue clv = (ConceptLiteralValue) value;
        String system = clv.getSystem();
        String code = clv.getCode();
        String display = clv.getDisplay() != null ? clv.getDisplay() : "";
        return getConcept(system, code, display, fhirType);
    } else if (value instanceof DoubleValue) {
        return new DecimalType(((DoubleValue) value).getValue());
    } else if (value instanceof IntegerValue) {
        return new IntegerType(((IntegerValue) value).getValue());
    } else if (value instanceof ReferenceValue) {
        ReferenceValue rv = (ReferenceValue) value;
        Reference ref = new Reference();
        String resourceType = rv.getResourceType();
        String resourceId = rv.getResourceId();
        boolean unique = uniqueIds.contains(resourceType + "<" + resourceId + ">");
        CodeInfo codeInfo = terminologyService.lookup(fhirPackage, resourceType);
        if (codeInfo.isProfile()) {
            resourceType = StringUtils.getLastPath(codeInfo.getBaseResource());
        }
        if (unique) {
            // This is a reference to a unique resource - no need to append row id
            if (fhirResourceMap.containsKey(resourceId)) {
                ref.setReference("/" + resourceType + "/" + resourceId);
            } else {
                log.debug("Did not find resource " + resourceType + "/" + resourceId);
            }
        } else {
            if (fhirResourceMap.containsKey(resourceId + "-" + recordId)) {
                ref.setReference("/" + resourceType + "/" + resourceId + "-" + recordId);
            } else {
                log.debug("Did not find resource " + resourceType + "/" + resourceId + "-" + recordId);
            }
        }
        return ref;
    } else if (value instanceof StringValue) {
        if (fhirType.equals(StringType.class)) {
            return new StringType(((StringValue) value).getStringValue());
        } else if (fhirType.equals(MarkdownType.class)) {
            return new MarkdownType(((StringValue) value).getStringValue());
        } else if (fhirType.equals(IdType.class)) {
            return new IdType(((StringValue) value).getStringValue());
        } else if (fhirType.equals(UriType.class)) {
            return new UriType(((StringValue) value).getStringValue());
        } else if (fhirType.equals(OidType.class)) {
            return new OidType(((StringValue) value).getStringValue());
        } else if (fhirType.equals(UuidType.class)) {
            return new UuidType(((StringValue) value).getStringValue());
        } else if (fhirType.equals(CanonicalType.class)) {
            return new CanonicalType(((StringValue) value).getStringValue());
        } else if (fhirType.equals(UrlType.class)) {
            return new UrlType(((StringValue) value).getStringValue());
        } else {
            throw new TransformationException("Got StringValue for FHIR type " + fhirType.getName() + ". This should not happen!");
        }
    } else if (value instanceof CodeSelectedValue) {
        CodeSelectedValue csv = (CodeSelectedValue) value;
        String fieldId = csv.getFieldId();
        Mapping m = getSelectedMapping(fieldId, vertex);
        if (m == null) {
            throw new TransformationException("Mapping for field " + fieldId + " is required but was not found.");
        }
        return getTarget(m).getCodeElement();
    } else if (value instanceof ConceptSelectedValue) {
        ConceptSelectedValue csv = (ConceptSelectedValue) value;
        String fieldId = csv.getFieldId();
        Mapping m = getSelectedMapping(fieldId, vertex);
        if (m == null) {
            throw new TransformationException("Mapping for field " + fieldId + " is required but was not found.");
        }
        if (fhirType.isAssignableFrom(Coding.class)) {
            return getTarget(m);
        } else if (fhirType.isAssignableFrom(CodeableConcept.class)) {
            return new CodeableConcept().addCoding(getTarget(m));
        } else {
            throw new TransformationException("FHIR type of field " + fieldId + " (" + fhirType + ") is incompatible with CONCEPT_SELECTED.");
        }
    } else if (value instanceof ConceptValue) {
        // Ontoserver REDCap plugin format: 74400008|Appendicitis|http://snomed.info/sct
        ConceptValue cv = (ConceptValue) value;
        String fieldId = cv.getFieldId();
        Mapping m = getMapping(fieldId);
        if (m != null) {
            if (fhirType.isAssignableFrom(Coding.class)) {
                return getTarget(m);
            } else if (fhirType.isAssignableFrom(CodeableConcept.class)) {
                return new CodeableConcept().addCoding(getTarget(m));
            } else {
                throw new TransformationException("FHIR type of field " + fieldId + " (" + fhirType + ") is incompatible with CONCEPT.");
            }
        } else {
            au.csiro.redmatch.model.Field field = doc.getSchema().getField(fieldId);
            Coding c = field.getCoding(vertex);
            if (c != null) {
                if (fhirType.isAssignableFrom(Coding.class)) {
                    return c;
                } else if (fhirType.isAssignableFrom(CodeableConcept.class)) {
                    return new CodeableConcept().addCoding(c);
                } else {
                    throw new TransformationException("FHIR type of field " + fieldId + " (" + fhirType + ") is incompatible with CONCEPT.");
                }
            }
        }
        throw new TransformationException("Could not get concept for field " + fieldId + ".");
    } else if (value instanceof FieldValue) {
        FieldValue fv = (FieldValue) value;
        String fieldId = fv.getFieldId();
        FieldValue.DatePrecision pr = fv.getDatePrecision();
        au.csiro.redmatch.model.Field field = doc.getSchema().getField(fieldId);
        return field.getValue(vertex, fhirType, pr);
    } else {
        throw new TransformationException("Unable to get VALUE for " + value);
    }
}
Also used : CodeInfo(au.csiro.redmatch.terminology.CodeInfo) Matcher(java.util.regex.Matcher) Field(java.lang.reflect.Field) org.hl7.fhir.r4.model(org.hl7.fhir.r4.model) Pattern(java.util.regex.Pattern) JsonElement(com.google.gson.JsonElement)

Example 87 with BooleanType

use of org.hl7.fhir.r5.model.BooleanType in project nia-patient-switching-standard-adaptor by NHSDigital.

the class PatientTransferRequestValidatorTest method createFullRecordComponent.

private Parameters.ParametersParameterComponent createFullRecordComponent() {
    BooleanType booleanType = new BooleanType();
    booleanType.setValue(true);
    Parameters.ParametersParameterComponent sensitiveInformationPart = new Parameters.ParametersParameterComponent();
    sensitiveInformationPart.setName("includeSensitiveInformation").setValue(booleanType);
    Parameters.ParametersParameterComponent fullRecordComponent = new Parameters.ParametersParameterComponent();
    fullRecordComponent.setName("includeFullRecord").addPart(sensitiveInformationPart);
    return fullRecordComponent;
}
Also used : Parameters(org.hl7.fhir.dstu3.model.Parameters) BooleanType(org.hl7.fhir.dstu3.model.BooleanType)

Example 88 with BooleanType

use of org.hl7.fhir.r5.model.BooleanType in project gpconnect-demonstrator by nhsconnect.

the class PatientResourceProvider method setStaticPatientData.

private Patient setStaticPatientData(Patient patient) {
    patient.setLanguage(("en-GB"));
    patient.addExtension(createCodingExtension("CG", "Greek Cypriot", SystemURL.CS_CC_ETHNIC_CATEGORY, SystemURL.SD_CC_EXT_ETHNIC_CATEGORY));
    patient.addExtension(createCodingExtension("SomeSnomedCode", "Some Snomed Code", SystemURL.CS_CC_RELIGIOUS_AFFILI, SystemURL.SD_CC_EXT_RELIGIOUS_AFFILI));
    patient.addExtension(new Extension(SystemURL.SD_PATIENT_CADAVERIC_DON, new BooleanType(false)));
    patient.addExtension(createCodingExtension("H", "UK Resident", SystemURL.CS_CC_RESIDENTIAL_STATUS, SystemURL.SD_CC_EXT_RESIDENTIAL_STATUS));
    patient.addExtension(createCodingExtension("3", "To pay hotel fees only", SystemURL.CS_CC_TREATMENT_CAT, SystemURL.SD_CC_EXT_TREATMENT_CAT));
    Extension nhsCommExtension = new Extension();
    nhsCommExtension.setUrl(SystemURL.SD_CC_EXT_NHS_COMMUNICATION);
    nhsCommExtension.addExtension(createCodingExtension("en", "English", SystemURL.CS_CC_HUMAN_LANG, SystemURL.SD_CC_EXT_COMM_LANGUAGE));
    nhsCommExtension.addExtension(new Extension(SystemURL.SD_CC_COMM_PREFERRED, new BooleanType(false)));
    nhsCommExtension.addExtension(createCodingExtension("RWR", "Received written", SystemURL.CS_CC_LANG_ABILITY_MODE, SystemURL.SD_CC_MODE_OF_COMM));
    nhsCommExtension.addExtension(createCodingExtension("E", "Excellent", SystemURL.CS_CC_LANG_ABILITY_PROFI, SystemURL.SD_CC_COMM_PROFICIENCY));
    nhsCommExtension.addExtension(new Extension(SystemURL.SD_CC_INTERPRETER_REQUIRED, new BooleanType(false)));
    patient.addExtension(nhsCommExtension);
    Identifier localIdentifier = new Identifier();
    localIdentifier.setUse(IdentifierUse.USUAL);
    localIdentifier.setSystem(SystemURL.ID_LOCAL_PATIENT_IDENTIFIER);
    localIdentifier.setValue("123456");
    CodeableConcept liType = new CodeableConcept();
    Coding liTypeCoding = new Coding();
    liTypeCoding.setCode("EN");
    liTypeCoding.setDisplay("Employer number");
    liTypeCoding.setSystem(SystemURL.VS_IDENTIFIER_TYPE);
    liType.addCoding(liTypeCoding);
    localIdentifier.setType(liType);
    localIdentifier.setAssigner(new Reference("Organization/1"));
    patient.addIdentifier(localIdentifier);
    Calendar calendar = Calendar.getInstance();
    calendar.set(2017, 1, 1);
    DateTimeDt endDate = new DateTimeDt(calendar.getTime());
    calendar.set(2016, 1, 1);
    DateTimeDt startDate = new DateTimeDt(calendar.getTime());
    Period pastPeriod = new Period().setStart(calendar.getTime()).setEnd(calendar.getTime());
    patient.addName().setFamily("AnotherOfficialFamilyName").addGiven("AnotherOfficialGivenName").setUse(NameUse.OFFICIAL).setPeriod(pastPeriod);
    patient.addName().setFamily("AdditionalFamily").addGiven("AdditionalGiven").setUse(NameUse.TEMP);
    patient.addTelecom(staticElHelper.getValidTelecom());
    patient.addAddress(staticElHelper.getValidAddress());
    return patient;
}
Also used : Extension(org.hl7.fhir.dstu3.model.Extension) Identifier(org.hl7.fhir.dstu3.model.Identifier) DateTimeDt(ca.uhn.fhir.model.primitive.DateTimeDt) Coding(org.hl7.fhir.dstu3.model.Coding) Reference(org.hl7.fhir.dstu3.model.Reference) Calendar(java.util.Calendar) BooleanType(org.hl7.fhir.dstu3.model.BooleanType) Period(org.hl7.fhir.dstu3.model.Period) CodeableConcept(org.hl7.fhir.dstu3.model.CodeableConcept)

Example 89 with BooleanType

use of org.hl7.fhir.r5.model.BooleanType 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 90 with BooleanType

use of org.hl7.fhir.r5.model.BooleanType in project synthea by synthetichealth.

the class FhirR4 method basicInfo.

/**
 * Map the given Person to a FHIR Patient resource, and add it to the given Bundle.
 *
 * @param person   The Person
 * @param bundle   The Bundle to add to
 * @param stopTime Time the simulation ended
 * @return The created Entry
 */
@SuppressWarnings("rawtypes")
private static BundleEntryComponent basicInfo(Person person, Bundle bundle, long stopTime) {
    Patient patientResource = new Patient();
    patientResource.addIdentifier().setSystem(SYNTHEA_IDENTIFIER).setValue((String) person.attributes.get(Person.ID));
    if (USE_US_CORE_IG) {
        Meta meta = new Meta();
        meta.addProfile("http://hl7.org/fhir/us/core/StructureDefinition/us-core-patient");
        patientResource.setMeta(meta);
    }
    Code mrnCode = new Code("http://terminology.hl7.org/CodeSystem/v2-0203", "MR", "Medical Record Number");
    patientResource.addIdentifier().setType(mapCodeToCodeableConcept(mrnCode, "http://terminology.hl7.org/CodeSystem/v2-0203")).setSystem("http://hospital.smarthealthit.org").setValue((String) person.attributes.get(Person.ID));
    Code ssnCode = new Code("http://terminology.hl7.org/CodeSystem/v2-0203", "SS", "Social Security Number");
    patientResource.addIdentifier().setType(mapCodeToCodeableConcept(ssnCode, "http://terminology.hl7.org/CodeSystem/v2-0203")).setSystem("http://hl7.org/fhir/sid/us-ssn").setValue((String) person.attributes.get(Person.IDENTIFIER_SSN));
    if (person.attributes.get(Person.IDENTIFIER_DRIVERS) != null) {
        Code driversCode = new Code("http://terminology.hl7.org/CodeSystem/v2-0203", "DL", "Driver's License");
        patientResource.addIdentifier().setType(mapCodeToCodeableConcept(driversCode, "http://terminology.hl7.org/CodeSystem/v2-0203")).setSystem("urn:oid:2.16.840.1.113883.4.3.25").setValue((String) person.attributes.get(Person.IDENTIFIER_DRIVERS));
    }
    if (person.attributes.get(Person.IDENTIFIER_PASSPORT) != null) {
        Code passportCode = new Code("http://terminology.hl7.org/CodeSystem/v2-0203", "PPN", "Passport Number");
        patientResource.addIdentifier().setType(mapCodeToCodeableConcept(passportCode, "http://terminology.hl7.org/CodeSystem/v2-0203")).setSystem(SHR_EXT + "passportNumber").setValue((String) person.attributes.get(Person.IDENTIFIER_PASSPORT));
    }
    if (person.attributes.get(Person.CONTACT_EMAIL) != null) {
        ContactComponent contact = new ContactComponent();
        HumanName contactName = new HumanName();
        contactName.setUse(HumanName.NameUse.OFFICIAL);
        contactName.addGiven((String) person.attributes.get(Person.CONTACT_GIVEN_NAME));
        contactName.setFamily((String) person.attributes.get(Person.CONTACT_FAMILY_NAME));
        contact.setName(contactName);
        contact.addTelecom().setSystem(ContactPointSystem.EMAIL).setUse(ContactPointUse.HOME).setValue((String) person.attributes.get(Person.CONTACT_EMAIL));
        patientResource.addContact(contact);
    }
    if (USE_US_CORE_IG) {
        // We do not yet account for mixed race
        Extension raceExtension = new Extension("http://hl7.org/fhir/us/core/StructureDefinition/us-core-race");
        String race = (String) person.attributes.get(Person.RACE);
        String raceDisplay;
        switch(race) {
            case "white":
                raceDisplay = "White";
                break;
            case "black":
                raceDisplay = "Black or African American";
                break;
            case "asian":
                raceDisplay = "Asian";
                break;
            case "native":
                raceDisplay = "American Indian or Alaska Native";
                break;
            case "hawaiian":
                raceDisplay = "Native Hawaiian or Other Pacific Islander";
                break;
            default:
                raceDisplay = "Other";
                break;
        }
        String raceNum = (String) raceEthnicityCodes.get(race);
        Extension raceCodingExtension = new Extension("ombCategory");
        Coding raceCoding = new Coding();
        if (raceDisplay.equals("Other")) {
            raceCoding.setSystem("http://terminology.hl7.org/CodeSystem/v3-NullFlavor");
            raceCoding.setCode("UNK");
            raceCoding.setDisplay("Unknown");
        } else {
            raceCoding.setSystem("urn:oid:2.16.840.1.113883.6.238");
            raceCoding.setCode(raceNum);
            raceCoding.setDisplay(raceDisplay);
        }
        raceCodingExtension.setValue(raceCoding);
        raceExtension.addExtension(raceCodingExtension);
        Extension raceTextExtension = new Extension("text");
        raceTextExtension.setValue(new StringType(raceDisplay));
        raceExtension.addExtension(raceTextExtension);
        patientResource.addExtension(raceExtension);
        // We do not yet account for mixed ethnicity
        Extension ethnicityExtension = new Extension("http://hl7.org/fhir/us/core/StructureDefinition/us-core-ethnicity");
        String ethnicity = (String) person.attributes.get(Person.ETHNICITY);
        String ethnicityDisplay;
        if (ethnicity.equals("hispanic")) {
            ethnicity = "hispanic";
            ethnicityDisplay = "Hispanic or Latino";
        } else {
            ethnicity = "nonhispanic";
            ethnicityDisplay = "Not Hispanic or Latino";
        }
        String ethnicityNum = (String) raceEthnicityCodes.get(ethnicity);
        Extension ethnicityCodingExtension = new Extension("ombCategory");
        Coding ethnicityCoding = new Coding();
        ethnicityCoding.setSystem("urn:oid:2.16.840.1.113883.6.238");
        ethnicityCoding.setCode(ethnicityNum);
        ethnicityCoding.setDisplay(ethnicityDisplay);
        ethnicityCodingExtension.setValue(ethnicityCoding);
        ethnicityExtension.addExtension(ethnicityCodingExtension);
        Extension ethnicityTextExtension = new Extension("text");
        ethnicityTextExtension.setValue(new StringType(ethnicityDisplay));
        ethnicityExtension.addExtension(ethnicityTextExtension);
        patientResource.addExtension(ethnicityExtension);
    }
    String firstLanguage = (String) person.attributes.get(Person.FIRST_LANGUAGE);
    Map languageMap = (Map) languageLookup.get(firstLanguage);
    Code languageCode = new Code((String) languageMap.get("system"), (String) languageMap.get("code"), (String) languageMap.get("display"));
    List<PatientCommunicationComponent> communication = new ArrayList<PatientCommunicationComponent>();
    communication.add(new PatientCommunicationComponent(mapCodeToCodeableConcept(languageCode, (String) languageMap.get("system"))));
    patientResource.setCommunication(communication);
    HumanName name = patientResource.addName();
    name.setUse(HumanName.NameUse.OFFICIAL);
    name.addGiven((String) person.attributes.get(Person.FIRST_NAME));
    name.setFamily((String) person.attributes.get(Person.LAST_NAME));
    if (person.attributes.get(Person.NAME_PREFIX) != null) {
        name.addPrefix((String) person.attributes.get(Person.NAME_PREFIX));
    }
    if (person.attributes.get(Person.NAME_SUFFIX) != null) {
        name.addSuffix((String) person.attributes.get(Person.NAME_SUFFIX));
    }
    if (person.attributes.get(Person.MAIDEN_NAME) != null) {
        HumanName maidenName = patientResource.addName();
        maidenName.setUse(HumanName.NameUse.MAIDEN);
        maidenName.addGiven((String) person.attributes.get(Person.FIRST_NAME));
        maidenName.setFamily((String) person.attributes.get(Person.MAIDEN_NAME));
        if (person.attributes.get(Person.NAME_PREFIX) != null) {
            maidenName.addPrefix((String) person.attributes.get(Person.NAME_PREFIX));
        }
        if (person.attributes.get(Person.NAME_SUFFIX) != null) {
            maidenName.addSuffix((String) person.attributes.get(Person.NAME_SUFFIX));
        }
    }
    Extension mothersMaidenNameExtension = new Extension("http://hl7.org/fhir/StructureDefinition/patient-mothersMaidenName");
    String mothersMaidenName = (String) person.attributes.get(Person.NAME_MOTHER);
    mothersMaidenNameExtension.setValue(new StringType(mothersMaidenName));
    patientResource.addExtension(mothersMaidenNameExtension);
    long birthdate = (long) person.attributes.get(Person.BIRTHDATE);
    patientResource.setBirthDate(new Date(birthdate));
    Extension birthSexExtension = new Extension("http://hl7.org/fhir/us/core/StructureDefinition/us-core-birthsex");
    if (person.attributes.get(Person.GENDER).equals("M")) {
        patientResource.setGender(AdministrativeGender.MALE);
        birthSexExtension.setValue(new CodeType("M"));
    } else if (person.attributes.get(Person.GENDER).equals("F")) {
        patientResource.setGender(AdministrativeGender.FEMALE);
        birthSexExtension.setValue(new CodeType("F"));
    } else if (person.attributes.get(Person.GENDER).equals("UNK")) {
        patientResource.setGender(AdministrativeGender.UNKNOWN);
    }
    if (USE_US_CORE_IG) {
        patientResource.addExtension(birthSexExtension);
    }
    String state = (String) person.attributes.get(Person.STATE);
    if (USE_US_CORE_IG) {
        state = Location.getAbbreviation(state);
    }
    Address addrResource = patientResource.addAddress();
    addrResource.addLine((String) person.attributes.get(Person.ADDRESS)).setCity((String) person.attributes.get(Person.CITY)).setPostalCode((String) person.attributes.get(Person.ZIP)).setState(state);
    if (COUNTRY_CODE != null) {
        addrResource.setCountry(COUNTRY_CODE);
    }
    Address birthplace = new Address();
    birthplace.setCity((String) person.attributes.get(Person.BIRTH_CITY)).setState((String) person.attributes.get(Person.BIRTH_STATE)).setCountry((String) person.attributes.get(Person.BIRTH_COUNTRY));
    Extension birthplaceExtension = new Extension("http://hl7.org/fhir/StructureDefinition/patient-birthPlace");
    birthplaceExtension.setValue(birthplace);
    patientResource.addExtension(birthplaceExtension);
    if (person.attributes.get(Person.MULTIPLE_BIRTH_STATUS) != null) {
        patientResource.setMultipleBirth(new IntegerType((int) person.attributes.get(Person.MULTIPLE_BIRTH_STATUS)));
    } else {
        patientResource.setMultipleBirth(new BooleanType(false));
    }
    patientResource.addTelecom().setSystem(ContactPointSystem.PHONE).setUse(ContactPointUse.HOME).setValue((String) person.attributes.get(Person.TELECOM));
    String maritalStatus = ((String) person.attributes.get(Person.MARITAL_STATUS));
    if (maritalStatus != null) {
        Code maritalStatusCode = new Code("http://terminology.hl7.org/CodeSystem/v3-MaritalStatus", maritalStatus, maritalStatus);
        patientResource.setMaritalStatus(mapCodeToCodeableConcept(maritalStatusCode, "http://terminology.hl7.org/CodeSystem/v3-MaritalStatus"));
    } else {
        Code maritalStatusCode = new Code("http://terminology.hl7.org/CodeSystem/v3-MaritalStatus", "S", "Never Married");
        patientResource.setMaritalStatus(mapCodeToCodeableConcept(maritalStatusCode, "http://terminology.hl7.org/CodeSystem/v3-MaritalStatus"));
    }
    Point2D.Double coord = person.getLonLat();
    if (coord != null) {
        Extension geolocation = addrResource.addExtension();
        geolocation.setUrl("http://hl7.org/fhir/StructureDefinition/geolocation");
        geolocation.addExtension("latitude", new DecimalType(coord.getY()));
        geolocation.addExtension("longitude", new DecimalType(coord.getX()));
    }
    if (!person.alive(stopTime)) {
        patientResource.setDeceased(convertFhirDateTime((Long) person.attributes.get(Person.DEATHDATE), true));
    }
    String generatedBySynthea = "Generated by <a href=\"https://github.com/synthetichealth/synthea\">Synthea</a>." + "Version identifier: " + Utilities.SYNTHEA_VERSION + " . " + "  Person seed: " + person.getSeed() + "  Population seed: " + person.populationSeed;
    patientResource.setText(new Narrative().setStatus(NarrativeStatus.GENERATED).setDiv(new XhtmlNode(NodeType.Element).setValue(generatedBySynthea)));
    if (USE_SHR_EXTENSIONS) {
        patientResource.setMeta(new Meta().addProfile(SHR_EXT + "shr-entity-Patient"));
        // Patient profile requires race, ethnicity, birthsex,
        // MothersMaidenName, FathersName, Person-extension
        patientResource.addExtension().setUrl(SHR_EXT + "shr-actor-FictionalPerson-extension").setValue(new BooleanType(true));
        String fathersName = (String) person.attributes.get(Person.NAME_FATHER);
        Extension fathersNameExtension = new Extension(SHR_EXT + "shr-entity-FathersName-extension", new HumanName().setText(fathersName));
        patientResource.addExtension(fathersNameExtension);
        String ssn = (String) person.attributes.get(Person.IDENTIFIER_SSN);
        Extension ssnExtension = new Extension(SHR_EXT + "shr-demographics-SocialSecurityNumber-extension", new StringType(ssn));
        patientResource.addExtension(ssnExtension);
    }
    // DALY and QALY values
    // we only write the last(current) one to the patient record
    Double dalyValue = (Double) person.attributes.get("most-recent-daly");
    Double qalyValue = (Double) person.attributes.get("most-recent-qaly");
    if (dalyValue != null) {
        Extension dalyExtension = new Extension(SYNTHEA_EXT + "disability-adjusted-life-years");
        DecimalType daly = new DecimalType(dalyValue);
        dalyExtension.setValue(daly);
        patientResource.addExtension(dalyExtension);
        Extension qalyExtension = new Extension(SYNTHEA_EXT + "quality-adjusted-life-years");
        DecimalType qaly = new DecimalType(qalyValue);
        qalyExtension.setValue(qaly);
        patientResource.addExtension(qalyExtension);
    }
    return newEntry(bundle, patientResource, (String) person.attributes.get(Person.ID));
}
Also used : Meta(org.hl7.fhir.r4.model.Meta) Address(org.hl7.fhir.r4.model.Address) StringType(org.hl7.fhir.r4.model.StringType) ArrayList(java.util.ArrayList) XhtmlNode(org.hl7.fhir.utilities.xhtml.XhtmlNode) HumanName(org.hl7.fhir.r4.model.HumanName) Coding(org.hl7.fhir.r4.model.Coding) PatientCommunicationComponent(org.hl7.fhir.r4.model.Patient.PatientCommunicationComponent) Point2D(java.awt.geom.Point2D) Narrative(org.hl7.fhir.r4.model.Narrative) ContactComponent(org.hl7.fhir.r4.model.Patient.ContactComponent) BooleanType(org.hl7.fhir.r4.model.BooleanType) Patient(org.hl7.fhir.r4.model.Patient) Code(org.mitre.synthea.world.concepts.HealthRecord.Code) Date(java.util.Date) Extension(org.hl7.fhir.r4.model.Extension) IntegerType(org.hl7.fhir.r4.model.IntegerType) CodeType(org.hl7.fhir.r4.model.CodeType) DecimalType(org.hl7.fhir.r4.model.DecimalType) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap)

Aggregations

ArrayList (java.util.ArrayList)59 BooleanType (org.hl7.fhir.r5.model.BooleanType)38 BooleanType (org.hl7.fhir.r4.model.BooleanType)37 FHIRException (org.hl7.fhir.exceptions.FHIRException)33 BooleanType (org.hl7.fhir.r4b.model.BooleanType)27 BooleanType (org.hl7.fhir.dstu3.model.BooleanType)19 NotImplementedException (org.apache.commons.lang3.NotImplementedException)18 Base (org.hl7.fhir.r5.model.Base)17 Test (org.junit.Test)16 StringType (org.hl7.fhir.r4.model.StringType)15 Base (org.hl7.fhir.r4b.model.Base)15 BooleanType (org.hl7.fhir.dstu2016may.model.BooleanType)13 IOException (java.io.IOException)12 HashMap (java.util.HashMap)11 BooleanType (org.hl7.fhir.dstu2.model.BooleanType)11 Base (org.hl7.fhir.dstu2.model.Base)10 StringType (org.hl7.fhir.dstu3.model.StringType)10 StringType (org.hl7.fhir.r5.model.StringType)10 DefinitionException (org.hl7.fhir.exceptions.DefinitionException)9 Coding (org.hl7.fhir.r4.model.Coding)9