# This file was auto-generated by Fern from our API Definition.

import typing
from json.decoder import JSONDecodeError

from ..core.api_error import ApiError
from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ..core.http_response import AsyncHttpResponse, HttpResponse
from ..core.jsonable_encoder import jsonable_encoder
from ..core.pydantic_utilities import parse_obj_as
from ..core.request_options import RequestOptions
from ..core.serialization import convert_and_respect_annotation_metadata
from ..errors.bad_request_error import BadRequestError
from ..errors.not_found_error import NotFoundError
from ..errors.unauthorized_error import UnauthorizedError
from ..types.bulk_upsert_async_response import BulkUpsertAsyncResponse
from ..types.error_response import ErrorResponse
from ..types.purchase_order_create_response import PurchaseOrderCreateResponse
from ..types.purchase_order_detail import PurchaseOrderDetail
from ..types.purchase_order_update_response import PurchaseOrderUpdateResponse
from .types.get_purchase_orders_root_request_status import GetPurchaseOrdersRootRequestStatus
from .types.get_purchase_orders_root_response import GetPurchaseOrdersRootResponse
from .types.patch_purchase_orders_id_request_items_item import PatchPurchaseOrdersIdRequestItemsItem
from .types.purchase_order_bulk_upsert_request_purchase_orders_item import (
    PurchaseOrderBulkUpsertRequestPurchaseOrdersItem,
)
from .types.purchase_order_create_request_items_item import PurchaseOrderCreateRequestItemsItem

# this is used as the default value for optional parameters
OMIT = typing.cast(typing.Any, ...)


class RawPurchaseOrdersClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._client_wrapper = client_wrapper

    def get_purchase_orders_root(
        self,
        *,
        ottimate_company_id: typing.Optional[int] = None,
        ottimate_location_id: typing.Optional[int] = None,
        erp_vendor_id: typing.Optional[str] = None,
        status: typing.Optional[GetPurchaseOrdersRootRequestStatus] = None,
        date_from: typing.Optional[str] = None,
        date_to: typing.Optional[str] = None,
        expand: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[GetPurchaseOrdersRootResponse]:
        """
        Returns a paginated list of purchase orders, filterable by company, location, vendor, status, and date range.

        Parameters
        ----------
        ottimate_company_id : typing.Optional[int]
            Filter by company ID

        ottimate_location_id : typing.Optional[int]
            Filter by location ID

        erp_vendor_id : typing.Optional[str]
            Filter by ERP vendor ID (external vendor identifier)

        status : typing.Optional[GetPurchaseOrdersRootRequestStatus]
            Filter by PO status

        date_from : typing.Optional[str]
            Filter by start date (YYYY-MM-DD)

        date_to : typing.Optional[str]
            Filter by end date (YYYY-MM-DD)

        expand : typing.Optional[str]
            Comma-separated list of fields to expand. Supported values: items. When expand=items is used, date_from and date_to must both be provided and within a 30-day window.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[GetPurchaseOrdersRootResponse]
            Successful response with paginated purchase order list
        """
        _response = self._client_wrapper.httpx_client.request(
            "purchase-orders",
            method="GET",
            params={
                "ottimate_company_id": ottimate_company_id,
                "ottimate_location_id": ottimate_location_id,
                "erp_vendor_id": erp_vendor_id,
                "status": status,
                "date_from": date_from,
                "date_to": date_to,
                "expand": expand,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    GetPurchaseOrdersRootResponse,
                    parse_obj_as(
                        type_=GetPurchaseOrdersRootResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorResponse,
                        parse_obj_as(
                            type_=ErrorResponse,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorResponse,
                        parse_obj_as(
                            type_=ErrorResponse,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def post_purchase_orders_root(
        self,
        *,
        ottimate_location_id: int,
        po_number: str,
        erp_vendor_id: str,
        date: str,
        total_amount: float,
        items: typing.Sequence[PurchaseOrderCreateRequestItemsItem],
        external_id: typing.Optional[str] = OMIT,
        erp_vendor_name: typing.Optional[str] = OMIT,
        tax: typing.Optional[float] = OMIT,
        freight: typing.Optional[float] = OMIT,
        miscellaneous_charges: typing.Optional[float] = OMIT,
        invoice_number_ref: typing.Optional[str] = OMIT,
        is2way: typing.Optional[bool] = OMIT,
        custom_fields: typing.Optional[typing.Dict[str, typing.Any]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[PurchaseOrderCreateResponse]:
        """
        Creates a new purchase order with the provided details. The `po_number` field is required and must be provided by the client (no auto-generation).

        Parameters
        ----------
        ottimate_location_id : int

        po_number : str

        erp_vendor_id : str
            External vendor identifier from ERP system

        date : str

        total_amount : float

        items : typing.Sequence[PurchaseOrderCreateRequestItemsItem]

        external_id : typing.Optional[str]

        erp_vendor_name : typing.Optional[str]
            Vendor name from ERP system

        tax : typing.Optional[float]

        freight : typing.Optional[float]

        miscellaneous_charges : typing.Optional[float]

        invoice_number_ref : typing.Optional[str]
            Invoice reference number

        is2way : typing.Optional[bool]
            Whether this is a 2-way match PO

        custom_fields : typing.Optional[typing.Dict[str, typing.Any]]
            Optional custom fields configured for this company's purchase orders

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[PurchaseOrderCreateResponse]
            Successfully created
        """
        _response = self._client_wrapper.httpx_client.request(
            "purchase-orders",
            method="POST",
            json={
                "ottimate_location_id": ottimate_location_id,
                "external_id": external_id,
                "po_number": po_number,
                "erp_vendor_id": erp_vendor_id,
                "erp_vendor_name": erp_vendor_name,
                "date": date,
                "total_amount": total_amount,
                "tax": tax,
                "freight": freight,
                "miscellaneous_charges": miscellaneous_charges,
                "invoice_number_ref": invoice_number_ref,
                "is_2_way": is2way,
                "items": convert_and_respect_annotation_metadata(
                    object_=items, annotation=typing.Sequence[PurchaseOrderCreateRequestItemsItem], direction="write"
                ),
                "custom_fields": custom_fields,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    PurchaseOrderCreateResponse,
                    parse_obj_as(
                        type_=PurchaseOrderCreateResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorResponse,
                        parse_obj_as(
                            type_=ErrorResponse,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def get_purchase_orders_id(
        self, id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[PurchaseOrderDetail]:
        """
        Returns detailed information for a single purchase order including all line items.

        Parameters
        ----------
        id : str
            The unique ID of the purchase order

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[PurchaseOrderDetail]
            Successful response with purchase order details
        """
        _response = self._client_wrapper.httpx_client.request(
            f"purchase-orders/{jsonable_encoder(id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    PurchaseOrderDetail,
                    parse_obj_as(
                        type_=PurchaseOrderDetail,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorResponse,
                        parse_obj_as(
                            type_=ErrorResponse,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def patch_purchase_orders_id(
        self,
        id: str,
        *,
        erp_vendor_name: typing.Optional[str] = OMIT,
        date: typing.Optional[str] = OMIT,
        total_amount: typing.Optional[float] = OMIT,
        tax: typing.Optional[float] = OMIT,
        freight: typing.Optional[float] = OMIT,
        miscellaneous_charges: typing.Optional[float] = OMIT,
        invoice_number_ref: typing.Optional[str] = OMIT,
        is2way: typing.Optional[bool] = OMIT,
        items: typing.Optional[typing.Sequence[PatchPurchaseOrdersIdRequestItemsItem]] = OMIT,
        custom_fields: typing.Optional[typing.Dict[str, typing.Any]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[PurchaseOrderUpdateResponse]:
        """
        Updates a purchase order. Note: `status`, `po_number`, `external_id`, `erp_vendor_id`, and `ottimate_location_id` cannot be changed.

        Parameters
        ----------
        id : str
            The unique ID of the purchase order

        erp_vendor_name : typing.Optional[str]
            Vendor name from ERP system

        date : typing.Optional[str]

        total_amount : typing.Optional[float]

        tax : typing.Optional[float]

        freight : typing.Optional[float]

        miscellaneous_charges : typing.Optional[float]

        invoice_number_ref : typing.Optional[str]

        is2way : typing.Optional[bool]

        items : typing.Optional[typing.Sequence[PatchPurchaseOrdersIdRequestItemsItem]]
            Items with `id` update the existing item. Items without `id` create a new item. When creating, `name`, `quantity`, and `price` are required.

        custom_fields : typing.Optional[typing.Dict[str, typing.Any]]
            Optional custom fields configured for this company's purchase orders

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[PurchaseOrderUpdateResponse]
            Successfully updated
        """
        _response = self._client_wrapper.httpx_client.request(
            f"purchase-orders/{jsonable_encoder(id)}",
            method="PATCH",
            json={
                "erp_vendor_name": erp_vendor_name,
                "date": date,
                "total_amount": total_amount,
                "tax": tax,
                "freight": freight,
                "miscellaneous_charges": miscellaneous_charges,
                "invoice_number_ref": invoice_number_ref,
                "is_2_way": is2way,
                "items": convert_and_respect_annotation_metadata(
                    object_=items, annotation=typing.Sequence[PatchPurchaseOrdersIdRequestItemsItem], direction="write"
                ),
                "custom_fields": custom_fields,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    PurchaseOrderUpdateResponse,
                    parse_obj_as(
                        type_=PurchaseOrderUpdateResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorResponse,
                        parse_obj_as(
                            type_=ErrorResponse,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorResponse,
                        parse_obj_as(
                            type_=ErrorResponse,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def post_purchase_orders_bulk(
        self,
        *,
        ottimate_company_id: int,
        ottimate_location_id: int,
        purchase_orders: typing.Sequence[PurchaseOrderBulkUpsertRequestPurchaseOrdersItem],
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[BulkUpsertAsyncResponse]:
        """
        Creates or updates multiple purchase orders in a single request. Maximum 100 purchase orders and 1000 total line items per request. Processing is always asynchronous via Celery and returns a batch tracking ID for polling progress.

        Parameters
        ----------
        ottimate_company_id : int
            Company ID for all purchase orders in this batch

        ottimate_location_id : int
            Default location ID for all purchase orders in this batch

        purchase_orders : typing.Sequence[PurchaseOrderBulkUpsertRequestPurchaseOrdersItem]
            Max 100 POs with max 1000 total items

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[BulkUpsertAsyncResponse]
            Asynchronous processing started. Poll batch_url for progress.
        """
        _response = self._client_wrapper.httpx_client.request(
            "purchase-orders/bulk",
            method="POST",
            json={
                "ottimate_company_id": ottimate_company_id,
                "ottimate_location_id": ottimate_location_id,
                "purchase_orders": convert_and_respect_annotation_metadata(
                    object_=purchase_orders,
                    annotation=typing.Sequence[PurchaseOrderBulkUpsertRequestPurchaseOrdersItem],
                    direction="write",
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    BulkUpsertAsyncResponse,
                    parse_obj_as(
                        type_=BulkUpsertAsyncResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorResponse,
                        parse_obj_as(
                            type_=ErrorResponse,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)


class AsyncRawPurchaseOrdersClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def get_purchase_orders_root(
        self,
        *,
        ottimate_company_id: typing.Optional[int] = None,
        ottimate_location_id: typing.Optional[int] = None,
        erp_vendor_id: typing.Optional[str] = None,
        status: typing.Optional[GetPurchaseOrdersRootRequestStatus] = None,
        date_from: typing.Optional[str] = None,
        date_to: typing.Optional[str] = None,
        expand: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[GetPurchaseOrdersRootResponse]:
        """
        Returns a paginated list of purchase orders, filterable by company, location, vendor, status, and date range.

        Parameters
        ----------
        ottimate_company_id : typing.Optional[int]
            Filter by company ID

        ottimate_location_id : typing.Optional[int]
            Filter by location ID

        erp_vendor_id : typing.Optional[str]
            Filter by ERP vendor ID (external vendor identifier)

        status : typing.Optional[GetPurchaseOrdersRootRequestStatus]
            Filter by PO status

        date_from : typing.Optional[str]
            Filter by start date (YYYY-MM-DD)

        date_to : typing.Optional[str]
            Filter by end date (YYYY-MM-DD)

        expand : typing.Optional[str]
            Comma-separated list of fields to expand. Supported values: items. When expand=items is used, date_from and date_to must both be provided and within a 30-day window.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[GetPurchaseOrdersRootResponse]
            Successful response with paginated purchase order list
        """
        _response = await self._client_wrapper.httpx_client.request(
            "purchase-orders",
            method="GET",
            params={
                "ottimate_company_id": ottimate_company_id,
                "ottimate_location_id": ottimate_location_id,
                "erp_vendor_id": erp_vendor_id,
                "status": status,
                "date_from": date_from,
                "date_to": date_to,
                "expand": expand,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    GetPurchaseOrdersRootResponse,
                    parse_obj_as(
                        type_=GetPurchaseOrdersRootResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorResponse,
                        parse_obj_as(
                            type_=ErrorResponse,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorResponse,
                        parse_obj_as(
                            type_=ErrorResponse,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def post_purchase_orders_root(
        self,
        *,
        ottimate_location_id: int,
        po_number: str,
        erp_vendor_id: str,
        date: str,
        total_amount: float,
        items: typing.Sequence[PurchaseOrderCreateRequestItemsItem],
        external_id: typing.Optional[str] = OMIT,
        erp_vendor_name: typing.Optional[str] = OMIT,
        tax: typing.Optional[float] = OMIT,
        freight: typing.Optional[float] = OMIT,
        miscellaneous_charges: typing.Optional[float] = OMIT,
        invoice_number_ref: typing.Optional[str] = OMIT,
        is2way: typing.Optional[bool] = OMIT,
        custom_fields: typing.Optional[typing.Dict[str, typing.Any]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[PurchaseOrderCreateResponse]:
        """
        Creates a new purchase order with the provided details. The `po_number` field is required and must be provided by the client (no auto-generation).

        Parameters
        ----------
        ottimate_location_id : int

        po_number : str

        erp_vendor_id : str
            External vendor identifier from ERP system

        date : str

        total_amount : float

        items : typing.Sequence[PurchaseOrderCreateRequestItemsItem]

        external_id : typing.Optional[str]

        erp_vendor_name : typing.Optional[str]
            Vendor name from ERP system

        tax : typing.Optional[float]

        freight : typing.Optional[float]

        miscellaneous_charges : typing.Optional[float]

        invoice_number_ref : typing.Optional[str]
            Invoice reference number

        is2way : typing.Optional[bool]
            Whether this is a 2-way match PO

        custom_fields : typing.Optional[typing.Dict[str, typing.Any]]
            Optional custom fields configured for this company's purchase orders

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[PurchaseOrderCreateResponse]
            Successfully created
        """
        _response = await self._client_wrapper.httpx_client.request(
            "purchase-orders",
            method="POST",
            json={
                "ottimate_location_id": ottimate_location_id,
                "external_id": external_id,
                "po_number": po_number,
                "erp_vendor_id": erp_vendor_id,
                "erp_vendor_name": erp_vendor_name,
                "date": date,
                "total_amount": total_amount,
                "tax": tax,
                "freight": freight,
                "miscellaneous_charges": miscellaneous_charges,
                "invoice_number_ref": invoice_number_ref,
                "is_2_way": is2way,
                "items": convert_and_respect_annotation_metadata(
                    object_=items, annotation=typing.Sequence[PurchaseOrderCreateRequestItemsItem], direction="write"
                ),
                "custom_fields": custom_fields,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    PurchaseOrderCreateResponse,
                    parse_obj_as(
                        type_=PurchaseOrderCreateResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorResponse,
                        parse_obj_as(
                            type_=ErrorResponse,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def get_purchase_orders_id(
        self, id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[PurchaseOrderDetail]:
        """
        Returns detailed information for a single purchase order including all line items.

        Parameters
        ----------
        id : str
            The unique ID of the purchase order

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[PurchaseOrderDetail]
            Successful response with purchase order details
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"purchase-orders/{jsonable_encoder(id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    PurchaseOrderDetail,
                    parse_obj_as(
                        type_=PurchaseOrderDetail,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorResponse,
                        parse_obj_as(
                            type_=ErrorResponse,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def patch_purchase_orders_id(
        self,
        id: str,
        *,
        erp_vendor_name: typing.Optional[str] = OMIT,
        date: typing.Optional[str] = OMIT,
        total_amount: typing.Optional[float] = OMIT,
        tax: typing.Optional[float] = OMIT,
        freight: typing.Optional[float] = OMIT,
        miscellaneous_charges: typing.Optional[float] = OMIT,
        invoice_number_ref: typing.Optional[str] = OMIT,
        is2way: typing.Optional[bool] = OMIT,
        items: typing.Optional[typing.Sequence[PatchPurchaseOrdersIdRequestItemsItem]] = OMIT,
        custom_fields: typing.Optional[typing.Dict[str, typing.Any]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[PurchaseOrderUpdateResponse]:
        """
        Updates a purchase order. Note: `status`, `po_number`, `external_id`, `erp_vendor_id`, and `ottimate_location_id` cannot be changed.

        Parameters
        ----------
        id : str
            The unique ID of the purchase order

        erp_vendor_name : typing.Optional[str]
            Vendor name from ERP system

        date : typing.Optional[str]

        total_amount : typing.Optional[float]

        tax : typing.Optional[float]

        freight : typing.Optional[float]

        miscellaneous_charges : typing.Optional[float]

        invoice_number_ref : typing.Optional[str]

        is2way : typing.Optional[bool]

        items : typing.Optional[typing.Sequence[PatchPurchaseOrdersIdRequestItemsItem]]
            Items with `id` update the existing item. Items without `id` create a new item. When creating, `name`, `quantity`, and `price` are required.

        custom_fields : typing.Optional[typing.Dict[str, typing.Any]]
            Optional custom fields configured for this company's purchase orders

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[PurchaseOrderUpdateResponse]
            Successfully updated
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"purchase-orders/{jsonable_encoder(id)}",
            method="PATCH",
            json={
                "erp_vendor_name": erp_vendor_name,
                "date": date,
                "total_amount": total_amount,
                "tax": tax,
                "freight": freight,
                "miscellaneous_charges": miscellaneous_charges,
                "invoice_number_ref": invoice_number_ref,
                "is_2_way": is2way,
                "items": convert_and_respect_annotation_metadata(
                    object_=items, annotation=typing.Sequence[PatchPurchaseOrdersIdRequestItemsItem], direction="write"
                ),
                "custom_fields": custom_fields,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    PurchaseOrderUpdateResponse,
                    parse_obj_as(
                        type_=PurchaseOrderUpdateResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorResponse,
                        parse_obj_as(
                            type_=ErrorResponse,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorResponse,
                        parse_obj_as(
                            type_=ErrorResponse,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def post_purchase_orders_bulk(
        self,
        *,
        ottimate_company_id: int,
        ottimate_location_id: int,
        purchase_orders: typing.Sequence[PurchaseOrderBulkUpsertRequestPurchaseOrdersItem],
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[BulkUpsertAsyncResponse]:
        """
        Creates or updates multiple purchase orders in a single request. Maximum 100 purchase orders and 1000 total line items per request. Processing is always asynchronous via Celery and returns a batch tracking ID for polling progress.

        Parameters
        ----------
        ottimate_company_id : int
            Company ID for all purchase orders in this batch

        ottimate_location_id : int
            Default location ID for all purchase orders in this batch

        purchase_orders : typing.Sequence[PurchaseOrderBulkUpsertRequestPurchaseOrdersItem]
            Max 100 POs with max 1000 total items

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[BulkUpsertAsyncResponse]
            Asynchronous processing started. Poll batch_url for progress.
        """
        _response = await self._client_wrapper.httpx_client.request(
            "purchase-orders/bulk",
            method="POST",
            json={
                "ottimate_company_id": ottimate_company_id,
                "ottimate_location_id": ottimate_location_id,
                "purchase_orders": convert_and_respect_annotation_metadata(
                    object_=purchase_orders,
                    annotation=typing.Sequence[PurchaseOrderBulkUpsertRequestPurchaseOrdersItem],
                    direction="write",
                ),
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    BulkUpsertAsyncResponse,
                    parse_obj_as(
                        type_=BulkUpsertAsyncResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        ErrorResponse,
                        parse_obj_as(
                            type_=ErrorResponse,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)
