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

import typing
from ..core.client_wrapper import SyncClientWrapper
from .raw_client import RawInvoicesClient
from ..core.request_options import RequestOptions
from ..core.pagination import SyncPager
from ..types.invoice import Invoice
from ..types.list_invoices_response import ListInvoicesResponse
from ..core.unchecked_base_model import construct_type
from json.decoder import JSONDecodeError
from ..core.api_error import ApiError
from ..requests.invoice import InvoiceParams
from ..types.create_invoice_response import CreateInvoiceResponse
from ..requests.invoice_query import InvoiceQueryParams
from ..types.search_invoices_response import SearchInvoicesResponse
from ..types.get_invoice_response import GetInvoiceResponse
from ..types.update_invoice_response import UpdateInvoiceResponse
from ..types.delete_invoice_response import DeleteInvoiceResponse
from ..requests.create_invoice_attachment_request_data import CreateInvoiceAttachmentRequestDataParams
from .. import core
from ..types.create_invoice_attachment_response import CreateInvoiceAttachmentResponse
from ..types.delete_invoice_attachment_response import DeleteInvoiceAttachmentResponse
from ..types.cancel_invoice_response import CancelInvoiceResponse
from ..types.publish_invoice_response import PublishInvoiceResponse
from ..core.client_wrapper import AsyncClientWrapper
from .raw_client import AsyncRawInvoicesClient
from ..core.pagination import AsyncPager

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


class InvoicesClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._raw_client = RawInvoicesClient(client_wrapper=client_wrapper)

    @property
    def with_raw_response(self) -> RawInvoicesClient:
        """
        Retrieves a raw implementation of this client that returns raw responses.

        Returns
        -------
        RawInvoicesClient
        """
        return self._raw_client

    def list(
        self,
        *,
        location_id: str,
        cursor: typing.Optional[str] = None,
        limit: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> SyncPager[Invoice]:
        """
        Returns a list of invoices for a given location. The response
        is paginated. If truncated, the response includes a `cursor` that you
        use in a subsequent request to retrieve the next set of invoices.

        Parameters
        ----------
        location_id : str
            The ID of the location for which to list invoices.

        cursor : typing.Optional[str]
            A pagination cursor returned by a previous call to this endpoint.
            Provide this cursor to retrieve the next set of results for your original query.

            For more information, see [Pagination](https://developer.squareup.com/docs/build-basics/common-api-patterns/pagination).

        limit : typing.Optional[int]
            The maximum number of invoices to return (200 is the maximum `limit`).
            If not provided, the server uses a default limit of 100 invoices.

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

        Returns
        -------
        SyncPager[Invoice]
            Success

        Examples
        --------
        from square import Square

        client = Square(
            token="YOUR_TOKEN",
        )
        response = client.invoices.list(
            location_id="location_id",
        )
        for item in response:
            yield item
        # alternatively, you can paginate page-by-page
        for page in response.iter_pages():
            yield page
        """
        _response = self._raw_client._client_wrapper.httpx_client.request(
            "v2/invoices",
            method="GET",
            params={
                "location_id": location_id,
                "cursor": cursor,
                "limit": limit,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ListInvoicesResponse,
                    construct_type(
                        type_=ListInvoicesResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                _parsed_next = _parsed_response.cursor
                _has_next = _parsed_next is not None and _parsed_next != ""
                _get_next = lambda: self.list(
                    location_id=location_id,
                    cursor=_parsed_next,
                    limit=limit,
                    request_options=request_options,
                )
                _items = _parsed_response.invoices
                return SyncPager(has_next=_has_next, items=_items, get_next=_get_next)
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def create(
        self,
        *,
        invoice: InvoiceParams,
        idempotency_key: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> CreateInvoiceResponse:
        """
        Creates a draft [invoice](entity:Invoice)
        for an order created using the Orders API.

        A draft invoice remains in your account and no action is taken.
        You must publish the invoice before Square can process it (send it to the customer's email address or charge the customer’s card on file).

        Parameters
        ----------
        invoice : InvoiceParams
            The invoice to create.

        idempotency_key : typing.Optional[str]
            A unique string that identifies the `CreateInvoice` request. If you do not
            provide `idempotency_key` (or provide an empty string as the value), the endpoint
            treats each request as independent.

            For more information, see [Idempotency](https://developer.squareup.com/docs/build-basics/common-api-patterns/idempotency).

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

        Returns
        -------
        CreateInvoiceResponse
            Success

        Examples
        --------
        from square import Square

        client = Square(
            token="YOUR_TOKEN",
        )
        client.invoices.create(
            invoice={
                "location_id": "ES0RJRZYEC39A",
                "order_id": "CAISENgvlJ6jLWAzERDzjyHVybY",
                "primary_recipient": {"customer_id": "JDKYHBWT1D4F8MFH63DBMEN8Y4"},
                "payment_requests": [
                    {
                        "request_type": "BALANCE",
                        "due_date": "2030-01-24",
                        "tipping_enabled": True,
                        "automatic_payment_source": "NONE",
                        "reminders": [
                            {
                                "relative_scheduled_days": -1,
                                "message": "Your invoice is due tomorrow",
                            }
                        ],
                    }
                ],
                "delivery_method": "EMAIL",
                "invoice_number": "inv-100",
                "title": "Event Planning Services",
                "description": "We appreciate your business!",
                "scheduled_at": "2030-01-13T10:00:00Z",
                "accepted_payment_methods": {
                    "card": True,
                    "square_gift_card": False,
                    "bank_account": False,
                    "buy_now_pay_later": False,
                    "cash_app_pay": False,
                },
                "custom_fields": [
                    {
                        "label": "Event Reference Number",
                        "value": "Ref. #1234",
                        "placement": "ABOVE_LINE_ITEMS",
                    },
                    {
                        "label": "Terms of Service",
                        "value": "The terms of service are...",
                        "placement": "BELOW_LINE_ITEMS",
                    },
                ],
                "sale_or_service_date": "2030-01-24",
                "store_payment_method_enabled": False,
            },
            idempotency_key="ce3748f9-5fc1-4762-aa12-aae5e843f1f4",
        )
        """
        response = self._raw_client.create(
            invoice=invoice, idempotency_key=idempotency_key, request_options=request_options
        )
        return response.data

    def search(
        self,
        *,
        query: InvoiceQueryParams,
        limit: typing.Optional[int] = OMIT,
        cursor: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> SearchInvoicesResponse:
        """
        Searches for invoices from a location specified in
        the filter. You can optionally specify customers in the filter for whom to
        retrieve invoices. In the current implementation, you can only specify one location and
        optionally one customer.

        The response is paginated. If truncated, the response includes a `cursor`
        that you use in a subsequent request to retrieve the next set of invoices.

        Parameters
        ----------
        query : InvoiceQueryParams
            Describes the query criteria for searching invoices.

        limit : typing.Optional[int]
            The maximum number of invoices to return (200 is the maximum `limit`).
            If not provided, the server uses a default limit of 100 invoices.

        cursor : typing.Optional[str]
            A pagination cursor returned by a previous call to this endpoint.
            Provide this cursor to retrieve the next set of results for your original query.

            For more information, see [Pagination](https://developer.squareup.com/docs/build-basics/common-api-patterns/pagination).

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

        Returns
        -------
        SearchInvoicesResponse
            Success

        Examples
        --------
        from square import Square

        client = Square(
            token="YOUR_TOKEN",
        )
        client.invoices.search(
            query={
                "filter": {
                    "location_ids": ["ES0RJRZYEC39A"],
                    "customer_ids": ["JDKYHBWT1D4F8MFH63DBMEN8Y4"],
                },
                "sort": {"field": "INVOICE_SORT_DATE", "order": "DESC"},
            },
            limit=100,
        )
        """
        response = self._raw_client.search(query=query, limit=limit, cursor=cursor, request_options=request_options)
        return response.data

    def get(self, invoice_id: str, *, request_options: typing.Optional[RequestOptions] = None) -> GetInvoiceResponse:
        """
        Retrieves an invoice by invoice ID.

        Parameters
        ----------
        invoice_id : str
            The ID of the invoice to retrieve.

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

        Returns
        -------
        GetInvoiceResponse
            Success

        Examples
        --------
        from square import Square

        client = Square(
            token="YOUR_TOKEN",
        )
        client.invoices.get(
            invoice_id="invoice_id",
        )
        """
        response = self._raw_client.get(invoice_id, request_options=request_options)
        return response.data

    def update(
        self,
        invoice_id: str,
        *,
        invoice: InvoiceParams,
        idempotency_key: typing.Optional[str] = OMIT,
        fields_to_clear: typing.Optional[typing.Sequence[str]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> UpdateInvoiceResponse:
        """
        Updates an invoice. This endpoint supports sparse updates, so you only need
        to specify the fields you want to change along with the required `version` field.
        Some restrictions apply to updating invoices. For example, you cannot change the
        `order_id` or `location_id` field.

        Parameters
        ----------
        invoice_id : str
            The ID of the invoice to update.

        invoice : InvoiceParams
            The invoice fields to add, change, or clear. Fields can be cleared using
            null values or the `remove` field (for individual payment requests or reminders).
            The current invoice `version` is also required. For more information, including requirements,
            limitations, and more examples, see [Update an Invoice](https://developer.squareup.com/docs/invoices-api/update-invoices).

        idempotency_key : typing.Optional[str]
            A unique string that identifies the `UpdateInvoice` request. If you do not
            provide `idempotency_key` (or provide an empty string as the value), the endpoint
            treats each request as independent.

            For more information, see [Idempotency](https://developer.squareup.com/docs/build-basics/common-api-patterns/idempotency).

        fields_to_clear : typing.Optional[typing.Sequence[str]]
            The list of fields to clear. Although this field is currently supported, we
            recommend using null values or the `remove` field when possible. For examples, see
            [Update an Invoice](https://developer.squareup.com/docs/invoices-api/update-invoices).

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

        Returns
        -------
        UpdateInvoiceResponse
            Success

        Examples
        --------
        from square import Square

        client = Square(
            token="YOUR_TOKEN",
        )
        client.invoices.update(
            invoice_id="invoice_id",
            invoice={
                "version": 1,
                "payment_requests": [
                    {
                        "uid": "2da7964f-f3d2-4f43-81e8-5aa220bf3355",
                        "tipping_enabled": False,
                    }
                ],
            },
            idempotency_key="4ee82288-0910-499e-ab4c-5d0071dad1be",
        )
        """
        response = self._raw_client.update(
            invoice_id,
            invoice=invoice,
            idempotency_key=idempotency_key,
            fields_to_clear=fields_to_clear,
            request_options=request_options,
        )
        return response.data

    def delete(
        self,
        invoice_id: str,
        *,
        version: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> DeleteInvoiceResponse:
        """
        Deletes the specified invoice. When an invoice is deleted, the
        associated order status changes to CANCELED. You can only delete a draft
        invoice (you cannot delete a published invoice, including one that is scheduled for processing).

        Parameters
        ----------
        invoice_id : str
            The ID of the invoice to delete.

        version : typing.Optional[int]
            The version of the [invoice](entity:Invoice) to delete.
            If you do not know the version, you can call [GetInvoice](api-endpoint:Invoices-GetInvoice) or
            [ListInvoices](api-endpoint:Invoices-ListInvoices).

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

        Returns
        -------
        DeleteInvoiceResponse
            Success

        Examples
        --------
        from square import Square

        client = Square(
            token="YOUR_TOKEN",
        )
        client.invoices.delete(
            invoice_id="invoice_id",
        )
        """
        response = self._raw_client.delete(invoice_id, version=version, request_options=request_options)
        return response.data

    def create_invoice_attachment(
        self,
        invoice_id: str,
        *,
        request: typing.Optional[CreateInvoiceAttachmentRequestDataParams] = OMIT,
        image_file: typing.Optional[core.File] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> CreateInvoiceAttachmentResponse:
        """
        Uploads a file and attaches it to an invoice. This endpoint accepts HTTP multipart/form-data file uploads
        with a JSON `request` part and a `file` part. The `file` part must be a `readable stream` that contains a file
        in a supported format: GIF, JPEG, PNG, TIFF, BMP, or PDF.

        Invoices can have up to 10 attachments with a total file size of 25 MB. Attachments can be added only to invoices
        in the `DRAFT`, `SCHEDULED`, `UNPAID`, or `PARTIALLY_PAID` state.

        __NOTE:__ When testing in the Sandbox environment, the total file size is limited to 1 KB.

        Parameters
        ----------
        invoice_id : str
            The ID of the [invoice](entity:Invoice) to attach the file to.

        request : typing.Optional[CreateInvoiceAttachmentRequestDataParams]

        image_file : typing.Optional[core.File]
            See core.File for more documentation

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

        Returns
        -------
        CreateInvoiceAttachmentResponse
            Success

        Examples
        --------
        from square import Square

        client = Square(
            token="YOUR_TOKEN",
        )
        client.invoices.create_invoice_attachment(
            invoice_id="invoice_id",
        )
        """
        response = self._raw_client.create_invoice_attachment(
            invoice_id, request=request, image_file=image_file, request_options=request_options
        )
        return response.data

    def delete_invoice_attachment(
        self, invoice_id: str, attachment_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> DeleteInvoiceAttachmentResponse:
        """
        Removes an attachment from an invoice and permanently deletes the file. Attachments can be removed only
        from invoices in the `DRAFT`, `SCHEDULED`, `UNPAID`, or `PARTIALLY_PAID` state.

        Parameters
        ----------
        invoice_id : str
            The ID of the [invoice](entity:Invoice) to delete the attachment from.

        attachment_id : str
            The ID of the [attachment](entity:InvoiceAttachment) to delete.

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

        Returns
        -------
        DeleteInvoiceAttachmentResponse
            Success

        Examples
        --------
        from square import Square

        client = Square(
            token="YOUR_TOKEN",
        )
        client.invoices.delete_invoice_attachment(
            invoice_id="invoice_id",
            attachment_id="attachment_id",
        )
        """
        response = self._raw_client.delete_invoice_attachment(
            invoice_id, attachment_id, request_options=request_options
        )
        return response.data

    def cancel(
        self, invoice_id: str, *, version: int, request_options: typing.Optional[RequestOptions] = None
    ) -> CancelInvoiceResponse:
        """
        Cancels an invoice. The seller cannot collect payments for
        the canceled invoice.

        You cannot cancel an invoice in the `DRAFT` state or in a terminal state: `PAID`, `REFUNDED`, `CANCELED`, or `FAILED`.

        Parameters
        ----------
        invoice_id : str
            The ID of the [invoice](entity:Invoice) to cancel.

        version : int
            The version of the [invoice](entity:Invoice) to cancel.
            If you do not know the version, you can call
            [GetInvoice](api-endpoint:Invoices-GetInvoice) or [ListInvoices](api-endpoint:Invoices-ListInvoices).

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

        Returns
        -------
        CancelInvoiceResponse
            Success

        Examples
        --------
        from square import Square

        client = Square(
            token="YOUR_TOKEN",
        )
        client.invoices.cancel(
            invoice_id="invoice_id",
            version=0,
        )
        """
        response = self._raw_client.cancel(invoice_id, version=version, request_options=request_options)
        return response.data

    def publish(
        self,
        invoice_id: str,
        *,
        version: int,
        idempotency_key: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> PublishInvoiceResponse:
        """
        Publishes the specified draft invoice.

        After an invoice is published, Square
        follows up based on the invoice configuration. For example, Square
        sends the invoice to the customer's email address, charges the customer's card on file, or does
        nothing. Square also makes the invoice available on a Square-hosted invoice page.

        The invoice `status` also changes from `DRAFT` to a status
        based on the invoice configuration. For example, the status changes to `UNPAID` if
        Square emails the invoice or `PARTIALLY_PAID` if Square charges a card on file for a portion of the
        invoice amount.

        In addition to the required `ORDERS_WRITE` and `INVOICES_WRITE` permissions, `CUSTOMERS_READ`
        and `PAYMENTS_WRITE` are required when publishing invoices configured for card-on-file payments.

        Parameters
        ----------
        invoice_id : str
            The ID of the invoice to publish.

        version : int
            The version of the [invoice](entity:Invoice) to publish.
            This must match the current version of the invoice; otherwise, the request is rejected.

        idempotency_key : typing.Optional[str]
            A unique string that identifies the `PublishInvoice` request. If you do not
            provide `idempotency_key` (or provide an empty string as the value), the endpoint
            treats each request as independent.

            For more information, see [Idempotency](https://developer.squareup.com/docs/build-basics/common-api-patterns/idempotency).

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

        Returns
        -------
        PublishInvoiceResponse
            Success

        Examples
        --------
        from square import Square

        client = Square(
            token="YOUR_TOKEN",
        )
        client.invoices.publish(
            invoice_id="invoice_id",
            version=1,
            idempotency_key="32da42d0-1997-41b0-826b-f09464fc2c2e",
        )
        """
        response = self._raw_client.publish(
            invoice_id, version=version, idempotency_key=idempotency_key, request_options=request_options
        )
        return response.data


class AsyncInvoicesClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._raw_client = AsyncRawInvoicesClient(client_wrapper=client_wrapper)

    @property
    def with_raw_response(self) -> AsyncRawInvoicesClient:
        """
        Retrieves a raw implementation of this client that returns raw responses.

        Returns
        -------
        AsyncRawInvoicesClient
        """
        return self._raw_client

    async def list(
        self,
        *,
        location_id: str,
        cursor: typing.Optional[str] = None,
        limit: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncPager[Invoice]:
        """
        Returns a list of invoices for a given location. The response
        is paginated. If truncated, the response includes a `cursor` that you
        use in a subsequent request to retrieve the next set of invoices.

        Parameters
        ----------
        location_id : str
            The ID of the location for which to list invoices.

        cursor : typing.Optional[str]
            A pagination cursor returned by a previous call to this endpoint.
            Provide this cursor to retrieve the next set of results for your original query.

            For more information, see [Pagination](https://developer.squareup.com/docs/build-basics/common-api-patterns/pagination).

        limit : typing.Optional[int]
            The maximum number of invoices to return (200 is the maximum `limit`).
            If not provided, the server uses a default limit of 100 invoices.

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

        Returns
        -------
        AsyncPager[Invoice]
            Success

        Examples
        --------
        import asyncio

        from square import AsyncSquare

        client = AsyncSquare(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            response = await client.invoices.list(
                location_id="location_id",
            )
            async for item in response:
                yield item
            # alternatively, you can paginate page-by-page
            async for page in response.iter_pages():
                yield page


        asyncio.run(main())
        """
        _response = await self._raw_client._client_wrapper.httpx_client.request(
            "v2/invoices",
            method="GET",
            params={
                "location_id": location_id,
                "cursor": cursor,
                "limit": limit,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ListInvoicesResponse,
                    construct_type(
                        type_=ListInvoicesResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                _parsed_next = _parsed_response.cursor
                _has_next = _parsed_next is not None and _parsed_next != ""
                _get_next = lambda: self.list(
                    location_id=location_id,
                    cursor=_parsed_next,
                    limit=limit,
                    request_options=request_options,
                )
                _items = _parsed_response.invoices
                return AsyncPager(has_next=_has_next, items=_items, get_next=_get_next)
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def create(
        self,
        *,
        invoice: InvoiceParams,
        idempotency_key: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> CreateInvoiceResponse:
        """
        Creates a draft [invoice](entity:Invoice)
        for an order created using the Orders API.

        A draft invoice remains in your account and no action is taken.
        You must publish the invoice before Square can process it (send it to the customer's email address or charge the customer’s card on file).

        Parameters
        ----------
        invoice : InvoiceParams
            The invoice to create.

        idempotency_key : typing.Optional[str]
            A unique string that identifies the `CreateInvoice` request. If you do not
            provide `idempotency_key` (or provide an empty string as the value), the endpoint
            treats each request as independent.

            For more information, see [Idempotency](https://developer.squareup.com/docs/build-basics/common-api-patterns/idempotency).

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

        Returns
        -------
        CreateInvoiceResponse
            Success

        Examples
        --------
        import asyncio

        from square import AsyncSquare

        client = AsyncSquare(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.invoices.create(
                invoice={
                    "location_id": "ES0RJRZYEC39A",
                    "order_id": "CAISENgvlJ6jLWAzERDzjyHVybY",
                    "primary_recipient": {"customer_id": "JDKYHBWT1D4F8MFH63DBMEN8Y4"},
                    "payment_requests": [
                        {
                            "request_type": "BALANCE",
                            "due_date": "2030-01-24",
                            "tipping_enabled": True,
                            "automatic_payment_source": "NONE",
                            "reminders": [
                                {
                                    "relative_scheduled_days": -1,
                                    "message": "Your invoice is due tomorrow",
                                }
                            ],
                        }
                    ],
                    "delivery_method": "EMAIL",
                    "invoice_number": "inv-100",
                    "title": "Event Planning Services",
                    "description": "We appreciate your business!",
                    "scheduled_at": "2030-01-13T10:00:00Z",
                    "accepted_payment_methods": {
                        "card": True,
                        "square_gift_card": False,
                        "bank_account": False,
                        "buy_now_pay_later": False,
                        "cash_app_pay": False,
                    },
                    "custom_fields": [
                        {
                            "label": "Event Reference Number",
                            "value": "Ref. #1234",
                            "placement": "ABOVE_LINE_ITEMS",
                        },
                        {
                            "label": "Terms of Service",
                            "value": "The terms of service are...",
                            "placement": "BELOW_LINE_ITEMS",
                        },
                    ],
                    "sale_or_service_date": "2030-01-24",
                    "store_payment_method_enabled": False,
                },
                idempotency_key="ce3748f9-5fc1-4762-aa12-aae5e843f1f4",
            )


        asyncio.run(main())
        """
        response = await self._raw_client.create(
            invoice=invoice, idempotency_key=idempotency_key, request_options=request_options
        )
        return response.data

    async def search(
        self,
        *,
        query: InvoiceQueryParams,
        limit: typing.Optional[int] = OMIT,
        cursor: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> SearchInvoicesResponse:
        """
        Searches for invoices from a location specified in
        the filter. You can optionally specify customers in the filter for whom to
        retrieve invoices. In the current implementation, you can only specify one location and
        optionally one customer.

        The response is paginated. If truncated, the response includes a `cursor`
        that you use in a subsequent request to retrieve the next set of invoices.

        Parameters
        ----------
        query : InvoiceQueryParams
            Describes the query criteria for searching invoices.

        limit : typing.Optional[int]
            The maximum number of invoices to return (200 is the maximum `limit`).
            If not provided, the server uses a default limit of 100 invoices.

        cursor : typing.Optional[str]
            A pagination cursor returned by a previous call to this endpoint.
            Provide this cursor to retrieve the next set of results for your original query.

            For more information, see [Pagination](https://developer.squareup.com/docs/build-basics/common-api-patterns/pagination).

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

        Returns
        -------
        SearchInvoicesResponse
            Success

        Examples
        --------
        import asyncio

        from square import AsyncSquare

        client = AsyncSquare(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.invoices.search(
                query={
                    "filter": {
                        "location_ids": ["ES0RJRZYEC39A"],
                        "customer_ids": ["JDKYHBWT1D4F8MFH63DBMEN8Y4"],
                    },
                    "sort": {"field": "INVOICE_SORT_DATE", "order": "DESC"},
                },
                limit=100,
            )


        asyncio.run(main())
        """
        response = await self._raw_client.search(
            query=query, limit=limit, cursor=cursor, request_options=request_options
        )
        return response.data

    async def get(
        self, invoice_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> GetInvoiceResponse:
        """
        Retrieves an invoice by invoice ID.

        Parameters
        ----------
        invoice_id : str
            The ID of the invoice to retrieve.

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

        Returns
        -------
        GetInvoiceResponse
            Success

        Examples
        --------
        import asyncio

        from square import AsyncSquare

        client = AsyncSquare(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.invoices.get(
                invoice_id="invoice_id",
            )


        asyncio.run(main())
        """
        response = await self._raw_client.get(invoice_id, request_options=request_options)
        return response.data

    async def update(
        self,
        invoice_id: str,
        *,
        invoice: InvoiceParams,
        idempotency_key: typing.Optional[str] = OMIT,
        fields_to_clear: typing.Optional[typing.Sequence[str]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> UpdateInvoiceResponse:
        """
        Updates an invoice. This endpoint supports sparse updates, so you only need
        to specify the fields you want to change along with the required `version` field.
        Some restrictions apply to updating invoices. For example, you cannot change the
        `order_id` or `location_id` field.

        Parameters
        ----------
        invoice_id : str
            The ID of the invoice to update.

        invoice : InvoiceParams
            The invoice fields to add, change, or clear. Fields can be cleared using
            null values or the `remove` field (for individual payment requests or reminders).
            The current invoice `version` is also required. For more information, including requirements,
            limitations, and more examples, see [Update an Invoice](https://developer.squareup.com/docs/invoices-api/update-invoices).

        idempotency_key : typing.Optional[str]
            A unique string that identifies the `UpdateInvoice` request. If you do not
            provide `idempotency_key` (or provide an empty string as the value), the endpoint
            treats each request as independent.

            For more information, see [Idempotency](https://developer.squareup.com/docs/build-basics/common-api-patterns/idempotency).

        fields_to_clear : typing.Optional[typing.Sequence[str]]
            The list of fields to clear. Although this field is currently supported, we
            recommend using null values or the `remove` field when possible. For examples, see
            [Update an Invoice](https://developer.squareup.com/docs/invoices-api/update-invoices).

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

        Returns
        -------
        UpdateInvoiceResponse
            Success

        Examples
        --------
        import asyncio

        from square import AsyncSquare

        client = AsyncSquare(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.invoices.update(
                invoice_id="invoice_id",
                invoice={
                    "version": 1,
                    "payment_requests": [
                        {
                            "uid": "2da7964f-f3d2-4f43-81e8-5aa220bf3355",
                            "tipping_enabled": False,
                        }
                    ],
                },
                idempotency_key="4ee82288-0910-499e-ab4c-5d0071dad1be",
            )


        asyncio.run(main())
        """
        response = await self._raw_client.update(
            invoice_id,
            invoice=invoice,
            idempotency_key=idempotency_key,
            fields_to_clear=fields_to_clear,
            request_options=request_options,
        )
        return response.data

    async def delete(
        self,
        invoice_id: str,
        *,
        version: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> DeleteInvoiceResponse:
        """
        Deletes the specified invoice. When an invoice is deleted, the
        associated order status changes to CANCELED. You can only delete a draft
        invoice (you cannot delete a published invoice, including one that is scheduled for processing).

        Parameters
        ----------
        invoice_id : str
            The ID of the invoice to delete.

        version : typing.Optional[int]
            The version of the [invoice](entity:Invoice) to delete.
            If you do not know the version, you can call [GetInvoice](api-endpoint:Invoices-GetInvoice) or
            [ListInvoices](api-endpoint:Invoices-ListInvoices).

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

        Returns
        -------
        DeleteInvoiceResponse
            Success

        Examples
        --------
        import asyncio

        from square import AsyncSquare

        client = AsyncSquare(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.invoices.delete(
                invoice_id="invoice_id",
            )


        asyncio.run(main())
        """
        response = await self._raw_client.delete(invoice_id, version=version, request_options=request_options)
        return response.data

    async def create_invoice_attachment(
        self,
        invoice_id: str,
        *,
        request: typing.Optional[CreateInvoiceAttachmentRequestDataParams] = OMIT,
        image_file: typing.Optional[core.File] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> CreateInvoiceAttachmentResponse:
        """
        Uploads a file and attaches it to an invoice. This endpoint accepts HTTP multipart/form-data file uploads
        with a JSON `request` part and a `file` part. The `file` part must be a `readable stream` that contains a file
        in a supported format: GIF, JPEG, PNG, TIFF, BMP, or PDF.

        Invoices can have up to 10 attachments with a total file size of 25 MB. Attachments can be added only to invoices
        in the `DRAFT`, `SCHEDULED`, `UNPAID`, or `PARTIALLY_PAID` state.

        __NOTE:__ When testing in the Sandbox environment, the total file size is limited to 1 KB.

        Parameters
        ----------
        invoice_id : str
            The ID of the [invoice](entity:Invoice) to attach the file to.

        request : typing.Optional[CreateInvoiceAttachmentRequestDataParams]

        image_file : typing.Optional[core.File]
            See core.File for more documentation

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

        Returns
        -------
        CreateInvoiceAttachmentResponse
            Success

        Examples
        --------
        import asyncio

        from square import AsyncSquare

        client = AsyncSquare(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.invoices.create_invoice_attachment(
                invoice_id="invoice_id",
            )


        asyncio.run(main())
        """
        response = await self._raw_client.create_invoice_attachment(
            invoice_id, request=request, image_file=image_file, request_options=request_options
        )
        return response.data

    async def delete_invoice_attachment(
        self, invoice_id: str, attachment_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> DeleteInvoiceAttachmentResponse:
        """
        Removes an attachment from an invoice and permanently deletes the file. Attachments can be removed only
        from invoices in the `DRAFT`, `SCHEDULED`, `UNPAID`, or `PARTIALLY_PAID` state.

        Parameters
        ----------
        invoice_id : str
            The ID of the [invoice](entity:Invoice) to delete the attachment from.

        attachment_id : str
            The ID of the [attachment](entity:InvoiceAttachment) to delete.

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

        Returns
        -------
        DeleteInvoiceAttachmentResponse
            Success

        Examples
        --------
        import asyncio

        from square import AsyncSquare

        client = AsyncSquare(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.invoices.delete_invoice_attachment(
                invoice_id="invoice_id",
                attachment_id="attachment_id",
            )


        asyncio.run(main())
        """
        response = await self._raw_client.delete_invoice_attachment(
            invoice_id, attachment_id, request_options=request_options
        )
        return response.data

    async def cancel(
        self, invoice_id: str, *, version: int, request_options: typing.Optional[RequestOptions] = None
    ) -> CancelInvoiceResponse:
        """
        Cancels an invoice. The seller cannot collect payments for
        the canceled invoice.

        You cannot cancel an invoice in the `DRAFT` state or in a terminal state: `PAID`, `REFUNDED`, `CANCELED`, or `FAILED`.

        Parameters
        ----------
        invoice_id : str
            The ID of the [invoice](entity:Invoice) to cancel.

        version : int
            The version of the [invoice](entity:Invoice) to cancel.
            If you do not know the version, you can call
            [GetInvoice](api-endpoint:Invoices-GetInvoice) or [ListInvoices](api-endpoint:Invoices-ListInvoices).

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

        Returns
        -------
        CancelInvoiceResponse
            Success

        Examples
        --------
        import asyncio

        from square import AsyncSquare

        client = AsyncSquare(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.invoices.cancel(
                invoice_id="invoice_id",
                version=0,
            )


        asyncio.run(main())
        """
        response = await self._raw_client.cancel(invoice_id, version=version, request_options=request_options)
        return response.data

    async def publish(
        self,
        invoice_id: str,
        *,
        version: int,
        idempotency_key: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> PublishInvoiceResponse:
        """
        Publishes the specified draft invoice.

        After an invoice is published, Square
        follows up based on the invoice configuration. For example, Square
        sends the invoice to the customer's email address, charges the customer's card on file, or does
        nothing. Square also makes the invoice available on a Square-hosted invoice page.

        The invoice `status` also changes from `DRAFT` to a status
        based on the invoice configuration. For example, the status changes to `UNPAID` if
        Square emails the invoice or `PARTIALLY_PAID` if Square charges a card on file for a portion of the
        invoice amount.

        In addition to the required `ORDERS_WRITE` and `INVOICES_WRITE` permissions, `CUSTOMERS_READ`
        and `PAYMENTS_WRITE` are required when publishing invoices configured for card-on-file payments.

        Parameters
        ----------
        invoice_id : str
            The ID of the invoice to publish.

        version : int
            The version of the [invoice](entity:Invoice) to publish.
            This must match the current version of the invoice; otherwise, the request is rejected.

        idempotency_key : typing.Optional[str]
            A unique string that identifies the `PublishInvoice` request. If you do not
            provide `idempotency_key` (or provide an empty string as the value), the endpoint
            treats each request as independent.

            For more information, see [Idempotency](https://developer.squareup.com/docs/build-basics/common-api-patterns/idempotency).

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

        Returns
        -------
        PublishInvoiceResponse
            Success

        Examples
        --------
        import asyncio

        from square import AsyncSquare

        client = AsyncSquare(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.invoices.publish(
                invoice_id="invoice_id",
                version=1,
                idempotency_key="32da42d0-1997-41b0-826b-f09464fc2c2e",
            )


        asyncio.run(main())
        """
        response = await self._raw_client.publish(
            invoice_id, version=version, idempotency_key=idempotency_key, request_options=request_options
        )
        return response.data
