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

from .basesdk import BaseSDK
from apideck_unify import models, utils
from apideck_unify._hooks import HookContext
from apideck_unify.types import OptionalNullable, UNSET
from apideck_unify.utils import get_security_from_env
from datetime import date
from jsonpath import JSONPath
from typing import Any, Dict, List, Mapping, Optional, Union


class PurchaseOrders(BaseSDK):
    def list(
        self,
        *,
        raw: Optional[bool] = False,
        service_id: Optional[str] = None,
        cursor: OptionalNullable[str] = UNSET,
        pass_through: Optional[Dict[str, Any]] = None,
        limit: Optional[int] = 20,
        filter_: Optional[
            Union[models.PurchaseOrdersFilter, models.PurchaseOrdersFilterTypedDict]
        ] = None,
        sort: Optional[
            Union[models.PurchaseOrdersSort, models.PurchaseOrdersSortTypedDict]
        ] = None,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> Optional[models.AccountingPurchaseOrdersAllResponse]:
        r"""List Purchase Orders

        List Purchase Orders

        :param raw: Include raw response. Mostly used for debugging purposes
        :param service_id: Provide the service id you want to call (e.g., pipedrive). Only needed when a consumer has activated multiple integrations for a Unified API.
        :param cursor: Cursor to start from. You can find cursors for next/previous pages in the meta.cursors property of the response.
        :param pass_through: Optional unmapped key/values that will be passed through to downstream as query parameters. Ie: ?pass_through[search]=leads becomes ?search=leads
        :param limit: Number of results to return. Minimum 1, Maximum 200, Default 20
        :param filter_: Apply filters
        :param sort: Apply sorting
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url

        request = models.AccountingPurchaseOrdersAllRequest(
            raw=raw,
            service_id=service_id,
            cursor=cursor,
            pass_through=pass_through,
            limit=limit,
            filter_=utils.get_pydantic_model(
                filter_, Optional[models.PurchaseOrdersFilter]
            ),
            sort=utils.get_pydantic_model(sort, Optional[models.PurchaseOrdersSort]),
        )

        req = self._build_request(
            method="GET",
            path="/accounting/purchase-orders",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=False,
            request_has_path_params=False,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            _globals=models.AccountingPurchaseOrdersAllGlobals(
                consumer_id=self.sdk_configuration.globals.consumer_id,
                app_id=self.sdk_configuration.globals.app_id,
            ),
            security=self.sdk_configuration.security,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config
            else:
                retries = utils.RetryConfig(
                    "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
                )

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["5XX"])

        http_res = self.do_request(
            hook_ctx=HookContext(
                operation_id="accounting.purchaseOrdersAll",
                oauth2_scopes=[],
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["400", "401", "402", "404", "422", "4XX", "5XX"],
            retry_config=retry_config,
        )

        def next_func() -> Optional[models.AccountingPurchaseOrdersAllResponse]:
            body = utils.unmarshal_json(http_res.text, Dict[Any, Any])
            next_cursor = JSONPath("$.meta.cursors.next").parse(body)

            if len(next_cursor) == 0:
                return None
            next_cursor = next_cursor[0]

            return self.list(
                raw=raw,
                service_id=service_id,
                cursor=next_cursor,
                pass_through=pass_through,
                limit=limit,
                filter_=filter_,
                sort=sort,
                retries=retries,
            )

        data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return models.AccountingPurchaseOrdersAllResponse(
                get_purchase_orders_response=utils.unmarshal_json(
                    http_res.text, Optional[models.GetPurchaseOrdersResponse]
                ),
                http_meta=models.HTTPMetadata(request=req, response=http_res),
                next=next_func,
            )
        if utils.match_response(http_res, "400", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.BadRequestResponseData)
            raise models.BadRequestResponse(data=data)
        if utils.match_response(http_res, "401", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.UnauthorizedResponseData)
            raise models.UnauthorizedResponse(data=data)
        if utils.match_response(http_res, "402", "application/json"):
            data = utils.unmarshal_json(
                http_res.text, models.PaymentRequiredResponseData
            )
            raise models.PaymentRequiredResponse(data=data)
        if utils.match_response(http_res, "404", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.NotFoundResponseData)
            raise models.NotFoundResponse(data=data)
        if utils.match_response(http_res, "422", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.UnprocessableResponseData)
            raise models.UnprocessableResponse(data=data)
        if utils.match_response(http_res, ["4XX", "5XX"], "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise models.APIError(
                "API error occurred", http_res.status_code, http_res_text, http_res
            )
        if utils.match_response(http_res, "default", "application/json"):
            return models.AccountingPurchaseOrdersAllResponse(
                unexpected_error_response=utils.unmarshal_json(
                    http_res.text, Optional[models.UnexpectedErrorResponse]
                ),
                http_meta=models.HTTPMetadata(request=req, response=http_res),
                next=next_func,
            )

        content_type = http_res.headers.get("Content-Type")
        http_res_text = utils.stream_to_text(http_res)
        raise models.APIError(
            f"Unexpected response received (code: {http_res.status_code}, type: {content_type})",
            http_res.status_code,
            http_res_text,
            http_res,
        )

    async def list_async(
        self,
        *,
        raw: Optional[bool] = False,
        service_id: Optional[str] = None,
        cursor: OptionalNullable[str] = UNSET,
        pass_through: Optional[Dict[str, Any]] = None,
        limit: Optional[int] = 20,
        filter_: Optional[
            Union[models.PurchaseOrdersFilter, models.PurchaseOrdersFilterTypedDict]
        ] = None,
        sort: Optional[
            Union[models.PurchaseOrdersSort, models.PurchaseOrdersSortTypedDict]
        ] = None,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> Optional[models.AccountingPurchaseOrdersAllResponse]:
        r"""List Purchase Orders

        List Purchase Orders

        :param raw: Include raw response. Mostly used for debugging purposes
        :param service_id: Provide the service id you want to call (e.g., pipedrive). Only needed when a consumer has activated multiple integrations for a Unified API.
        :param cursor: Cursor to start from. You can find cursors for next/previous pages in the meta.cursors property of the response.
        :param pass_through: Optional unmapped key/values that will be passed through to downstream as query parameters. Ie: ?pass_through[search]=leads becomes ?search=leads
        :param limit: Number of results to return. Minimum 1, Maximum 200, Default 20
        :param filter_: Apply filters
        :param sort: Apply sorting
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url

        request = models.AccountingPurchaseOrdersAllRequest(
            raw=raw,
            service_id=service_id,
            cursor=cursor,
            pass_through=pass_through,
            limit=limit,
            filter_=utils.get_pydantic_model(
                filter_, Optional[models.PurchaseOrdersFilter]
            ),
            sort=utils.get_pydantic_model(sort, Optional[models.PurchaseOrdersSort]),
        )

        req = self._build_request_async(
            method="GET",
            path="/accounting/purchase-orders",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=False,
            request_has_path_params=False,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            _globals=models.AccountingPurchaseOrdersAllGlobals(
                consumer_id=self.sdk_configuration.globals.consumer_id,
                app_id=self.sdk_configuration.globals.app_id,
            ),
            security=self.sdk_configuration.security,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config
            else:
                retries = utils.RetryConfig(
                    "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
                )

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["5XX"])

        http_res = await self.do_request_async(
            hook_ctx=HookContext(
                operation_id="accounting.purchaseOrdersAll",
                oauth2_scopes=[],
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["400", "401", "402", "404", "422", "4XX", "5XX"],
            retry_config=retry_config,
        )

        def next_func() -> Optional[models.AccountingPurchaseOrdersAllResponse]:
            body = utils.unmarshal_json(http_res.text, Dict[Any, Any])
            next_cursor = JSONPath("$.meta.cursors.next").parse(body)

            if len(next_cursor) == 0:
                return None
            next_cursor = next_cursor[0]

            return self.list(
                raw=raw,
                service_id=service_id,
                cursor=next_cursor,
                pass_through=pass_through,
                limit=limit,
                filter_=filter_,
                sort=sort,
                retries=retries,
            )

        data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return models.AccountingPurchaseOrdersAllResponse(
                get_purchase_orders_response=utils.unmarshal_json(
                    http_res.text, Optional[models.GetPurchaseOrdersResponse]
                ),
                http_meta=models.HTTPMetadata(request=req, response=http_res),
                next=next_func,
            )
        if utils.match_response(http_res, "400", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.BadRequestResponseData)
            raise models.BadRequestResponse(data=data)
        if utils.match_response(http_res, "401", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.UnauthorizedResponseData)
            raise models.UnauthorizedResponse(data=data)
        if utils.match_response(http_res, "402", "application/json"):
            data = utils.unmarshal_json(
                http_res.text, models.PaymentRequiredResponseData
            )
            raise models.PaymentRequiredResponse(data=data)
        if utils.match_response(http_res, "404", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.NotFoundResponseData)
            raise models.NotFoundResponse(data=data)
        if utils.match_response(http_res, "422", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.UnprocessableResponseData)
            raise models.UnprocessableResponse(data=data)
        if utils.match_response(http_res, ["4XX", "5XX"], "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise models.APIError(
                "API error occurred", http_res.status_code, http_res_text, http_res
            )
        if utils.match_response(http_res, "default", "application/json"):
            return models.AccountingPurchaseOrdersAllResponse(
                unexpected_error_response=utils.unmarshal_json(
                    http_res.text, Optional[models.UnexpectedErrorResponse]
                ),
                http_meta=models.HTTPMetadata(request=req, response=http_res),
                next=next_func,
            )

        content_type = http_res.headers.get("Content-Type")
        http_res_text = await utils.stream_to_text_async(http_res)
        raise models.APIError(
            f"Unexpected response received (code: {http_res.status_code}, type: {content_type})",
            http_res.status_code,
            http_res_text,
            http_res,
        )

    def create(
        self,
        *,
        raw: Optional[bool] = False,
        service_id: Optional[str] = None,
        po_number: OptionalNullable[str] = UNSET,
        reference: OptionalNullable[str] = UNSET,
        supplier: OptionalNullable[
            Union[models.LinkedSupplierInput, models.LinkedSupplierInputTypedDict]
        ] = UNSET,
        company_id: OptionalNullable[str] = UNSET,
        status: OptionalNullable[models.PurchaseOrderStatus] = UNSET,
        issued_date: OptionalNullable[date] = UNSET,
        delivery_date: OptionalNullable[date] = UNSET,
        expected_arrival_date: OptionalNullable[date] = UNSET,
        currency: OptionalNullable[models.Currency] = UNSET,
        currency_rate: OptionalNullable[float] = UNSET,
        sub_total: OptionalNullable[float] = UNSET,
        total_tax: OptionalNullable[float] = UNSET,
        total: OptionalNullable[float] = UNSET,
        tax_inclusive: OptionalNullable[bool] = UNSET,
        line_items: Optional[
            Union[
                List[models.InvoiceLineItemInput],
                List[models.InvoiceLineItemInputTypedDict],
            ]
        ] = None,
        shipping_address: Optional[
            Union[models.Address, models.AddressTypedDict]
        ] = None,
        ledger_account: OptionalNullable[
            Union[
                models.LinkedLedgerAccountInput,
                models.LinkedLedgerAccountInputTypedDict,
            ]
        ] = UNSET,
        template_id: OptionalNullable[str] = UNSET,
        discount_percentage: OptionalNullable[float] = UNSET,
        bank_account: Optional[
            Union[models.BankAccount, models.BankAccountTypedDict]
        ] = None,
        accounting_by_row: OptionalNullable[bool] = UNSET,
        due_date: OptionalNullable[date] = UNSET,
        payment_method: OptionalNullable[str] = UNSET,
        tax_code: OptionalNullable[str] = UNSET,
        channel: OptionalNullable[str] = UNSET,
        memo: OptionalNullable[str] = UNSET,
        tracking_categories: OptionalNullable[
            Union[
                List[models.LinkedTrackingCategory],
                List[models.LinkedTrackingCategoryTypedDict],
            ]
        ] = UNSET,
        row_version: OptionalNullable[str] = UNSET,
        pass_through: Optional[
            Union[List[models.PassThroughBody], List[models.PassThroughBodyTypedDict]]
        ] = None,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.AccountingPurchaseOrdersAddResponse:
        r"""Create Purchase Order

        Create Purchase Order

        :param raw: Include raw response. Mostly used for debugging purposes
        :param service_id: Provide the service id you want to call (e.g., pipedrive). Only needed when a consumer has activated multiple integrations for a Unified API.
        :param po_number: A PO Number uniquely identifies a purchase order and is generally defined by the buyer.
        :param reference: Optional purchase order reference.
        :param supplier: The supplier this entity is linked to.
        :param company_id: The company or subsidiary id the transaction belongs to
        :param status:
        :param issued_date: Date purchase order was issued - YYYY-MM-DD.
        :param delivery_date: The date on which the purchase order is to be delivered - YYYY-MM-DD.
        :param expected_arrival_date: The date on which the order is expected to arrive - YYYY-MM-DD.
        :param currency: Indicates the associated currency for an amount of money. Values correspond to [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217).
        :param currency_rate: Currency Exchange Rate at the time entity was recorded/generated.
        :param sub_total: Sub-total amount, normally before tax.
        :param total_tax: Total tax amount applied to this invoice.
        :param total: Total amount of invoice, including tax.
        :param tax_inclusive: Amounts are including tax
        :param line_items:
        :param shipping_address:
        :param ledger_account:
        :param template_id: Optional purchase order template
        :param discount_percentage: Discount percentage applied to this transaction.
        :param bank_account:
        :param accounting_by_row: Indicates if accounting by row is used (true) or not (false). Accounting by row means that a separate ledger transaction is created for each row.
        :param due_date: The due date is the date on which a payment is scheduled to be received - YYYY-MM-DD.
        :param payment_method: Payment method used for the transaction, such as cash, credit card, bank transfer, or check
        :param tax_code: Applicable tax id/code override if tax is not supplied on a line item basis.
        :param channel: The channel through which the transaction is processed.
        :param memo: Message for the supplier. This text appears on the Purchase Order.
        :param tracking_categories: A list of linked tracking categories.
        :param row_version: 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.
        :param pass_through: The pass_through property allows passing service-specific, custom data or structured modifications in request body when creating or updating resources.
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url

        request = models.AccountingPurchaseOrdersAddRequest(
            raw=raw,
            service_id=service_id,
            purchase_order=models.PurchaseOrderInput(
                po_number=po_number,
                reference=reference,
                supplier=utils.get_pydantic_model(
                    supplier, OptionalNullable[models.LinkedSupplierInput]
                ),
                company_id=company_id,
                status=status,
                issued_date=issued_date,
                delivery_date=delivery_date,
                expected_arrival_date=expected_arrival_date,
                currency=currency,
                currency_rate=currency_rate,
                sub_total=sub_total,
                total_tax=total_tax,
                total=total,
                tax_inclusive=tax_inclusive,
                line_items=utils.get_pydantic_model(
                    line_items, Optional[List[models.InvoiceLineItemInput]]
                ),
                shipping_address=utils.get_pydantic_model(
                    shipping_address, Optional[models.Address]
                ),
                ledger_account=utils.get_pydantic_model(
                    ledger_account, OptionalNullable[models.LinkedLedgerAccountInput]
                ),
                template_id=template_id,
                discount_percentage=discount_percentage,
                bank_account=utils.get_pydantic_model(
                    bank_account, Optional[models.BankAccount]
                ),
                accounting_by_row=accounting_by_row,
                due_date=due_date,
                payment_method=payment_method,
                tax_code=tax_code,
                channel=channel,
                memo=memo,
                tracking_categories=utils.get_pydantic_model(
                    tracking_categories,
                    OptionalNullable[List[models.LinkedTrackingCategory]],
                ),
                row_version=row_version,
                pass_through=utils.get_pydantic_model(
                    pass_through, Optional[List[models.PassThroughBody]]
                ),
            ),
        )

        req = self._build_request(
            method="POST",
            path="/accounting/purchase-orders",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=True,
            request_has_path_params=False,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            _globals=models.AccountingPurchaseOrdersAddGlobals(
                consumer_id=self.sdk_configuration.globals.consumer_id,
                app_id=self.sdk_configuration.globals.app_id,
            ),
            security=self.sdk_configuration.security,
            get_serialized_body=lambda: utils.serialize_request_body(
                request.purchase_order, False, False, "json", models.PurchaseOrderInput
            ),
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config
            else:
                retries = utils.RetryConfig(
                    "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
                )

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["5XX"])

        http_res = self.do_request(
            hook_ctx=HookContext(
                operation_id="accounting.purchaseOrdersAdd",
                oauth2_scopes=[],
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["400", "401", "402", "404", "422", "4XX", "5XX"],
            retry_config=retry_config,
        )

        data: Any = None
        if utils.match_response(http_res, "201", "application/json"):
            return models.AccountingPurchaseOrdersAddResponse(
                create_purchase_order_response=utils.unmarshal_json(
                    http_res.text, Optional[models.CreatePurchaseOrderResponse]
                ),
                http_meta=models.HTTPMetadata(request=req, response=http_res),
            )
        if utils.match_response(http_res, "400", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.BadRequestResponseData)
            raise models.BadRequestResponse(data=data)
        if utils.match_response(http_res, "401", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.UnauthorizedResponseData)
            raise models.UnauthorizedResponse(data=data)
        if utils.match_response(http_res, "402", "application/json"):
            data = utils.unmarshal_json(
                http_res.text, models.PaymentRequiredResponseData
            )
            raise models.PaymentRequiredResponse(data=data)
        if utils.match_response(http_res, "404", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.NotFoundResponseData)
            raise models.NotFoundResponse(data=data)
        if utils.match_response(http_res, "422", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.UnprocessableResponseData)
            raise models.UnprocessableResponse(data=data)
        if utils.match_response(http_res, ["4XX", "5XX"], "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise models.APIError(
                "API error occurred", http_res.status_code, http_res_text, http_res
            )
        if utils.match_response(http_res, "default", "application/json"):
            return models.AccountingPurchaseOrdersAddResponse(
                unexpected_error_response=utils.unmarshal_json(
                    http_res.text, Optional[models.UnexpectedErrorResponse]
                ),
                http_meta=models.HTTPMetadata(request=req, response=http_res),
            )

        content_type = http_res.headers.get("Content-Type")
        http_res_text = utils.stream_to_text(http_res)
        raise models.APIError(
            f"Unexpected response received (code: {http_res.status_code}, type: {content_type})",
            http_res.status_code,
            http_res_text,
            http_res,
        )

    async def create_async(
        self,
        *,
        raw: Optional[bool] = False,
        service_id: Optional[str] = None,
        po_number: OptionalNullable[str] = UNSET,
        reference: OptionalNullable[str] = UNSET,
        supplier: OptionalNullable[
            Union[models.LinkedSupplierInput, models.LinkedSupplierInputTypedDict]
        ] = UNSET,
        company_id: OptionalNullable[str] = UNSET,
        status: OptionalNullable[models.PurchaseOrderStatus] = UNSET,
        issued_date: OptionalNullable[date] = UNSET,
        delivery_date: OptionalNullable[date] = UNSET,
        expected_arrival_date: OptionalNullable[date] = UNSET,
        currency: OptionalNullable[models.Currency] = UNSET,
        currency_rate: OptionalNullable[float] = UNSET,
        sub_total: OptionalNullable[float] = UNSET,
        total_tax: OptionalNullable[float] = UNSET,
        total: OptionalNullable[float] = UNSET,
        tax_inclusive: OptionalNullable[bool] = UNSET,
        line_items: Optional[
            Union[
                List[models.InvoiceLineItemInput],
                List[models.InvoiceLineItemInputTypedDict],
            ]
        ] = None,
        shipping_address: Optional[
            Union[models.Address, models.AddressTypedDict]
        ] = None,
        ledger_account: OptionalNullable[
            Union[
                models.LinkedLedgerAccountInput,
                models.LinkedLedgerAccountInputTypedDict,
            ]
        ] = UNSET,
        template_id: OptionalNullable[str] = UNSET,
        discount_percentage: OptionalNullable[float] = UNSET,
        bank_account: Optional[
            Union[models.BankAccount, models.BankAccountTypedDict]
        ] = None,
        accounting_by_row: OptionalNullable[bool] = UNSET,
        due_date: OptionalNullable[date] = UNSET,
        payment_method: OptionalNullable[str] = UNSET,
        tax_code: OptionalNullable[str] = UNSET,
        channel: OptionalNullable[str] = UNSET,
        memo: OptionalNullable[str] = UNSET,
        tracking_categories: OptionalNullable[
            Union[
                List[models.LinkedTrackingCategory],
                List[models.LinkedTrackingCategoryTypedDict],
            ]
        ] = UNSET,
        row_version: OptionalNullable[str] = UNSET,
        pass_through: Optional[
            Union[List[models.PassThroughBody], List[models.PassThroughBodyTypedDict]]
        ] = None,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.AccountingPurchaseOrdersAddResponse:
        r"""Create Purchase Order

        Create Purchase Order

        :param raw: Include raw response. Mostly used for debugging purposes
        :param service_id: Provide the service id you want to call (e.g., pipedrive). Only needed when a consumer has activated multiple integrations for a Unified API.
        :param po_number: A PO Number uniquely identifies a purchase order and is generally defined by the buyer.
        :param reference: Optional purchase order reference.
        :param supplier: The supplier this entity is linked to.
        :param company_id: The company or subsidiary id the transaction belongs to
        :param status:
        :param issued_date: Date purchase order was issued - YYYY-MM-DD.
        :param delivery_date: The date on which the purchase order is to be delivered - YYYY-MM-DD.
        :param expected_arrival_date: The date on which the order is expected to arrive - YYYY-MM-DD.
        :param currency: Indicates the associated currency for an amount of money. Values correspond to [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217).
        :param currency_rate: Currency Exchange Rate at the time entity was recorded/generated.
        :param sub_total: Sub-total amount, normally before tax.
        :param total_tax: Total tax amount applied to this invoice.
        :param total: Total amount of invoice, including tax.
        :param tax_inclusive: Amounts are including tax
        :param line_items:
        :param shipping_address:
        :param ledger_account:
        :param template_id: Optional purchase order template
        :param discount_percentage: Discount percentage applied to this transaction.
        :param bank_account:
        :param accounting_by_row: Indicates if accounting by row is used (true) or not (false). Accounting by row means that a separate ledger transaction is created for each row.
        :param due_date: The due date is the date on which a payment is scheduled to be received - YYYY-MM-DD.
        :param payment_method: Payment method used for the transaction, such as cash, credit card, bank transfer, or check
        :param tax_code: Applicable tax id/code override if tax is not supplied on a line item basis.
        :param channel: The channel through which the transaction is processed.
        :param memo: Message for the supplier. This text appears on the Purchase Order.
        :param tracking_categories: A list of linked tracking categories.
        :param row_version: 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.
        :param pass_through: The pass_through property allows passing service-specific, custom data or structured modifications in request body when creating or updating resources.
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url

        request = models.AccountingPurchaseOrdersAddRequest(
            raw=raw,
            service_id=service_id,
            purchase_order=models.PurchaseOrderInput(
                po_number=po_number,
                reference=reference,
                supplier=utils.get_pydantic_model(
                    supplier, OptionalNullable[models.LinkedSupplierInput]
                ),
                company_id=company_id,
                status=status,
                issued_date=issued_date,
                delivery_date=delivery_date,
                expected_arrival_date=expected_arrival_date,
                currency=currency,
                currency_rate=currency_rate,
                sub_total=sub_total,
                total_tax=total_tax,
                total=total,
                tax_inclusive=tax_inclusive,
                line_items=utils.get_pydantic_model(
                    line_items, Optional[List[models.InvoiceLineItemInput]]
                ),
                shipping_address=utils.get_pydantic_model(
                    shipping_address, Optional[models.Address]
                ),
                ledger_account=utils.get_pydantic_model(
                    ledger_account, OptionalNullable[models.LinkedLedgerAccountInput]
                ),
                template_id=template_id,
                discount_percentage=discount_percentage,
                bank_account=utils.get_pydantic_model(
                    bank_account, Optional[models.BankAccount]
                ),
                accounting_by_row=accounting_by_row,
                due_date=due_date,
                payment_method=payment_method,
                tax_code=tax_code,
                channel=channel,
                memo=memo,
                tracking_categories=utils.get_pydantic_model(
                    tracking_categories,
                    OptionalNullable[List[models.LinkedTrackingCategory]],
                ),
                row_version=row_version,
                pass_through=utils.get_pydantic_model(
                    pass_through, Optional[List[models.PassThroughBody]]
                ),
            ),
        )

        req = self._build_request_async(
            method="POST",
            path="/accounting/purchase-orders",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=True,
            request_has_path_params=False,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            _globals=models.AccountingPurchaseOrdersAddGlobals(
                consumer_id=self.sdk_configuration.globals.consumer_id,
                app_id=self.sdk_configuration.globals.app_id,
            ),
            security=self.sdk_configuration.security,
            get_serialized_body=lambda: utils.serialize_request_body(
                request.purchase_order, False, False, "json", models.PurchaseOrderInput
            ),
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config
            else:
                retries = utils.RetryConfig(
                    "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
                )

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["5XX"])

        http_res = await self.do_request_async(
            hook_ctx=HookContext(
                operation_id="accounting.purchaseOrdersAdd",
                oauth2_scopes=[],
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["400", "401", "402", "404", "422", "4XX", "5XX"],
            retry_config=retry_config,
        )

        data: Any = None
        if utils.match_response(http_res, "201", "application/json"):
            return models.AccountingPurchaseOrdersAddResponse(
                create_purchase_order_response=utils.unmarshal_json(
                    http_res.text, Optional[models.CreatePurchaseOrderResponse]
                ),
                http_meta=models.HTTPMetadata(request=req, response=http_res),
            )
        if utils.match_response(http_res, "400", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.BadRequestResponseData)
            raise models.BadRequestResponse(data=data)
        if utils.match_response(http_res, "401", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.UnauthorizedResponseData)
            raise models.UnauthorizedResponse(data=data)
        if utils.match_response(http_res, "402", "application/json"):
            data = utils.unmarshal_json(
                http_res.text, models.PaymentRequiredResponseData
            )
            raise models.PaymentRequiredResponse(data=data)
        if utils.match_response(http_res, "404", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.NotFoundResponseData)
            raise models.NotFoundResponse(data=data)
        if utils.match_response(http_res, "422", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.UnprocessableResponseData)
            raise models.UnprocessableResponse(data=data)
        if utils.match_response(http_res, ["4XX", "5XX"], "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise models.APIError(
                "API error occurred", http_res.status_code, http_res_text, http_res
            )
        if utils.match_response(http_res, "default", "application/json"):
            return models.AccountingPurchaseOrdersAddResponse(
                unexpected_error_response=utils.unmarshal_json(
                    http_res.text, Optional[models.UnexpectedErrorResponse]
                ),
                http_meta=models.HTTPMetadata(request=req, response=http_res),
            )

        content_type = http_res.headers.get("Content-Type")
        http_res_text = await utils.stream_to_text_async(http_res)
        raise models.APIError(
            f"Unexpected response received (code: {http_res.status_code}, type: {content_type})",
            http_res.status_code,
            http_res_text,
            http_res,
        )

    def get(
        self,
        *,
        id: str,
        service_id: Optional[str] = None,
        raw: Optional[bool] = False,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.AccountingPurchaseOrdersOneResponse:
        r"""Get Purchase Order

        Get Purchase Order

        :param id: ID of the record you are acting upon.
        :param service_id: Provide the service id you want to call (e.g., pipedrive). Only needed when a consumer has activated multiple integrations for a Unified API.
        :param raw: Include raw response. Mostly used for debugging purposes
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url

        request = models.AccountingPurchaseOrdersOneRequest(
            id=id,
            service_id=service_id,
            raw=raw,
        )

        req = self._build_request(
            method="GET",
            path="/accounting/purchase-orders/{id}",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=False,
            request_has_path_params=True,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            _globals=models.AccountingPurchaseOrdersOneGlobals(
                consumer_id=self.sdk_configuration.globals.consumer_id,
                app_id=self.sdk_configuration.globals.app_id,
            ),
            security=self.sdk_configuration.security,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config
            else:
                retries = utils.RetryConfig(
                    "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
                )

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["5XX"])

        http_res = self.do_request(
            hook_ctx=HookContext(
                operation_id="accounting.purchaseOrdersOne",
                oauth2_scopes=[],
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["400", "401", "402", "404", "422", "4XX", "5XX"],
            retry_config=retry_config,
        )

        data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return models.AccountingPurchaseOrdersOneResponse(
                get_purchase_order_response=utils.unmarshal_json(
                    http_res.text, Optional[models.GetPurchaseOrderResponse]
                ),
                http_meta=models.HTTPMetadata(request=req, response=http_res),
            )
        if utils.match_response(http_res, "400", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.BadRequestResponseData)
            raise models.BadRequestResponse(data=data)
        if utils.match_response(http_res, "401", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.UnauthorizedResponseData)
            raise models.UnauthorizedResponse(data=data)
        if utils.match_response(http_res, "402", "application/json"):
            data = utils.unmarshal_json(
                http_res.text, models.PaymentRequiredResponseData
            )
            raise models.PaymentRequiredResponse(data=data)
        if utils.match_response(http_res, "404", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.NotFoundResponseData)
            raise models.NotFoundResponse(data=data)
        if utils.match_response(http_res, "422", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.UnprocessableResponseData)
            raise models.UnprocessableResponse(data=data)
        if utils.match_response(http_res, ["4XX", "5XX"], "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise models.APIError(
                "API error occurred", http_res.status_code, http_res_text, http_res
            )
        if utils.match_response(http_res, "default", "application/json"):
            return models.AccountingPurchaseOrdersOneResponse(
                unexpected_error_response=utils.unmarshal_json(
                    http_res.text, Optional[models.UnexpectedErrorResponse]
                ),
                http_meta=models.HTTPMetadata(request=req, response=http_res),
            )

        content_type = http_res.headers.get("Content-Type")
        http_res_text = utils.stream_to_text(http_res)
        raise models.APIError(
            f"Unexpected response received (code: {http_res.status_code}, type: {content_type})",
            http_res.status_code,
            http_res_text,
            http_res,
        )

    async def get_async(
        self,
        *,
        id: str,
        service_id: Optional[str] = None,
        raw: Optional[bool] = False,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.AccountingPurchaseOrdersOneResponse:
        r"""Get Purchase Order

        Get Purchase Order

        :param id: ID of the record you are acting upon.
        :param service_id: Provide the service id you want to call (e.g., pipedrive). Only needed when a consumer has activated multiple integrations for a Unified API.
        :param raw: Include raw response. Mostly used for debugging purposes
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url

        request = models.AccountingPurchaseOrdersOneRequest(
            id=id,
            service_id=service_id,
            raw=raw,
        )

        req = self._build_request_async(
            method="GET",
            path="/accounting/purchase-orders/{id}",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=False,
            request_has_path_params=True,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            _globals=models.AccountingPurchaseOrdersOneGlobals(
                consumer_id=self.sdk_configuration.globals.consumer_id,
                app_id=self.sdk_configuration.globals.app_id,
            ),
            security=self.sdk_configuration.security,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config
            else:
                retries = utils.RetryConfig(
                    "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
                )

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["5XX"])

        http_res = await self.do_request_async(
            hook_ctx=HookContext(
                operation_id="accounting.purchaseOrdersOne",
                oauth2_scopes=[],
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["400", "401", "402", "404", "422", "4XX", "5XX"],
            retry_config=retry_config,
        )

        data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return models.AccountingPurchaseOrdersOneResponse(
                get_purchase_order_response=utils.unmarshal_json(
                    http_res.text, Optional[models.GetPurchaseOrderResponse]
                ),
                http_meta=models.HTTPMetadata(request=req, response=http_res),
            )
        if utils.match_response(http_res, "400", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.BadRequestResponseData)
            raise models.BadRequestResponse(data=data)
        if utils.match_response(http_res, "401", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.UnauthorizedResponseData)
            raise models.UnauthorizedResponse(data=data)
        if utils.match_response(http_res, "402", "application/json"):
            data = utils.unmarshal_json(
                http_res.text, models.PaymentRequiredResponseData
            )
            raise models.PaymentRequiredResponse(data=data)
        if utils.match_response(http_res, "404", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.NotFoundResponseData)
            raise models.NotFoundResponse(data=data)
        if utils.match_response(http_res, "422", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.UnprocessableResponseData)
            raise models.UnprocessableResponse(data=data)
        if utils.match_response(http_res, ["4XX", "5XX"], "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise models.APIError(
                "API error occurred", http_res.status_code, http_res_text, http_res
            )
        if utils.match_response(http_res, "default", "application/json"):
            return models.AccountingPurchaseOrdersOneResponse(
                unexpected_error_response=utils.unmarshal_json(
                    http_res.text, Optional[models.UnexpectedErrorResponse]
                ),
                http_meta=models.HTTPMetadata(request=req, response=http_res),
            )

        content_type = http_res.headers.get("Content-Type")
        http_res_text = await utils.stream_to_text_async(http_res)
        raise models.APIError(
            f"Unexpected response received (code: {http_res.status_code}, type: {content_type})",
            http_res.status_code,
            http_res_text,
            http_res,
        )

    def update(
        self,
        *,
        id: str,
        service_id: Optional[str] = None,
        raw: Optional[bool] = False,
        po_number: OptionalNullable[str] = UNSET,
        reference: OptionalNullable[str] = UNSET,
        supplier: OptionalNullable[
            Union[models.LinkedSupplierInput, models.LinkedSupplierInputTypedDict]
        ] = UNSET,
        company_id: OptionalNullable[str] = UNSET,
        status: OptionalNullable[models.PurchaseOrderStatus] = UNSET,
        issued_date: OptionalNullable[date] = UNSET,
        delivery_date: OptionalNullable[date] = UNSET,
        expected_arrival_date: OptionalNullable[date] = UNSET,
        currency: OptionalNullable[models.Currency] = UNSET,
        currency_rate: OptionalNullable[float] = UNSET,
        sub_total: OptionalNullable[float] = UNSET,
        total_tax: OptionalNullable[float] = UNSET,
        total: OptionalNullable[float] = UNSET,
        tax_inclusive: OptionalNullable[bool] = UNSET,
        line_items: Optional[
            Union[
                List[models.InvoiceLineItemInput],
                List[models.InvoiceLineItemInputTypedDict],
            ]
        ] = None,
        shipping_address: Optional[
            Union[models.Address, models.AddressTypedDict]
        ] = None,
        ledger_account: OptionalNullable[
            Union[
                models.LinkedLedgerAccountInput,
                models.LinkedLedgerAccountInputTypedDict,
            ]
        ] = UNSET,
        template_id: OptionalNullable[str] = UNSET,
        discount_percentage: OptionalNullable[float] = UNSET,
        bank_account: Optional[
            Union[models.BankAccount, models.BankAccountTypedDict]
        ] = None,
        accounting_by_row: OptionalNullable[bool] = UNSET,
        due_date: OptionalNullable[date] = UNSET,
        payment_method: OptionalNullable[str] = UNSET,
        tax_code: OptionalNullable[str] = UNSET,
        channel: OptionalNullable[str] = UNSET,
        memo: OptionalNullable[str] = UNSET,
        tracking_categories: OptionalNullable[
            Union[
                List[models.LinkedTrackingCategory],
                List[models.LinkedTrackingCategoryTypedDict],
            ]
        ] = UNSET,
        row_version: OptionalNullable[str] = UNSET,
        pass_through: Optional[
            Union[List[models.PassThroughBody], List[models.PassThroughBodyTypedDict]]
        ] = None,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.AccountingPurchaseOrdersUpdateResponse:
        r"""Update Purchase Order

        Update Purchase Order

        :param id: ID of the record you are acting upon.
        :param service_id: Provide the service id you want to call (e.g., pipedrive). Only needed when a consumer has activated multiple integrations for a Unified API.
        :param raw: Include raw response. Mostly used for debugging purposes
        :param po_number: A PO Number uniquely identifies a purchase order and is generally defined by the buyer.
        :param reference: Optional purchase order reference.
        :param supplier: The supplier this entity is linked to.
        :param company_id: The company or subsidiary id the transaction belongs to
        :param status:
        :param issued_date: Date purchase order was issued - YYYY-MM-DD.
        :param delivery_date: The date on which the purchase order is to be delivered - YYYY-MM-DD.
        :param expected_arrival_date: The date on which the order is expected to arrive - YYYY-MM-DD.
        :param currency: Indicates the associated currency for an amount of money. Values correspond to [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217).
        :param currency_rate: Currency Exchange Rate at the time entity was recorded/generated.
        :param sub_total: Sub-total amount, normally before tax.
        :param total_tax: Total tax amount applied to this invoice.
        :param total: Total amount of invoice, including tax.
        :param tax_inclusive: Amounts are including tax
        :param line_items:
        :param shipping_address:
        :param ledger_account:
        :param template_id: Optional purchase order template
        :param discount_percentage: Discount percentage applied to this transaction.
        :param bank_account:
        :param accounting_by_row: Indicates if accounting by row is used (true) or not (false). Accounting by row means that a separate ledger transaction is created for each row.
        :param due_date: The due date is the date on which a payment is scheduled to be received - YYYY-MM-DD.
        :param payment_method: Payment method used for the transaction, such as cash, credit card, bank transfer, or check
        :param tax_code: Applicable tax id/code override if tax is not supplied on a line item basis.
        :param channel: The channel through which the transaction is processed.
        :param memo: Message for the supplier. This text appears on the Purchase Order.
        :param tracking_categories: A list of linked tracking categories.
        :param row_version: 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.
        :param pass_through: The pass_through property allows passing service-specific, custom data or structured modifications in request body when creating or updating resources.
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url

        request = models.AccountingPurchaseOrdersUpdateRequest(
            id=id,
            service_id=service_id,
            raw=raw,
            purchase_order=models.PurchaseOrderInput(
                po_number=po_number,
                reference=reference,
                supplier=utils.get_pydantic_model(
                    supplier, OptionalNullable[models.LinkedSupplierInput]
                ),
                company_id=company_id,
                status=status,
                issued_date=issued_date,
                delivery_date=delivery_date,
                expected_arrival_date=expected_arrival_date,
                currency=currency,
                currency_rate=currency_rate,
                sub_total=sub_total,
                total_tax=total_tax,
                total=total,
                tax_inclusive=tax_inclusive,
                line_items=utils.get_pydantic_model(
                    line_items, Optional[List[models.InvoiceLineItemInput]]
                ),
                shipping_address=utils.get_pydantic_model(
                    shipping_address, Optional[models.Address]
                ),
                ledger_account=utils.get_pydantic_model(
                    ledger_account, OptionalNullable[models.LinkedLedgerAccountInput]
                ),
                template_id=template_id,
                discount_percentage=discount_percentage,
                bank_account=utils.get_pydantic_model(
                    bank_account, Optional[models.BankAccount]
                ),
                accounting_by_row=accounting_by_row,
                due_date=due_date,
                payment_method=payment_method,
                tax_code=tax_code,
                channel=channel,
                memo=memo,
                tracking_categories=utils.get_pydantic_model(
                    tracking_categories,
                    OptionalNullable[List[models.LinkedTrackingCategory]],
                ),
                row_version=row_version,
                pass_through=utils.get_pydantic_model(
                    pass_through, Optional[List[models.PassThroughBody]]
                ),
            ),
        )

        req = self._build_request(
            method="PATCH",
            path="/accounting/purchase-orders/{id}",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=True,
            request_has_path_params=True,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            _globals=models.AccountingPurchaseOrdersUpdateGlobals(
                consumer_id=self.sdk_configuration.globals.consumer_id,
                app_id=self.sdk_configuration.globals.app_id,
            ),
            security=self.sdk_configuration.security,
            get_serialized_body=lambda: utils.serialize_request_body(
                request.purchase_order, False, False, "json", models.PurchaseOrderInput
            ),
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config
            else:
                retries = utils.RetryConfig(
                    "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
                )

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["5XX"])

        http_res = self.do_request(
            hook_ctx=HookContext(
                operation_id="accounting.purchaseOrdersUpdate",
                oauth2_scopes=[],
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["400", "401", "402", "404", "422", "4XX", "5XX"],
            retry_config=retry_config,
        )

        data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return models.AccountingPurchaseOrdersUpdateResponse(
                update_purchase_order_response=utils.unmarshal_json(
                    http_res.text, Optional[models.UpdatePurchaseOrderResponse]
                ),
                http_meta=models.HTTPMetadata(request=req, response=http_res),
            )
        if utils.match_response(http_res, "400", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.BadRequestResponseData)
            raise models.BadRequestResponse(data=data)
        if utils.match_response(http_res, "401", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.UnauthorizedResponseData)
            raise models.UnauthorizedResponse(data=data)
        if utils.match_response(http_res, "402", "application/json"):
            data = utils.unmarshal_json(
                http_res.text, models.PaymentRequiredResponseData
            )
            raise models.PaymentRequiredResponse(data=data)
        if utils.match_response(http_res, "404", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.NotFoundResponseData)
            raise models.NotFoundResponse(data=data)
        if utils.match_response(http_res, "422", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.UnprocessableResponseData)
            raise models.UnprocessableResponse(data=data)
        if utils.match_response(http_res, ["4XX", "5XX"], "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise models.APIError(
                "API error occurred", http_res.status_code, http_res_text, http_res
            )
        if utils.match_response(http_res, "default", "application/json"):
            return models.AccountingPurchaseOrdersUpdateResponse(
                unexpected_error_response=utils.unmarshal_json(
                    http_res.text, Optional[models.UnexpectedErrorResponse]
                ),
                http_meta=models.HTTPMetadata(request=req, response=http_res),
            )

        content_type = http_res.headers.get("Content-Type")
        http_res_text = utils.stream_to_text(http_res)
        raise models.APIError(
            f"Unexpected response received (code: {http_res.status_code}, type: {content_type})",
            http_res.status_code,
            http_res_text,
            http_res,
        )

    async def update_async(
        self,
        *,
        id: str,
        service_id: Optional[str] = None,
        raw: Optional[bool] = False,
        po_number: OptionalNullable[str] = UNSET,
        reference: OptionalNullable[str] = UNSET,
        supplier: OptionalNullable[
            Union[models.LinkedSupplierInput, models.LinkedSupplierInputTypedDict]
        ] = UNSET,
        company_id: OptionalNullable[str] = UNSET,
        status: OptionalNullable[models.PurchaseOrderStatus] = UNSET,
        issued_date: OptionalNullable[date] = UNSET,
        delivery_date: OptionalNullable[date] = UNSET,
        expected_arrival_date: OptionalNullable[date] = UNSET,
        currency: OptionalNullable[models.Currency] = UNSET,
        currency_rate: OptionalNullable[float] = UNSET,
        sub_total: OptionalNullable[float] = UNSET,
        total_tax: OptionalNullable[float] = UNSET,
        total: OptionalNullable[float] = UNSET,
        tax_inclusive: OptionalNullable[bool] = UNSET,
        line_items: Optional[
            Union[
                List[models.InvoiceLineItemInput],
                List[models.InvoiceLineItemInputTypedDict],
            ]
        ] = None,
        shipping_address: Optional[
            Union[models.Address, models.AddressTypedDict]
        ] = None,
        ledger_account: OptionalNullable[
            Union[
                models.LinkedLedgerAccountInput,
                models.LinkedLedgerAccountInputTypedDict,
            ]
        ] = UNSET,
        template_id: OptionalNullable[str] = UNSET,
        discount_percentage: OptionalNullable[float] = UNSET,
        bank_account: Optional[
            Union[models.BankAccount, models.BankAccountTypedDict]
        ] = None,
        accounting_by_row: OptionalNullable[bool] = UNSET,
        due_date: OptionalNullable[date] = UNSET,
        payment_method: OptionalNullable[str] = UNSET,
        tax_code: OptionalNullable[str] = UNSET,
        channel: OptionalNullable[str] = UNSET,
        memo: OptionalNullable[str] = UNSET,
        tracking_categories: OptionalNullable[
            Union[
                List[models.LinkedTrackingCategory],
                List[models.LinkedTrackingCategoryTypedDict],
            ]
        ] = UNSET,
        row_version: OptionalNullable[str] = UNSET,
        pass_through: Optional[
            Union[List[models.PassThroughBody], List[models.PassThroughBodyTypedDict]]
        ] = None,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.AccountingPurchaseOrdersUpdateResponse:
        r"""Update Purchase Order

        Update Purchase Order

        :param id: ID of the record you are acting upon.
        :param service_id: Provide the service id you want to call (e.g., pipedrive). Only needed when a consumer has activated multiple integrations for a Unified API.
        :param raw: Include raw response. Mostly used for debugging purposes
        :param po_number: A PO Number uniquely identifies a purchase order and is generally defined by the buyer.
        :param reference: Optional purchase order reference.
        :param supplier: The supplier this entity is linked to.
        :param company_id: The company or subsidiary id the transaction belongs to
        :param status:
        :param issued_date: Date purchase order was issued - YYYY-MM-DD.
        :param delivery_date: The date on which the purchase order is to be delivered - YYYY-MM-DD.
        :param expected_arrival_date: The date on which the order is expected to arrive - YYYY-MM-DD.
        :param currency: Indicates the associated currency for an amount of money. Values correspond to [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217).
        :param currency_rate: Currency Exchange Rate at the time entity was recorded/generated.
        :param sub_total: Sub-total amount, normally before tax.
        :param total_tax: Total tax amount applied to this invoice.
        :param total: Total amount of invoice, including tax.
        :param tax_inclusive: Amounts are including tax
        :param line_items:
        :param shipping_address:
        :param ledger_account:
        :param template_id: Optional purchase order template
        :param discount_percentage: Discount percentage applied to this transaction.
        :param bank_account:
        :param accounting_by_row: Indicates if accounting by row is used (true) or not (false). Accounting by row means that a separate ledger transaction is created for each row.
        :param due_date: The due date is the date on which a payment is scheduled to be received - YYYY-MM-DD.
        :param payment_method: Payment method used for the transaction, such as cash, credit card, bank transfer, or check
        :param tax_code: Applicable tax id/code override if tax is not supplied on a line item basis.
        :param channel: The channel through which the transaction is processed.
        :param memo: Message for the supplier. This text appears on the Purchase Order.
        :param tracking_categories: A list of linked tracking categories.
        :param row_version: 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.
        :param pass_through: The pass_through property allows passing service-specific, custom data or structured modifications in request body when creating or updating resources.
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url

        request = models.AccountingPurchaseOrdersUpdateRequest(
            id=id,
            service_id=service_id,
            raw=raw,
            purchase_order=models.PurchaseOrderInput(
                po_number=po_number,
                reference=reference,
                supplier=utils.get_pydantic_model(
                    supplier, OptionalNullable[models.LinkedSupplierInput]
                ),
                company_id=company_id,
                status=status,
                issued_date=issued_date,
                delivery_date=delivery_date,
                expected_arrival_date=expected_arrival_date,
                currency=currency,
                currency_rate=currency_rate,
                sub_total=sub_total,
                total_tax=total_tax,
                total=total,
                tax_inclusive=tax_inclusive,
                line_items=utils.get_pydantic_model(
                    line_items, Optional[List[models.InvoiceLineItemInput]]
                ),
                shipping_address=utils.get_pydantic_model(
                    shipping_address, Optional[models.Address]
                ),
                ledger_account=utils.get_pydantic_model(
                    ledger_account, OptionalNullable[models.LinkedLedgerAccountInput]
                ),
                template_id=template_id,
                discount_percentage=discount_percentage,
                bank_account=utils.get_pydantic_model(
                    bank_account, Optional[models.BankAccount]
                ),
                accounting_by_row=accounting_by_row,
                due_date=due_date,
                payment_method=payment_method,
                tax_code=tax_code,
                channel=channel,
                memo=memo,
                tracking_categories=utils.get_pydantic_model(
                    tracking_categories,
                    OptionalNullable[List[models.LinkedTrackingCategory]],
                ),
                row_version=row_version,
                pass_through=utils.get_pydantic_model(
                    pass_through, Optional[List[models.PassThroughBody]]
                ),
            ),
        )

        req = self._build_request_async(
            method="PATCH",
            path="/accounting/purchase-orders/{id}",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=True,
            request_has_path_params=True,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            _globals=models.AccountingPurchaseOrdersUpdateGlobals(
                consumer_id=self.sdk_configuration.globals.consumer_id,
                app_id=self.sdk_configuration.globals.app_id,
            ),
            security=self.sdk_configuration.security,
            get_serialized_body=lambda: utils.serialize_request_body(
                request.purchase_order, False, False, "json", models.PurchaseOrderInput
            ),
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config
            else:
                retries = utils.RetryConfig(
                    "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
                )

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["5XX"])

        http_res = await self.do_request_async(
            hook_ctx=HookContext(
                operation_id="accounting.purchaseOrdersUpdate",
                oauth2_scopes=[],
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["400", "401", "402", "404", "422", "4XX", "5XX"],
            retry_config=retry_config,
        )

        data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return models.AccountingPurchaseOrdersUpdateResponse(
                update_purchase_order_response=utils.unmarshal_json(
                    http_res.text, Optional[models.UpdatePurchaseOrderResponse]
                ),
                http_meta=models.HTTPMetadata(request=req, response=http_res),
            )
        if utils.match_response(http_res, "400", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.BadRequestResponseData)
            raise models.BadRequestResponse(data=data)
        if utils.match_response(http_res, "401", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.UnauthorizedResponseData)
            raise models.UnauthorizedResponse(data=data)
        if utils.match_response(http_res, "402", "application/json"):
            data = utils.unmarshal_json(
                http_res.text, models.PaymentRequiredResponseData
            )
            raise models.PaymentRequiredResponse(data=data)
        if utils.match_response(http_res, "404", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.NotFoundResponseData)
            raise models.NotFoundResponse(data=data)
        if utils.match_response(http_res, "422", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.UnprocessableResponseData)
            raise models.UnprocessableResponse(data=data)
        if utils.match_response(http_res, ["4XX", "5XX"], "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise models.APIError(
                "API error occurred", http_res.status_code, http_res_text, http_res
            )
        if utils.match_response(http_res, "default", "application/json"):
            return models.AccountingPurchaseOrdersUpdateResponse(
                unexpected_error_response=utils.unmarshal_json(
                    http_res.text, Optional[models.UnexpectedErrorResponse]
                ),
                http_meta=models.HTTPMetadata(request=req, response=http_res),
            )

        content_type = http_res.headers.get("Content-Type")
        http_res_text = await utils.stream_to_text_async(http_res)
        raise models.APIError(
            f"Unexpected response received (code: {http_res.status_code}, type: {content_type})",
            http_res.status_code,
            http_res_text,
            http_res,
        )

    def delete(
        self,
        *,
        id: str,
        service_id: Optional[str] = None,
        raw: Optional[bool] = False,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.AccountingPurchaseOrdersDeleteResponse:
        r"""Delete Purchase Order

        Delete Purchase Order

        :param id: ID of the record you are acting upon.
        :param service_id: Provide the service id you want to call (e.g., pipedrive). Only needed when a consumer has activated multiple integrations for a Unified API.
        :param raw: Include raw response. Mostly used for debugging purposes
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url

        request = models.AccountingPurchaseOrdersDeleteRequest(
            id=id,
            service_id=service_id,
            raw=raw,
        )

        req = self._build_request(
            method="DELETE",
            path="/accounting/purchase-orders/{id}",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=False,
            request_has_path_params=True,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            _globals=models.AccountingPurchaseOrdersDeleteGlobals(
                consumer_id=self.sdk_configuration.globals.consumer_id,
                app_id=self.sdk_configuration.globals.app_id,
            ),
            security=self.sdk_configuration.security,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config
            else:
                retries = utils.RetryConfig(
                    "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
                )

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["5XX"])

        http_res = self.do_request(
            hook_ctx=HookContext(
                operation_id="accounting.purchaseOrdersDelete",
                oauth2_scopes=[],
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["400", "401", "402", "404", "422", "4XX", "5XX"],
            retry_config=retry_config,
        )

        data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return models.AccountingPurchaseOrdersDeleteResponse(
                delete_purchase_order_response=utils.unmarshal_json(
                    http_res.text, Optional[models.DeletePurchaseOrderResponse]
                ),
                http_meta=models.HTTPMetadata(request=req, response=http_res),
            )
        if utils.match_response(http_res, "400", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.BadRequestResponseData)
            raise models.BadRequestResponse(data=data)
        if utils.match_response(http_res, "401", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.UnauthorizedResponseData)
            raise models.UnauthorizedResponse(data=data)
        if utils.match_response(http_res, "402", "application/json"):
            data = utils.unmarshal_json(
                http_res.text, models.PaymentRequiredResponseData
            )
            raise models.PaymentRequiredResponse(data=data)
        if utils.match_response(http_res, "404", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.NotFoundResponseData)
            raise models.NotFoundResponse(data=data)
        if utils.match_response(http_res, "422", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.UnprocessableResponseData)
            raise models.UnprocessableResponse(data=data)
        if utils.match_response(http_res, ["4XX", "5XX"], "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise models.APIError(
                "API error occurred", http_res.status_code, http_res_text, http_res
            )
        if utils.match_response(http_res, "default", "application/json"):
            return models.AccountingPurchaseOrdersDeleteResponse(
                unexpected_error_response=utils.unmarshal_json(
                    http_res.text, Optional[models.UnexpectedErrorResponse]
                ),
                http_meta=models.HTTPMetadata(request=req, response=http_res),
            )

        content_type = http_res.headers.get("Content-Type")
        http_res_text = utils.stream_to_text(http_res)
        raise models.APIError(
            f"Unexpected response received (code: {http_res.status_code}, type: {content_type})",
            http_res.status_code,
            http_res_text,
            http_res,
        )

    async def delete_async(
        self,
        *,
        id: str,
        service_id: Optional[str] = None,
        raw: Optional[bool] = False,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.AccountingPurchaseOrdersDeleteResponse:
        r"""Delete Purchase Order

        Delete Purchase Order

        :param id: ID of the record you are acting upon.
        :param service_id: Provide the service id you want to call (e.g., pipedrive). Only needed when a consumer has activated multiple integrations for a Unified API.
        :param raw: Include raw response. Mostly used for debugging purposes
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url

        request = models.AccountingPurchaseOrdersDeleteRequest(
            id=id,
            service_id=service_id,
            raw=raw,
        )

        req = self._build_request_async(
            method="DELETE",
            path="/accounting/purchase-orders/{id}",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=False,
            request_has_path_params=True,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            _globals=models.AccountingPurchaseOrdersDeleteGlobals(
                consumer_id=self.sdk_configuration.globals.consumer_id,
                app_id=self.sdk_configuration.globals.app_id,
            ),
            security=self.sdk_configuration.security,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config
            else:
                retries = utils.RetryConfig(
                    "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
                )

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["5XX"])

        http_res = await self.do_request_async(
            hook_ctx=HookContext(
                operation_id="accounting.purchaseOrdersDelete",
                oauth2_scopes=[],
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["400", "401", "402", "404", "422", "4XX", "5XX"],
            retry_config=retry_config,
        )

        data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return models.AccountingPurchaseOrdersDeleteResponse(
                delete_purchase_order_response=utils.unmarshal_json(
                    http_res.text, Optional[models.DeletePurchaseOrderResponse]
                ),
                http_meta=models.HTTPMetadata(request=req, response=http_res),
            )
        if utils.match_response(http_res, "400", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.BadRequestResponseData)
            raise models.BadRequestResponse(data=data)
        if utils.match_response(http_res, "401", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.UnauthorizedResponseData)
            raise models.UnauthorizedResponse(data=data)
        if utils.match_response(http_res, "402", "application/json"):
            data = utils.unmarshal_json(
                http_res.text, models.PaymentRequiredResponseData
            )
            raise models.PaymentRequiredResponse(data=data)
        if utils.match_response(http_res, "404", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.NotFoundResponseData)
            raise models.NotFoundResponse(data=data)
        if utils.match_response(http_res, "422", "application/json"):
            data = utils.unmarshal_json(http_res.text, models.UnprocessableResponseData)
            raise models.UnprocessableResponse(data=data)
        if utils.match_response(http_res, ["4XX", "5XX"], "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise models.APIError(
                "API error occurred", http_res.status_code, http_res_text, http_res
            )
        if utils.match_response(http_res, "default", "application/json"):
            return models.AccountingPurchaseOrdersDeleteResponse(
                unexpected_error_response=utils.unmarshal_json(
                    http_res.text, Optional[models.UnexpectedErrorResponse]
                ),
                http_meta=models.HTTPMetadata(request=req, response=http_res),
            )

        content_type = http_res.headers.get("Content-Type")
        http_res_text = await utils.stream_to_text_async(http_res)
        raise models.APIError(
            f"Unexpected response received (code: {http_res.status_code}, type: {content_type})",
            http_res.status_code,
            http_res_text,
            http_res,
        )
