Metadata-Version: 2.4
Name: tillcast
Version: 0.2.1
Summary: Python client for the Tillcast print API (pre-release).
License-Expression: MIT
License-File: LICENSE
Author: w3center Daniel Miedzik
Requires-Python: >=3.10,<4.0
Classifier: Intended Audience :: Developers
Classifier: Operating System :: MacOS
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: OS Independent
Classifier: Operating System :: POSIX
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Provides-Extra: aiohttp
Requires-Dist: aiohttp (>=3.14.1,<4) ; (python_version >= "3.10") and (extra == "aiohttp")
Requires-Dist: httpx (>=0.21.2)
Requires-Dist: httpx-aiohttp (>=0.1.8,<0.2.0) ; (python_version >= "3.10") and (extra == "aiohttp")
Requires-Dist: pydantic (>=1.9.2)
Requires-Dist: pydantic-core (>=2.18.2,<3.0.0)
Requires-Dist: typing_extensions (>=4.0.0)
Project-URL: Documentation, https://docs.tillcast.com
Description-Content-Type: text/markdown

# Tillcast Python Library

[![fern shield](https://img.shields.io/badge/%F0%9F%8C%BF-Built%20with%20Fern-brightgreen)](https://buildwithfern.com?utm_source=github&utm_medium=github&utm_campaign=readme&utm_source=Tillcast%2FPython)
[![pypi](https://img.shields.io/pypi/v/tillcast)](https://pypi.python.org/pypi/tillcast)

Send a receipt to a printer from your own software: create a print job, make the call safe to retry and read the job back. Pre-release (0.x): the Tillcast API is live, but method names can still change before 1.0, so pin the version.

## Table of Contents

- [Documentation](#documentation)
- [Installation](#installation)
- [Reference](#reference)
- [Before You Start](#before-you-start)
- [Create A Print Job](#create-a-print-job)
- [Retry Safely](#retry-safely)
- [Read A Job](#read-a-job)
- [A Refused Document](#a-refused-document)
- [Usage](#usage)
- [Environments](#environments)
- [Async Client](#async-client)
- [Exception Handling](#exception-handling)
- [Advanced](#advanced)
  - [Access Raw Response Data](#access-raw-response-data)
  - [Retries](#retries)
  - [Timeouts](#timeouts)
  - [Custom Client](#custom-client)
- [Contributing](#contributing)

## Documentation

API reference documentation is available [here](https://docs.tillcast.com/api-reference).

## Installation

```sh
pip install tillcast
```

## Reference

A full reference for this library is available [here](https://docs.tillcast.com/api-reference).

## Before you start

You need an API key and the id of a printer.

- **An API key.** In the [dashboard](https://dashboard.tillcast.com), open **API keys** and create a key with the scopes `jobs:write` (create a job), `jobs:read` (read one) and `printers:read` (list printers). The key is shown once. Keep it in an environment variable, never in your code. [Authentication and API keys](https://docs.tillcast.com/api/authentication) says more, and the [quickstart](https://docs.tillcast.com/quickstart) goes from sign-up to a first receipt.
- **The id of a printer**, `prn_...`. It is in the answer that adds the printer, in the printers list of the dashboard, and from `client.printers.list()` (see "Read a job" below).

Build the client with the key as `token`. The samples below read the key and the printer id from `TILLCAST_API_KEY` and `TILLCAST_PRINTER_ID`, and they continue one another, so they run as one script.

```python
import os

from tillcast import Tillcast

client = Tillcast(token=os.environ["TILLCAST_API_KEY"])
```


## Create a print job

A job is one document for one printer. The `document` is a list of blocks in print order, written as plain dicts. This receipt has a centred title, a table with a rule and a total.

```python
job = client.jobs.create(
    printer=os.environ["TILLCAST_PRINTER_ID"],
    idempotency_key="order-4711-bill",
    document=[
        {"type": "text", "text": "Harbour Cafe", "align": "center", "bold": True, "size": 2},
        {"type": "text", "text": "Table 7", "align": "center"},
        {
            "type": "table",
            "columns": ["*", {"width": 9, "align": "right"}],
            "rows": [
                ["Flat white", "3.40"],
                ["Lemon cake", "4.20"],
                {"type": "rule"},
                [{"text": "Total", "bold": True}, {"text": "7.60", "bold": True}],
            ],
        },
    ],
    client_reference_id="order-4711",
)
print(job.id, job.status, job.warnings)
```

The answer is the job, and its `status` is `queued`. The printer takes it at its next poll and prints it. Text of your own, such as the name of an item, goes into a block as it is: nothing in a block is markup. [Receipt documents](https://docs.tillcast.com/concepts/documents) describes every block.

If you have text written for other ReceiptLine tools, send it as `receiptline` instead of `document`. Send one of the two, never both.

```python
client.jobs.create(
    printer=os.environ["TILLCAST_PRINTER_ID"],
    idempotency_key="order-4712",
    receiptline="Harbour Cafe\nTable 7\n{width:*,9}\nFlat white | 3.40\nLemon cake | 4.20\n-\nTotal | 7.60",
    client_reference_id="order-4712",
)
```

[Create a print job](https://docs.tillcast.com/create-a-print-job) in the docs has the same call with cURL, every field and the refusals.


## Retry safely

A call can fail after Tillcast has accepted it. Send an idempotency key with every job, the argument `idempotency_key` in Python. If you send the same request again with the same key, you get the first job back and nothing is printed twice. Use one key for each print you intend, for example the order number and the kind of paper, and a new key for a new receipt.

The client also retries a request on its own, twice, when the answer is `408`, `409`, `429` or a `5xx`. The retry carries the same key, so with a key it is safe. Without one, a retry after a lost answer can print twice.

This sends the same request twice, as a retry would. The first answer is `201`. The second is `200` with the header `Idempotent-Replayed: true` and the same job `id`.

```python
def send():
    return client.jobs.with_raw_response.create(
        printer=os.environ["TILLCAST_PRINTER_ID"],
        idempotency_key="order-4711-kitchen",
        document=[{"type": "text", "text": "Table 7: flat white"}],
        client_reference_id="order-4711",
    )


first = send()
again = send()

print(first.status_code, first.data.id)
print(again.status_code, again.headers.get("idempotent-replayed"), again.data.id)
```

The same key with a different request is `422 idempotency_key_reused`. A key is remembered for 24 hours. [Idempotency](https://docs.tillcast.com/api/idempotency) has the rules.


## Read a job

Read a job back with its `id`. It moves from `queued` to `delivered` to `printed`, or it ends `failed`, `expired` or `cancelled`. When it is `failed`, `reason` and `result_code` say why.

```python
status = client.jobs.get(job.id)
print(status.status, status.reason, status.result_code)
```

A printer takes a job within about one poll interval, 5 seconds by default, so do not poll faster than you need. Webhooks, which would tell you without polling, are planned and do not exist yet.

The printer id comes from the answer that adds the printer, from the printers list of the dashboard, or from the API. If you gave each printer your own `client_reference_id`, look the printer up with it.

```python
printers = client.printers.list(client_reference_id="kitchen-1")
print([printer.id for printer in printers.data])
```


## A refused document

Tillcast checks the document when it accepts the job, so a mistake is an answer to your request and no job is made. A document that cannot be printed as it is said is `422 document_invalid`, and `param` is the path of the first problem. This table has two columns and a row of three cells.

```python
from tillcast import UnprocessableEntityError

try:
    client.jobs.create(
        printer=os.environ["TILLCAST_PRINTER_ID"],
        idempotency_key="order-4713-bill",
        document=[
            {"type": "text", "text": "Harbour Cafe"},
            {"type": "table", "columns": ["*", 9], "rows": [["Flat white", "3.40", "1"]]},
        ],
    )
except UnprocessableEntityError as err:
    error = err.body.error
    print(error.code, error.param, error.message, error.request_id)
```

Here `code` is `document_invalid` and `param` is `document[1].rows[0]`: block 1 is the table, and row 0 is its first row. A refused request leaves its key free. Any other refusal is a subclass of `ApiError` (`tillcast.core.api_error.ApiError`) with `status_code` and `body`. Branch on `body.error.code`, for example `resource_missing` when there is no such printer, `customer_suspended` or `queue_full`. [Errors](https://docs.tillcast.com/api/errors) lists the codes and what to do.


## Usage

Instantiate and use the client with the following:

```python
from tillcast import Tillcast

client = Tillcast(
    token="<token>",
)

client.jobs.create(
    printer="prn_01M44X7TQ0A9R2H5J8K1M4N7P0",
    idempotency_key="order-1042",
    client_reference_id="order-1042",
    document=[
        {
            "type": "text",
            "align": "center",
            "bold": True,
            "size": 2,
            "text": "Harbour Cafe"
        },
        {
            "type": "text",
            "align": "center",
            "text": "Old Town 1"
        },
        {
            "type": "table",
            "columns": [
                "*",
                {
                    "align": "right",
                    "width": 9
                }
            ],
            "rows": [
                [
                    "Flat white",
                    "3.40"
                ],
                [
                    "Lemon cake",
                    "4.20"
                ],
                {
                    "type": "rule"
                },
                [
                    {
                        "bold": True,
                        "text": "Total"
                    },
                    {
                        "bold": True,
                        "text": "7.60"
                    }
                ]
            ]
        },
        {
            "type": "qr",
            "align": "center",
            "data": "https://tillcast.com/"
        }
    ],
    expires_in=3600,
    metadata={
        "table": "7"
    },
)
```

## Environments

This SDK allows you to configure different environments for API requests.

```python
from tillcast import Tillcast
from tillcast.environment import TillcastEnvironment

client = Tillcast(
    environment=TillcastEnvironment.PRODUCTION,
)
```

## Async Client

The SDK also exports an `async` client so that you can make non-blocking calls to our API. Note that if you are constructing an Async httpx client class to pass into this client, use `httpx.AsyncClient()` instead of `httpx.Client()` (e.g. for the `httpx_client` parameter of this client).

```python
import asyncio

from tillcast import AsyncTillcast

client = AsyncTillcast(
    token="<token>",
)


async def main() -> None:
    await client.jobs.create(
        printer="prn_01M44X7TQ0A9R2H5J8K1M4N7P0",
        idempotency_key="order-1042",
        client_reference_id="order-1042",
        document=[
            {
                "type": "text",
                "align": "center",
                "bold": True,
                "size": 2,
                "text": "Harbour Cafe"
            },
            {
                "type": "text",
                "align": "center",
                "text": "Old Town 1"
            },
            {
                "type": "table",
                "columns": [
                    "*",
                    {
                        "align": "right",
                        "width": 9
                    }
                ],
                "rows": [
                    [
                        "Flat white",
                        "3.40"
                    ],
                    [
                        "Lemon cake",
                        "4.20"
                    ],
                    {
                        "type": "rule"
                    },
                    [
                        {
                            "bold": True,
                            "text": "Total"
                        },
                        {
                            "bold": True,
                            "text": "7.60"
                        }
                    ]
                ]
            },
            {
                "type": "qr",
                "align": "center",
                "data": "https://tillcast.com/"
            }
        ],
        expires_in=3600,
        metadata={
            "table": "7"
        },
    )


asyncio.run(main())
```

## Exception Handling

When the API returns a non-success status code (4xx or 5xx response), a subclass of the following error
will be thrown.

```python
from tillcast.core.api_error import ApiError

try:
    client.jobs.create(...)
except ApiError as e:
    print(e.status_code)
    print(e.body)
```

## Advanced

### Access Raw Response Data

The SDK provides access to raw response data, including headers, through the `.with_raw_response` property.
The `.with_raw_response` property returns a "raw" client that can be used to access the `.headers` and `.data` attributes.

```python
from tillcast import Tillcast

client = Tillcast(...)
response = client.jobs.with_raw_response.create(...)
print(response.headers)  # access the response headers
print(response.status_code)  # access the response status code
print(response.data)  # access the underlying object
```

### Retries

The SDK is instrumented with automatic retries with exponential backoff. A request will be retried as long
as the request is deemed retryable and the number of retry attempts has not grown larger than the configured
retry limit (default: 2).

Which status codes are retried depends on the `retryStatusCodes` generator configuration:

**`legacy`** (current default): retries on
- [408](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/408) (Timeout)
- [409](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409) (Conflict)
- [429](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429) (Too Many Requests)
- [5XX](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#server_error_responses) (All server errors, including 500)

**`recommended`**: retries on
- [408](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/408) (Timeout)
- [409](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409) (Conflict)
- [429](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429) (Too Many Requests)
- [502](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/502) (Bad Gateway)
- [503](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/503) (Service Unavailable)
- [504](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504) (Gateway Timeout)

Use the `max_retries` request option to configure this behavior.

```python
client.jobs.create(..., request_options={
    "max_retries": 1
})
```

### Timeouts

The SDK defaults to a 60 second timeout. You can configure this with a timeout option at the client or request level.

```python
from tillcast import Tillcast

client = Tillcast(..., timeout=20.0)

# Override timeout for a specific method
client.jobs.create(..., request_options={
    "timeout": 1
})
```

### Custom Client

You can override the `httpx` client to customize it for your use-case. Some common use-cases include support for proxies
and transports.

```python
import httpx
from tillcast import Tillcast

client = Tillcast(
    ...,
    httpx_client=httpx.Client(
        proxy="http://my.test.proxy.example.com",
        transport=httpx.HTTPTransport(local_address="0.0.0.0"),
    ),
)
```

## Contributing

While we value open-source contributions to this SDK, this library is generated programmatically.
Additions made directly to this library would have to be moved over to our generation code,
otherwise they would be overwritten upon the next generated release. Feel free to open a PR as
a proof of concept, but know that we will not be able to merge it as-is. We suggest opening
an issue first to discuss with us!

On the other hand, contributions to the README are always very welcome!

