From 45c38197cc9ea8e36f33e6d7329cbc3f7e35c6e4 Mon Sep 17 00:00:00 2001 From: Sander van Hooft <7265703+sandervanhooft@users.noreply.github.com> Date: Mon, 30 Nov 2026 09:59:33 +0000 Subject: [PATCH 1/2] Checkout and order discounts Adds CreateCheckoutRequest.discounts (one CheckoutDiscount: percentage or fixed EUR amount, optional description) and read-only Order/OrderLine.discounts, also in order webhooks, with amounts excluding taxes. Syncs openapi.yaml with docs.vatly.com. Amp-Thread-ID: https://ampcode.com/threads/T-3f59dfd0-1f6e-41a8-b940-15b496a7ab0c Co-authored-by: Amp --- CHANGELOG.md | 13 +++ docs/Checkouts.md | 32 ++++++ docs/Development.md | 14 ++- docs/Orders.md | 24 ++++ openapi.yaml | 149 ++++++++++++++++++++++++- scripts/generate.py | 10 ++ src/vatly/models.py | 259 +++++++++++++++++++++++++++++++------------- tests/test_sdk.py | 90 +++++++++++++++ 8 files changed, 504 insertions(+), 87 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d87aae..8f4837d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,19 @@ ## Unreleased +- Sync `openapi.yaml` with the production specification (discounts). +- `CreateCheckoutRequest.discounts` takes an optional list of `CheckoutDiscount`, at + most one for now: a `percentage` or a fixed EUR `amount`, plus an optional + `description`. A fixed amount follows the products' tax basis. Validation errors + from Vatly are keyed `discounts.0.*`. +- Add `Order.discounts` and `OrderLine.discounts`, lists of `Discount` with `id`, + `description`, `discount_type`, `percentage` and `amount` (always excluding taxes), + on order resources and in order webhooks. `discount_type` is an open string: + values other than `percentage` and `fixed_amount` parse. Orders and lines without + `discounts`, such as webhook events stored before discounts existed, read as `[]`. +- `OrderLine` field descriptions now say `subtotal`, `taxes` and `total` are net of + discounts, and `base_price` is on the product's tax basis. + - The `User-Agent` is now a chain of `vendor/package/version` tokens, starting with `vatly/vatly-api-python/ Python/ httpx/` instead of `vatly-api-python/`, matching the other Vatly SDKs. diff --git a/docs/Checkouts.md b/docs/Checkouts.md index 2eebb72..b565025 100644 --- a/docs/Checkouts.md +++ b/docs/Checkouts.md @@ -35,6 +35,7 @@ that convenience belongs to Fluent. | `redirect_url_canceled` | `redirectUrlCanceled` | Yes | | `customer_id` | `customerId` | No: an authorized existing customer | | `locale`, `metadata`, `billing_address` | `locale`, `metadata`, `billingAddress` | No | +| `discounts` | `discounts` | No: at most one [discount](#add-a-discount) | Pydantic inputs accept Python names. Dictionary inputs use wire keys, including `trialDays` inside product dictionaries. Omit `customer_id` for a guest checkout. @@ -42,6 +43,37 @@ Omit `trialDays`, or pass `None`, for no trial; `0` is rejected before sending. `metadata` takes up to 50 string values, with keys up to 40 characters and values up to 500 characters. The SDK rejects anything else before calling Vatly. +## Add a discount + +```python +from vatly import VatlyClient +from vatly.models import CheckoutDiscount, CreateCheckoutRequest + + +def example(client: VatlyClient): + checkout = client.checkouts.create( + CreateCheckoutRequest( + products=[{"id": "one_off_product_example", "quantity": 1}], + redirect_url_success="https://app.example.com/billing/success", + redirect_url_canceled="https://app.example.com/billing/canceled", + discounts=[CheckoutDiscount(percentage="20", description="Black Friday")], + ) + ) + return checkout.id +``` + +A `CheckoutDiscount` takes a `percentage` (above 0 and below 100, at most three +decimals) or a fixed `amount` such as `{"value": "10.00", "currency": "EUR"}`, not +both, and an optional `description` of up to 255 characters shown on the checkout +and invoice. Send at most one discount; a second is rejected before sending. + +A fixed `amount` follows the products' tax basis: it includes taxes on tax-inclusive +products and excludes them on tax-exclusive ones. The discount applies to each +product's first payment only; renewals are charged in full. On a subscription in +trial it moves to the first paid charge, on tax-inclusive prices too. Validation +errors are keyed `discounts.0.*`, for example `error.errors["discounts.0.amount"]` +on a `VatlyValidationError`. + ## Read a checkout or traverse pages ```python diff --git a/docs/Development.md b/docs/Development.md index 9ad1009..bb31d0e 100644 --- a/docs/Development.md +++ b/docs/Development.md @@ -59,8 +59,10 @@ Review the generated diff and rerun the checks above. Do not hand-edit generated models, resources, clients or `docs/API.md`. Output models preserve extra fields and keep URLs and emails as strings. The -generator handles two observed API differences: metadata `[]` becomes `{}`, and -response product types stay open to catalogue values added before the next sync. +generator handles three observed API differences: metadata `[]` becomes `{}`, +response product types stay open to catalogue values added before the next sync, and +order and order-line `discounts` default to `[]` for webhook payloads stored before +discounts existed. Request validation follows the pinned schema: dictionaries are validated through the request model, request metadata limits are checked, and only spec-defined fields are sent, with `null` only where the specification allows it. Invalid responses raise `VatlyApiError`; avoid @@ -70,14 +72,14 @@ logging response bodies that may contain personal data. | Source | Revision | | --- | --- | -| Production OpenAPI, retrieved 2026-11-24 | [vatly-docs specification](https://github.com/vatly/vatly-docs/blob/7ec49a749e7b3df53cfce8e498160f03003e0dd9/public/openapi.yaml) | +| Production OpenAPI, retrieved 2026-11-30 | [vatly-docs specification](https://github.com/vatly/vatly-docs/blob/0caf974016352f9aabb1910a01e3002ecd882d68/public/openapi.yaml) | | Original JS design reference | [SDK revision](https://github.com/vatly/vatly-api-js/commit/8b0b920c29f7e7b30bf71b9e379ec0a8a1a22028) | -The checked-in specification is byte-identical to that source and to the bundle -published by Vatly's production release. Its SHA-256 is: +The checked-in specification is byte-identical to that source, which docs.vatly.com +serves. Its SHA-256 is: ```text -a8aff52f58ff58cda5b1de0f911849ba21109ea07d5df66d55747262eb21f29d +75c539cd33a5d3f5629ae5c806b9e0158ebcd48c1ff5d2a96f95a4ca47ed167c ``` The specification's generated-at date is not its retrieval date. diff --git a/docs/Orders.md b/docs/Orders.md index 0ecbac9..a6e84fd 100644 --- a/docs/Orders.md +++ b/docs/Orders.md @@ -28,6 +28,7 @@ def example(client: VatlyClient): | `id`, `status`, `customer_id` | Order identity and payment state | | `lines` | OrderLine models with `id`, `product_type`, `product_id`, `quantity`, `related_resources` | | `refundable_subtotal`, `reversed_subtotal` | Money wrappers; read `.root.value` and `.root.currency` | +| `discounts` | Discount models applied to the order; each line also has its share in `line.discounts` | | `links.customer_invoice` | Optional customer invoice link | | `testmode`, `metadata` | Mode and custom data | @@ -41,6 +42,29 @@ until the subscription is available; read the order again later. An ID alone does not prove activation or entitlement: check the subscription's ownership and status before granting access. +## Read discounts + +```python +from decimal import Decimal +from vatly import VatlyClient + + +def example(client: VatlyClient): + order = client.orders.get("order_example") + off = {d.id: Decimal(d.amount.root.value) for d in order.discounts} + per_line = [(line.id, [d.id for d in line.discounts]) for line in order.lines] + return off, per_line +``` + +`order.discounts` lists each discount once with its total over all lines; each +line's `discounts` holds its share, matched by `id`. Line `subtotal`, `taxes` and +`total` are already net of discounts. A discount's `amount` always excludes taxes, +even on tax-inclusive products. `discount_type` is `"percentage"` or +`"fixed_amount"` today, but more values may be added: treat an unknown value as a +discount of an unknown kind. `id` and `discount_type` are `None` only on discounts +applied before they were recorded. Orders and lines in webhook events stored before +discounts existed parse with empty `discounts`. + ## List orders and request an invoice-details link ```python diff --git a/openapi.yaml b/openapi.yaml index 2f4018d..3e0714a 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -26,14 +26,13 @@ info: #### Payment methods in test mode - A few payment methods work in live mode but cannot be completed in test mode, + Some payment methods work in live mode but cannot be completed in test mode, because the payment provider cannot settle them there. A test-mode checkout still lists them, greyed out and labelled as unavailable, so you can see they exist without being able to select one: | Method | Test mode | Reason | |--------|-----------|--------| - | `banktransfer` | Not selectable | The provider cannot settle bank transfers in test mode | | `paybybank` | Not selectable | The provider cannot settle Pay by Bank in test mode | Every other method behaves identically in both modes. Test a checkout with any @@ -1906,6 +1905,7 @@ paths: lines: - id: order_item_Mn6xBtPvKw2RjTgYcZaE resource: orderline + discounts: [] description: Pro Monthly Subscription quantity: 1 basePrice: @@ -1927,6 +1927,7 @@ paths: currency: EUR productType: subscription productId: subscription_Hn5xWqVfKm8RjTgYbUcP + discounts: [] customerDetails: fullName: John Doe companyName: Acme Corp @@ -2015,6 +2016,7 @@ paths: lines: - id: order_item_Jk4pQrSvWm8NjLhYbUcP resource: orderline + discounts: [] description: Pro Monthly Subscription — initial checkout quantity: 1 basePrice: @@ -2038,6 +2040,7 @@ paths: productId: subscription_plan_Hn5xWqVfKm8RjTgYbUcP relatedResources: subscriptionId: subscription_Hn5xWqVfKm8RjTgYbUcP + discounts: [] customerDetails: fullName: John Doe companyName: Acme Corp @@ -3236,6 +3239,7 @@ paths: lines: - id: order_item_Mn6xBtPvKw2RjTgYcZaE resource: orderline + discounts: [] description: Pro Monthly Subscription quantity: 1 basePrice: @@ -3257,6 +3261,7 @@ paths: currency: EUR productType: subscription productId: subscription_Hn5xWqVfKm8RjTgYbUcP + discounts: [] customerDetails: fullName: John Doe companyName: Acme Corp @@ -4512,6 +4517,7 @@ paths: lines: - id: order_item_Jk4pQrSvWm8NjLhYbUcP resource: orderline + discounts: [] description: Pro Monthly Subscription quantity: 1 basePrice: @@ -4533,6 +4539,7 @@ paths: currency: EUR productType: subscription productId: subscription_Hn5xWqVfKm8RjTgYbUcP + discounts: [] customerDetails: fullName: John Doe companyName: Acme Corp @@ -6155,6 +6162,32 @@ components: quantity: 1 - id: subscription_plan_Rk5pQrSvWm8NjLhYbUcP trialDays: 14 + discounts: + type: + - array + - 'null' + description: | + Discounts on the whole checkout, spread over the discountable lines in + proportion to each line's subtotal. At most one entry for now; a second returns a `422`. + Entries will apply in array order, each on what the earlier ones left. + + The discount reduces the first payment of each product only; renewals + are charged the full price. For a subscription on trial, that is its + first payment after the trial, which stays discounted if its plan or + quantity changes during the trial. A percentage applies to every + product's first payment. A fixed amount is split over the same first + payments in proportion to their prices, as a percentage of the same + size would be, keeping at least the smallest unit payable today. On + tax-inclusive prices a fixed amount includes taxes, on today's lines + and on the first payment after a trial alike. + + The resulting order and its lines list the discount under `discounts`. + maxItems: 1 + items: + $ref: '#/components/schemas/CheckoutDiscount' + example: + - description: Black Friday + percentage: 20 Customer: type: object description: | @@ -6738,6 +6771,7 @@ components: - taxSummary - lines - customerDetails + - discounts - links additionalProperties: false properties: @@ -6839,6 +6873,15 @@ components: customerDetails: $ref: '#/components/schemas/BillingDetails' description: Customer billing details (buyer) + discounts: + type: array + description: | + Every discount on the order, each listed once with the amount it takes + off all lines added up, in the order it first appears on the lines. + Empty when the order has no discount. Match an entry to its share on + each line by `id`. + items: + $ref: '#/components/schemas/Discount' links: type: object description: HATEOAS links to related resources @@ -6883,6 +6926,7 @@ components: - total - subtotal - taxes + - discounts additionalProperties: false properties: id: @@ -6905,18 +6949,26 @@ components: example: 1 basePrice: $ref: '#/components/schemas/Money' - description: Price per unit before taxes + description: 'Price per unit before discounts, on the product''s tax basis: excluding taxes for tax-exclusive products, including them for tax-inclusive products' total: $ref: '#/components/schemas/Money' - description: Total price including taxes (basePrice * quantity + taxes) + description: Total price including taxes, after discounts (subtotal + taxes) subtotal: $ref: '#/components/schemas/Money' - description: Subtotal before taxes (basePrice * quantity) + description: Subtotal excluding taxes, after discounts taxes: type: array description: Tax breakdown by rate for this line items: $ref: '#/components/schemas/TaxSummaryItem' + discounts: + type: array + description: | + This line's share of each discount, in the order they apply. Empty when + the line has no discount. `subtotal`, `taxes` and `total` are already + net of these discounts. + items: + $ref: '#/components/schemas/Discount' productType: type: - string @@ -8157,6 +8209,41 @@ components: every 5 minutes) and the field updates from `null` to the resolved value once the sync completes. example: '4242' + CheckoutDiscount: + type: object + description: | + A discount: a `percentage` or a fixed `amount`, not both. + additionalProperties: false + properties: + description: + type: + - string + - 'null' + maxLength: 255 + description: Label shown on the checkout and the invoice. + example: Black Friday + percentage: + oneOf: + - type: number + - type: string + description: | + Percentage to take off, above 0 and below 100, with at most three + decimals. + example: 20 + amount: + allOf: + - $ref: '#/components/schemas/EurMoney' + description: | + Fixed amount to take off, in EUR, on the same basis as the products' + prices: excluding taxes on tax-exclusive products, including them on + tax-inclusive ones. €10.00 off a €121.00 price including taxes charges + €111.00. It must be below the subtotal of the products it discounts, + on that same basis, counting a subscription on trial at its first + payment. When the customer pays in another currency, it is converted + at checkout. + + The order always reports a discount's `amount` excluding taxes, like + `subtotal`: the €10.00 above reads 8.26 at a 21% tax rate. UpdateCustomerRequest: type: object description: | @@ -8368,6 +8455,58 @@ components: amount: $ref: '#/components/schemas/Money' description: Tax amount for this rate + Discount: + type: object + description: | + A discount applied to an order. Amounts exclude taxes; the line's `taxes` + already reflect the discount. + required: + - id + - description + - discountType + - percentage + - amount + additionalProperties: false + properties: + id: + type: + - string + - 'null' + description: | + Identifies this discount on this order. Every line's share of a + discount and the order's entry for it carry the same id. It names one + application, not a reusable coupon: every order, and every subscription + renewal, gets new ids. `null` only on discounts applied before ids were + introduced. + example: discount_KKYYk6SohKNdSqKyHAzZJ2 + description: + type: + - string + - 'null' + description: The label sent with the discount, if any. + example: Black Friday + discountType: + type: + - string + - 'null' + description: | + How the discount is defined: `percentage` or `fixed_amount`. More + values may be added; treat an unknown value as a discount of an + unknown kind. `null` only on discounts applied before it was recorded. + example: percentage + percentage: + type: + - string + - 'null' + description: | + The percentage taken off, as a decimal string, for a `percentage` + discount. `null` for a `fixed_amount` discount. + example: '20.00' + amount: + $ref: '#/components/schemas/Money' + description: | + The amount taken off, excluding taxes, also when the products' prices + include them: €10.00 off a €121.00 price at a 21% tax rate reads 8.26. RefundItem: type: object description: An item to refund from an order diff --git a/scripts/generate.py b/scripts/generate.py index ad3e1b5..afdbcee 100644 --- a/scripts/generate.py +++ b/scripts/generate.py @@ -99,6 +99,11 @@ def wire_strings(value): # Keep the response product type open so catalogue values added before the # next spec sync still parse; request enums stay constrained. schemas["OneOffProduct"]["properties"]["productType"].pop("enum", None) + # Webhook events keep the payload stored when they fired, so orders and lines + # from before discounts were introduced have no `discounts`: read that as none. + for name in ("Order", "OrderLine"): + schemas[name]["required"].remove("discounts") + schemas[name]["properties"]["discounts"]["default"] = [] # Mark request-body fields so the base model sends only spec-defined fields, # sends null only where the spec allows it, and validates request metadata. @@ -177,6 +182,11 @@ def mark(schema: dict, seen: set[str]) -> None: ], check=True, ) + # The codegen makes optional fields nullable; the API never sends a null `discounts`. + models_file = out / "models.py" + models_file.write_text( + models_file.read_text().replace("Sequence[Discount] | None,", "Sequence[Discount],") + ) groups = {} for operation in operations: group = operation[0].split("/")[1] diff --git a/src/vatly/models.py b/src/vatly/models.py index 7c9bfcd..75e7928 100644 --- a/src/vatly/models.py +++ b/src/vatly/models.py @@ -548,79 +548,6 @@ class CheckoutProduct(VatlyModel): ] = None -class CreateCheckoutRequest(VatlyModel): - """ - Request body for creating a new checkout - """ - - model_config = ConfigDict( - extra="allow", - populate_by_name=True, - ) - redirect_url_success: Annotated[ - str, - Field( - alias="redirectUrlSuccess", - description="URL to redirect customers after successful payment.\n\nYou may include the literal `{CHECKOUT_ID}` placeholder anywhere in the\nURL (e.g. `https://example.com/return?checkout_id={CHECKOUT_ID}`). Vatly\nsubstitutes it with this checkout's id at creation time, so the host can\nlearn the checkout id on the redirect back without any server-side token\nstore. Only `{CHECKOUT_ID}` is supported.\n", - examples=["https://example.com/return?checkout_id={CHECKOUT_ID}"], - ), - ] - redirect_url_canceled: Annotated[ - str, - Field( - alias="redirectUrlCanceled", - description="URL to redirect customers if they cancel the checkout.\n\nSupports the same `{CHECKOUT_ID}` placeholder as `redirectUrlSuccess`.\n", - examples=["https://example.com/canceled?checkout_id={CHECKOUT_ID}"], - ), - ] - customer_id: Annotated[ - str | None, - Field( - alias="customerId", - description="Existing customer ID to associate with this checkout.\nIf provided, the customer's email will be pre-filled.\nMust match the testmode of the API token.\n", - examples=["customer_7kBmRtPvXw2NjLhYcZaE"], - json_schema_extra={"x-vatly-nullable": True}, - ), - ] = None - billing_address: Annotated[ - BillingAddress | None, - Field( - alias="billingAddress", - description="Optional editable prefill for the billing address fields on the hosted\ncheckout. When `country` is supplied, it takes precedence over the\nshopper's IP address for determining their country. A supplied `taxId`\nis only a prefill; it is not registered until the buyer submits the\ncheckout.\n", - ), - ] = None - metadata: Annotated[ - Metadata | None, - Field( - json_schema_extra={ - "x-vatly-nullable": True, - "x-vatly-request-metadata": True, - } - ), - ] = None - locale: Annotated[ - str | None, - Field( - description="Language to present the hosted checkout in, including its validation and\nerror messages. Set this when you already know the customer's language —\nit is a better signal than their browser's.\n\nSend a bare language code (`de`), a BCP 47 tag (`de-AT`), or a POSIX /\nISO 15897 locale (`de_DE`) — whichever your stack already stores. All\nthree are folded to the language, so `de`, `de-AT` and `de_DE` are the\nsame request. There are no region-specific variants: an Austrian and a\nGerman customer are both served `de`.\n\nThe language also carries through to the payment provider's own hosted\npage, in whatever format that provider expects.\n\nSupported languages: `en`, `de`, `fr`, `nl`, `es`, `it`, `pt`, `pl`,\n`cs`, `ca`, `da`, `el`, `fi`, `hu`, `is`, `lt`, `lv`, `nb`, `sk`, `sl`,\n`sv`, `tr`. Norwegian is served as `nb`; `no` and `nn` fold to it.\nAnything else is a `422` naming the supported set.\n\nOmit it (or send `null`) to detect the language from the shopper's\n`Accept-Language` header, falling back to English. A shopper can always\noverride your choice with the checkout's own language switcher.\n\nThe response echoes back the folded language, not the string you sent.\n", - examples=["de"], - json_schema_extra={"x-vatly-nullable": True}, - ), - ] = None - products: Annotated[ - Sequence[CheckoutProduct], - Field( - description="Products to include in this checkout", - examples=[ - [ - {"id": "one_off_product_Vr8kQdFhSrG4Y3DnfsdqH", "quantity": 1}, - {"id": "subscription_plan_Rk5pQrSvWm8NjLhYbUcP", "trialDays": 14}, - ] - ], - min_length=1, - ), - ] - - class Links1(VatlyModel): """ HATEOAS links to related resources @@ -1620,6 +1547,40 @@ class Mandate(VatlyModel): ] = None +class CheckoutDiscount(VatlyModel): + """ + A discount: a `percentage` or a fixed `amount`, not both. + + """ + + model_config = ConfigDict( + extra="allow", + populate_by_name=True, + ) + description: Annotated[ + str | None, + Field( + description="Label shown on the checkout and the invoice.", + examples=["Black Friday"], + json_schema_extra={"x-vatly-nullable": True}, + max_length=255, + ), + ] = None + percentage: Annotated[ + float | str | None, + Field( + description="Percentage to take off, above 0 and below 100, with at most three\ndecimals.\n", + examples=[20], + ), + ] = None + amount: Annotated[ + EurMoney | None, + Field( + description="Fixed amount to take off, in EUR, on the same basis as the products'\nprices: excluding taxes on tax-exclusive products, including them on\ntax-inclusive ones. €10.00 off a €121.00 price including taxes charges\n€111.00. It must be below the subtotal of the products it discounts,\non that same basis, counting a subscription on trial at its first\npayment. When the customer pays in another currency, it is converted\nat checkout.\n\nThe order always reports a discount's `amount` excluding taxes, like\n`subtotal`: the €10.00 above reads 8.26 at a 21% tax rate.\n" + ), + ] = None + + class UpdateCustomerRequest(VatlyModel): """ Request body for updating a customer's identity fields. Only `name` and @@ -1851,6 +1812,54 @@ class TaxSummaryItem(VatlyModel): amount: Annotated[Money, Field(description="Tax amount for this rate")] +class Discount(VatlyModel): + """ + A discount applied to an order. Amounts exclude taxes; the line's `taxes` + already reflect the discount. + + """ + + model_config = ConfigDict( + extra="allow", + populate_by_name=True, + ) + id: Annotated[ + str | None, + Field( + description="Identifies this discount on this order. Every line's share of a\ndiscount and the order's entry for it carry the same id. It names one\napplication, not a reusable coupon: every order, and every subscription\nrenewal, gets new ids. `null` only on discounts applied before ids were\nintroduced.\n", + examples=["discount_KKYYk6SohKNdSqKyHAzZJ2"], + ), + ] = None + description: Annotated[ + str | None, + Field( + description="The label sent with the discount, if any.", + examples=["Black Friday"], + ), + ] = None + discount_type: Annotated[ + str | None, + Field( + alias="discountType", + description="How the discount is defined: `percentage` or `fixed_amount`. More\nvalues may be added; treat an unknown value as a discount of an\nunknown kind. `null` only on discounts applied before it was recorded.\n", + examples=["percentage"], + ), + ] = None + percentage: Annotated[ + str | None, + Field( + description="The percentage taken off, as a decimal string, for a `percentage`\ndiscount. `null` for a `fixed_amount` discount.\n", + examples=["20.00"], + ), + ] = None + amount: Annotated[ + Money, + Field( + description="The amount taken off, excluding taxes, also when the products' prices\ninclude them: €10.00 off a €121.00 price at a 21% tax rate reads 8.26.\n" + ), + ] + + class RefundItem(VatlyModel): """ An item to refund from an order @@ -2237,6 +2246,88 @@ class CreateSubscriptionBillingUpdateLinkResponse(VatlyModel): type: Annotated[Literal["text/html"], Field(examples=["text/html"])] +class CreateCheckoutRequest(VatlyModel): + """ + Request body for creating a new checkout + """ + + model_config = ConfigDict( + extra="allow", + populate_by_name=True, + ) + redirect_url_success: Annotated[ + str, + Field( + alias="redirectUrlSuccess", + description="URL to redirect customers after successful payment.\n\nYou may include the literal `{CHECKOUT_ID}` placeholder anywhere in the\nURL (e.g. `https://example.com/return?checkout_id={CHECKOUT_ID}`). Vatly\nsubstitutes it with this checkout's id at creation time, so the host can\nlearn the checkout id on the redirect back without any server-side token\nstore. Only `{CHECKOUT_ID}` is supported.\n", + examples=["https://example.com/return?checkout_id={CHECKOUT_ID}"], + ), + ] + redirect_url_canceled: Annotated[ + str, + Field( + alias="redirectUrlCanceled", + description="URL to redirect customers if they cancel the checkout.\n\nSupports the same `{CHECKOUT_ID}` placeholder as `redirectUrlSuccess`.\n", + examples=["https://example.com/canceled?checkout_id={CHECKOUT_ID}"], + ), + ] + customer_id: Annotated[ + str | None, + Field( + alias="customerId", + description="Existing customer ID to associate with this checkout.\nIf provided, the customer's email will be pre-filled.\nMust match the testmode of the API token.\n", + examples=["customer_7kBmRtPvXw2NjLhYcZaE"], + json_schema_extra={"x-vatly-nullable": True}, + ), + ] = None + billing_address: Annotated[ + BillingAddress | None, + Field( + alias="billingAddress", + description="Optional editable prefill for the billing address fields on the hosted\ncheckout. When `country` is supplied, it takes precedence over the\nshopper's IP address for determining their country. A supplied `taxId`\nis only a prefill; it is not registered until the buyer submits the\ncheckout.\n", + ), + ] = None + metadata: Annotated[ + Metadata | None, + Field( + json_schema_extra={ + "x-vatly-nullable": True, + "x-vatly-request-metadata": True, + } + ), + ] = None + locale: Annotated[ + str | None, + Field( + description="Language to present the hosted checkout in, including its validation and\nerror messages. Set this when you already know the customer's language —\nit is a better signal than their browser's.\n\nSend a bare language code (`de`), a BCP 47 tag (`de-AT`), or a POSIX /\nISO 15897 locale (`de_DE`) — whichever your stack already stores. All\nthree are folded to the language, so `de`, `de-AT` and `de_DE` are the\nsame request. There are no region-specific variants: an Austrian and a\nGerman customer are both served `de`.\n\nThe language also carries through to the payment provider's own hosted\npage, in whatever format that provider expects.\n\nSupported languages: `en`, `de`, `fr`, `nl`, `es`, `it`, `pt`, `pl`,\n`cs`, `ca`, `da`, `el`, `fi`, `hu`, `is`, `lt`, `lv`, `nb`, `sk`, `sl`,\n`sv`, `tr`. Norwegian is served as `nb`; `no` and `nn` fold to it.\nAnything else is a `422` naming the supported set.\n\nOmit it (or send `null`) to detect the language from the shopper's\n`Accept-Language` header, falling back to English. A shopper can always\noverride your choice with the checkout's own language switcher.\n\nThe response echoes back the folded language, not the string you sent.\n", + examples=["de"], + json_schema_extra={"x-vatly-nullable": True}, + ), + ] = None + products: Annotated[ + Sequence[CheckoutProduct], + Field( + description="Products to include in this checkout", + examples=[ + [ + {"id": "one_off_product_Vr8kQdFhSrG4Y3DnfsdqH", "quantity": 1}, + {"id": "subscription_plan_Rk5pQrSvWm8NjLhYbUcP", "trialDays": 14}, + ] + ], + min_length=1, + ), + ] + discounts: Annotated[ + Sequence[CheckoutDiscount] | None, + Field( + description="Discounts on the whole checkout, spread over the discountable lines in\nproportion to each line's subtotal. At most one entry for now; a second returns a `422`.\nEntries will apply in array order, each on what the earlier ones left.\n\nThe discount reduces the first payment of each product only; renewals\nare charged the full price. For a subscription on trial, that is its\nfirst payment after the trial, which stays discounted if its plan or\nquantity changes during the trial. A percentage applies to every\nproduct's first payment. A fixed amount is split over the same first\npayments in proportion to their prices, as a percentage of the same\nsize would be, keeping at least the smallest unit payable today. On\ntax-inclusive prices a fixed amount includes taxes, on today's lines\nand on the first payment after a trial alike.\n\nThe resulting order and its lines list the discount under `discounts`.\n", + examples=[[{"description": "Black Friday", "percentage": 20}]], + json_schema_extra={"x-vatly-nullable": True}, + max_length=1, + ), + ] = None + + class OrderLine(VatlyModel): """ A line item in an order. `productType`/`productId` retain their existing meaning: @@ -2270,17 +2361,27 @@ class OrderLine(VatlyModel): ] quantity: Annotated[int, Field(description="Number of units", examples=[1], ge=1)] base_price: Annotated[ - Money, Field(alias="basePrice", description="Price per unit before taxes") + Money, + Field( + alias="basePrice", + description="Price per unit before discounts, on the product's tax basis: excluding taxes for tax-exclusive products, including them for tax-inclusive products", + ), ] total: Annotated[ Money, - Field(description="Total price including taxes (basePrice * quantity + taxes)"), + Field(description="Total price including taxes, after discounts (subtotal + taxes)"), ] - subtotal: Annotated[Money, Field(description="Subtotal before taxes (basePrice * quantity)")] + subtotal: Annotated[Money, Field(description="Subtotal excluding taxes, after discounts")] taxes: Annotated[ Sequence[TaxSummaryItem], Field(description="Tax breakdown by rate for this line"), ] + discounts: Annotated[ + Sequence[Discount], + Field( + description="This line's share of each discount, in the order they apply. Empty when\nthe line has no discount. `subtotal`, `taxes` and `total` are already\nnet of these discounts.\n" + ), + ] = [] product_type: Annotated[ Literal[ "one_off_product", @@ -2823,6 +2924,12 @@ class Order(VatlyModel): BillingDetails, Field(alias="customerDetails", description="Customer billing details (buyer)"), ] + discounts: Annotated[ + Sequence[Discount], + Field( + description="Every discount on the order, each listed once with the amount it takes\noff all lines added up, in the order it first appears on the lines.\nEmpty when the order has no discount. Match an entry to its share on\neach line by `id`.\n" + ), + ] = [] links: Annotated[Links4, Field(description="HATEOAS links to related resources")] diff --git a/tests/test_sdk.py b/tests/test_sdk.py index d61324a..3b58545 100644 --- a/tests/test_sdk.py +++ b/tests/test_sdk.py @@ -726,3 +726,93 @@ def test_refund_metadata_is_typed_in_resources_and_webhooks(spec): event = construct_webhook_event(raw, f"t=100,v1={signature}", "secret", now=100) assert isinstance(event.object, Refund) assert event.object.metadata.root == {"ticketId": "SUPPORT-1"} + + +def test_checkout_discounts_are_sent_as_typed_and_limited_to_one(): + from vatly.models import CheckoutDiscount + + base = { + "redirectUrlSuccess": "https://a.test/ok", + "redirectUrlCanceled": "https://a.test/no", + "products": [{"id": "one_off_product_a"}], + } + amount = {"value": "10.00", "currency": "EUR"} + sent = _sent_bodies( + lambda c: c.checkouts.create( + {**base, "discounts": [{"percentage": 12.5, "description": None, "unknown": 1}]} + ), + lambda c: c.checkouts.create( + CreateCheckoutRequest( + **base, discounts=[CheckoutDiscount(amount=amount, description="Black Friday")] + ) + ), + lambda c: c.checkouts.create({**base, "discounts": [{"percentage": "12.125"}]}), + lambda c: c.checkouts.create({**base, "discounts": None}), + ) + assert [body.get("discounts", "omitted") for body in sent] == [ + [{"percentage": 12.5, "description": None}], + [{"amount": amount, "description": "Black Friday"}], + [{"percentage": "12.125"}], + None, + ] + with VatlyClient(KEY, transport=httpx.MockTransport(lambda r: pytest.fail())) as c: + for discounts in ( + [{"percentage": 10}, {"percentage": 5}], + [{"amount": {"value": "10", "currency": "EUR"}}], + [{"amount": {"value": "10.00", "currency": "USD"}}], + [{"description": "x" * 256}], + ): + with pytest.raises(ValidationError): + c.checkouts.create({**base, "discounts": discounts}) + errors = {"discounts.0.amount": ["The amount must be below the subtotal."]} + with VatlyClient( + KEY, + transport=httpx.MockTransport( + lambda r: httpx.Response(422, json={"message": "Invalid", "errors": errors}) + ), + ) as c: + with pytest.raises(vatly.VatlyValidationError) as raised: + c.checkouts.create({**base, "discounts": [{"amount": amount}]}) + assert raised.value.errors == errors + + +def test_order_discounts_are_typed_and_missing_ones_read_as_none(spec): + from vatly.models import Order + + order = example(spec["components"]["schemas"]["Order"], spec) + money = {"value": "8.26", "currency": "EUR"} + discounts = [ + { + "id": "discount_a", + "description": "Black Friday", + "discountType": "percentage", + "percentage": "20.00", + "amount": money, + }, + # Open list: unknown kinds parse, and older discounts have no id or type. + { + "id": None, + "description": None, + "discountType": "loyalty_credit", + "percentage": None, + "amount": money, + }, + ] + order["lines"][0]["discounts"] = discounts + parsed = Order.model_validate({**order, "discounts": discounts}) + for found in (parsed.discounts, parsed.lines[0].discounts): + assert [d.discount_type for d in found] == ["percentage", "loyalty_credit"] + assert found[0].id == "discount_a" and found[0].percentage == "20.00" + assert found[0].amount.root.value == "8.26" and found[1].id is None + assert parsed.model_dump(by_alias=True)["discounts"] == discounts + + # Webhook events stored before discounts existed have none on the order or its lines. + legacy = {k: v for k, v in order.items() if k != "discounts"} + legacy["lines"] = [{k: v for k, v in ln.items() if k != "discounts"} for ln in order["lines"]] + payload = example(spec["components"]["schemas"]["WebhookDelivery"], spec) + payload.update(eventName="order.paid", entityType="order", entityId=order["id"], object=legacy) + raw = json.dumps(payload).encode() + signature = compute_signature_v1(raw, "secret", 100) + event = construct_webhook_event(raw, f"t=100,v1={signature}", "secret", now=100) + assert isinstance(event.object, Order) + assert event.object.discounts == [] and event.object.lines[0].discounts == [] From 62f63988d5cc668a514437329c60e34f7961b1f8 Mon Sep 17 00:00:00 2001 From: Sander van Hooft <7265703+sandervanhooft@users.noreply.github.com> Date: Mon, 30 Nov 2026 10:01:27 +0000 Subject: [PATCH 2/2] Release 0.1.0a5 Amp-Thread-ID: https://ampcode.com/threads/T-3f59dfd0-1f6e-41a8-b940-15b496a7ab0c Co-authored-by: Amp --- CHANGELOG.md | 2 ++ README.md | 2 +- pyproject.toml | 2 +- src/vatly/_version.py | 2 +- uv.lock | 2 +- 5 files changed, 6 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8f4837d..ea1d581 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +## 0.1.0a5 — 2026-11-30 + - Sync `openapi.yaml` with the production specification (discounts). - `CreateCheckoutRequest.discounts` takes an optional list of `CheckoutDiscount`, at most one for now: a `percentage` or a fixed EUR `amount`, plus an optional diff --git a/README.md b/README.md index 6dc8c4c..2f7d980 100644 --- a/README.md +++ b/README.md @@ -88,7 +88,7 @@ uses, so Vatly sees the whole chain: ```python client.add_version_string("vatly/vatly-fluent-python/0.1.0a4") -# User-Agent: vatly/vatly-api-python/0.1.0a4 Python/3.12.8 httpx/0.28.1 vatly/vatly-fluent-python/0.1.0a4 +# User-Agent: vatly/vatly-api-python/0.1.0a5 Python/3.12.8 httpx/0.28.1 vatly/vatly-fluent-python/0.1.0a4 ``` Use your PyPI package name and its version constant. Whitespace in a token becomes `-`, diff --git a/pyproject.toml b/pyproject.toml index 827a777..10b9676 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "vatly-api-python" -version = "0.1.0a4" +version = "0.1.0a5" description = "Python SDK for Vatly, the European Merchant of Record for AI, software and digital products" keywords = ["vatly", "merchant-of-record", "billing", "payments", "vat", "ai", "sdk"] readme = "README.md" diff --git a/src/vatly/_version.py b/src/vatly/_version.py index b0548b6..0a0820d 100644 --- a/src/vatly/_version.py +++ b/src/vatly/_version.py @@ -1 +1 @@ -__version__ = "0.1.0a4" +__version__ = "0.1.0a5" diff --git a/uv.lock b/uv.lock index bbfde40..70ec8f0 100644 --- a/uv.lock +++ b/uv.lock @@ -2017,7 +2017,7 @@ wheels = [ [[package]] name = "vatly-api-python" -version = "0.1.0a4" +version = "0.1.0a5" source = { editable = "." } dependencies = [ { name = "httpx" },