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

from __future__ import annotations
from .currency import Currency
from .customfield import CustomField, CustomFieldTypedDict
from .expensereportlineitem import ExpenseReportLineItem, ExpenseReportLineItemTypedDict
from .expensereportlineitem_input import (
    ExpenseReportLineItemInput,
    ExpenseReportLineItemInputTypedDict,
)
from .linkeddepartment import LinkedDepartment, LinkedDepartmentTypedDict
from .linkeddepartment_input import (
    LinkedDepartmentInput,
    LinkedDepartmentInputTypedDict,
)
from .linkedledgeraccount import LinkedLedgerAccount, LinkedLedgerAccountTypedDict
from .linkedlocation import LinkedLocation, LinkedLocationTypedDict
from .linkedlocation_input import LinkedLocationInput, LinkedLocationInputTypedDict
from .linkedsubsidiary import LinkedSubsidiary, LinkedSubsidiaryTypedDict
from .linkedsubsidiary_input import (
    LinkedSubsidiaryInput,
    LinkedSubsidiaryInputTypedDict,
)
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 date, datetime
from enum import Enum
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 ExpenseReportEmployeeTypedDict(TypedDict):
    r"""The employee who submitted the expense report."""

    id: NotRequired[str]
    r"""A unique identifier for the employee."""
    display_name: NotRequired[Nullable[str]]
    r"""The display name of the employee."""


class ExpenseReportEmployee(BaseModel):
    r"""The employee who submitted the expense report."""

    id: Optional[str] = None
    r"""A unique identifier for the employee."""

    display_name: OptionalNullable[str] = UNSET
    r"""The display name of the employee."""

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        optional_fields = ["id", "display_name"]
        nullable_fields = ["display_name"]
        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 ExpenseReportStatus(str, Enum, metaclass=utils.OpenEnumMeta):
    r"""The status of the expense report."""

    DRAFT = "draft"
    SUBMITTED = "submitted"
    APPROVED = "approved"
    REIMBURSED = "reimbursed"
    REJECTED = "rejected"
    REVERSED = "reversed"
    VOIDED = "voided"


class AccountingPeriodTypedDict(TypedDict):
    r"""The accounting period the expense report is posted to."""

    id: NotRequired[str]
    r"""A unique identifier for the accounting period."""
    name: NotRequired[Nullable[str]]
    r"""The name of the accounting period."""


class AccountingPeriod(BaseModel):
    r"""The accounting period the expense report is posted to."""

    id: Optional[str] = None
    r"""A unique identifier for the accounting period."""

    name: OptionalNullable[str] = UNSET
    r"""The name of the accounting period."""

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        optional_fields = ["id", "name"]
        nullable_fields = ["name"]
        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 ApprovedByTypedDict(TypedDict):
    r"""The person who approved the expense report."""

    id: NotRequired[str]
    r"""A unique identifier for the approver."""
    display_name: NotRequired[Nullable[str]]
    r"""The display name of the approver."""


class ApprovedBy(BaseModel):
    r"""The person who approved the expense report."""

    id: Optional[str] = None
    r"""A unique identifier for the approver."""

    display_name: OptionalNullable[str] = UNSET
    r"""The display name of the approver."""

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        optional_fields = ["id", "display_name"]
        nullable_fields = ["display_name"]
        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 ExpenseReportTypedDict(TypedDict):
    employee: ExpenseReportEmployeeTypedDict
    r"""The employee who submitted the expense report."""
    transaction_date: Nullable[datetime]
    r"""The date of the transaction - YYYY:MM::DDThh:mm:ss.sTZD"""
    line_items: List[ExpenseReportLineItemTypedDict]
    r"""Expense line items linked to this expense report."""
    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"""The expense report number."""
    title: NotRequired[Nullable[str]]
    r"""Title or purpose of the expense report."""
    status: NotRequired[Nullable[ExpenseReportStatus]]
    r"""The status of the expense report."""
    posting_date: NotRequired[Nullable[date]]
    r"""The date the expense report was posted to the general ledger."""
    due_date: NotRequired[Nullable[date]]
    r"""Date when reimbursement is due."""
    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."""
    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"""Total amount of all expense lines including tax."""
    reimbursable_amount: NotRequired[Nullable[float]]
    r"""Total reimbursable amount (may differ from total if some expenses are non-reimbursable)."""
    memo: NotRequired[Nullable[str]]
    r"""The memo of the expense report."""
    department: NotRequired[Nullable[LinkedDepartmentTypedDict]]
    location: NotRequired[Nullable[LinkedLocationTypedDict]]
    account: NotRequired[Nullable[LinkedLedgerAccountTypedDict]]
    accounting_period: NotRequired[Nullable[AccountingPeriodTypedDict]]
    r"""The accounting period the expense report is posted to."""
    subsidiary: NotRequired[Nullable[LinkedSubsidiaryTypedDict]]
    tracking_categories: NotRequired[
        Nullable[List[Nullable[LinkedTrackingCategoryTypedDict]]]
    ]
    r"""A list of linked tracking categories."""
    tax_inclusive: NotRequired[Nullable[bool]]
    r"""Amounts are including tax"""
    approved_by: NotRequired[Nullable[ApprovedByTypedDict]]
    r"""The person who approved the expense report."""
    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."""
    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."""
    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."""
    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 ExpenseReport(BaseModel):
    employee: ExpenseReportEmployee
    r"""The employee who submitted the expense report."""

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

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

    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"""The expense report number."""

    title: OptionalNullable[str] = UNSET
    r"""Title or purpose of the expense report."""

    status: Annotated[
        OptionalNullable[ExpenseReportStatus], PlainValidator(validate_open_enum(False))
    ] = UNSET
    r"""The status of the expense report."""

    posting_date: OptionalNullable[date] = UNSET
    r"""The date the expense report was posted to the general ledger."""

    due_date: OptionalNullable[date] = UNSET
    r"""Date when reimbursement is due."""

    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."""

    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"""Total amount of all expense lines including tax."""

    reimbursable_amount: OptionalNullable[float] = UNSET
    r"""Total reimbursable amount (may differ from total if some expenses are non-reimbursable)."""

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

    department: OptionalNullable[LinkedDepartment] = UNSET

    location: OptionalNullable[LinkedLocation] = UNSET

    account: OptionalNullable[LinkedLedgerAccount] = UNSET

    accounting_period: OptionalNullable[AccountingPeriod] = UNSET
    r"""The accounting period the expense report is posted to."""

    subsidiary: OptionalNullable[LinkedSubsidiary] = UNSET

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

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

    approved_by: OptionalNullable[ApprovedBy] = UNSET
    r"""The person who approved the expense report."""

    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."""

    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."""

    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."""

    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("status")
    def serialize_status(self, value):
        if isinstance(value, str):
            try:
                return models.ExpenseReportStatus(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

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        optional_fields = [
            "id",
            "display_id",
            "number",
            "title",
            "status",
            "posting_date",
            "due_date",
            "currency",
            "currency_rate",
            "sub_total",
            "total_tax",
            "total_amount",
            "reimbursable_amount",
            "memo",
            "department",
            "location",
            "account",
            "accounting_period",
            "subsidiary",
            "tracking_categories",
            "tax_inclusive",
            "approved_by",
            "custom_fields",
            "custom_mappings",
            "row_version",
            "updated_by",
            "created_by",
            "updated_at",
            "created_at",
            "pass_through",
        ]
        nullable_fields = [
            "display_id",
            "number",
            "title",
            "status",
            "transaction_date",
            "posting_date",
            "due_date",
            "currency",
            "currency_rate",
            "sub_total",
            "total_tax",
            "total_amount",
            "reimbursable_amount",
            "memo",
            "department",
            "location",
            "account",
            "accounting_period",
            "subsidiary",
            "tracking_categories",
            "tax_inclusive",
            "approved_by",
            "custom_mappings",
            "row_version",
            "updated_by",
            "created_by",
            "updated_at",
            "created_at",
        ]
        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 ExpenseReportInputTypedDict(TypedDict):
    employee: ExpenseReportEmployeeTypedDict
    r"""The employee who submitted the expense report."""
    transaction_date: Nullable[datetime]
    r"""The date of the transaction - YYYY:MM::DDThh:mm:ss.sTZD"""
    line_items: List[ExpenseReportLineItemInputTypedDict]
    r"""Expense line items linked to this expense report."""
    display_id: NotRequired[Nullable[str]]
    r"""Id to be displayed."""
    number: NotRequired[Nullable[str]]
    r"""The expense report number."""
    title: NotRequired[Nullable[str]]
    r"""Title or purpose of the expense report."""
    status: NotRequired[Nullable[ExpenseReportStatus]]
    r"""The status of the expense report."""
    posting_date: NotRequired[Nullable[date]]
    r"""The date the expense report was posted to the general ledger."""
    due_date: NotRequired[Nullable[date]]
    r"""Date when reimbursement is due."""
    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."""
    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"""Total amount of all expense lines including tax."""
    reimbursable_amount: NotRequired[Nullable[float]]
    r"""Total reimbursable amount (may differ from total if some expenses are non-reimbursable)."""
    memo: NotRequired[Nullable[str]]
    r"""The memo of the expense report."""
    department: NotRequired[Nullable[LinkedDepartmentInputTypedDict]]
    location: NotRequired[Nullable[LinkedLocationInputTypedDict]]
    account: NotRequired[Nullable[LinkedLedgerAccountTypedDict]]
    accounting_period: NotRequired[Nullable[AccountingPeriodTypedDict]]
    r"""The accounting period the expense report is posted to."""
    subsidiary: NotRequired[Nullable[LinkedSubsidiaryInputTypedDict]]
    tracking_categories: NotRequired[
        Nullable[List[Nullable[LinkedTrackingCategoryTypedDict]]]
    ]
    r"""A list of linked tracking categories."""
    tax_inclusive: NotRequired[Nullable[bool]]
    r"""Amounts are including tax"""
    approved_by: NotRequired[Nullable[ApprovedByTypedDict]]
    r"""The person who approved the expense report."""
    custom_fields: NotRequired[List[CustomFieldTypedDict]]
    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 ExpenseReportInput(BaseModel):
    employee: ExpenseReportEmployee
    r"""The employee who submitted the expense report."""

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

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

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

    number: OptionalNullable[str] = UNSET
    r"""The expense report number."""

    title: OptionalNullable[str] = UNSET
    r"""Title or purpose of the expense report."""

    status: Annotated[
        OptionalNullable[ExpenseReportStatus], PlainValidator(validate_open_enum(False))
    ] = UNSET
    r"""The status of the expense report."""

    posting_date: OptionalNullable[date] = UNSET
    r"""The date the expense report was posted to the general ledger."""

    due_date: OptionalNullable[date] = UNSET
    r"""Date when reimbursement is due."""

    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."""

    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"""Total amount of all expense lines including tax."""

    reimbursable_amount: OptionalNullable[float] = UNSET
    r"""Total reimbursable amount (may differ from total if some expenses are non-reimbursable)."""

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

    department: OptionalNullable[LinkedDepartmentInput] = UNSET

    location: OptionalNullable[LinkedLocationInput] = UNSET

    account: OptionalNullable[LinkedLedgerAccount] = UNSET

    accounting_period: OptionalNullable[AccountingPeriod] = UNSET
    r"""The accounting period the expense report is posted to."""

    subsidiary: OptionalNullable[LinkedSubsidiaryInput] = UNSET

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

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

    approved_by: OptionalNullable[ApprovedBy] = UNSET
    r"""The person who approved the expense report."""

    custom_fields: Optional[List[CustomField]] = None

    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("status")
    def serialize_status(self, value):
        if isinstance(value, str):
            try:
                return models.ExpenseReportStatus(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

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        optional_fields = [
            "display_id",
            "number",
            "title",
            "status",
            "posting_date",
            "due_date",
            "currency",
            "currency_rate",
            "sub_total",
            "total_tax",
            "total_amount",
            "reimbursable_amount",
            "memo",
            "department",
            "location",
            "account",
            "accounting_period",
            "subsidiary",
            "tracking_categories",
            "tax_inclusive",
            "approved_by",
            "custom_fields",
            "row_version",
            "pass_through",
        ]
        nullable_fields = [
            "display_id",
            "number",
            "title",
            "status",
            "transaction_date",
            "posting_date",
            "due_date",
            "currency",
            "currency_rate",
            "sub_total",
            "total_tax",
            "total_amount",
            "reimbursable_amount",
            "memo",
            "department",
            "location",
            "account",
            "accounting_period",
            "subsidiary",
            "tracking_categories",
            "tax_inclusive",
            "approved_by",
            "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
