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

from __future__ import annotations
from .currency import Currency
from .customfield import CustomField, CustomFieldTypedDict
from .expenselineitem import ExpenseLineItem, ExpenseLineItemTypedDict
from .expenselineitem_input import ExpenseLineItemInput, ExpenseLineItemInputTypedDict
from .linkeddepartment import LinkedDepartment, LinkedDepartmentTypedDict
from .linkeddepartment_input import (
    LinkedDepartmentInput,
    LinkedDepartmentInputTypedDict,
)
from .linkedfinancialaccount import (
    LinkedFinancialAccount,
    LinkedFinancialAccountInput,
    LinkedFinancialAccountInputTypedDict,
    LinkedFinancialAccountTypedDict,
)
from .linkedlocation import LinkedLocation, LinkedLocationTypedDict
from .linkedlocation_input import LinkedLocationInput, LinkedLocationInputTypedDict
from .linkedsupplier import LinkedSupplier, LinkedSupplierTypedDict
from .linkedsupplier_input import LinkedSupplierInput, LinkedSupplierInputTypedDict
from .linkedtaxrate import LinkedTaxRate, LinkedTaxRateTypedDict
from .linkedtaxrate_input import LinkedTaxRateInput, LinkedTaxRateInputTypedDict
from .linkedtrackingcategory import (
    LinkedTrackingCategory,
    LinkedTrackingCategoryTypedDict,
)
from .passthroughbody import PassThroughBody, PassThroughBodyTypedDict
from apideck_unify import models, utils
from apideck_unify.types import (
    BaseModel,
    Nullable,
    OptionalNullable,
    UNSET,
    UNSET_SENTINEL,
)
from apideck_unify.utils import validate_open_enum
from datetime import datetime
from enum import Enum
import pydantic
from pydantic import field_serializer, model_serializer
from pydantic.functional_validators import PlainValidator
from typing import Any, Dict, List, Optional
from typing_extensions import Annotated, NotRequired, TypedDict


class ExpensePaymentType(str, Enum, metaclass=utils.OpenEnumMeta):
    r"""The type of payment for the expense."""

    CASH = "cash"
    CHECK = "check"
    CREDIT_CARD = "credit_card"
    OTHER = "other"


class ExpenseType(str, Enum, metaclass=utils.OpenEnumMeta):
    r"""The type of expense."""

    EXPENSE = "expense"
    REFUND = "refund"


class ExpenseStatus(str, Enum, metaclass=utils.OpenEnumMeta):
    r"""Expense status"""

    DRAFT = "draft"
    POSTED = "posted"
    VOIDED = "voided"


class ExpenseTypedDict(TypedDict):
    transaction_date: Nullable[datetime]
    r"""The date of the transaction - YYYY:MM::DDThh:mm:ss.sTZD"""
    line_items: List[ExpenseLineItemTypedDict]
    r"""Expense line items linked to this expense."""
    id: NotRequired[str]
    r"""A unique identifier for an object."""
    display_id: NotRequired[Nullable[str]]
    r"""Id to be displayed."""
    number: NotRequired[Nullable[str]]
    r"""Number."""
    account_id: NotRequired[str]
    r"""The unique identifier for the ledger account that this expense should be credited to. Deprecated, use account instead."""
    account: NotRequired[Nullable[LinkedFinancialAccountTypedDict]]
    r"""A flexible account reference that can represent a ledger account (GL account), a bank account, or an employee payable account, depending on the connector's requirements."""
    supplier_id: NotRequired[str]
    r"""The ID of the supplier this entity is linked to. Deprecated, use supplier instead."""
    supplier: NotRequired[Nullable[LinkedSupplierTypedDict]]
    r"""The supplier this entity is linked to."""
    company_id: NotRequired[Nullable[str]]
    r"""The company ID the transaction belongs to"""
    location: NotRequired[Nullable[LinkedLocationTypedDict]]
    department_id: NotRequired[Nullable[str]]
    r"""The ID of the department"""
    department: NotRequired[Nullable[LinkedDepartmentTypedDict]]
    payment_type: NotRequired[Nullable[ExpensePaymentType]]
    r"""The type of payment for the expense."""
    currency: NotRequired[Nullable[Currency]]
    r"""Indicates the associated currency for an amount of money. Values correspond to [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217)."""
    currency_rate: NotRequired[Nullable[float]]
    r"""Currency Exchange Rate at the time entity was recorded/generated."""
    type: NotRequired[Nullable[ExpenseType]]
    r"""The type of expense."""
    memo: NotRequired[Nullable[str]]
    r"""The memo of the expense."""
    tax_rate: NotRequired[LinkedTaxRateTypedDict]
    tax_inclusive: NotRequired[Nullable[bool]]
    r"""Amounts are including tax"""
    sub_total: NotRequired[Nullable[float]]
    r"""Subtotal amount, normally before tax."""
    total_tax: NotRequired[Nullable[float]]
    r"""Total tax amount applied to this transaction."""
    total_amount: NotRequired[Nullable[float]]
    r"""The total amount of the expense line item."""
    tracking_categories: NotRequired[
        Nullable[List[Nullable[LinkedTrackingCategoryTypedDict]]]
    ]
    r"""A list of linked tracking categories."""
    reference: NotRequired[Nullable[str]]
    r"""Optional reference identifier for the transaction."""
    source_document_url: NotRequired[Nullable[str]]
    r"""URL link to a source document - shown as 'Go to [appName]' in the downstream app. Currently only supported for Xero."""
    custom_fields: NotRequired[List[CustomFieldTypedDict]]
    custom_mappings: NotRequired[Nullable[Dict[str, Any]]]
    r"""When custom mappings are configured on the resource, the result is included here."""
    status: NotRequired[Nullable[ExpenseStatus]]
    r"""Expense status"""
    updated_at: NotRequired[Nullable[datetime]]
    r"""The date and time when the object was last updated."""
    created_at: NotRequired[Nullable[datetime]]
    r"""The date and time when the object was created."""
    row_version: NotRequired[Nullable[str]]
    r"""A binary value used to detect updates to a object and prevent data conflicts. It is incremented each time an update is made to the object."""
    updated_by: NotRequired[Nullable[str]]
    r"""The user who last updated the object."""
    created_by: NotRequired[Nullable[str]]
    r"""The user who created the object."""
    pass_through: NotRequired[List[PassThroughBodyTypedDict]]
    r"""The pass_through property allows passing service-specific, custom data or structured modifications in request body when creating or updating resources."""


class Expense(BaseModel):
    transaction_date: Nullable[datetime]
    r"""The date of the transaction - YYYY:MM::DDThh:mm:ss.sTZD"""

    line_items: List[ExpenseLineItem]
    r"""Expense line items linked to this expense."""

    id: Optional[str] = None
    r"""A unique identifier for an object."""

    display_id: OptionalNullable[str] = UNSET
    r"""Id to be displayed."""

    number: OptionalNullable[str] = UNSET
    r"""Number."""

    account_id: Annotated[
        Optional[str],
        pydantic.Field(
            deprecated="warning: ** DEPRECATED ** - Deprecated. Use account instead.."
        ),
    ] = None
    r"""The unique identifier for the ledger account that this expense should be credited to. Deprecated, use account instead."""

    account: OptionalNullable[LinkedFinancialAccount] = UNSET
    r"""A flexible account reference that can represent a ledger account (GL account), a bank account, or an employee payable account, depending on the connector's requirements."""

    supplier_id: Annotated[
        Optional[str],
        pydantic.Field(
            deprecated="warning: ** DEPRECATED ** - Deprecated. Use supplier instead.."
        ),
    ] = None
    r"""The ID of the supplier this entity is linked to. Deprecated, use supplier instead."""

    supplier: OptionalNullable[LinkedSupplier] = UNSET
    r"""The supplier this entity is linked to."""

    company_id: OptionalNullable[str] = UNSET
    r"""The company ID the transaction belongs to"""

    location: OptionalNullable[LinkedLocation] = UNSET

    department_id: OptionalNullable[str] = UNSET
    r"""The ID of the department"""

    department: OptionalNullable[LinkedDepartment] = UNSET

    payment_type: Annotated[
        OptionalNullable[ExpensePaymentType], PlainValidator(validate_open_enum(False))
    ] = UNSET
    r"""The type of payment for the expense."""

    currency: Annotated[
        OptionalNullable[Currency], PlainValidator(validate_open_enum(False))
    ] = UNSET
    r"""Indicates the associated currency for an amount of money. Values correspond to [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217)."""

    currency_rate: OptionalNullable[float] = UNSET
    r"""Currency Exchange Rate at the time entity was recorded/generated."""

    type: Annotated[
        OptionalNullable[ExpenseType], PlainValidator(validate_open_enum(False))
    ] = UNSET
    r"""The type of expense."""

    memo: OptionalNullable[str] = UNSET
    r"""The memo of the expense."""

    tax_rate: Optional[LinkedTaxRate] = None

    tax_inclusive: OptionalNullable[bool] = UNSET
    r"""Amounts are including tax"""

    sub_total: OptionalNullable[float] = UNSET
    r"""Subtotal amount, normally before tax."""

    total_tax: OptionalNullable[float] = UNSET
    r"""Total tax amount applied to this transaction."""

    total_amount: OptionalNullable[float] = UNSET
    r"""The total amount of the expense line item."""

    tracking_categories: OptionalNullable[List[Nullable[LinkedTrackingCategory]]] = (
        UNSET
    )
    r"""A list of linked tracking categories."""

    reference: OptionalNullable[str] = UNSET
    r"""Optional reference identifier for the transaction."""

    source_document_url: OptionalNullable[str] = UNSET
    r"""URL link to a source document - shown as 'Go to [appName]' in the downstream app. Currently only supported for Xero."""

    custom_fields: Optional[List[CustomField]] = None

    custom_mappings: OptionalNullable[Dict[str, Any]] = UNSET
    r"""When custom mappings are configured on the resource, the result is included here."""

    status: Annotated[
        OptionalNullable[ExpenseStatus], PlainValidator(validate_open_enum(False))
    ] = UNSET
    r"""Expense status"""

    updated_at: OptionalNullable[datetime] = UNSET
    r"""The date and time when the object was last updated."""

    created_at: OptionalNullable[datetime] = UNSET
    r"""The date and time when the object was created."""

    row_version: OptionalNullable[str] = UNSET
    r"""A binary value used to detect updates to a object and prevent data conflicts. It is incremented each time an update is made to the object."""

    updated_by: OptionalNullable[str] = UNSET
    r"""The user who last updated the object."""

    created_by: OptionalNullable[str] = UNSET
    r"""The user who created the object."""

    pass_through: Optional[List[PassThroughBody]] = None
    r"""The pass_through property allows passing service-specific, custom data or structured modifications in request body when creating or updating resources."""

    @field_serializer("payment_type")
    def serialize_payment_type(self, value):
        if isinstance(value, str):
            try:
                return models.ExpensePaymentType(value)
            except ValueError:
                return value
        return value

    @field_serializer("currency")
    def serialize_currency(self, value):
        if isinstance(value, str):
            try:
                return models.Currency(value)
            except ValueError:
                return value
        return value

    @field_serializer("type")
    def serialize_type(self, value):
        if isinstance(value, str):
            try:
                return models.ExpenseType(value)
            except ValueError:
                return value
        return value

    @field_serializer("status")
    def serialize_status(self, value):
        if isinstance(value, str):
            try:
                return models.ExpenseStatus(value)
            except ValueError:
                return value
        return value

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        optional_fields = [
            "id",
            "display_id",
            "number",
            "account_id",
            "account",
            "supplier_id",
            "supplier",
            "company_id",
            "location",
            "department_id",
            "department",
            "payment_type",
            "currency",
            "currency_rate",
            "type",
            "memo",
            "tax_rate",
            "tax_inclusive",
            "sub_total",
            "total_tax",
            "total_amount",
            "tracking_categories",
            "reference",
            "source_document_url",
            "custom_fields",
            "custom_mappings",
            "status",
            "updated_at",
            "created_at",
            "row_version",
            "updated_by",
            "created_by",
            "pass_through",
        ]
        nullable_fields = [
            "display_id",
            "number",
            "transaction_date",
            "account",
            "supplier",
            "company_id",
            "location",
            "department_id",
            "department",
            "payment_type",
            "currency",
            "currency_rate",
            "type",
            "memo",
            "tax_inclusive",
            "sub_total",
            "total_tax",
            "total_amount",
            "tracking_categories",
            "reference",
            "source_document_url",
            "custom_mappings",
            "status",
            "updated_at",
            "created_at",
            "row_version",
            "updated_by",
            "created_by",
        ]
        null_default_fields = []

        serialized = handler(self)

        m = {}

        for n, f in type(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 ExpenseInputTypedDict(TypedDict):
    transaction_date: Nullable[datetime]
    r"""The date of the transaction - YYYY:MM::DDThh:mm:ss.sTZD"""
    line_items: List[ExpenseLineItemInputTypedDict]
    r"""Expense line items linked to this expense."""
    display_id: NotRequired[Nullable[str]]
    r"""Id to be displayed."""
    number: NotRequired[Nullable[str]]
    r"""Number."""
    account_id: NotRequired[str]
    r"""The unique identifier for the ledger account that this expense should be credited to. Deprecated, use account instead."""
    account: NotRequired[Nullable[LinkedFinancialAccountInputTypedDict]]
    r"""A flexible account reference that can represent a ledger account (GL account), a bank account, or an employee payable account, depending on the connector's requirements."""
    supplier_id: NotRequired[str]
    r"""The ID of the supplier this entity is linked to. Deprecated, use supplier instead."""
    supplier: NotRequired[Nullable[LinkedSupplierInputTypedDict]]
    r"""The supplier this entity is linked to."""
    company_id: NotRequired[Nullable[str]]
    r"""The company ID the transaction belongs to"""
    location: NotRequired[Nullable[LinkedLocationInputTypedDict]]
    department_id: NotRequired[Nullable[str]]
    r"""The ID of the department"""
    department: NotRequired[Nullable[LinkedDepartmentInputTypedDict]]
    payment_type: NotRequired[Nullable[ExpensePaymentType]]
    r"""The type of payment for the expense."""
    currency: NotRequired[Nullable[Currency]]
    r"""Indicates the associated currency for an amount of money. Values correspond to [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217)."""
    currency_rate: NotRequired[Nullable[float]]
    r"""Currency Exchange Rate at the time entity was recorded/generated."""
    type: NotRequired[Nullable[ExpenseType]]
    r"""The type of expense."""
    memo: NotRequired[Nullable[str]]
    r"""The memo of the expense."""
    tax_rate: NotRequired[LinkedTaxRateInputTypedDict]
    tax_inclusive: NotRequired[Nullable[bool]]
    r"""Amounts are including tax"""
    sub_total: NotRequired[Nullable[float]]
    r"""Subtotal amount, normally before tax."""
    total_tax: NotRequired[Nullable[float]]
    r"""Total tax amount applied to this transaction."""
    total_amount: NotRequired[Nullable[float]]
    r"""The total amount of the expense line item."""
    tracking_categories: NotRequired[
        Nullable[List[Nullable[LinkedTrackingCategoryTypedDict]]]
    ]
    r"""A list of linked tracking categories."""
    reference: NotRequired[Nullable[str]]
    r"""Optional reference identifier for the transaction."""
    source_document_url: NotRequired[Nullable[str]]
    r"""URL link to a source document - shown as 'Go to [appName]' in the downstream app. Currently only supported for Xero."""
    custom_fields: NotRequired[List[CustomFieldTypedDict]]
    status: NotRequired[Nullable[ExpenseStatus]]
    r"""Expense status"""
    row_version: NotRequired[Nullable[str]]
    r"""A binary value used to detect updates to a object and prevent data conflicts. It is incremented each time an update is made to the object."""
    pass_through: NotRequired[List[PassThroughBodyTypedDict]]
    r"""The pass_through property allows passing service-specific, custom data or structured modifications in request body when creating or updating resources."""


class ExpenseInput(BaseModel):
    transaction_date: Nullable[datetime]
    r"""The date of the transaction - YYYY:MM::DDThh:mm:ss.sTZD"""

    line_items: List[ExpenseLineItemInput]
    r"""Expense line items linked to this expense."""

    display_id: OptionalNullable[str] = UNSET
    r"""Id to be displayed."""

    number: OptionalNullable[str] = UNSET
    r"""Number."""

    account_id: Annotated[
        Optional[str],
        pydantic.Field(
            deprecated="warning: ** DEPRECATED ** - Deprecated. Use account instead.."
        ),
    ] = None
    r"""The unique identifier for the ledger account that this expense should be credited to. Deprecated, use account instead."""

    account: OptionalNullable[LinkedFinancialAccountInput] = UNSET
    r"""A flexible account reference that can represent a ledger account (GL account), a bank account, or an employee payable account, depending on the connector's requirements."""

    supplier_id: Annotated[
        Optional[str],
        pydantic.Field(
            deprecated="warning: ** DEPRECATED ** - Deprecated. Use supplier instead.."
        ),
    ] = None
    r"""The ID of the supplier this entity is linked to. Deprecated, use supplier instead."""

    supplier: OptionalNullable[LinkedSupplierInput] = UNSET
    r"""The supplier this entity is linked to."""

    company_id: OptionalNullable[str] = UNSET
    r"""The company ID the transaction belongs to"""

    location: OptionalNullable[LinkedLocationInput] = UNSET

    department_id: OptionalNullable[str] = UNSET
    r"""The ID of the department"""

    department: OptionalNullable[LinkedDepartmentInput] = UNSET

    payment_type: Annotated[
        OptionalNullable[ExpensePaymentType], PlainValidator(validate_open_enum(False))
    ] = UNSET
    r"""The type of payment for the expense."""

    currency: Annotated[
        OptionalNullable[Currency], PlainValidator(validate_open_enum(False))
    ] = UNSET
    r"""Indicates the associated currency for an amount of money. Values correspond to [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217)."""

    currency_rate: OptionalNullable[float] = UNSET
    r"""Currency Exchange Rate at the time entity was recorded/generated."""

    type: Annotated[
        OptionalNullable[ExpenseType], PlainValidator(validate_open_enum(False))
    ] = UNSET
    r"""The type of expense."""

    memo: OptionalNullable[str] = UNSET
    r"""The memo of the expense."""

    tax_rate: Optional[LinkedTaxRateInput] = None

    tax_inclusive: OptionalNullable[bool] = UNSET
    r"""Amounts are including tax"""

    sub_total: OptionalNullable[float] = UNSET
    r"""Subtotal amount, normally before tax."""

    total_tax: OptionalNullable[float] = UNSET
    r"""Total tax amount applied to this transaction."""

    total_amount: OptionalNullable[float] = UNSET
    r"""The total amount of the expense line item."""

    tracking_categories: OptionalNullable[List[Nullable[LinkedTrackingCategory]]] = (
        UNSET
    )
    r"""A list of linked tracking categories."""

    reference: OptionalNullable[str] = UNSET
    r"""Optional reference identifier for the transaction."""

    source_document_url: OptionalNullable[str] = UNSET
    r"""URL link to a source document - shown as 'Go to [appName]' in the downstream app. Currently only supported for Xero."""

    custom_fields: Optional[List[CustomField]] = None

    status: Annotated[
        OptionalNullable[ExpenseStatus], PlainValidator(validate_open_enum(False))
    ] = UNSET
    r"""Expense status"""

    row_version: OptionalNullable[str] = UNSET
    r"""A binary value used to detect updates to a object and prevent data conflicts. It is incremented each time an update is made to the object."""

    pass_through: Optional[List[PassThroughBody]] = None
    r"""The pass_through property allows passing service-specific, custom data or structured modifications in request body when creating or updating resources."""

    @field_serializer("payment_type")
    def serialize_payment_type(self, value):
        if isinstance(value, str):
            try:
                return models.ExpensePaymentType(value)
            except ValueError:
                return value
        return value

    @field_serializer("currency")
    def serialize_currency(self, value):
        if isinstance(value, str):
            try:
                return models.Currency(value)
            except ValueError:
                return value
        return value

    @field_serializer("type")
    def serialize_type(self, value):
        if isinstance(value, str):
            try:
                return models.ExpenseType(value)
            except ValueError:
                return value
        return value

    @field_serializer("status")
    def serialize_status(self, value):
        if isinstance(value, str):
            try:
                return models.ExpenseStatus(value)
            except ValueError:
                return value
        return value

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        optional_fields = [
            "display_id",
            "number",
            "account_id",
            "account",
            "supplier_id",
            "supplier",
            "company_id",
            "location",
            "department_id",
            "department",
            "payment_type",
            "currency",
            "currency_rate",
            "type",
            "memo",
            "tax_rate",
            "tax_inclusive",
            "sub_total",
            "total_tax",
            "total_amount",
            "tracking_categories",
            "reference",
            "source_document_url",
            "custom_fields",
            "status",
            "row_version",
            "pass_through",
        ]
        nullable_fields = [
            "display_id",
            "number",
            "transaction_date",
            "account",
            "supplier",
            "company_id",
            "location",
            "department_id",
            "department",
            "payment_type",
            "currency",
            "currency_rate",
            "type",
            "memo",
            "tax_inclusive",
            "sub_total",
            "total_tax",
            "total_amount",
            "tracking_categories",
            "reference",
            "source_document_url",
            "status",
            "row_version",
        ]
        null_default_fields = []

        serialized = handler(self)

        m = {}

        for n, f in type(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
