Metadata-Version: 2.5
Name: cheqi-sdk
Version: 2.1.2
Summary: Cheqi Python SDK for end-to-end encrypted receipt processing
Author-email: Cheqi <support@cheqi.io>
License-Expression: MIT
Classifier: Development Status :: 3 - Alpha
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
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: Typing :: Typed
Requires-Python: >=3.9
Requires-Dist: cryptography>=42.0
Requires-Dist: httpx>=0.27
Requires-Dist: lxml>=5.2
Requires-Dist: pydantic>=2.5
Requires-Dist: wasmtime<51,>=50.0.1
Provides-Extra: dev
Requires-Dist: lxml-stubs>=0.5; extra == 'dev'
Requires-Dist: mypy>=1.0; extra == 'dev'
Requires-Dist: pytest-cov>=4.0; extra == 'dev'
Requires-Dist: pytest-httpx>=0.30; extra == 'dev'
Requires-Dist: pytest>=7.0; extra == 'dev'
Requires-Dist: pyyaml>=6.0; extra == 'dev'
Requires-Dist: ruff>=0.4; extra == 'dev'
Requires-Dist: types-pyyaml>=6.0; extra == 'dev'
Description-Content-Type: text/markdown

# Cheqi Python SDK

Python SDK for resolving receipt recipients and issuing end-to-end encrypted Cheqi receipts and
credit notes. It also provides client-encrypted receipt downloads, receipt-envelope decryption,
integrity helpers, and store management.

The SDK preserves Cheqi's zero-knowledge boundary: the issuer supplies definitive receipt values,
which are encrypted locally for each owner device. The SDK does not calculate totals, enrich
payment data, fiscalize receipts, or submit plaintext receipt bodies to Cheqi on the digital route.

## Install

```bash
pip install cheqi-sdk
```

Python 3.9 or newer is required.

Version `2.1.2` preserves exact monetary values as decimal strings, encrypts the
same receipt snapshot that passed validation, and adds local credit-note download
preparation with the original invoice reference for matching in the receiving wallet.

Version `2.1.0` adds automatic receipt validation and
`sdk.receipt_service.validate(payload)` for an explicit check before issuance.
New receipts must include the payment amounts and VAT facts described in
[Receipt validation](#receipt-validation).

Version `2.0.0` replaces the per-method `access_token` argument with a keyword-only
`options: RequestOptions` on every API call, and adds `sdk.oauth_service` for requesting
per-Grant company access tokens. See [Request options and OAuth](#request-options-and-oauth).
It retains version 2 QR download envelopes, match-recovery tools, company-expense receipt
attribution, member receipt identities, employee invitation roles, and the latest encrypted
delivery metadata.

Upgrading from 1.x: replace `access_token=token` with
`options=RequestOptions.with_access_token(token)`, and pass `resend_pending` to
`invite_users` before the keyword-only options.

## Initialize

```python
from cheqi import CheqiSDK, Environment

sdk = CheqiSDK(
    environment=Environment.SANDBOX,
    api_key="your_api_key",
)
```

A custom backend can be used with `custom_api_endpoint=` and, when needed,
`receipt_download_base_url=`.

## Request options and OAuth

Every API method takes a keyword-only `options: RequestOptions`. Use it to act on behalf of a
connected company with its OAuth access token, or to override the timeout or retry count for one
call. Without an access token, the call uses the configured `api_key`.

```python
from cheqi import RequestOptions

options = RequestOptions.with_access_token(access_token)
stores = sdk.store_service.get_stores(company_id, options=options)
```

The same `RequestOptions` can also set `timeout_seconds` and `max_retries` for a single call.

Company access tokens are short-lived and bound to one Grant, so an integration that serves
several companies holds one token per Grant. Request one with the client-credentials grant:

```python
from cheqi.models.generated.client_credentials_token_request import ClientCredentialsTokenRequest

token = sdk.oauth_service.request_access_token(ClientCredentialsTokenRequest(
    client_id=client_id,
    client_secret=client_secret,
    grant_id=str(grant_id),
    scope="receipt:issue",
))
# token.access_token, token.expires_in
```

The SDK does not cache or refresh tokens. Store each token with its expiry in your own token
store, request a new one before it expires, and pass the current token with `RequestOptions`.

An existing synchronous `httpx.Client` can be injected with `http_client=`. The SDK leaves an
injected client open; clients created by the SDK are closed by `sdk.close()` or the context manager.

## Issue a receipt

The generated classes are the canonical API contract. Handwritten receipt classes subclass that
contract only to add Python-friendly `Decimal` handling and small convenience methods.

```python
from datetime import datetime, timezone

from cheqi.models import (
    CardDetails,
    IdentificationDetails,
    PaymentDetails,
    PaymentType,
    Product,
    ReceiptPayload,
    Tax,
    TaxCategoryCode,
    UnitCode,
)

identification = IdentificationDetails(
    payment_type=PaymentType.CARD_PAYMENT,
    card_details=CardDetails(
        payment_account_reference="PAR123456789",
        card_provider="VISA",
        last_four_digits="4242",
    ),
)

product = Product(
    name="Coffee beans",
    brand_name="Cheqi Coffee",
    identifier="SKU-COFFEE-001",
    quantity=1,
    base_quantity=1,
    unit_code=UnitCode.C62,
    unit_price="10.00",
    subtotal="10.00",
    total="12.10",
).add_tax(Tax(rate=21, type="VAT", taxable_amount=10, amount=2.1, category=TaxCategoryCode.STANDARD))

payload = ReceiptPayload(
    document_number="POS-2026-0001",
    issue_date=datetime.now(timezone.utc),
    currency="EUR",
    receipt_subtotal="10.00",
    total_before_tax="10.00",
    total_tax_amount="2.10",
    total_amount="12.10",
    taxes_applied=True,
    products=[product],
    taxes=[Tax(rate=21, type="VAT", taxable_amount=10, amount=2.1, category=TaxCategoryCode.STANDARD)],
    payment_details=PaymentDetails(
        paid_amount=12.1,
        amount_due=0,
        rounding_amount=0,
        payment_means_code="48",
        description="Card payment",
        card_provider="VISA",
        card_last_four="4242",
        merchant_id="MID-123",
        payment_terminal_id="TID-456",
    ),
)

result = sdk.receipt_service.issue_receipt(identification, payload)

if result.is_accepted:
    print(result.cheqi_receipt_id)
elif result.email_receipt_required:
    # Generate and submit the permitted email-fallback receipt explicitly.
    pass
elif result.download_envelope_required:
    # Generate the final ReceiptEnvelope locally and complete the fallback.
    pass
```

To associate a receipt with a store or use OAuth:

```python
result = sdk.receipt_service.issue_receipt(
    identification,
    payload,
    store_id=store_id,
    options=RequestOptions.with_access_token(access_token),
)
```

All monetary, tax, payment, barcode, and jurisdictional values remain caller-supplied. For example,
`Product.add_tax(...)` only appends the supplied tax; it does not calculate it.

## Receipt validation

The SDK checks receipt data locally before matching, encryption or submission.
Supply all payment amounts, including zero, and the VAT category and amount for
each line and receipt-level tax entry. Invalid data stops issuance; the SDK
never fills in or corrects financial values.

```python
from cheqi import CheqiSDKError

try:
    result = sdk.receipt_service.issue_receipt(identification, payload)
except CheqiSDKError as error:
    if error.validation_report is None:
        raise
    for issue in error.validation_report.issues:
        print(f"{issue.rule_id} — {issue.path}: {issue.message}")
```

For an optional preflight without issuing a receipt:

```python
report = sdk.receipt_service.validate(payload)
if not report.valid:
    for issue in report.issues:
        print(f"{issue.rule_id} — {issue.path}: {issue.message}")
```

The method returns a report for valid and invalid receipt data without changing
the payload or making an API request. Invalid fields appear in the report; wrong
payload types, serialization errors and validator failures raise `CheqiSDKError`.
The standalone `ReceiptPayloadValidator().validate(payload)` remains available
after importing `ReceiptPayloadValidator` from `cheqi`.
The validator is bundled with the SDK and runs without a network request.
Issuance validates one JSON snapshot and encrypts that same snapshot for every
device and fallback download, even if application callbacks later change the model.
Monetary fields in the public receipt models retain `Decimal` values and serialize
as decimal strings, preserving precision and trailing zeros, as in the Java SDK.
Use `Decimal` or strings for exact input; precision already lost in a Python float
cannot be recovered. Generated models remain unchanged.

Use `sdk.receipt_service.prepare_download(payload)` to validate and prepare an
encrypted browser receipt locally without matching or uploading it. The existing
`validate(payload)` and `ReceiptPayloadValidator().validate_or_raise(payload)`
methods remain available.

The [validation flow](docs/receipt-validation.mmd) precedes the existing issuance flow.

## Delivery routes and downloads

The backend selects `DIGITAL`, `DOWNLOAD_FALLBACK`, or `EMAIL_FALLBACK`.

- Digital receipts are independently encrypted for every matched device and submitted immediately.
- Download fallback is completed automatically when `IdentificationDetails.payment_type` is set.
- Without local payment context, `download_envelope_required` asks the caller for a final generated
  `ReceiptEnvelope`.
- Email fallback is returned as an explicit action and is not performed automatically.

An explicit customer-without-Cheqi flow can skip matching:

```python
result = sdk.receipt_service.issue_download_receipt(
    IdentificationDetails(payment_type=PaymentType.CASH),
    payload,
    options=RequestOptions.with_access_token(access_token),
)
print(result.download_url)
```

The AES key is stored only in the URL fragment and is never sent to Cheqi.

## Credit notes and return requests

Definitive merchant-issued credit notes use the same device encryption model and a separate API
envelope:

```python
result = sdk.credit_note_service.issue_credit_note(
    identification,
    parent_cheqi_receipt_id,
    credit_note_payload,
    options=RequestOptions.with_access_token(access_token),
)
```

Customer return requests are represented by `CreditNoteInitiationRequest`, `ReturnLineItem`,
`ReturnReasonCode`, and `RefundPreference`. Pydantic validates positive return quantities and the
bank-account rules for `BANK_TRANSFER`. Receiving issuers can decrypt and validate queued or
webhook requests in one call:

```python
request = sdk.decryption_service.decrypt_credit_note_initiation_request(
    encrypted_request,
    private_key_base64,
)
```

## Receipt decryption

```python
envelope = sdk.decryption_service.decrypt_receipt(
    encrypted_receipt_delivery_or_webhook_envelope,
    private_key_base64,
)
```

The plaintext is the generated `ReceiptEnvelope`; no backend-context merge step is required.
For company-expense deliveries, its optional `expense_submission` field contains the encrypted
`ExpenseSubmissionEnvelope` attribution metadata.

## Lower-level operations

The matching, encryption, submission, download, verification, and store services are exposed on
`CheqiSDK`. Examples include:

```python
resolution = sdk.matching_service.match_customer(identification, options=options)
delivery = sdk.encryption_service.encrypt_for_device(payload.to_json(), resolution.recipients[0])
receipt_hash = sdk.verification_service.calculate_cheqi_receipt_hash(payload.to_json())
canonical_json = sdk.verification_service.canonicalize_cheqi_receipt(payload)
ubl_hash = sdk.verification_service.calculate_ubl_hash(ubl_xml)
stores = sdk.store_service.get_stores(company_id, options=options)
```

## Development

```bash
python -m pip install -e '.[dev]'
pytest
ruff check src tests
mypy src/cheqi
```


## Match recovery and low-level tools

`issue_receipt` returns `ReceiptResult.state`: `DIGITAL_SUBMITTED`, `DIGITAL_PENDING`,
`DIGITAL_EXPIRED`, `DOWNLOAD_FALLBACK`, or the existing `EMAIL_FALLBACK`.
An uncertain digital acknowledgement preserves `match_id` and prepares an encrypted
download locally. Upload `prepared_download` before the QR can serve its content.
Persist that object locally (it includes the secret URL fragment), and retain the original QR.

```python
match = sdk.receipt_service.get_match(match_id)
envelope = sdk.receipt_service.generate_encrypted_receipt_envelope(
    match, receipt_payload, store_id=store_id,
)
submission = sdk.receipt_service.submit_encrypted_receipt(envelope)

# Alternatively, one explicit high-level recovery operation:
result = sdk.receipt_service.resume_receipt(match_id, receipt_payload, store_id=store_id)
# Upload the original persisted fallback independently:
sdk.receipt_service.upload_prepared_download(prepared_download)
```

Generated `MatchStatusResponse`, `MatchState`, `EncryptedReceiptEnvelope`,
`ReceiptSubmissionResponse`, and `ClientReceiptDownloadRequest` are reused.
Recovery needs no PAR, PAR-derived hash, saved resolution, or saved recipient keys.
Completed submissions are recoverable after expiry; unsubmitted expiry is terminal
(`DIGITAL_EXPIRED`, `retryable=False`). A healthy no-route match still raises
customer-not-found rather than bypassing fallback policy.
The existing HTTP retry policy is unchanged. No polling, queues, storage, or background
workers are added: integration partners own scheduling and recovery architecture.
Low-level failures preserve API status, code, correlation id and in-progress retry delay.
See [the recovery flow](docs/receipt-retry.mmd).

## Credit notes in the web wallet

For the web wallet, issue the credit note through an ordinary encrypted receipt
link. Include its own `documentNumber`, the original invoice's exact number in
`originatorDocumentReference`, and the normal `taxesApplied` boolean. The helper
also accepts the existing generation wrapper with `taxesApplied` at its root and
`creditNoteTemplateRequest` as its body. Amounts are preserved without calculations.

The reference stays inside the ciphertext. There is no backend invoice lookup,
reference hash, parent Cheqi ID or encrypted parent-link field. Once the customer
opens the credit note's link, the wallet matches the decrypted reference to one
local invoice with that exact document number from the same issuer. If no unique
invoice is available, the note remains visible on its own and can link later.
The original invoice is unchanged, and both documents support ordinary PDF/XML
export and independent removal.

Preparation is local and reuses the existing `PreparedReceiptDownload` result and
backend-generated envelope/upload models. Persist it before upload; retry the same
prepared ciphertext after uncertain outcomes. For a custom receipt host, supply
`baseUrl` (`base_url` in Python) to preparation. The browser needs the updated
credit-note envelope support; no new backend routing endpoint or migration is needed.

```python
prepared = sdk.credit_note_service.prepare_download(credit_note_payload)
# Persist prepared and show prepared.download_url as the normal receipt link/QR.
sdk.receipt_service.upload_prepared_download(prepared)
```
