"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""

from __future__ import annotations
from ascend_sdk import utils
from ascend_sdk.types import (
    BaseModel,
    Nullable,
    OptionalNullable,
    UNSET,
    UNSET_SENTINEL,
)
from ascend_sdk.utils import validate_open_enum
from datetime import datetime
from enum import Enum
from pydantic import model_serializer
from pydantic.functional_validators import PlainValidator
from typing import Any, Dict, List, Optional
from typing_extensions import Annotated, NotRequired, TypedDict


class IctDepositAmountTypedDict(TypedDict):
    r"""The amount of the transfer being deposited into the customer's account in USD"""

    value: NotRequired[str]
    r"""The decimal value, as a string; Refer to [Google’s Decimal type protocol buffer](https://github.com/googleapis/googleapis/blob/40203ca1880849480bbff7b8715491060bbccdf1/google/type/decimal.proto#L33) for details"""


class IctDepositAmount(BaseModel):
    r"""The amount of the transfer being deposited into the customer's account in USD"""

    value: Optional[str] = None
    r"""The decimal value, as a string; Refer to [Google’s Decimal type protocol buffer](https://github.com/googleapis/googleapis/blob/40203ca1880849480bbff7b8715491060bbccdf1/google/type/decimal.proto#L33) for details"""


class IctDepositProgram(str, Enum, metaclass=utils.OpenEnumMeta):
    r"""The name of the program the ICT deposit is associated with"""

    ICT_PROGRAM_UNSPECIFIED = "ICT_PROGRAM_UNSPECIFIED"
    BROKER_PARTNER = "BROKER_PARTNER"
    DEPOSIT_ONLY = "DEPOSIT_ONLY"
    BANKING_PARTNER = "BANKING_PARTNER"
    MONEY_TRANSMITTER = "MONEY_TRANSMITTER"
    WITHDRAWAL_ONLY = "WITHDRAWAL_ONLY"
    DIGITAL_PARTNER = "DIGITAL_PARTNER"


class IctDepositType(str, Enum, metaclass=utils.OpenEnumMeta):
    r"""The type of retirement contribution."""

    TYPE_UNSPECIFIED = "TYPE_UNSPECIFIED"
    REGULAR = "REGULAR"
    EMPLOYEE = "EMPLOYEE"
    EMPLOYER = "EMPLOYER"
    RECHARACTERIZATION = "RECHARACTERIZATION"
    ROLLOVER_60_DAY = "ROLLOVER_60_DAY"
    ROLLOVER_DIRECT = "ROLLOVER_DIRECT"
    TRANSFER = "TRANSFER"
    TRUSTEE_FEE = "TRUSTEE_FEE"
    CONVERSION = "CONVERSION"
    REPAYMENT = "REPAYMENT"


class IctDepositRetirementContributionTypedDict(TypedDict):
    r"""Retirement contribution details for deposit to retirement account"""

    tax_year: NotRequired[int]
    r"""Tax year for which the contribution is applied. Current year is always valid; prior year is only valid before tax deadline. Must be in \"YYYY\" format."""
    type: NotRequired[IctDepositType]
    r"""The type of retirement contribution."""


class IctDepositRetirementContribution(BaseModel):
    r"""Retirement contribution details for deposit to retirement account"""

    tax_year: Optional[int] = None
    r"""Tax year for which the contribution is applied. Current year is always valid; prior year is only valid before tax deadline. Must be in \"YYYY\" format."""

    type: Annotated[
        Optional[IctDepositType], PlainValidator(validate_open_enum(False))
    ] = None
    r"""The type of retirement contribution."""


class IctDepositState(str, Enum, metaclass=utils.OpenEnumMeta):
    r"""The high level state of a transfer, one of:
    - `PROCESSING` - The transfer is being processed and will be posted if successful.
    - `PENDING_REVIEW` - The transfer is pending review and will continue processing if approved.
    - `POSTED` - The transfer has been posted to the ledger and will be completed at the end of the processing window if not canceled first.
    - `COMPLETED` - The transfer has been batched and completed.
    - `REJECTED` - The transfer was rejected.
    - `CANCELED` - The transfer was canceled.
    - `RETURNED` - The transfer was returned.
    - `POSTPONED` - The transfer is postponed and will resume processing during the next processing window.
    """

    STATE_UNSPECIFIED = "STATE_UNSPECIFIED"
    PROCESSING = "PROCESSING"
    PENDING_REVIEW = "PENDING_REVIEW"
    POSTED = "POSTED"
    COMPLETED = "COMPLETED"
    REJECTED = "REJECTED"
    CANCELED = "CANCELED"
    RETURNED = "RETURNED"
    POSTPONED = "POSTPONED"


class TransferStateTypedDict(TypedDict):
    r"""The state of the ICT deposit"""

    actor: NotRequired[str]
    r"""The user or service that triggered the state update."""
    message: NotRequired[str]
    r"""Additional description of the transfer state."""
    metadata: NotRequired[Nullable[Dict[str, Any]]]
    r"""Additional metadata relating to the transfer state. Included data depends on the state, e.g.:
    - Rejection reasons are included when the `state` is `REJECTED`
    - Reason and comment are included when `state` is `CANCELED`
    """
    state: NotRequired[IctDepositState]
    r"""The high level state of a transfer, one of:
    - `PROCESSING` - The transfer is being processed and will be posted if successful.
    - `PENDING_REVIEW` - The transfer is pending review and will continue processing if approved.
    - `POSTED` - The transfer has been posted to the ledger and will be completed at the end of the processing window if not canceled first.
    - `COMPLETED` - The transfer has been batched and completed.
    - `REJECTED` - The transfer was rejected.
    - `CANCELED` - The transfer was canceled.
    - `RETURNED` - The transfer was returned.
    - `POSTPONED` - The transfer is postponed and will resume processing during the next processing window.
    """
    update_time: NotRequired[Nullable[datetime]]
    r"""The time of the state update."""


class TransferState(BaseModel):
    r"""The state of the ICT deposit"""

    actor: Optional[str] = None
    r"""The user or service that triggered the state update."""

    message: Optional[str] = None
    r"""Additional description of the transfer state."""

    metadata: OptionalNullable[Dict[str, Any]] = UNSET
    r"""Additional metadata relating to the transfer state. Included data depends on the state, e.g.:
    - Rejection reasons are included when the `state` is `REJECTED`
    - Reason and comment are included when `state` is `CANCELED`
    """

    state: Annotated[
        Optional[IctDepositState], PlainValidator(validate_open_enum(False))
    ] = None
    r"""The high level state of a transfer, one of:
    - `PROCESSING` - The transfer is being processed and will be posted if successful.
    - `PENDING_REVIEW` - The transfer is pending review and will continue processing if approved.
    - `POSTED` - The transfer has been posted to the ledger and will be completed at the end of the processing window if not canceled first.
    - `COMPLETED` - The transfer has been batched and completed.
    - `REJECTED` - The transfer was rejected.
    - `CANCELED` - The transfer was canceled.
    - `RETURNED` - The transfer was returned.
    - `POSTPONED` - The transfer is postponed and will resume processing during the next processing window.
    """

    update_time: OptionalNullable[datetime] = UNSET
    r"""The time of the state update."""

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        optional_fields = ["actor", "message", "metadata", "state", "update_time"]
        nullable_fields = ["metadata", "update_time"]
        null_default_fields = []

        serialized = handler(self)

        m = {}

        for n, f in self.model_fields.items():
            k = f.alias or n
            val = serialized.get(k)
            serialized.pop(k, None)

            optional_nullable = k in optional_fields and k in nullable_fields
            is_set = (
                self.__pydantic_fields_set__.intersection({n})
                or k in null_default_fields
            )  # pylint: disable=no-member

            if val is not None and val != UNSET_SENTINEL:
                m[k] = val
            elif val != UNSET_SENTINEL and (
                not k in optional_fields or (optional_nullable and is_set)
            ):
                m[k] = val

        return m


class IctDepositTravelRuleEntityOriginatingPartyAddressTypedDict(TypedDict):
    r"""The address of the entity"""

    address_lines: NotRequired[List[str]]
    r"""Unstructured address lines describing the lower levels of an address.

    Because values in address_lines do not have type information and may sometimes contain multiple values in a single field (e.g. \"Austin, TX\"), it is important that the line order is clear. The order of address lines should be \"envelope order\" for the country/region of the address. In places where this can vary (e.g. Japan), address_language is used to make it explicit (e.g. \"ja\" for large-to-small ordering and \"ja-Latn\" or \"en\" for small-to-large). This way, the most specific line of an address can be selected based on the language.

    The minimum permitted structural representation of an address consists of a region_code with all remaining information placed in the address_lines. It would be possible to format such an address very approximately without geocoding, but no semantic reasoning could be made about any of the address components until it was at least partially resolved.

    Creating an address only containing a region_code and address_lines, and then geocoding is the recommended way to handle completely unstructured addresses (as opposed to guessing which parts of the address should be localities or administrative areas).
    """
    administrative_area: NotRequired[str]
    r"""Optional. Highest administrative subdivision which is used for postal addresses of a country or region. For example, this can be a state, a province, an oblast, or a prefecture. Specifically, for Spain this is the province and not the autonomous community (e.g. \"Barcelona\" and not \"Catalonia\"). Many countries don't use an administrative area in postal addresses. E.g. in Switzerland this should be left unpopulated."""
    language_code: NotRequired[str]
    r"""Optional. BCP-47 language code of the contents of this address (if known). This is often the UI language of the input form or is expected to match one of the languages used in the address' country/region, or their transliterated equivalents. This can affect formatting in certain countries, but is not critical to the correctness of the data and will never affect any validation or other non-formatting related operations.

    If this value is not known, it should be omitted (rather than specifying a possibly incorrect default).

    Examples: \"zh-Hant\", \"ja\", \"ja-Latn\", \"en\".
    """
    locality: NotRequired[str]
    r"""Optional. Generally refers to the city/town portion of the address. Examples: US city, IT comune, UK post town. In regions of the world where localities are not well defined or do not fit into this structure well, leave locality empty and use address_lines."""
    organization: NotRequired[str]
    r"""Optional. The name of the organization at the address."""
    postal_code: NotRequired[str]
    r"""Optional. Postal code of the address. Not all countries use or require postal codes to be present, but where they are used, they may trigger additional validation with other parts of the address (e.g. state/zip validation in the U.S.A.)."""
    recipients: NotRequired[List[str]]
    r"""Optional. The recipient at the address. This field may, under certain circumstances, contain multiline information. For example, it might contain \"care of\" information."""
    region_code: NotRequired[str]
    r"""Required. CLDR region code of the country/region of the address. This is never inferred and it is up to the user to ensure the value is correct. See http://cldr.unicode.org/ and http://www.unicode.org/cldr/charts/30/supplemental/territory_information.html for details. Example: \"CH\" for Switzerland."""
    revision: NotRequired[int]
    r"""The schema revision of the `PostalAddress`. This must be set to 0, which is the latest revision.

    All new revisions **must** be backward compatible with old revisions.
    """
    sorting_code: NotRequired[str]
    r"""Optional. Additional, country-specific, sorting code. This is not used in most regions. Where it is used, the value is either a string like \"CEDEX\", optionally followed by a number (e.g. \"CEDEX 7\"), or just a number alone, representing the \"sector code\" (Jamaica), \"delivery area indicator\" (Malawi) or \"post office indicator\" (e.g. Côte d'Ivoire)."""
    sublocality: NotRequired[str]
    r"""Optional. Sublocality of the address. For example, this can be neighborhoods, boroughs, districts."""


class IctDepositTravelRuleEntityOriginatingPartyAddress(BaseModel):
    r"""The address of the entity"""

    address_lines: Optional[List[str]] = None
    r"""Unstructured address lines describing the lower levels of an address.

    Because values in address_lines do not have type information and may sometimes contain multiple values in a single field (e.g. \"Austin, TX\"), it is important that the line order is clear. The order of address lines should be \"envelope order\" for the country/region of the address. In places where this can vary (e.g. Japan), address_language is used to make it explicit (e.g. \"ja\" for large-to-small ordering and \"ja-Latn\" or \"en\" for small-to-large). This way, the most specific line of an address can be selected based on the language.

    The minimum permitted structural representation of an address consists of a region_code with all remaining information placed in the address_lines. It would be possible to format such an address very approximately without geocoding, but no semantic reasoning could be made about any of the address components until it was at least partially resolved.

    Creating an address only containing a region_code and address_lines, and then geocoding is the recommended way to handle completely unstructured addresses (as opposed to guessing which parts of the address should be localities or administrative areas).
    """

    administrative_area: Optional[str] = None
    r"""Optional. Highest administrative subdivision which is used for postal addresses of a country or region. For example, this can be a state, a province, an oblast, or a prefecture. Specifically, for Spain this is the province and not the autonomous community (e.g. \"Barcelona\" and not \"Catalonia\"). Many countries don't use an administrative area in postal addresses. E.g. in Switzerland this should be left unpopulated."""

    language_code: Optional[str] = None
    r"""Optional. BCP-47 language code of the contents of this address (if known). This is often the UI language of the input form or is expected to match one of the languages used in the address' country/region, or their transliterated equivalents. This can affect formatting in certain countries, but is not critical to the correctness of the data and will never affect any validation or other non-formatting related operations.

    If this value is not known, it should be omitted (rather than specifying a possibly incorrect default).

    Examples: \"zh-Hant\", \"ja\", \"ja-Latn\", \"en\".
    """

    locality: Optional[str] = None
    r"""Optional. Generally refers to the city/town portion of the address. Examples: US city, IT comune, UK post town. In regions of the world where localities are not well defined or do not fit into this structure well, leave locality empty and use address_lines."""

    organization: Optional[str] = None
    r"""Optional. The name of the organization at the address."""

    postal_code: Optional[str] = None
    r"""Optional. Postal code of the address. Not all countries use or require postal codes to be present, but where they are used, they may trigger additional validation with other parts of the address (e.g. state/zip validation in the U.S.A.)."""

    recipients: Optional[List[str]] = None
    r"""Optional. The recipient at the address. This field may, under certain circumstances, contain multiline information. For example, it might contain \"care of\" information."""

    region_code: Optional[str] = None
    r"""Required. CLDR region code of the country/region of the address. This is never inferred and it is up to the user to ensure the value is correct. See http://cldr.unicode.org/ and http://www.unicode.org/cldr/charts/30/supplemental/territory_information.html for details. Example: \"CH\" for Switzerland."""

    revision: Optional[int] = None
    r"""The schema revision of the `PostalAddress`. This must be set to 0, which is the latest revision.

    All new revisions **must** be backward compatible with old revisions.
    """

    sorting_code: Optional[str] = None
    r"""Optional. Additional, country-specific, sorting code. This is not used in most regions. Where it is used, the value is either a string like \"CEDEX\", optionally followed by a number (e.g. \"CEDEX 7\"), or just a number alone, representing the \"sector code\" (Jamaica), \"delivery area indicator\" (Malawi) or \"post office indicator\" (e.g. Côte d'Ivoire)."""

    sublocality: Optional[str] = None
    r"""Optional. Sublocality of the address. For example, this can be neighborhoods, boroughs, districts."""


class EntityOriginatingPartyTypedDict(TypedDict):
    r"""An entity originating party"""

    address: NotRequired[
        Nullable[IctDepositTravelRuleEntityOriginatingPartyAddressTypedDict]
    ]
    r"""The address of the entity"""
    tax_id: NotRequired[str]
    r"""The tax identification number of the entity"""
    title: NotRequired[str]
    r"""The name of the entity"""


class EntityOriginatingParty(BaseModel):
    r"""An entity originating party"""

    address: OptionalNullable[IctDepositTravelRuleEntityOriginatingPartyAddress] = UNSET
    r"""The address of the entity"""

    tax_id: Optional[str] = None
    r"""The tax identification number of the entity"""

    title: Optional[str] = None
    r"""The name of the entity"""

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        optional_fields = ["address", "tax_id", "title"]
        nullable_fields = ["address"]
        null_default_fields = []

        serialized = handler(self)

        m = {}

        for n, f in self.model_fields.items():
            k = f.alias or n
            val = serialized.get(k)
            serialized.pop(k, None)

            optional_nullable = k in optional_fields and k in nullable_fields
            is_set = (
                self.__pydantic_fields_set__.intersection({n})
                or k in null_default_fields
            )  # pylint: disable=no-member

            if val is not None and val != UNSET_SENTINEL:
                m[k] = val
            elif val != UNSET_SENTINEL and (
                not k in optional_fields or (optional_nullable and is_set)
            ):
                m[k] = val

        return m


class IctDepositAddressTypedDict(TypedDict):
    r"""The address of the entity"""

    address_lines: NotRequired[List[str]]
    r"""Unstructured address lines describing the lower levels of an address.

    Because values in address_lines do not have type information and may sometimes contain multiple values in a single field (e.g. \"Austin, TX\"), it is important that the line order is clear. The order of address lines should be \"envelope order\" for the country/region of the address. In places where this can vary (e.g. Japan), address_language is used to make it explicit (e.g. \"ja\" for large-to-small ordering and \"ja-Latn\" or \"en\" for small-to-large). This way, the most specific line of an address can be selected based on the language.

    The minimum permitted structural representation of an address consists of a region_code with all remaining information placed in the address_lines. It would be possible to format such an address very approximately without geocoding, but no semantic reasoning could be made about any of the address components until it was at least partially resolved.

    Creating an address only containing a region_code and address_lines, and then geocoding is the recommended way to handle completely unstructured addresses (as opposed to guessing which parts of the address should be localities or administrative areas).
    """
    administrative_area: NotRequired[str]
    r"""Optional. Highest administrative subdivision which is used for postal addresses of a country or region. For example, this can be a state, a province, an oblast, or a prefecture. Specifically, for Spain this is the province and not the autonomous community (e.g. \"Barcelona\" and not \"Catalonia\"). Many countries don't use an administrative area in postal addresses. E.g. in Switzerland this should be left unpopulated."""
    language_code: NotRequired[str]
    r"""Optional. BCP-47 language code of the contents of this address (if known). This is often the UI language of the input form or is expected to match one of the languages used in the address' country/region, or their transliterated equivalents. This can affect formatting in certain countries, but is not critical to the correctness of the data and will never affect any validation or other non-formatting related operations.

    If this value is not known, it should be omitted (rather than specifying a possibly incorrect default).

    Examples: \"zh-Hant\", \"ja\", \"ja-Latn\", \"en\".
    """
    locality: NotRequired[str]
    r"""Optional. Generally refers to the city/town portion of the address. Examples: US city, IT comune, UK post town. In regions of the world where localities are not well defined or do not fit into this structure well, leave locality empty and use address_lines."""
    organization: NotRequired[str]
    r"""Optional. The name of the organization at the address."""
    postal_code: NotRequired[str]
    r"""Optional. Postal code of the address. Not all countries use or require postal codes to be present, but where they are used, they may trigger additional validation with other parts of the address (e.g. state/zip validation in the U.S.A.)."""
    recipients: NotRequired[List[str]]
    r"""Optional. The recipient at the address. This field may, under certain circumstances, contain multiline information. For example, it might contain \"care of\" information."""
    region_code: NotRequired[str]
    r"""Required. CLDR region code of the country/region of the address. This is never inferred and it is up to the user to ensure the value is correct. See http://cldr.unicode.org/ and http://www.unicode.org/cldr/charts/30/supplemental/territory_information.html for details. Example: \"CH\" for Switzerland."""
    revision: NotRequired[int]
    r"""The schema revision of the `PostalAddress`. This must be set to 0, which is the latest revision.

    All new revisions **must** be backward compatible with old revisions.
    """
    sorting_code: NotRequired[str]
    r"""Optional. Additional, country-specific, sorting code. This is not used in most regions. Where it is used, the value is either a string like \"CEDEX\", optionally followed by a number (e.g. \"CEDEX 7\"), or just a number alone, representing the \"sector code\" (Jamaica), \"delivery area indicator\" (Malawi) or \"post office indicator\" (e.g. Côte d'Ivoire)."""
    sublocality: NotRequired[str]
    r"""Optional. Sublocality of the address. For example, this can be neighborhoods, boroughs, districts."""


class IctDepositAddress(BaseModel):
    r"""The address of the entity"""

    address_lines: Optional[List[str]] = None
    r"""Unstructured address lines describing the lower levels of an address.

    Because values in address_lines do not have type information and may sometimes contain multiple values in a single field (e.g. \"Austin, TX\"), it is important that the line order is clear. The order of address lines should be \"envelope order\" for the country/region of the address. In places where this can vary (e.g. Japan), address_language is used to make it explicit (e.g. \"ja\" for large-to-small ordering and \"ja-Latn\" or \"en\" for small-to-large). This way, the most specific line of an address can be selected based on the language.

    The minimum permitted structural representation of an address consists of a region_code with all remaining information placed in the address_lines. It would be possible to format such an address very approximately without geocoding, but no semantic reasoning could be made about any of the address components until it was at least partially resolved.

    Creating an address only containing a region_code and address_lines, and then geocoding is the recommended way to handle completely unstructured addresses (as opposed to guessing which parts of the address should be localities or administrative areas).
    """

    administrative_area: Optional[str] = None
    r"""Optional. Highest administrative subdivision which is used for postal addresses of a country or region. For example, this can be a state, a province, an oblast, or a prefecture. Specifically, for Spain this is the province and not the autonomous community (e.g. \"Barcelona\" and not \"Catalonia\"). Many countries don't use an administrative area in postal addresses. E.g. in Switzerland this should be left unpopulated."""

    language_code: Optional[str] = None
    r"""Optional. BCP-47 language code of the contents of this address (if known). This is often the UI language of the input form or is expected to match one of the languages used in the address' country/region, or their transliterated equivalents. This can affect formatting in certain countries, but is not critical to the correctness of the data and will never affect any validation or other non-formatting related operations.

    If this value is not known, it should be omitted (rather than specifying a possibly incorrect default).

    Examples: \"zh-Hant\", \"ja\", \"ja-Latn\", \"en\".
    """

    locality: Optional[str] = None
    r"""Optional. Generally refers to the city/town portion of the address. Examples: US city, IT comune, UK post town. In regions of the world where localities are not well defined or do not fit into this structure well, leave locality empty and use address_lines."""

    organization: Optional[str] = None
    r"""Optional. The name of the organization at the address."""

    postal_code: Optional[str] = None
    r"""Optional. Postal code of the address. Not all countries use or require postal codes to be present, but where they are used, they may trigger additional validation with other parts of the address (e.g. state/zip validation in the U.S.A.)."""

    recipients: Optional[List[str]] = None
    r"""Optional. The recipient at the address. This field may, under certain circumstances, contain multiline information. For example, it might contain \"care of\" information."""

    region_code: Optional[str] = None
    r"""Required. CLDR region code of the country/region of the address. This is never inferred and it is up to the user to ensure the value is correct. See http://cldr.unicode.org/ and http://www.unicode.org/cldr/charts/30/supplemental/territory_information.html for details. Example: \"CH\" for Switzerland."""

    revision: Optional[int] = None
    r"""The schema revision of the `PostalAddress`. This must be set to 0, which is the latest revision.

    All new revisions **must** be backward compatible with old revisions.
    """

    sorting_code: Optional[str] = None
    r"""Optional. Additional, country-specific, sorting code. This is not used in most regions. Where it is used, the value is either a string like \"CEDEX\", optionally followed by a number (e.g. \"CEDEX 7\"), or just a number alone, representing the \"sector code\" (Jamaica), \"delivery area indicator\" (Malawi) or \"post office indicator\" (e.g. Côte d'Ivoire)."""

    sublocality: Optional[str] = None
    r"""Optional. Sublocality of the address. For example, this can be neighborhoods, boroughs, districts."""


class EntityRecipientPartyTypedDict(TypedDict):
    r"""An entity recipient party"""

    address: NotRequired[Nullable[IctDepositAddressTypedDict]]
    r"""The address of the entity"""
    tax_id: NotRequired[str]
    r"""The tax identification number of the entity"""
    title: NotRequired[str]
    r"""The name of the entity"""


class EntityRecipientParty(BaseModel):
    r"""An entity recipient party"""

    address: OptionalNullable[IctDepositAddress] = UNSET
    r"""The address of the entity"""

    tax_id: Optional[str] = None
    r"""The tax identification number of the entity"""

    title: Optional[str] = None
    r"""The name of the entity"""

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        optional_fields = ["address", "tax_id", "title"]
        nullable_fields = ["address"]
        null_default_fields = []

        serialized = handler(self)

        m = {}

        for n, f in self.model_fields.items():
            k = f.alias or n
            val = serialized.get(k)
            serialized.pop(k, None)

            optional_nullable = k in optional_fields and k in nullable_fields
            is_set = (
                self.__pydantic_fields_set__.intersection({n})
                or k in null_default_fields
            )  # pylint: disable=no-member

            if val is not None and val != UNSET_SENTINEL:
                m[k] = val
            elif val != UNSET_SENTINEL and (
                not k in optional_fields or (optional_nullable and is_set)
            ):
                m[k] = val

        return m


class IctDepositTravelRuleAddressTypedDict(TypedDict):
    r"""The address of the party"""

    address_lines: NotRequired[List[str]]
    r"""Unstructured address lines describing the lower levels of an address.

    Because values in address_lines do not have type information and may sometimes contain multiple values in a single field (e.g. \"Austin, TX\"), it is important that the line order is clear. The order of address lines should be \"envelope order\" for the country/region of the address. In places where this can vary (e.g. Japan), address_language is used to make it explicit (e.g. \"ja\" for large-to-small ordering and \"ja-Latn\" or \"en\" for small-to-large). This way, the most specific line of an address can be selected based on the language.

    The minimum permitted structural representation of an address consists of a region_code with all remaining information placed in the address_lines. It would be possible to format such an address very approximately without geocoding, but no semantic reasoning could be made about any of the address components until it was at least partially resolved.

    Creating an address only containing a region_code and address_lines, and then geocoding is the recommended way to handle completely unstructured addresses (as opposed to guessing which parts of the address should be localities or administrative areas).
    """
    administrative_area: NotRequired[str]
    r"""Optional. Highest administrative subdivision which is used for postal addresses of a country or region. For example, this can be a state, a province, an oblast, or a prefecture. Specifically, for Spain this is the province and not the autonomous community (e.g. \"Barcelona\" and not \"Catalonia\"). Many countries don't use an administrative area in postal addresses. E.g. in Switzerland this should be left unpopulated."""
    language_code: NotRequired[str]
    r"""Optional. BCP-47 language code of the contents of this address (if known). This is often the UI language of the input form or is expected to match one of the languages used in the address' country/region, or their transliterated equivalents. This can affect formatting in certain countries, but is not critical to the correctness of the data and will never affect any validation or other non-formatting related operations.

    If this value is not known, it should be omitted (rather than specifying a possibly incorrect default).

    Examples: \"zh-Hant\", \"ja\", \"ja-Latn\", \"en\".
    """
    locality: NotRequired[str]
    r"""Optional. Generally refers to the city/town portion of the address. Examples: US city, IT comune, UK post town. In regions of the world where localities are not well defined or do not fit into this structure well, leave locality empty and use address_lines."""
    organization: NotRequired[str]
    r"""Optional. The name of the organization at the address."""
    postal_code: NotRequired[str]
    r"""Optional. Postal code of the address. Not all countries use or require postal codes to be present, but where they are used, they may trigger additional validation with other parts of the address (e.g. state/zip validation in the U.S.A.)."""
    recipients: NotRequired[List[str]]
    r"""Optional. The recipient at the address. This field may, under certain circumstances, contain multiline information. For example, it might contain \"care of\" information."""
    region_code: NotRequired[str]
    r"""Required. CLDR region code of the country/region of the address. This is never inferred and it is up to the user to ensure the value is correct. See http://cldr.unicode.org/ and http://www.unicode.org/cldr/charts/30/supplemental/territory_information.html for details. Example: \"CH\" for Switzerland."""
    revision: NotRequired[int]
    r"""The schema revision of the `PostalAddress`. This must be set to 0, which is the latest revision.

    All new revisions **must** be backward compatible with old revisions.
    """
    sorting_code: NotRequired[str]
    r"""Optional. Additional, country-specific, sorting code. This is not used in most regions. Where it is used, the value is either a string like \"CEDEX\", optionally followed by a number (e.g. \"CEDEX 7\"), or just a number alone, representing the \"sector code\" (Jamaica), \"delivery area indicator\" (Malawi) or \"post office indicator\" (e.g. Côte d'Ivoire)."""
    sublocality: NotRequired[str]
    r"""Optional. Sublocality of the address. For example, this can be neighborhoods, boroughs, districts."""


class IctDepositTravelRuleAddress(BaseModel):
    r"""The address of the party"""

    address_lines: Optional[List[str]] = None
    r"""Unstructured address lines describing the lower levels of an address.

    Because values in address_lines do not have type information and may sometimes contain multiple values in a single field (e.g. \"Austin, TX\"), it is important that the line order is clear. The order of address lines should be \"envelope order\" for the country/region of the address. In places where this can vary (e.g. Japan), address_language is used to make it explicit (e.g. \"ja\" for large-to-small ordering and \"ja-Latn\" or \"en\" for small-to-large). This way, the most specific line of an address can be selected based on the language.

    The minimum permitted structural representation of an address consists of a region_code with all remaining information placed in the address_lines. It would be possible to format such an address very approximately without geocoding, but no semantic reasoning could be made about any of the address components until it was at least partially resolved.

    Creating an address only containing a region_code and address_lines, and then geocoding is the recommended way to handle completely unstructured addresses (as opposed to guessing which parts of the address should be localities or administrative areas).
    """

    administrative_area: Optional[str] = None
    r"""Optional. Highest administrative subdivision which is used for postal addresses of a country or region. For example, this can be a state, a province, an oblast, or a prefecture. Specifically, for Spain this is the province and not the autonomous community (e.g. \"Barcelona\" and not \"Catalonia\"). Many countries don't use an administrative area in postal addresses. E.g. in Switzerland this should be left unpopulated."""

    language_code: Optional[str] = None
    r"""Optional. BCP-47 language code of the contents of this address (if known). This is often the UI language of the input form or is expected to match one of the languages used in the address' country/region, or their transliterated equivalents. This can affect formatting in certain countries, but is not critical to the correctness of the data and will never affect any validation or other non-formatting related operations.

    If this value is not known, it should be omitted (rather than specifying a possibly incorrect default).

    Examples: \"zh-Hant\", \"ja\", \"ja-Latn\", \"en\".
    """

    locality: Optional[str] = None
    r"""Optional. Generally refers to the city/town portion of the address. Examples: US city, IT comune, UK post town. In regions of the world where localities are not well defined or do not fit into this structure well, leave locality empty and use address_lines."""

    organization: Optional[str] = None
    r"""Optional. The name of the organization at the address."""

    postal_code: Optional[str] = None
    r"""Optional. Postal code of the address. Not all countries use or require postal codes to be present, but where they are used, they may trigger additional validation with other parts of the address (e.g. state/zip validation in the U.S.A.)."""

    recipients: Optional[List[str]] = None
    r"""Optional. The recipient at the address. This field may, under certain circumstances, contain multiline information. For example, it might contain \"care of\" information."""

    region_code: Optional[str] = None
    r"""Required. CLDR region code of the country/region of the address. This is never inferred and it is up to the user to ensure the value is correct. See http://cldr.unicode.org/ and http://www.unicode.org/cldr/charts/30/supplemental/territory_information.html for details. Example: \"CH\" for Switzerland."""

    revision: Optional[int] = None
    r"""The schema revision of the `PostalAddress`. This must be set to 0, which is the latest revision.

    All new revisions **must** be backward compatible with old revisions.
    """

    sorting_code: Optional[str] = None
    r"""Optional. Additional, country-specific, sorting code. This is not used in most regions. Where it is used, the value is either a string like \"CEDEX\", optionally followed by a number (e.g. \"CEDEX 7\"), or just a number alone, representing the \"sector code\" (Jamaica), \"delivery area indicator\" (Malawi) or \"post office indicator\" (e.g. Côte d'Ivoire)."""

    sublocality: Optional[str] = None
    r"""Optional. Sublocality of the address. For example, this can be neighborhoods, boroughs, districts."""


class IndividualOriginatingPartyTypedDict(TypedDict):
    r"""An individual originating party"""

    address: NotRequired[Nullable[IctDepositTravelRuleAddressTypedDict]]
    r"""The address of the party"""
    family_name: NotRequired[str]
    r"""The last name of the party"""
    given_names: NotRequired[List[str]]
    r"""The first name of the party as well as any non-primary given names (e.g. middle names)"""


class IndividualOriginatingParty(BaseModel):
    r"""An individual originating party"""

    address: OptionalNullable[IctDepositTravelRuleAddress] = UNSET
    r"""The address of the party"""

    family_name: Optional[str] = None
    r"""The last name of the party"""

    given_names: Optional[List[str]] = None
    r"""The first name of the party as well as any non-primary given names (e.g. middle names)"""

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        optional_fields = ["address", "family_name", "given_names"]
        nullable_fields = ["address"]
        null_default_fields = []

        serialized = handler(self)

        m = {}

        for n, f in self.model_fields.items():
            k = f.alias or n
            val = serialized.get(k)
            serialized.pop(k, None)

            optional_nullable = k in optional_fields and k in nullable_fields
            is_set = (
                self.__pydantic_fields_set__.intersection({n})
                or k in null_default_fields
            )  # pylint: disable=no-member

            if val is not None and val != UNSET_SENTINEL:
                m[k] = val
            elif val != UNSET_SENTINEL and (
                not k in optional_fields or (optional_nullable and is_set)
            ):
                m[k] = val

        return m


class IctDepositTravelRuleIndividualRecipientPartyAddressTypedDict(TypedDict):
    r"""The address of the party"""

    address_lines: NotRequired[List[str]]
    r"""Unstructured address lines describing the lower levels of an address.

    Because values in address_lines do not have type information and may sometimes contain multiple values in a single field (e.g. \"Austin, TX\"), it is important that the line order is clear. The order of address lines should be \"envelope order\" for the country/region of the address. In places where this can vary (e.g. Japan), address_language is used to make it explicit (e.g. \"ja\" for large-to-small ordering and \"ja-Latn\" or \"en\" for small-to-large). This way, the most specific line of an address can be selected based on the language.

    The minimum permitted structural representation of an address consists of a region_code with all remaining information placed in the address_lines. It would be possible to format such an address very approximately without geocoding, but no semantic reasoning could be made about any of the address components until it was at least partially resolved.

    Creating an address only containing a region_code and address_lines, and then geocoding is the recommended way to handle completely unstructured addresses (as opposed to guessing which parts of the address should be localities or administrative areas).
    """
    administrative_area: NotRequired[str]
    r"""Optional. Highest administrative subdivision which is used for postal addresses of a country or region. For example, this can be a state, a province, an oblast, or a prefecture. Specifically, for Spain this is the province and not the autonomous community (e.g. \"Barcelona\" and not \"Catalonia\"). Many countries don't use an administrative area in postal addresses. E.g. in Switzerland this should be left unpopulated."""
    language_code: NotRequired[str]
    r"""Optional. BCP-47 language code of the contents of this address (if known). This is often the UI language of the input form or is expected to match one of the languages used in the address' country/region, or their transliterated equivalents. This can affect formatting in certain countries, but is not critical to the correctness of the data and will never affect any validation or other non-formatting related operations.

    If this value is not known, it should be omitted (rather than specifying a possibly incorrect default).

    Examples: \"zh-Hant\", \"ja\", \"ja-Latn\", \"en\".
    """
    locality: NotRequired[str]
    r"""Optional. Generally refers to the city/town portion of the address. Examples: US city, IT comune, UK post town. In regions of the world where localities are not well defined or do not fit into this structure well, leave locality empty and use address_lines."""
    organization: NotRequired[str]
    r"""Optional. The name of the organization at the address."""
    postal_code: NotRequired[str]
    r"""Optional. Postal code of the address. Not all countries use or require postal codes to be present, but where they are used, they may trigger additional validation with other parts of the address (e.g. state/zip validation in the U.S.A.)."""
    recipients: NotRequired[List[str]]
    r"""Optional. The recipient at the address. This field may, under certain circumstances, contain multiline information. For example, it might contain \"care of\" information."""
    region_code: NotRequired[str]
    r"""Required. CLDR region code of the country/region of the address. This is never inferred and it is up to the user to ensure the value is correct. See http://cldr.unicode.org/ and http://www.unicode.org/cldr/charts/30/supplemental/territory_information.html for details. Example: \"CH\" for Switzerland."""
    revision: NotRequired[int]
    r"""The schema revision of the `PostalAddress`. This must be set to 0, which is the latest revision.

    All new revisions **must** be backward compatible with old revisions.
    """
    sorting_code: NotRequired[str]
    r"""Optional. Additional, country-specific, sorting code. This is not used in most regions. Where it is used, the value is either a string like \"CEDEX\", optionally followed by a number (e.g. \"CEDEX 7\"), or just a number alone, representing the \"sector code\" (Jamaica), \"delivery area indicator\" (Malawi) or \"post office indicator\" (e.g. Côte d'Ivoire)."""
    sublocality: NotRequired[str]
    r"""Optional. Sublocality of the address. For example, this can be neighborhoods, boroughs, districts."""


class IctDepositTravelRuleIndividualRecipientPartyAddress(BaseModel):
    r"""The address of the party"""

    address_lines: Optional[List[str]] = None
    r"""Unstructured address lines describing the lower levels of an address.

    Because values in address_lines do not have type information and may sometimes contain multiple values in a single field (e.g. \"Austin, TX\"), it is important that the line order is clear. The order of address lines should be \"envelope order\" for the country/region of the address. In places where this can vary (e.g. Japan), address_language is used to make it explicit (e.g. \"ja\" for large-to-small ordering and \"ja-Latn\" or \"en\" for small-to-large). This way, the most specific line of an address can be selected based on the language.

    The minimum permitted structural representation of an address consists of a region_code with all remaining information placed in the address_lines. It would be possible to format such an address very approximately without geocoding, but no semantic reasoning could be made about any of the address components until it was at least partially resolved.

    Creating an address only containing a region_code and address_lines, and then geocoding is the recommended way to handle completely unstructured addresses (as opposed to guessing which parts of the address should be localities or administrative areas).
    """

    administrative_area: Optional[str] = None
    r"""Optional. Highest administrative subdivision which is used for postal addresses of a country or region. For example, this can be a state, a province, an oblast, or a prefecture. Specifically, for Spain this is the province and not the autonomous community (e.g. \"Barcelona\" and not \"Catalonia\"). Many countries don't use an administrative area in postal addresses. E.g. in Switzerland this should be left unpopulated."""

    language_code: Optional[str] = None
    r"""Optional. BCP-47 language code of the contents of this address (if known). This is often the UI language of the input form or is expected to match one of the languages used in the address' country/region, or their transliterated equivalents. This can affect formatting in certain countries, but is not critical to the correctness of the data and will never affect any validation or other non-formatting related operations.

    If this value is not known, it should be omitted (rather than specifying a possibly incorrect default).

    Examples: \"zh-Hant\", \"ja\", \"ja-Latn\", \"en\".
    """

    locality: Optional[str] = None
    r"""Optional. Generally refers to the city/town portion of the address. Examples: US city, IT comune, UK post town. In regions of the world where localities are not well defined or do not fit into this structure well, leave locality empty and use address_lines."""

    organization: Optional[str] = None
    r"""Optional. The name of the organization at the address."""

    postal_code: Optional[str] = None
    r"""Optional. Postal code of the address. Not all countries use or require postal codes to be present, but where they are used, they may trigger additional validation with other parts of the address (e.g. state/zip validation in the U.S.A.)."""

    recipients: Optional[List[str]] = None
    r"""Optional. The recipient at the address. This field may, under certain circumstances, contain multiline information. For example, it might contain \"care of\" information."""

    region_code: Optional[str] = None
    r"""Required. CLDR region code of the country/region of the address. This is never inferred and it is up to the user to ensure the value is correct. See http://cldr.unicode.org/ and http://www.unicode.org/cldr/charts/30/supplemental/territory_information.html for details. Example: \"CH\" for Switzerland."""

    revision: Optional[int] = None
    r"""The schema revision of the `PostalAddress`. This must be set to 0, which is the latest revision.

    All new revisions **must** be backward compatible with old revisions.
    """

    sorting_code: Optional[str] = None
    r"""Optional. Additional, country-specific, sorting code. This is not used in most regions. Where it is used, the value is either a string like \"CEDEX\", optionally followed by a number (e.g. \"CEDEX 7\"), or just a number alone, representing the \"sector code\" (Jamaica), \"delivery area indicator\" (Malawi) or \"post office indicator\" (e.g. Côte d'Ivoire)."""

    sublocality: Optional[str] = None
    r"""Optional. Sublocality of the address. For example, this can be neighborhoods, boroughs, districts."""


class IndividualRecipientPartyTypedDict(TypedDict):
    r"""An individual recipient party"""

    address: NotRequired[
        Nullable[IctDepositTravelRuleIndividualRecipientPartyAddressTypedDict]
    ]
    r"""The address of the party"""
    family_name: NotRequired[str]
    r"""The last name of the party"""
    given_names: NotRequired[List[str]]
    r"""The first name of the party as well as any non-primary given names (e.g. middle names)"""


class IndividualRecipientParty(BaseModel):
    r"""An individual recipient party"""

    address: OptionalNullable[
        IctDepositTravelRuleIndividualRecipientPartyAddress
    ] = UNSET
    r"""The address of the party"""

    family_name: Optional[str] = None
    r"""The last name of the party"""

    given_names: Optional[List[str]] = None
    r"""The first name of the party as well as any non-primary given names (e.g. middle names)"""

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        optional_fields = ["address", "family_name", "given_names"]
        nullable_fields = ["address"]
        null_default_fields = []

        serialized = handler(self)

        m = {}

        for n, f in self.model_fields.items():
            k = f.alias or n
            val = serialized.get(k)
            serialized.pop(k, None)

            optional_nullable = k in optional_fields and k in nullable_fields
            is_set = (
                self.__pydantic_fields_set__.intersection({n})
                or k in null_default_fields
            )  # pylint: disable=no-member

            if val is not None and val != UNSET_SENTINEL:
                m[k] = val
            elif val != UNSET_SENTINEL and (
                not k in optional_fields or (optional_nullable and is_set)
            ):
                m[k] = val

        return m


class OriginatingInstitutionTypedDict(TypedDict):
    r"""The name of the external financial institution and account that is the source of the funds"""

    account_id: NotRequired[str]
    r"""Account id at institution"""
    title: NotRequired[str]
    r"""Name of the institution"""


class OriginatingInstitution(BaseModel):
    r"""The name of the external financial institution and account that is the source of the funds"""

    account_id: Optional[str] = None
    r"""Account id at institution"""

    title: Optional[str] = None
    r"""Name of the institution"""


class RecipientInstitutionTypedDict(TypedDict):
    r"""The name and account id of institution receiving the funds. Always 'Apex Clearing' and investor account id for ICT deposits;"""

    account_id: NotRequired[str]
    r"""Account id at institution"""
    title: NotRequired[str]
    r"""Name of the institution"""


class RecipientInstitution(BaseModel):
    r"""The name and account id of institution receiving the funds. Always 'Apex Clearing' and investor account id for ICT deposits;"""

    account_id: Optional[str] = None
    r"""Account id at institution"""

    title: Optional[str] = None
    r"""Name of the institution"""


class TravelRuleTypedDict(TypedDict):
    r"""The travel rule information for the ICT deposit"""

    entity_originating_party: NotRequired[Nullable[EntityOriginatingPartyTypedDict]]
    r"""An entity originating party"""
    entity_recipient_party: NotRequired[Nullable[EntityRecipientPartyTypedDict]]
    r"""An entity recipient party"""
    individual_originating_party: NotRequired[
        Nullable[IndividualOriginatingPartyTypedDict]
    ]
    r"""An individual originating party"""
    individual_recipient_party: NotRequired[Nullable[IndividualRecipientPartyTypedDict]]
    r"""An individual recipient party"""
    originating_institution: NotRequired[Nullable[OriginatingInstitutionTypedDict]]
    r"""The name of the external financial institution and account that is the source of the funds"""
    recipient_institution: NotRequired[Nullable[RecipientInstitutionTypedDict]]
    r"""The name and account id of institution receiving the funds. Always 'Apex Clearing' and investor account id for ICT deposits;"""


class TravelRule(BaseModel):
    r"""The travel rule information for the ICT deposit"""

    entity_originating_party: OptionalNullable[EntityOriginatingParty] = UNSET
    r"""An entity originating party"""

    entity_recipient_party: OptionalNullable[EntityRecipientParty] = UNSET
    r"""An entity recipient party"""

    individual_originating_party: OptionalNullable[IndividualOriginatingParty] = UNSET
    r"""An individual originating party"""

    individual_recipient_party: OptionalNullable[IndividualRecipientParty] = UNSET
    r"""An individual recipient party"""

    originating_institution: OptionalNullable[OriginatingInstitution] = UNSET
    r"""The name of the external financial institution and account that is the source of the funds"""

    recipient_institution: OptionalNullable[RecipientInstitution] = UNSET
    r"""The name and account id of institution receiving the funds. Always 'Apex Clearing' and investor account id for ICT deposits;"""

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        optional_fields = [
            "entity_originating_party",
            "entity_recipient_party",
            "individual_originating_party",
            "individual_recipient_party",
            "originating_institution",
            "recipient_institution",
        ]
        nullable_fields = [
            "entity_originating_party",
            "entity_recipient_party",
            "individual_originating_party",
            "individual_recipient_party",
            "originating_institution",
            "recipient_institution",
        ]
        null_default_fields = []

        serialized = handler(self)

        m = {}

        for n, f in self.model_fields.items():
            k = f.alias or n
            val = serialized.get(k)
            serialized.pop(k, None)

            optional_nullable = k in optional_fields and k in nullable_fields
            is_set = (
                self.__pydantic_fields_set__.intersection({n})
                or k in null_default_fields
            )  # pylint: disable=no-member

            if val is not None and val != UNSET_SENTINEL:
                m[k] = val
            elif val != UNSET_SENTINEL and (
                not k in optional_fields or (optional_nullable and is_set)
            ):
                m[k] = val

        return m


class IctDepositTypedDict(TypedDict):
    r"""An Instant Cash Transfer. Funds are moved from a configured Firm account to a customer's brokerage account."""

    amount: NotRequired[Nullable[IctDepositAmountTypedDict]]
    r"""The amount of the transfer being deposited into the customer's account in USD"""
    client_transfer_id: NotRequired[str]
    r"""External identifier supplied by the API caller. Each request must have a unique pairing of client_transfer_id and account."""
    name: NotRequired[str]
    r"""Full name of the ICT deposit resource, which contains account id and ICT deposit id"""
    program: NotRequired[IctDepositProgram]
    r"""The name of the program the ICT deposit is associated with"""
    retirement_contribution: NotRequired[
        Nullable[IctDepositRetirementContributionTypedDict]
    ]
    r"""Retirement contribution details for deposit to retirement account"""
    transfer_state: NotRequired[Nullable[TransferStateTypedDict]]
    r"""The state of the ICT deposit"""
    travel_rule: NotRequired[Nullable[TravelRuleTypedDict]]
    r"""The travel rule information for the ICT deposit"""


class IctDeposit(BaseModel):
    r"""An Instant Cash Transfer. Funds are moved from a configured Firm account to a customer's brokerage account."""

    amount: OptionalNullable[IctDepositAmount] = UNSET
    r"""The amount of the transfer being deposited into the customer's account in USD"""

    client_transfer_id: Optional[str] = None
    r"""External identifier supplied by the API caller. Each request must have a unique pairing of client_transfer_id and account."""

    name: Optional[str] = None
    r"""Full name of the ICT deposit resource, which contains account id and ICT deposit id"""

    program: Annotated[
        Optional[IctDepositProgram], PlainValidator(validate_open_enum(False))
    ] = None
    r"""The name of the program the ICT deposit is associated with"""

    retirement_contribution: OptionalNullable[IctDepositRetirementContribution] = UNSET
    r"""Retirement contribution details for deposit to retirement account"""

    transfer_state: OptionalNullable[TransferState] = UNSET
    r"""The state of the ICT deposit"""

    travel_rule: OptionalNullable[TravelRule] = UNSET
    r"""The travel rule information for the ICT deposit"""

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        optional_fields = [
            "amount",
            "client_transfer_id",
            "name",
            "program",
            "retirement_contribution",
            "transfer_state",
            "travel_rule",
        ]
        nullable_fields = [
            "amount",
            "retirement_contribution",
            "transfer_state",
            "travel_rule",
        ]
        null_default_fields = []

        serialized = handler(self)

        m = {}

        for n, f in self.model_fields.items():
            k = f.alias or n
            val = serialized.get(k)
            serialized.pop(k, None)

            optional_nullable = k in optional_fields and k in nullable_fields
            is_set = (
                self.__pydantic_fields_set__.intersection({n})
                or k in null_default_fields
            )  # pylint: disable=no-member

            if val is not None and val != UNSET_SENTINEL:
                m[k] = val
            elif val != UNSET_SENTINEL and (
                not k in optional_fields or (optional_nullable and is_set)
            ):
                m[k] = val

        return m
