<filename>fhir/resources/conditiondefinition.py<gh_stars>0
# -*- coding: utf-8 -*-
"""
Profile: http://hl7.org/fhir/StructureDefinition/ConditionDefinition
Release: R5
Version: 4.5.0
Build ID: 0d95498
Last updated: 2021-04-03T00:34:11.075+00:00
"""
import typing
from pydantic import Field
from pydantic import root_validator

from pydantic.error_wrappers import ErrorWrapper, ValidationError
from pydantic.errors import MissingError, NoneIsNotAllowedError

from . import fhirtypes


from . import metadataresource


class ConditionDefinition(metadataresource.MetadataResource):
    """Disclaimer: Any field name ends with ``__ext`` doesn't part of
    Resource StructureDefinition, instead used to enable Extensibility feature
    for FHIR Primitive Data Types.

    A definition of a condition.
    A definition of a condition and information relevant to managing it.
    """

    resource_type = Field("ConditionDefinition", const=True)

    bodySite: fhirtypes.CodeableConceptType = Field(
        None,
        alias="bodySite",
        title="Anatomical location, if relevant",
        description="The anatomical location where this condition manifests itself.",
        # if property is element of this resource.
        element_property=True,
    )

    code: fhirtypes.CodeableConceptType = Field(
        ...,
        alias="code",
        title="Identification of the condition, problem or diagnosis",
        description=None,
        # if property is element of this resource.
        element_property=True,
    )

    contact: typing.List[fhirtypes.ContactDetailType] = Field(
        None,
        alias="contact",
        title="Contact details for the publisher",
        description=(
            "Contact details to assist a user in finding and communicating with the"
            " publisher."
        ),
        # if property is element of this resource.
        element_property=True,
    )

    date: fhirtypes.DateTime = Field(
        None,
        alias="date",
        title="Date last changed",
        description=(
            "The date  (and optionally time) when the condition definition was "
            "published. The date must change when the business version changes and "
            "it must change if the status code changes. In addition, it should "
            "change when the substantive content of the condition definition "
            "changes."
        ),
        # if property is element of this resource.
        element_property=True,
    )
    date__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
        None, alias="_date", title="Extension field for ``date``."
    )

    definition: typing.List[fhirtypes.Uri] = Field(
        None,
        alias="definition",
        title="Formal Definition for the condition",
        description=(
            "Formal definitions of the condition. These may be references to "
            "ontologies, published clinical protocols or research papers."
        ),
        # if property is element of this resource.
        element_property=True,
    )
    definition__ext: typing.List[
        typing.Union[fhirtypes.FHIRPrimitiveExtensionType, None]
    ] = Field(None, alias="_definition", title="Extension field for ``definition``.")

    description: fhirtypes.Markdown = Field(
        None,
        alias="description",
        title="Natural language description of the condition definition",
        description=(
            "A free text natural language description of the condition definition "
            "from a consumer's perspective."
        ),
        # if property is element of this resource.
        element_property=True,
    )
    description__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
        None, alias="_description", title="Extension field for ``description``."
    )

    experimental: bool = Field(
        None,
        alias="experimental",
        title="For testing purposes, not real usage",
        description=(
            "A Boolean value to indicate that this condition definition is authored"
            " for testing purposes (or education/evaluation/marketing) and is not "
            "intended to be used for genuine usage."
        ),
        # if property is element of this resource.
        element_property=True,
    )
    experimental__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
        None, alias="_experimental", title="Extension field for ``experimental``."
    )

    hasBodySite: bool = Field(
        None,
        alias="hasBodySite",
        title="Whether bodySite is appropriate",
        description="Whether bodySite is appropriate to collect for this condition.",
        # if property is element of this resource.
        element_property=True,
    )
    hasBodySite__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
        None, alias="_hasBodySite", title="Extension field for ``hasBodySite``."
    )

    hasSeverity: bool = Field(
        None,
        alias="hasSeverity",
        title="Whether Severity is appropriate",
        description="Whether Severity is appropriate to collect for this condition.",
        # if property is element of this resource.
        element_property=True,
    )
    hasSeverity__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
        None, alias="_hasSeverity", title="Extension field for ``hasSeverity``."
    )

    hasStage: bool = Field(
        None,
        alias="hasStage",
        title="Whether stage is appropriate",
        description="Whether stage is appropriate to collect for this condition.",
        # if property is element of this resource.
        element_property=True,
    )
    hasStage__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
        None, alias="_hasStage", title="Extension field for ``hasStage``."
    )

    identifier: typing.List[fhirtypes.IdentifierType] = Field(
        None,
        alias="identifier",
        title="Additional identifier for the condition definition",
        description=(
            "A formal identifier that is used to identify this condition definition"
            " when it is represented in other formats, or referenced in a "
            "specification, model, design or an instance."
        ),
        # if property is element of this resource.
        element_property=True,
    )

    jurisdiction: typing.List[fhirtypes.CodeableConceptType] = Field(
        None,
        alias="jurisdiction",
        title="Intended jurisdiction for condition definition (if applicable)",
        description=(
            "A legal or geographic region in which the condition definition is "
            "intended to be used."
        ),
        # if property is element of this resource.
        element_property=True,
    )

    medication: typing.List[fhirtypes.ConditionDefinitionMedicationType] = Field(
        None,
        alias="medication",
        title="Medications particularly relevant for this condition",
        description=None,
        # if property is element of this resource.
        element_property=True,
    )

    name: fhirtypes.String = Field(
        None,
        alias="name",
        title="Name for this condition definition (computer friendly)",
        description=(
            "A natural language name identifying the condition definition. This "
            "name should be usable as an identifier for the module by machine "
            "processing applications such as code generation."
        ),
        # if property is element of this resource.
        element_property=True,
    )
    name__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
        None, alias="_name", title="Extension field for ``name``."
    )

    observation: typing.List[fhirtypes.ConditionDefinitionObservationType] = Field(
        None,
        alias="observation",
        title="Observations particularly relevant to this condition",
        description=None,
        # if property is element of this resource.
        element_property=True,
    )

    plan: typing.List[fhirtypes.ConditionDefinitionPlanType] = Field(
        None,
        alias="plan",
        title="Plan that is appropriate",
        description=None,
        # if property is element of this resource.
        element_property=True,
    )

    precondition: typing.List[fhirtypes.ConditionDefinitionPreconditionType] = Field(
        None,
        alias="precondition",
        title="Observation that suggets this condition",
        description="An observation that suggests that this condition applies.",
        # if property is element of this resource.
        element_property=True,
    )

    publisher: fhirtypes.String = Field(
        None,
        alias="publisher",
        title="Name of the publisher (organization or individual)",
        description=(
            "The name of the organization or individual that published the "
            "condition definition."
        ),
        # if property is element of this resource.
        element_property=True,
    )
    publisher__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
        None, alias="_publisher", title="Extension field for ``publisher``."
    )

    questionnaire: typing.List[fhirtypes.ConditionDefinitionQuestionnaireType] = Field(
        None,
        alias="questionnaire",
        title="Questionnaire for this condition",
        description=None,
        # if property is element of this resource.
        element_property=True,
    )

    severity: fhirtypes.CodeableConceptType = Field(
        None,
        alias="severity",
        title="Subjective severity of condition",
        description=(
            "A subjective assessment of the severity of the condition as evaluated "
            "by the clinician."
        ),
        # if property is element of this resource.
        element_property=True,
    )

    stage: fhirtypes.CodeableConceptType = Field(
        None,
        alias="stage",
        title="Stage/grade, usually assessed formally",
        description=(
            "Clinical stage or grade of a condition. May include formal severity "
            "assessments."
        ),
        # if property is element of this resource.
        element_property=True,
    )

    status: fhirtypes.Code = Field(
        None,
        alias="status",
        title="draft | active | retired | unknown",
        description=(
            "The status of this condition definition. Enables tracking the life-"
            "cycle of the content."
        ),
        # if property is element of this resource.
        element_property=True,
        element_required=True,
        # note: Enum values can be used in validation,
        # but use in your own responsibilities, read official FHIR documentation.
        enum_values=["draft", "active", "retired", "unknown"],
    )
    status__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
        None, alias="_status", title="Extension field for ``status``."
    )

    subtitle: fhirtypes.String = Field(
        None,
        alias="subtitle",
        title="Subordinate title of the event definition",
        description=(
            "An explanatory or alternate title for the event definition giving "
            "additional information about its content."
        ),
        # if property is element of this resource.
        element_property=True,
    )
    subtitle__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
        None, alias="_subtitle", title="Extension field for ``subtitle``."
    )

    team: typing.List[fhirtypes.ReferenceType] = Field(
        None,
        alias="team",
        title="Appropriate team for this condition",
        description=None,
        # if property is element of this resource.
        element_property=True,
        # note: Listed Resource Type(s) should be allowed as Reference.
        enum_reference_types=["CareTeam"],
    )

    title: fhirtypes.String = Field(
        None,
        alias="title",
        title="Name for this condition definition (human friendly)",
        description=(
            "A short, descriptive, user-friendly title for the condition " "definition."
        ),
        # if property is element of this resource.
        element_property=True,
    )
    title__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
        None, alias="_title", title="Extension field for ``title``."
    )

    url: fhirtypes.Uri = Field(
        None,
        alias="url",
        title=(
            "Canonical identifier for this condition definition, represented as a "
            "URI (globally unique)"
        ),
        description=(
            "An absolute URI that is used to identify this condition definition "
            "when it is referenced in a specification, model, design or an "
            "instance; also called its canonical identifier. This SHOULD be "
            "globally unique and SHOULD be a literal address at which at which an "
            "authoritative instance of this condition definition is (or will be) "
            "published. This URL can be the target of a canonical reference. It "
            "SHALL remain the same when the condition definition is stored on "
            "different servers."
        ),
        # if property is element of this resource.
        element_property=True,
    )
    url__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
        None, alias="_url", title="Extension field for ``url``."
    )

    useContext: typing.List[fhirtypes.UsageContextType] = Field(
        None,
        alias="useContext",
        title="The context that the content is intended to support",
        description=(
            "The content was developed with a focus and intent of supporting the "
            "contexts that are listed. These contexts may be general categories "
            "(gender, age, ...) or may be references to specific programs "
            "(insurance plans, studies, ...) and may be used to assist with "
            "indexing and searching for appropriate condition definition instances."
        ),
        # if property is element of this resource.
        element_property=True,
    )

    version: fhirtypes.String = Field(
        None,
        alias="version",
        title="Business version of the condition definition",
        description=(
            "The identifier that is used to identify this version of the condition "
            "definition when it is referenced in a specification, model, design or "
            "instance. This is an arbitrary value managed by the condition "
            "definition author and is not expected to be globally unique. For "
            "example, it might be a timestamp (e.g. yyyymmdd) if a managed version "
            "is not available. There is also no expectation that versions can be "
            "placed in a lexicographical sequence."
        ),
        # if property is element of this resource.
        element_property=True,
    )
    version__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
        None, alias="_version", title="Extension field for ``version``."
    )

    @classmethod
    def elements_sequence(cls):
        """returning all elements names from ``ConditionDefinition`` according specification,
        with preserving original sequence order.
        """
        return [
            "id",
            "meta",
            "implicitRules",
            "language",
            "text",
            "contained",
            "extension",
            "modifierExtension",
            "url",
            "identifier",
            "version",
            "name",
            "title",
            "status",
            "experimental",
            "date",
            "publisher",
            "contact",
            "description",
            "useContext",
            "jurisdiction",
            "purpose",
            "copyright",
            "approvalDate",
            "lastReviewDate",
            "effectivePeriod",
            "topic",
            "author",
            "editor",
            "reviewer",
            "endorser",
            "relatedArtifact",
            "url",
            "identifier",
            "version",
            "name",
            "title",
            "subtitle",
            "status",
            "experimental",
            "date",
            "publisher",
            "contact",
            "description",
            "useContext",
            "jurisdiction",
            "code",
            "severity",
            "bodySite",
            "stage",
            "hasSeverity",
            "hasBodySite",
            "hasStage",
            "definition",
            "observation",
            "medication",
            "precondition",
            "team",
            "questionnaire",
            "plan",
        ]

    @root_validator(pre=True, allow_reuse=True)
    def validate_required_primitive_elements_2145(
        cls, values: typing.Dict[str, typing.Any]
    ) -> typing.Dict[str, typing.Any]:
        """https://www.hl7.org/fhir/extensibility.html#Special-Case
        In some cases, implementers might find that they do not have appropriate data for
        an element with minimum cardinality = 1. In this case, the element must be present,
        but unless the resource or a profile on it has made the actual value of the primitive
        data type mandatory, it is possible to provide an extension that explains why
        the primitive value is not present.
        """
        required_fields = [("status", "status__ext")]
        _missing = object()

        def _fallback():
            return ""

        errors: typing.List["ErrorWrapper"] = []
        for name, ext in required_fields:
            field = cls.__fields__[name]
            ext_field = cls.__fields__[ext]
            value = values.get(field.alias, _missing)
            if value not in (_missing, None):
                continue
            ext_value = values.get(ext_field.alias, _missing)
            missing_ext = True
            if ext_value not in (_missing, None):
                if isinstance(ext_value, dict):
                    missing_ext = len(ext_value.get("extension", [])) == 0
                elif (
                    getattr(ext_value.__class__, "get_resource_type", _fallback)()
                    == "FHIRPrimitiveExtension"
                ):
                    if ext_value.extension and len(ext_value.extension) > 0:
                        missing_ext = False
                else:
                    validate_pass = True
                    for validator in ext_field.type_.__get_validators__():
                        try:
                            ext_value = validator(v=ext_value)
                        except ValidationError as exc:
                            errors.append(ErrorWrapper(exc, loc=ext_field.alias))
                            validate_pass = False
                    if not validate_pass:
                        continue
                    if ext_value.extension and len(ext_value.extension) > 0:
                        missing_ext = False
            if missing_ext:
                if value is _missing:
                    errors.append(ErrorWrapper(MissingError(), loc=field.alias))
                else:
                    errors.append(
                        ErrorWrapper(NoneIsNotAllowedError(), loc=field.alias)
                    )
        if len(errors) > 0:
            raise ValidationError(errors, cls)  # type: ignore

        return values


from . import backboneelement


class ConditionDefinitionMedication(backboneelement.BackboneElement):
    """Disclaimer: Any field name ends with ``__ext`` doesn't part of
    Resource StructureDefinition, instead used to enable Extensibility feature
    for FHIR Primitive Data Types.

    Medications particularly relevant for this condition.
    """

    resource_type = Field("ConditionDefinitionMedication", const=True)

    category: fhirtypes.CodeableConceptType = Field(
        None,
        alias="category",
        title="Category that is relevant",
        description=None,
        # if property is element of this resource.
        element_property=True,
    )

    code: fhirtypes.CodeableConceptType = Field(
        None,
        alias="code",
        title="Code for relevant Medication",
        description=None,
        # if property is element of this resource.
        element_property=True,
    )

    @classmethod
    def elements_sequence(cls):
        """returning all elements names from ``ConditionDefinitionMedication`` according specification,
        with preserving original sequence order.
        """
        return ["id", "extension", "modifierExtension", "category", "code"]


class ConditionDefinitionObservation(backboneelement.BackboneElement):
    """Disclaimer: Any field name ends with ``__ext`` doesn't part of
    Resource StructureDefinition, instead used to enable Extensibility feature
    for FHIR Primitive Data Types.

    Observations particularly relevant to this condition.
    """

    resource_type = Field("ConditionDefinitionObservation", const=True)

    category: fhirtypes.CodeableConceptType = Field(
        None,
        alias="category",
        title="Category that is relevant",
        description=None,
        # if property is element of this resource.
        element_property=True,
    )

    code: fhirtypes.CodeableConceptType = Field(
        None,
        alias="code",
        title="Code for relevant Observation",
        description=None,
        # if property is element of this resource.
        element_property=True,
    )

    @classmethod
    def elements_sequence(cls):
        """returning all elements names from ``ConditionDefinitionObservation`` according specification,
        with preserving original sequence order.
        """
        return ["id", "extension", "modifierExtension", "category", "code"]


class ConditionDefinitionPlan(backboneelement.BackboneElement):
    """Disclaimer: Any field name ends with ``__ext`` doesn't part of
    Resource StructureDefinition, instead used to enable Extensibility feature
    for FHIR Primitive Data Types.

    Plan that is appropriate.
    """

    resource_type = Field("ConditionDefinitionPlan", const=True)

    reference: fhirtypes.ReferenceType = Field(
        ...,
        alias="reference",
        title="The actual plan",
        description=None,
        # if property is element of this resource.
        element_property=True,
        # note: Listed Resource Type(s) should be allowed as Reference.
        enum_reference_types=["PlanDefinition"],
    )

    role: fhirtypes.CodeableConceptType = Field(
        None,
        alias="role",
        title="Use for the plan",
        description=None,
        # if property is element of this resource.
        element_property=True,
    )

    @classmethod
    def elements_sequence(cls):
        """returning all elements names from ``ConditionDefinitionPlan`` according specification,
        with preserving original sequence order.
        """
        return ["id", "extension", "modifierExtension", "role", "reference"]


class ConditionDefinitionPrecondition(backboneelement.BackboneElement):
    """Disclaimer: Any field name ends with ``__ext`` doesn't part of
    Resource StructureDefinition, instead used to enable Extensibility feature
    for FHIR Primitive Data Types.

    Observation that suggets this condition.
    An observation that suggests that this condition applies.
    """

    resource_type = Field("ConditionDefinitionPrecondition", const=True)

    code: fhirtypes.CodeableConceptType = Field(
        ...,
        alias="code",
        title="Code for relevant Observation",
        description=None,
        # if property is element of this resource.
        element_property=True,
    )

    type: fhirtypes.Code = Field(
        None,
        alias="type",
        title="sensitive | specific",
        description="Kind of pre-condition.",
        # if property is element of this resource.
        element_property=True,
        element_required=True,
        # note: Enum values can be used in validation,
        # but use in your own responsibilities, read official FHIR documentation.
        enum_values=["sensitive", "specific"],
    )
    type__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
        None, alias="_type", title="Extension field for ``type``."
    )

    valueCodeableConcept: fhirtypes.CodeableConceptType = Field(
        None,
        alias="valueCodeableConcept",
        title="Value of Observation",
        description=None,
        # if property is element of this resource.
        element_property=True,
        # Choice of Data Types. i.e value[x]
        one_of_many="value",
        one_of_many_required=False,
    )

    valueQuantity: fhirtypes.QuantityType = Field(
        None,
        alias="valueQuantity",
        title="Value of Observation",
        description=None,
        # if property is element of this resource.
        element_property=True,
        # Choice of Data Types. i.e value[x]
        one_of_many="value",
        one_of_many_required=False,
    )

    @classmethod
    def elements_sequence(cls):
        """returning all elements names from ``ConditionDefinitionPrecondition`` according specification,
        with preserving original sequence order.
        """
        return [
            "id",
            "extension",
            "modifierExtension",
            "type",
            "code",
            "valueCodeableConcept",
            "valueQuantity",
        ]

    @root_validator(pre=True, allow_reuse=True)
    def validate_required_primitive_elements_3407(
        cls, values: typing.Dict[str, typing.Any]
    ) -> typing.Dict[str, typing.Any]:
        """https://www.hl7.org/fhir/extensibility.html#Special-Case
        In some cases, implementers might find that they do not have appropriate data for
        an element with minimum cardinality = 1. In this case, the element must be present,
        but unless the resource or a profile on it has made the actual value of the primitive
        data type mandatory, it is possible to provide an extension that explains why
        the primitive value is not present.
        """
        required_fields = [("type", "type__ext")]
        _missing = object()

        def _fallback():
            return ""

        errors: typing.List["ErrorWrapper"] = []
        for name, ext in required_fields:
            field = cls.__fields__[name]
            ext_field = cls.__fields__[ext]
            value = values.get(field.alias, _missing)
            if value not in (_missing, None):
                continue
            ext_value = values.get(ext_field.alias, _missing)
            missing_ext = True
            if ext_value not in (_missing, None):
                if isinstance(ext_value, dict):
                    missing_ext = len(ext_value.get("extension", [])) == 0
                elif (
                    getattr(ext_value.__class__, "get_resource_type", _fallback)()
                    == "FHIRPrimitiveExtension"
                ):
                    if ext_value.extension and len(ext_value.extension) > 0:
                        missing_ext = False
                else:
                    validate_pass = True
                    for validator in ext_field.type_.__get_validators__():
                        try:
                            ext_value = validator(v=ext_value)
                        except ValidationError as exc:
                            errors.append(ErrorWrapper(exc, loc=ext_field.alias))
                            validate_pass = False
                    if not validate_pass:
                        continue
                    if ext_value.extension and len(ext_value.extension) > 0:
                        missing_ext = False
            if missing_ext:
                if value is _missing:
                    errors.append(ErrorWrapper(MissingError(), loc=field.alias))
                else:
                    errors.append(
                        ErrorWrapper(NoneIsNotAllowedError(), loc=field.alias)
                    )
        if len(errors) > 0:
            raise ValidationError(errors, cls)  # type: ignore

        return values

    @root_validator(pre=True, allow_reuse=True)
    def validate_one_of_many_3407(
        cls, values: typing.Dict[str, typing.Any]
    ) -> typing.Dict[str, typing.Any]:
        """https://www.hl7.org/fhir/formats.html#choice
        A few elements have a choice of more than one data type for their content.
        All such elements have a name that takes the form nnn[x].
        The "nnn" part of the name is constant, and the "[x]" is replaced with
        the title-cased name of the type that is actually used.
        The table view shows each of these names explicitly.

        Elements that have a choice of data type cannot repeat - they must have a
        maximum cardinality of 1. When constructing an instance of an element with a
        choice of types, the authoring system must create a single element with a
        data type chosen from among the list of permitted data types.
        """
        one_of_many_fields = {"value": ["valueCodeableConcept", "valueQuantity"]}
        for prefix, fields in one_of_many_fields.items():
            assert cls.__fields__[fields[0]].field_info.extra["one_of_many"] == prefix
            required = (
                cls.__fields__[fields[0]].field_info.extra["one_of_many_required"]
                is True
            )
            found = False
            for field in fields:
                if field in values and values[field] is not None:
                    if found is True:
                        raise ValueError(
                            "Any of one field value is expected from "
                            f"this list {fields}, but got multiple!"
                        )
                    else:
                        found = True
            if required is True and found is False:
                raise ValueError(f"Expect any of field value from this list {fields}.")

        return values


class ConditionDefinitionQuestionnaire(backboneelement.BackboneElement):
    """Disclaimer: Any field name ends with ``__ext`` doesn't part of
    Resource StructureDefinition, instead used to enable Extensibility feature
    for FHIR Primitive Data Types.

    Questionnaire for this condition.
    """

    resource_type = Field("ConditionDefinitionQuestionnaire", const=True)

    purpose: fhirtypes.Code = Field(
        None,
        alias="purpose",
        title="preadmit | diff-diagnosis | outcome",
        description="Use of the questionnaire.",
        # if property is element of this resource.
        element_property=True,
        element_required=True,
        # note: Enum values can be used in validation,
        # but use in your own responsibilities, read official FHIR documentation.
        enum_values=["preadmit", "diff-diagnosis", "outcome"],
    )
    purpose__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
        None, alias="_purpose", title="Extension field for ``purpose``."
    )

    reference: fhirtypes.ReferenceType = Field(
        ...,
        alias="reference",
        title="Specific Questionnaire",
        description=None,
        # if property is element of this resource.
        element_property=True,
        # note: Listed Resource Type(s) should be allowed as Reference.
        enum_reference_types=["Questionnaire"],
    )

    @classmethod
    def elements_sequence(cls):
        """returning all elements names from ``ConditionDefinitionQuestionnaire`` according specification,
        with preserving original sequence order.
        """
        return ["id", "extension", "modifierExtension", "purpose", "reference"]

    @root_validator(pre=True, allow_reuse=True)
    def validate_required_primitive_elements_3519(
        cls, values: typing.Dict[str, typing.Any]
    ) -> typing.Dict[str, typing.Any]:
        """https://www.hl7.org/fhir/extensibility.html#Special-Case
        In some cases, implementers might find that they do not have appropriate data for
        an element with minimum cardinality = 1. In this case, the element must be present,
        but unless the resource or a profile on it has made the actual value of the primitive
        data type mandatory, it is possible to provide an extension that explains why
        the primitive value is not present.
        """
        required_fields = [("purpose", "purpose__ext")]
        _missing = object()

        def _fallback():
            return ""

        errors: typing.List["ErrorWrapper"] = []
        for name, ext in required_fields:
            field = cls.__fields__[name]
            ext_field = cls.__fields__[ext]
            value = values.get(field.alias, _missing)
            if value not in (_missing, None):
                continue
            ext_value = values.get(ext_field.alias, _missing)
            missing_ext = True
            if ext_value not in (_missing, None):
                if isinstance(ext_value, dict):
                    missing_ext = len(ext_value.get("extension", [])) == 0
                elif (
                    getattr(ext_value.__class__, "get_resource_type", _fallback)()
                    == "FHIRPrimitiveExtension"
                ):
                    if ext_value.extension and len(ext_value.extension) > 0:
                        missing_ext = False
                else:
                    validate_pass = True
                    for validator in ext_field.type_.__get_validators__():
                        try:
                            ext_value = validator(v=ext_value)
                        except ValidationError as exc:
                            errors.append(ErrorWrapper(exc, loc=ext_field.alias))
                            validate_pass = False
                    if not validate_pass:
                        continue
                    if ext_value.extension and len(ext_value.extension) > 0:
                        missing_ext = False
            if missing_ext:
                if value is _missing:
                    errors.append(ErrorWrapper(MissingError(), loc=field.alias))
                else:
                    errors.append(
                        ErrorWrapper(NoneIsNotAllowedError(), loc=field.alias)
                    )
        if len(errors) > 0:
            raise ValidationError(errors, cls)  # type: ignore

        return values

<filename>fhir/resources/conditiondefinition.py<gh_stars>0
# -*- coding: utf-8 -*-
"""
Profile: http://hl7.org/fhir/StructureDefinition/ConditionDefinition
Release: R5
Version: 4.5.0
Build ID: 0d95498
Last updated: 2021-04-03T00:34:11.075+00:00
"""
import typing
from pydantic import Field
from pydantic import root_validator

from pydantic.error_wrappers import ErrorWrapper, ValidationError
from pydantic.errors import MissingError, NoneIsNotAllowedError

from . import fhirtypes


from . import metadataresource


class ConditionDefinition(metadataresource.MetadataResource):
    """Disclaimer: Any field name ends with ``__ext`` doesn't part of
    Resource StructureDefinition, instead used to enable Extensibility feature
    for FHIR Primitive Data Types.

    A definition of a condition.
    A definition of a condition and information relevant to managing it.
    """

    resource_type = Field("ConditionDefinition", const=True)

    bodySite: fhirtypes.CodeableConceptType = Field(
        None,
        alias="bodySite",
        title="Anatomical location, if relevant",
        description="The anatomical location where this condition manifests itself.",
        # if property is element of this resource.
        element_property=True,
    )

    code: fhirtypes.CodeableConceptType = Field(
        ...,
        alias="code",
        title="Identification of the condition, problem or diagnosis",
        description=None,
        # if property is element of this resource.
        element_property=True,
    )

    contact: typing.List[fhirtypes.ContactDetailType] = Field(
        None,
        alias="contact",
        title="Contact details for the publisher",
        description=(
            "Contact details to assist a user in finding and communicating with the"
            " publisher."
        ),
        # if property is element of this resource.
        element_property=True,
    )

    date: fhirtypes.DateTime = Field(
        None,
        alias="date",
        title="Date last changed",
        description=(
            "The date  (and optionally time) when the condition definition was "
            "published. The date must change when the business version changes and "
            "it must change if the status code changes. In addition, it should "
            "change when the substantive content of the condition definition "
            "changes."
        ),
        # if property is element of this resource.
        element_property=True,
    )
    date__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
        None, alias="_date", title="Extension field for ``date``."
    )

    definition: typing.List[fhirtypes.Uri] = Field(
        None,
        alias="definition",
        title="Formal Definition for the condition",
        description=(
            "Formal definitions of the condition. These may be references to "
            "ontologies, published clinical protocols or research papers."
        ),
        # if property is element of this resource.
        element_property=True,
    )
    definition__ext: typing.List[
        typing.Union[fhirtypes.FHIRPrimitiveExtensionType, None]
    ] = Field(None, alias="_definition", title="Extension field for ``definition``.")

    description: fhirtypes.Markdown = Field(
        None,
        alias="description",
        title="Natural language description of the condition definition",
        description=(
            "A free text natural language description of the condition definition "
            "from a consumer's perspective."
        ),
        # if property is element of this resource.
        element_property=True,
    )
    description__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
        None, alias="_description", title="Extension field for ``description``."
    )

    experimental: bool = Field(
        None,
        alias="experimental",
        title="For testing purposes, not real usage",
        description=(
            "A Boolean value to indicate that this condition definition is authored"
            " for testing purposes (or education/evaluation/marketing) and is not "
            "intended to be used for genuine usage."
        ),
        # if property is element of this resource.
        element_property=True,
    )
    experimental__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
        None, alias="_experimental", title="Extension field for ``experimental``."
    )

    hasBodySite: bool = Field(
        None,
        alias="hasBodySite",
        title="Whether bodySite is appropriate",
        description="Whether bodySite is appropriate to collect for this condition.",
        # if property is element of this resource.
        element_property=True,
    )
    hasBodySite__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
        None, alias="_hasBodySite", title="Extension field for ``hasBodySite``."
    )

    hasSeverity: bool = Field(
        None,
        alias="hasSeverity",
        title="Whether Severity is appropriate",
        description="Whether Severity is appropriate to collect for this condition.",
        # if property is element of this resource.
        element_property=True,
    )
    hasSeverity__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
        None, alias="_hasSeverity", title="Extension field for ``hasSeverity``."
    )

    hasStage: bool = Field(
        None,
        alias="hasStage",
        title="Whether stage is appropriate",
        description="Whether stage is appropriate to collect for this condition.",
        # if property is element of this resource.
        element_property=True,
    )
    hasStage__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
        None, alias="_hasStage", title="Extension field for ``hasStage``."
    )

    identifier: typing.List[fhirtypes.IdentifierType] = Field(
        None,
        alias="identifier",
        title="Additional identifier for the condition definition",
        description=(
            "A formal identifier that is used to identify this condition definition"
            " when it is represented in other formats, or referenced in a "
            "specification, model, design or an instance."
        ),
        # if property is element of this resource.
        element_property=True,
    )

    jurisdiction: typing.List[fhirtypes.CodeableConceptType] = Field(
        None,
        alias="jurisdiction",
        title="Intended jurisdiction for condition definition (if applicable)",
        description=(
            "A legal or geographic region in which the condition definition is "
            "intended to be used."
        ),
        # if property is element of this resource.
        element_property=True,
    )

    medication: typing.List[fhirtypes.ConditionDefinitionMedicationType] = Field(
        None,
        alias="medication",
        title="Medications particularly relevant for this condition",
        description=None,
        # if property is element of this resource.
        element_property=True,
    )

    name: fhirtypes.String = Field(
        None,
        alias="name",
        title="Name for this condition definition (computer friendly)",
        description=(
            "A natural language name identifying the condition definition. This "
            "name should be usable as an identifier for the module by machine "
            "processing applications such as code generation."
        ),
        # if property is element of this resource.
        element_property=True,
    )
    name__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
        None, alias="_name", title="Extension field for ``name``."
    )

    observation: typing.List[fhirtypes.ConditionDefinitionObservationType] = Field(
        None,
        alias="observation",
        title="Observations particularly relevant to this condition",
        description=None,
        # if property is element of this resource.
        element_property=True,
    )

    plan: typing.List[fhirtypes.ConditionDefinitionPlanType] = Field(
        None,
        alias="plan",
        title="Plan that is appropriate",
        description=None,
        # if property is element of this resource.
        element_property=True,
    )

    precondition: typing.List[fhirtypes.ConditionDefinitionPreconditionType] = Field(
        None,
        alias="precondition",
        title="Observation that suggets this condition",
        description="An observation that suggests that this condition applies.",
        # if property is element of this resource.
        element_property=True,
    )

    publisher: fhirtypes.String = Field(
        None,
        alias="publisher",
        title="Name of the publisher (organization or individual)",
        description=(
            "The name of the organization or individual that published the "
            "condition definition."
        ),
        # if property is element of this resource.
        element_property=True,
    )
    publisher__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
        None, alias="_publisher", title="Extension field for ``publisher``."
    )

    questionnaire: typing.List[fhirtypes.ConditionDefinitionQuestionnaireType] = Field(
        None,
        alias="questionnaire",
        title="Questionnaire for this condition",
        description=None,
        # if property is element of this resource.
        element_property=True,
    )

    severity: fhirtypes.CodeableConceptType = Field(
        None,
        alias="severity",
        title="Subjective severity of condition",
        description=(
            "A subjective assessment of the severity of the condition as evaluated "
            "by the clinician."
        ),
        # if property is element of this resource.
        element_property=True,
    )

    stage: fhirtypes.CodeableConceptType = Field(
        None,
        alias="stage",
        title="Stage/grade, usually assessed formally",
        description=(
            "Clinical stage or grade of a condition. May include formal severity "
            "assessments."
        ),
        # if property is element of this resource.
        element_property=True,
    )

    status: fhirtypes.Code = Field(
        None,
        alias="status",
        title="draft | active | retired | unknown",
        description=(
            "The status of this condition definition. Enables tracking the life-"
            "cycle of the content."
        ),
        # if property is element of this resource.
        element_property=True,
        element_required=True,
        # note: Enum values can be used in validation,
        # but use in your own responsibilities, read official FHIR documentation.
        enum_values=["draft", "active", "retired", "unknown"],
    )
    status__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
        None, alias="_status", title="Extension field for ``status``."
    )

    subtitle: fhirtypes.String = Field(
        None,
        alias="subtitle",
        title="Subordinate title of the event definition",
        description=(
            "An explanatory or alternate title for the event definition giving "
            "additional information about its content."
        ),
        # if property is element of this resource.
        element_property=True,
    )
    subtitle__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
        None, alias="_subtitle", title="Extension field for ``subtitle``."
    )

    team: typing.List[fhirtypes.ReferenceType] = Field(
        None,
        alias="team",
        title="Appropriate team for this condition",
        description=None,
        # if property is element of this resource.
        element_property=True,
        # note: Listed Resource Type(s) should be allowed as Reference.
        enum_reference_types=["CareTeam"],
    )

    title: fhirtypes.String = Field(
        None,
        alias="title",
        title="Name for this condition definition (human friendly)",
        description=(
            "A short, descriptive, user-friendly title for the condition " "definition."
        ),
        # if property is element of this resource.
        element_property=True,
    )
    title__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
        None, alias="_title", title="Extension field for ``title``."
    )

    url: fhirtypes.Uri = Field(
        None,
        alias="url",
        title=(
            "Canonical identifier for this condition definition, represented as a "
            "URI (globally unique)"
        ),
        description=(
            "An absolute URI that is used to identify this condition definition "
            "when it is referenced in a specification, model, design or an "
            "instance; also called its canonical identifier. This SHOULD be "
            "globally unique and SHOULD be a literal address at which at which an "
            "authoritative instance of this condition definition is (or will be) "
            "published. This URL can be the target of a canonical reference. It "
            "SHALL remain the same when the condition definition is stored on "
            "different servers."
        ),
        # if property is element of this resource.
        element_property=True,
    )
    url__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
        None, alias="_url", title="Extension field for ``url``."
    )

    useContext: typing.List[fhirtypes.UsageContextType] = Field(
        None,
        alias="useContext",
        title="The context that the content is intended to support",
        description=(
            "The content was developed with a focus and intent of supporting the "
            "contexts that are listed. These contexts may be general categories "
            "(gender, age, ...) or may be references to specific programs "
            "(insurance plans, studies, ...) and may be used to assist with "
            "indexing and searching for appropriate condition definition instances."
        ),
        # if property is element of this resource.
        element_property=True,
    )

    version: fhirtypes.String = Field(
        None,
        alias="version",
        title="Business version of the condition definition",
        description=(
            "The identifier that is used to identify this version of the condition "
            "definition when it is referenced in a specification, model, design or "
            "instance. This is an arbitrary value managed by the condition "
            "definition author and is not expected to be globally unique. For "
            "example, it might be a timestamp (e.g. yyyymmdd) if a managed version "
            "is not available. There is also no expectation that versions can be "
            "placed in a lexicographical sequence."
        ),
        # if property is element of this resource.
        element_property=True,
    )
    version__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
        None, alias="_version", title="Extension field for ``version``."
    )

    @classmethod
    def elements_sequence(cls):
        """returning all elements names from ``ConditionDefinition`` according specification,
        with preserving original sequence order.
        """
        return [
            "id",
            "meta",
            "implicitRules",
            "language",
            "text",
            "contained",
            "extension",
            "modifierExtension",
            "url",
            "identifier",
            "version",
            "name",
            "title",
            "status",
            "experimental",
            "date",
            "publisher",
            "contact",
            "description",
            "useContext",
            "jurisdiction",
            "purpose",
            "copyright",
            "approvalDate",
            "lastReviewDate",
            "effectivePeriod",
            "topic",
            "author",
            "editor",
            "reviewer",
            "endorser",
            "relatedArtifact",
            "url",
            "identifier",
            "version",
            "name",
            "title",
            "subtitle",
            "status",
            "experimental",
            "date",
            "publisher",
            "contact",
            "description",
            "useContext",
            "jurisdiction",
            "code",
            "severity",
            "bodySite",
            "stage",
            "hasSeverity",
            "hasBodySite",
            "hasStage",
            "definition",
            "observation",
            "medication",
            "precondition",
            "team",
            "questionnaire",
            "plan",
        ]

    @root_validator(pre=True, allow_reuse=True)
    def validate_required_primitive_elements_2145(
        cls, values: typing.Dict[str, typing.Any]
    ) -> typing.Dict[str, typing.Any]:
        """https://www.hl7.org/fhir/extensibility.html#Special-Case
        In some cases, implementers might find that they do not have appropriate data for
        an element with minimum cardinality = 1. In this case, the element must be present,
        but unless the resource or a profile on it has made the actual value of the primitive
        data type mandatory, it is possible to provide an extension that explains why
        the primitive value is not present.
        """
        required_fields = [("status", "status__ext")]
        _missing = object()

        def _fallback():
            return ""

        errors: typing.List["ErrorWrapper"] = []
        for name, ext in required_fields:
            field = cls.__fields__[name]
            ext_field = cls.__fields__[ext]
            value = values.get(field.alias, _missing)
            if value not in (_missing, None):
                continue
            ext_value = values.get(ext_field.alias, _missing)
            missing_ext = True
            if ext_value not in (_missing, None):
                if isinstance(ext_value, dict):
                    missing_ext = len(ext_value.get("extension", [])) == 0
                elif (
                    getattr(ext_value.__class__, "get_resource_type", _fallback)()
                    == "FHIRPrimitiveExtension"
                ):
                    if ext_value.extension and len(ext_value.extension) > 0:
                        missing_ext = False
                else:
                    validate_pass = True
                    for validator in ext_field.type_.__get_validators__():
                        try:
                            ext_value = validator(v=ext_value)
                        except ValidationError as exc:
                            errors.append(ErrorWrapper(exc, loc=ext_field.alias))
                            validate_pass = False
                    if not validate_pass:
                        continue
                    if ext_value.extension and len(ext_value.extension) > 0:
                        missing_ext = False
            if missing_ext:
                if value is _missing:
                    errors.append(ErrorWrapper(MissingError(), loc=field.alias))
                else:
                    errors.append(
                        ErrorWrapper(NoneIsNotAllowedError(), loc=field.alias)
                    )
        if len(errors) > 0:
            raise ValidationError(errors, cls)  # type: ignore

        return values


from . import backboneelement


class ConditionDefinitionMedication(backboneelement.BackboneElement):
    """Disclaimer: Any field name ends with ``__ext`` doesn't part of
    Resource StructureDefinition, instead used to enable Extensibility feature
    for FHIR Primitive Data Types.

    Medications particularly relevant for this condition.
    """

    resource_type = Field("ConditionDefinitionMedication", const=True)

    category: fhirtypes.CodeableConceptType = Field(
        None,
        alias="category",
        title="Category that is relevant",
        description=None,
        # if property is element of this resource.
        element_property=True,
    )

    code: fhirtypes.CodeableConceptType = Field(
        None,
        alias="code",
        title="Code for relevant Medication",
        description=None,
        # if property is element of this resource.
        element_property=True,
    )

    @classmethod
    def elements_sequence(cls):
        """returning all elements names from ``ConditionDefinitionMedication`` according specification,
        with preserving original sequence order.
        """
        return ["id", "extension", "modifierExtension", "category", "code"]


class ConditionDefinitionObservation(backboneelement.BackboneElement):
    """Disclaimer: Any field name ends with ``__ext`` doesn't part of
    Resource StructureDefinition, instead used to enable Extensibility feature
    for FHIR Primitive Data Types.

    Observations particularly relevant to this condition.
    """

    resource_type = Field("ConditionDefinitionObservation", const=True)

    category: fhirtypes.CodeableConceptType = Field(
        None,
        alias="category",
        title="Category that is relevant",
        description=None,
        # if property is element of this resource.
        element_property=True,
    )

    code: fhirtypes.CodeableConceptType = Field(
        None,
        alias="code",
        title="Code for relevant Observation",
        description=None,
        # if property is element of this resource.
        element_property=True,
    )

    @classmethod
    def elements_sequence(cls):
        """returning all elements names from ``ConditionDefinitionObservation`` according specification,
        with preserving original sequence order.
        """
        return ["id", "extension", "modifierExtension", "category", "code"]


class ConditionDefinitionPlan(backboneelement.BackboneElement):
    """Disclaimer: Any field name ends with ``__ext`` doesn't part of
    Resource StructureDefinition, instead used to enable Extensibility feature
    for FHIR Primitive Data Types.

    Plan that is appropriate.
    """

    resource_type = Field("ConditionDefinitionPlan", const=True)

    reference: fhirtypes.ReferenceType = Field(
        ...,
        alias="reference",
        title="The actual plan",
        description=None,
        # if property is element of this resource.
        element_property=True,
        # note: Listed Resource Type(s) should be allowed as Reference.
        enum_reference_types=["PlanDefinition"],
    )

    role: fhirtypes.CodeableConceptType = Field(
        None,
        alias="role",
        title="Use for the plan",
        description=None,
        # if property is element of this resource.
        element_property=True,
    )

    @classmethod
    def elements_sequence(cls):
        """returning all elements names from ``ConditionDefinitionPlan`` according specification,
        with preserving original sequence order.
        """
        return ["id", "extension", "modifierExtension", "role", "reference"]


class ConditionDefinitionPrecondition(backboneelement.BackboneElement):
    """Disclaimer: Any field name ends with ``__ext`` doesn't part of
    Resource StructureDefinition, instead used to enable Extensibility feature
    for FHIR Primitive Data Types.

    Observation that suggets this condition.
    An observation that suggests that this condition applies.
    """

    resource_type = Field("ConditionDefinitionPrecondition", const=True)

    code: fhirtypes.CodeableConceptType = Field(
        ...,
        alias="code",
        title="Code for relevant Observation",
        description=None,
        # if property is element of this resource.
        element_property=True,
    )

    type: fhirtypes.Code = Field(
        None,
        alias="type",
        title="sensitive | specific",
        description="Kind of pre-condition.",
        # if property is element of this resource.
        element_property=True,
        element_required=True,
        # note: Enum values can be used in validation,
        # but use in your own responsibilities, read official FHIR documentation.
        enum_values=["sensitive", "specific"],
    )
    type__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
        None, alias="_type", title="Extension field for ``type``."
    )

    valueCodeableConcept: fhirtypes.CodeableConceptType = Field(
        None,
        alias="valueCodeableConcept",
        title="Value of Observation",
        description=None,
        # if property is element of this resource.
        element_property=True,
        # Choice of Data Types. i.e value[x]
        one_of_many="value",
        one_of_many_required=False,
    )

    valueQuantity: fhirtypes.QuantityType = Field(
        None,
        alias="valueQuantity",
        title="Value of Observation",
        description=None,
        # if property is element of this resource.
        element_property=True,
        # Choice of Data Types. i.e value[x]
        one_of_many="value",
        one_of_many_required=False,
    )

    @classmethod
    def elements_sequence(cls):
        """returning all elements names from ``ConditionDefinitionPrecondition`` according specification,
        with preserving original sequence order.
        """
        return [
            "id",
            "extension",
            "modifierExtension",
            "type",
            "code",
            "valueCodeableConcept",
            "valueQuantity",
        ]

    @root_validator(pre=True, allow_reuse=True)
    def validate_required_primitive_elements_3407(
        cls, values: typing.Dict[str, typing.Any]
    ) -> typing.Dict[str, typing.Any]:
        """https://www.hl7.org/fhir/extensibility.html#Special-Case
        In some cases, implementers might find that they do not have appropriate data for
        an element with minimum cardinality = 1. In this case, the element must be present,
        but unless the resource or a profile on it has made the actual value of the primitive
        data type mandatory, it is possible to provide an extension that explains why
        the primitive value is not present.
        """
        required_fields = [("type", "type__ext")]
        _missing = object()

        def _fallback():
            return ""

        errors: typing.List["ErrorWrapper"] = []
        for name, ext in required_fields:
            field = cls.__fields__[name]
            ext_field = cls.__fields__[ext]
            value = values.get(field.alias, _missing)
            if value not in (_missing, None):
                continue
            ext_value = values.get(ext_field.alias, _missing)
            missing_ext = True
            if ext_value not in (_missing, None):
                if isinstance(ext_value, dict):
                    missing_ext = len(ext_value.get("extension", [])) == 0
                elif (
                    getattr(ext_value.__class__, "get_resource_type", _fallback)()
                    == "FHIRPrimitiveExtension"
                ):
                    if ext_value.extension and len(ext_value.extension) > 0:
                        missing_ext = False
                else:
                    validate_pass = True
                    for validator in ext_field.type_.__get_validators__():
                        try:
                            ext_value = validator(v=ext_value)
                        except ValidationError as exc:
                            errors.append(ErrorWrapper(exc, loc=ext_field.alias))
                            validate_pass = False
                    if not validate_pass:
                        continue
                    if ext_value.extension and len(ext_value.extension) > 0:
                        missing_ext = False
            if missing_ext:
                if value is _missing:
                    errors.append(ErrorWrapper(MissingError(), loc=field.alias))
                else:
                    errors.append(
                        ErrorWrapper(NoneIsNotAllowedError(), loc=field.alias)
                    )
        if len(errors) > 0:
            raise ValidationError(errors, cls)  # type: ignore

        return values

    @root_validator(pre=True, allow_reuse=True)
    def validate_one_of_many_3407(
        cls, values: typing.Dict[str, typing.Any]
    ) -> typing.Dict[str, typing.Any]:
        """https://www.hl7.org/fhir/formats.html#choice
        A few elements have a choice of more than one data type for their content.
        All such elements have a name that takes the form nnn[x].
        The "nnn" part of the name is constant, and the "[x]" is replaced with
        the title-cased name of the type that is actually used.
        The table view shows each of these names explicitly.

        Elements that have a choice of data type cannot repeat - they must have a
        maximum cardinality of 1. When constructing an instance of an element with a
        choice of types, the authoring system must create a single element with a
        data type chosen from among the list of permitted data types.
        """
        one_of_many_fields = {"value": ["valueCodeableConcept", "valueQuantity"]}
        for prefix, fields in one_of_many_fields.items():
            assert cls.__fields__[fields[0]].field_info.extra["one_of_many"] == prefix
            required = (
                cls.__fields__[fields[0]].field_info.extra["one_of_many_required"]
                is True
            )
            found = False
            for field in fields:
                if field in values and values[field] is not None:
                    if found is True:
                        raise ValueError(
                            "Any of one field value is expected from "
                            f"this list {fields}, but got multiple!"
                        )
                    else:
                        found = True
            if required is True and found is False:
                raise ValueError(f"Expect any of field value from this list {fields}.")

        return values


class ConditionDefinitionQuestionnaire(backboneelement.BackboneElement):
    """Disclaimer: Any field name ends with ``__ext`` doesn't part of
    Resource StructureDefinition, instead used to enable Extensibility feature
    for FHIR Primitive Data Types.

    Questionnaire for this condition.
    """

    resource_type = Field("ConditionDefinitionQuestionnaire", const=True)

    purpose: fhirtypes.Code = Field(
        None,
        alias="purpose",
        title="preadmit | diff-diagnosis | outcome",
        description="Use of the questionnaire.",
        # if property is element of this resource.
        element_property=True,
        element_required=True,
        # note: Enum values can be used in validation,
        # but use in your own responsibilities, read official FHIR documentation.
        enum_values=["preadmit", "diff-diagnosis", "outcome"],
    )
    purpose__ext: fhirtypes.FHIRPrimitiveExtensionType = Field(
        None, alias="_purpose", title="Extension field for ``purpose``."
    )

    reference: fhirtypes.ReferenceType = Field(
        ...,
        alias="reference",
        title="Specific Questionnaire",
        description=None,
        # if property is element of this resource.
        element_property=True,
        # note: Listed Resource Type(s) should be allowed as Reference.
        enum_reference_types=["Questionnaire"],
    )

    @classmethod
    def elements_sequence(cls):
        """returning all elements names from ``ConditionDefinitionQuestionnaire`` according specification,
        with preserving original sequence order.
        """
        return ["id", "extension", "modifierExtension", "purpose", "reference"]

    @root_validator(pre=True, allow_reuse=True)
    def validate_required_primitive_elements_3519(
        cls, values: typing.Dict[str, typing.Any]
    ) -> typing.Dict[str, typing.Any]:
        """https://www.hl7.org/fhir/extensibility.html#Special-Case
        In some cases, implementers might find that they do not have appropriate data for
        an element with minimum cardinality = 1. In this case, the element must be present,
        but unless the resource or a profile on it has made the actual value of the primitive
        data type mandatory, it is possible to provide an extension that explains why
        the primitive value is not present.
        """
        required_fields = [("purpose", "purpose__ext")]
        _missing = object()

        def _fallback():
            return ""

        errors: typing.List["ErrorWrapper"] = []
        for name, ext in required_fields:
            field = cls.__fields__[name]
            ext_field = cls.__fields__[ext]
            value = values.get(field.alias, _missing)
            if value not in (_missing, None):
                continue
            ext_value = values.get(ext_field.alias, _missing)
            missing_ext = True
            if ext_value not in (_missing, None):
                if isinstance(ext_value, dict):
                    missing_ext = len(ext_value.get("extension", [])) == 0
                elif (
                    getattr(ext_value.__class__, "get_resource_type", _fallback)()
                    == "FHIRPrimitiveExtension"
                ):
                    if ext_value.extension and len(ext_value.extension) > 0:
                        missing_ext = False
                else:
                    validate_pass = True
                    for validator in ext_field.type_.__get_validators__():
                        try:
                            ext_value = validator(v=ext_value)
                        except ValidationError as exc:
                            errors.append(ErrorWrapper(exc, loc=ext_field.alias))
                            validate_pass = False
                    if not validate_pass:
                        continue
                    if ext_value.extension and len(ext_value.extension) > 0:
                        missing_ext = False
            if missing_ext:
                if value is _missing:
                    errors.append(ErrorWrapper(MissingError(), loc=field.alias))
                else:
                    errors.append(
                        ErrorWrapper(NoneIsNotAllowedError(), loc=field.alias)
                    )
        if len(errors) > 0:
            raise ValidationError(errors, cls)  # type: ignore

        return values

# -*- coding: utf-8 -*- Profile: http://hl7.org/fhir/StructureDefinition/ConditionDefinition Release: R5 Version: 4.5.0 Build ID: 0d95498 Last updated: 2021-04-03T00:34:11.075+00:00 Disclaimer: Any field name ends with ``__ext`` doesn't part of     Resource StructureDefinition, instead used to enable Extensibility feature     for FHIR Primitive Data Types.      A definition of a condition.     A definition of a condition and information relevant to managing it. # if property is element of this resource. # if property is element of this resource. # if property is element of this resource. # if property is element of this resource. # if property is element of this resource. # if property is element of this resource. # if property is element of this resource. # if property is element of this resource. # if property is element of this resource. # if property is element of this resource. # if property is element of this resource. # if property is element of this resource. # if property is element of this resource. # if property is element of this resource. # if property is element of this resource. # if property is element of this resource. # if property is element of this resource. # if property is element of this resource. # if property is element of this resource. # if property is element of this resource. # if property is element of this resource. # if property is element of this resource. # note: Enum values can be used in validation, # but use in your own responsibilities, read official FHIR documentation. # if property is element of this resource. # if property is element of this resource. # note: Listed Resource Type(s) should be allowed as Reference. # if property is element of this resource. # if property is element of this resource. # if property is element of this resource. # if property is element of this resource. returning all elements names from ``ConditionDefinition`` according specification,         with preserving original sequence order. https://www.hl7.org/fhir/extensibility.html#Special-Case         In some cases, implementers might find that they do not have appropriate data for         an element with minimum cardinality = 1. In this case, the element must be present,         but unless the resource or a profile on it has made the actual value of the primitive         data type mandatory, it is possible to provide an extension that explains why         the primitive value is not present. # type: ignore Disclaimer: Any field name ends with ``__ext`` doesn't part of     Resource StructureDefinition, instead used to enable Extensibility feature     for FHIR Primitive Data Types.      Medications particularly relevant for this condition. # if property is element of this resource. # if property is element of this resource. returning all elements names from ``ConditionDefinitionMedication`` according specification,         with preserving original sequence order. Disclaimer: Any field name ends with ``__ext`` doesn't part of     Resource StructureDefinition, instead used to enable Extensibility feature     for FHIR Primitive Data Types.      Observations particularly relevant to this condition. # if property is element of this resource. # if property is element of this resource. returning all elements names from ``ConditionDefinitionObservation`` according specification,         with preserving original sequence order. Disclaimer: Any field name ends with ``__ext`` doesn't part of     Resource StructureDefinition, instead used to enable Extensibility feature     for FHIR Primitive Data Types.      Plan that is appropriate. # if property is element of this resource. # note: Listed Resource Type(s) should be allowed as Reference. # if property is element of this resource. returning all elements names from ``ConditionDefinitionPlan`` according specification,         with preserving original sequence order. Disclaimer: Any field name ends with ``__ext`` doesn't part of     Resource StructureDefinition, instead used to enable Extensibility feature     for FHIR Primitive Data Types.      Observation that suggets this condition.     An observation that suggests that this condition applies. # if property is element of this resource. # if property is element of this resource. # note: Enum values can be used in validation, # but use in your own responsibilities, read official FHIR documentation. # if property is element of this resource. # Choice of Data Types. i.e value[x] # if property is element of this resource. # Choice of Data Types. i.e value[x] returning all elements names from ``ConditionDefinitionPrecondition`` according specification,         with preserving original sequence order. https://www.hl7.org/fhir/extensibility.html#Special-Case         In some cases, implementers might find that they do not have appropriate data for         an element with minimum cardinality = 1. In this case, the element must be present,         but unless the resource or a profile on it has made the actual value of the primitive         data type mandatory, it is possible to provide an extension that explains why         the primitive value is not present. # type: ignore https://www.hl7.org/fhir/formats.html#choice         A few elements have a choice of more than one data type for their content.         All such elements have a name that takes the form nnn[x].         The "nnn" part of the name is constant, and the "[x]" is replaced with         the title-cased name of the type that is actually used.         The table view shows each of these names explicitly.          Elements that have a choice of data type cannot repeat - they must have a         maximum cardinality of 1. When constructing an instance of an element with a         choice of types, the authoring system must create a single element with a         data type chosen from among the list of permitted data types. Disclaimer: Any field name ends with ``__ext`` doesn't part of     Resource StructureDefinition, instead used to enable Extensibility feature     for FHIR Primitive Data Types.      Questionnaire for this condition. # if property is element of this resource. # note: Enum values can be used in validation, # but use in your own responsibilities, read official FHIR documentation. # if property is element of this resource. # note: Listed Resource Type(s) should be allowed as Reference. returning all elements names from ``ConditionDefinitionQuestionnaire`` according specification,         with preserving original sequence order. https://www.hl7.org/fhir/extensibility.html#Special-Case         In some cases, implementers might find that they do not have appropriate data for         an element with minimum cardinality = 1. In this case, the element must be present,         but unless the resource or a profile on it has made the actual value of the primitive         data type mandatory, it is possible to provide an extension that explains why         the primitive value is not present. # type: ignore