diff --git a/CHANGELOG.md b/CHANGELOG.md index fc0cee9..b9da9d3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,25 @@ # Changelog +## 0.11.1 (2026-11-17) + +Follows API 1.21.2. The saved spec has 165 operations and 175 schemas, as in 0.11.0, and the models are regenerated from it. +No method or argument changed, and nothing is removed. + +New fields: + +- `Subscription.cancel_at` is when Stripe is set to end the subscription. A cancel in the billing portal sets it and leaves `cancel_at_period_end` false. +- `Subscription.ends_at` is when the plan ends without another charge. It is `None` while the plan renews, and once the plan has ended. +- The public document requires both. The saved spec leaves them optional, so an older payload still parses. Both default to `None`. + +`OneTimeConfirmSummary.state` reads `link_canceled` for the confirm link of an order that was canceled. +`one_time_sends.confirm` on that link raises `ConflictError` with the code `link_canceled`, and its docstring says so. + +`ConflictError.reason` reads `details["reason"]`, or `None` when the API sent none. +A second `billing.create_subscription_checkout` raises `ConflictError` with the reason `plan_active` while the plan is active. +The reason is `checkout_open` while a payment page of the plan is still open, and `details["url"]` is that page. + +The generated `OneTimeOrder` docstring follows the public document, which splits it into shorter sentences. + ## 0.11.0 (2026-11-16) Follows API 1.21.0. The saved spec has 165 operations and 175 schemas, and the models are regenerated from it. diff --git a/README.md b/README.md index 60d74ed..6369739 100644 --- a/README.md +++ b/README.md @@ -94,6 +94,9 @@ The same in async form, with `AsyncClient` and `await` on every call. Agent workspace plan as CSV text, for a range of UTC days. Without the plan they raise `ScopeError` with the code `workspace_required`. - A test quote is free. Its `live_amount_micro` says what the same fax costs with a live key. +- `billing.list_subscriptions()` names `ends_at` on each subscription, when the Agent workspace ends without + another charge. A second `billing.create_subscription_checkout()` raises `ConflictError`, whose `reason` + is `plan_active` or `checkout_open`. - `one_time_sends.preview(file=...)` counts the pages of a document before any order exists, with no key. `one_time_sends.check_cover(message=...)` says whether a cover message fits on its page. - `billing.get_topup_session(id, check_checkout=True)` asks Stripe about the hosted Checkout of an open @@ -172,7 +175,8 @@ not reached. `NotFoundError.field` names the id that was not found when the API says which: on a quote it is `document_id` or `from`. `ConflictError.state` is the state of a fax whose receipt was asked for -before the fax ended. Both are `None` when the API sent no such detail. +before the fax ended. `ConflictError.reason` says why a call was refused, such as `checkout_open` when a +payment page of the Agent workspace is still open. Each is `None` when the API sent no such detail. Every refusal is the same envelope, a 422 for a field that fails validation included. A 413 `payload_too_large` is a plain `APIError`: the body is over the limit of its route. The published @@ -326,7 +330,7 @@ ruff check src tests && mypy src sh scripts/truthcheck.sh ``` -`spec/openapi.yaml` follows the public document at API version 1.21.0. It has the same 165 operations and no schema that document lacks. +`spec/openapi.yaml` follows the public document at API version 1.21.2. It has the same 165 operations and no schema that document lacks. It also declares fields a route returns beyond the public schemas, in `InboxItemSummary` and `ExtractionPage`. 0.5.0 removed the two validation error schemas, because the server never sent that shape. 0.6.0 removed two cost fields of an extraction, because the server stopped sending them. @@ -334,6 +338,7 @@ It also declares fields a route returns beyond the public schemas, in `InboxItem 0.9.0 leaves `Delivery.webhook_deleted` optional, where the public document requires it. 0.10.0 removed the 70 schemas of earlier server documents that no operation reaches, such as those of the admin console. 0.11.0 leaves `SubscriptionList.plan` optional, where the public document requires it. +0.11.1 leaves `Subscription.cancel_at` and `Subscription.ends_at` optional, where the public document requires them. `scripts/gen_models.py` writes a model only for a schema an operation reaches, through its paths, a shared response or a field. If a refresh brings in a schema that no operation reaches, it gets no model and `tests/test_removed_models.py` fails. To refresh it, merge the public document while preserving existing declarations, then run `uv run python scripts/gen_models.py`. diff --git a/pyproject.toml b/pyproject.toml index 803aa1f..27d9924 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "faxforagents" -version = "0.11.0" +version = "0.11.1" description = "Python client for Fax for Agents: a fax API, a hosted MCP server and SDKs built so AI agents can send and receive faxes." readme = "README.md" requires-python = ">=3.10" diff --git a/spec/openapi.yaml b/spec/openapi.yaml index baf1ec6..0928285 100644 --- a/spec/openapi.yaml +++ b/spec/openapi.yaml @@ -1,4 +1,4 @@ -# Fax for Agents API, refreshed from the public document of https://github.com/faxforagents/openapi at API 1.21.0. +# Fax for Agents API, refreshed from the public document of https://github.com/faxforagents/openapi at API 1.21.2. # An operation reaches every schema here. 0.10.0 dropped 70 earlier schemas that no operation reached. # Existing SDK routes, model names and serializer additions are retained. openapi: 3.1.0 @@ -27,7 +27,7 @@ info: x-logo: url: https://faxforagents.com/brand/logo-512.png altText: Fax for Agents - version: 1.21.0 + version: 1.21.2 servers: - url: https://api.faxforagents.com description: Production (live and test keys) @@ -3648,6 +3648,8 @@ paths: tags: - billing summary: Open a hosted Checkout for the Agent workspace subscription + description: Answers the address of Stripe's payment page for the plan. It is refused with 409 while the plan + is active or a Checkout of it is still open, so the plan is never paid twice. operationId: create_subscription_checkout responses: '201': @@ -3672,7 +3674,15 @@ paths: '404': $ref: '#/components/responses/NotFound' '409': - $ref: '#/components/responses/Conflict' + description: 'The plan cannot be bought twice. error.code is conflict and error.details.reason says why. + "plan_active": the Agent workspace is active, here or at Stripe after a payment of a moment ago. "checkout_open": + a Checkout of the plan is still open, and error.details.url is its page, error.details.expires_at when + it closes. idempotency_key_conflict: the Idempotency-Key was used with a different request, or that + request is still being processed.' + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorEnvelope' '410': $ref: '#/components/responses/Gone' '422': @@ -4413,10 +4423,10 @@ paths: tags: - organizations summary: 'The fax history as CSV: every fax sent and received in the range' - description: 'One line per fax of the key''s environment, sent and received, oldest first. A sent fax counts - by when it was created and a received one by when it arrived. The lines carry what each fax cost the wallet, - never the document or its text. A range of more than 20000 lines answers 422: choose fewer days. Needs the - scopes fax:read and inbox:read.' + description: 'Needs two scopes: fax:read, which x-required-scope names, and inbox:read as well. One line per + fax of the key''s environment, sent and received, oldest first. A sent fax counts by when it was created + and a received one by when it arrived. The lines carry what each fax cost the wallet, never the document + or its text. A range of more than 20000 lines answers 422: choose fewer days.' operationId: get_fax_history_csv parameters: - name: from @@ -4449,9 +4459,10 @@ paths: '401': $ref: '#/components/responses/Unauthorized' '403': - description: error.code is workspace_required while the organization's Agent workspace plan is not active + description: 'error.code is workspace_required while the organization''s Agent workspace plan is not active and ended more than 30 days ago, or never started. error.details.ended_at is when it ended and error.details.closed_at - when the export closed. scope_missing names a scope the credential lacks. + when the export closed. scope_missing names a scope the credential lacks: fax:read, or inbox:read, which + this export needs as well.' content: application/json: schema: @@ -8984,8 +8995,8 @@ paths: schema: $ref: '#/components/schemas/ErrorEnvelope' '409': - description: The link was already used (link_used), expired (link_expired), or the browser is signed in - as someone else (link_other_session). + description: The link was already used (link_used), its order was canceled and the hold released (link_canceled), + it expired (link_expired), or the browser is signed in as someone else (link_other_session). content: application/json: schema: @@ -13515,6 +13526,7 @@ components: enum: - ok - link_used + - link_canceled - link_expired title: State status: @@ -13575,7 +13587,8 @@ components: title: OneTimeConfirmSummary description: |- What the confirm page shows before the click. ``state`` is ``ok`` while the link can still be used, - else ``link_used`` or ``link_expired``. Reading it consumes nothing. + else ``link_used``, ``link_canceled`` (the order was canceled and its hold released) or + ``link_expired``. Reading it consumes nothing. OneTimeConfirmed: properties: order: @@ -14134,9 +14147,9 @@ components: ``confirm`` (click the mailed link), ``wait`` (read again later) or ``done``. Money is integer micro-USD. The field ``captured_micro`` is what the card was charged, written only once the payment provider confirmed it. The field ``fax`` is the fax job once the order was released, with the - carrier's evidence once it has any. Three statuses come from a person at Fax for Agents: ``refunding`` - (a refund is on its way to the card), ``refunded`` (the whole charge went back) and ``canceled`` (the - order was canceled and the hold on the card released, nothing charged). + carrier's evidence once it has any. Three statuses come from a person at Fax for Agents. With + ``refunding`` a refund is on its way to the card, and with ``refunded`` the whole charge went back. With + ``canceled`` the order was canceled and the hold on the card released, so nothing was charged. OneTimeOrderCreated: properties: id: @@ -16219,6 +16232,21 @@ components: cancel_at_period_end: type: boolean title: Cancel At Period End + cancel_at: + anyOf: + - type: string + - type: 'null' + title: Cancel At + description: When Stripe is set to end the subscription. A cancel in the billing portal sets it to the + end of the period and leaves cancel_at_period_end false. + ends_at: + anyOf: + - type: string + - type: 'null' + title: Ends At + description: When the subscription ends without being charged again. That is cancel_at when it comes no + later than current_period_end, or current_period_end after a cancel at the period's end. Null while + it renews. current_period_end: anyOf: - type: string diff --git a/src/faxforagents/__init__.py b/src/faxforagents/__init__.py index 2c9c961..62f6ea7 100644 --- a/src/faxforagents/__init__.py +++ b/src/faxforagents/__init__.py @@ -18,7 +18,7 @@ from __future__ import annotations -__version__ = "0.11.0" +__version__ = "0.11.1" from faxforagents._http import ORDER_TOKEN_HEADER from faxforagents.async_client import AsyncClient diff --git a/src/faxforagents/async_client.py b/src/faxforagents/async_client.py index 0de740b..a2a27ec 100644 --- a/src/faxforagents/async_client.py +++ b/src/faxforagents/async_client.py @@ -731,7 +731,11 @@ async def get_invoice_receipt(self, invoice_id: str) -> m.PaymentReceipt: async def create_subscription_checkout( self, *, idempotency_key: str | None = None ) -> m.SubscriptionCheckout: - """A hosted Checkout for the Agent workspace subscription. Scope: billing:write.""" + """A hosted Checkout for the Agent workspace subscription. Scope: billing:write. + + ``url`` is Stripe's payment page for the plan. While the plan is active, or a payment page of it is + still open, this raises ``ConflictError``, so the plan is never paid twice. Its ``reason`` is + ``plan_active`` or ``checkout_open``. With ``checkout_open``, ``details["url"]`` is the open page.""" return await self._h.request( "POST", "/v1/subscriptions/checkout", @@ -745,7 +749,11 @@ async def list_subscriptions(self) -> m.SubscriptionList: ``plan`` says what the Agent workspace gives and where the organization stands with it. It names the request limit, the included number, how long records are kept and whether the records export - is open. It is ``None`` from a server older than API 1.21.0.""" + is open. It is ``None`` from a server older than API 1.21.0. + + Each subscription names ``cancel_at``, the end date Stripe holds, and ``ends_at``, when the plan ends + without another charge. ``ends_at`` is ``None`` while the plan renews and once it no longer + entitles. Both are ``None`` from a server older than API 1.21.2.""" return await self._h.request("GET", "/v1/subscriptions", model=m.SubscriptionList) async def create_portal_session(self, *, idempotency_key: str | None = None) -> m.PortalSession: @@ -1902,9 +1910,10 @@ async def get_by_token(self, token: str) -> m.OneTimeConfirmSummary: ) async def confirm(self, order_id: str, *, token: str) -> m.OneTimeConfirmed: - """Confirm the order with the token of the mailed link. The fax is released. No key needed. + """Confirm the order with the token of the mailed link. The fax is released. It takes no API key. - The link works once. A repeat answers 409 ``link_used`` and sends nothing.""" + The link works once. A repeat answers 409 ``link_used`` and sends nothing. The link of an order + that was canceled answers 409 ``link_canceled``, since API 1.21.2.""" return await self._h.request( "POST", f"/v1/one-time-sends/{order_id}/confirm", diff --git a/src/faxforagents/client.py b/src/faxforagents/client.py index 498ac8e..e8dd86a 100644 --- a/src/faxforagents/client.py +++ b/src/faxforagents/client.py @@ -760,7 +760,11 @@ def get_invoice_receipt(self, invoice_id: str) -> m.PaymentReceipt: return self._h.request("GET", f"/v1/invoices/{invoice_id}/receipt", model=m.PaymentReceipt) def create_subscription_checkout(self, *, idempotency_key: str | None = None) -> m.SubscriptionCheckout: - """A hosted Checkout for the Agent workspace subscription. Scope: billing:write.""" + """A hosted Checkout for the Agent workspace subscription. Scope: billing:write. + + ``url`` is Stripe's payment page for the plan. While the plan is active, or a payment page of it is + still open, this raises ``ConflictError``, so the plan is never paid twice. Its ``reason`` is + ``plan_active`` or ``checkout_open``. With ``checkout_open``, ``details["url"]`` is the open page.""" return self._h.request( "POST", "/v1/subscriptions/checkout", @@ -774,7 +778,11 @@ def list_subscriptions(self) -> m.SubscriptionList: ``plan`` says what the Agent workspace gives and where the organization stands with it. It names the request limit, the included number, how long records are kept and whether the records export - is open. It is ``None`` from a server older than API 1.21.0.""" + is open. It is ``None`` from a server older than API 1.21.0. + + Each subscription names ``cancel_at``, the end date Stripe holds, and ``ends_at``, when the plan ends + without another charge. ``ends_at`` is ``None`` while the plan renews and once it no longer + entitles. Both are ``None`` from a server older than API 1.21.2.""" return self._h.request("GET", "/v1/subscriptions", model=m.SubscriptionList) def create_portal_session(self, *, idempotency_key: str | None = None) -> m.PortalSession: @@ -1907,9 +1915,10 @@ def get_by_token(self, token: str) -> m.OneTimeConfirmSummary: return self._h.request("GET", f"/v1/one-time-sends/by-token/{token}", model=m.OneTimeConfirmSummary) def confirm(self, order_id: str, *, token: str) -> m.OneTimeConfirmed: - """Confirm the order with the token of the mailed link. The fax is released. No key needed. + """Confirm the order with the token of the mailed link. The fax is released. It takes no API key. - The link works once. A repeat answers 409 ``link_used`` and sends nothing.""" + The link works once. A repeat answers 409 ``link_used`` and sends nothing. The link of an order + that was canceled answers 409 ``link_canceled``, since API 1.21.2.""" return self._h.request( "POST", f"/v1/one-time-sends/{order_id}/confirm", diff --git a/src/faxforagents/errors.py b/src/faxforagents/errors.py index 3204f45..ffba9e3 100644 --- a/src/faxforagents/errors.py +++ b/src/faxforagents/errors.py @@ -86,6 +86,17 @@ def state(self) -> str | None: value = self.details.get("state") if isinstance(self.details, dict) else None return value if isinstance(value, str) else None + @property + def reason(self) -> str | None: + """``details["reason"]``: why the call was refused, else ``None``. + + ``billing.create_subscription_checkout`` names ``plan_active`` while the Agent workspace is active. + It names ``checkout_open`` while a payment page of the plan is still open. Then ``details["url"]`` + is that page and ``details["expires_at"]`` is when it closes. The checkout sends a reason since API + 1.21.2. Other routes name their own, such as ``webhook_deleted`` on a delivery replay.""" + value = self.details.get("reason") if isinstance(self.details, dict) else None + return value if isinstance(value, str) else None + class OneTimeOffer(TypedDict, total=False): """``details["one_time_offer"]`` of 402 insufficient_balance: the card path for this exact send. diff --git a/src/faxforagents/models.py b/src/faxforagents/models.py index 736a6d3..a0c1a24 100644 --- a/src/faxforagents/models.py +++ b/src/faxforagents/models.py @@ -1,6 +1,6 @@ """Typed models of the Fax for Agents API. -GENERATED by scripts/gen_models.py from spec/openapi.yaml (API version 1.21.0). Do not edit by hand. +GENERATED by scripts/gen_models.py from spec/openapi.yaml (API version 1.21.2). Do not edit by hand. Money fields ending in ``_micro`` are integer USD micro-units (39000 is $0.039). Timestamps are ISO 8601 strings in UTC. Response models accept fields the API adds later. Request models refuse unknown fields. """ @@ -1073,10 +1073,10 @@ class OneTimeConfirm(_Request): class OneTimeConfirmSummary(_Response): - """What the confirm page shows before the click. ``state`` is ``ok`` while the link can still be used, else ``link_used`` or ``link_expired``. Reading it consumes nothing.""" + """What the confirm page shows before the click. ``state`` is ``ok`` while the link can still be used, else ``link_used``, ``link_canceled`` (the order was canceled and its hold released) or ``link_expired``. Reading it consumes nothing.""" order_id: str - state: Literal["ok", "link_used", "link_expired"] + state: Literal["ok", "link_used", "link_canceled", "link_expired"] status: Literal["draft", "checkout_open", "authorized", "awaiting_confirmation", "released", "capturing", "canceling", "captured", "released_hold", "expired", "refused", "settle_failed", "refunding", "refunded", "canceled"] to: str sender_name: str @@ -1105,7 +1105,7 @@ class OneTimePrice(_Response): class OneTimeOrder(_Response): - """One order of the one-time send. The field ``next`` is what the caller does now: ``checkout`` (pay), ``confirm`` (click the mailed link), ``wait`` (read again later) or ``done``. Money is integer micro-USD. The field ``captured_micro`` is what the card was charged, written only once the payment provider confirmed it. The field ``fax`` is the fax job once the order was released, with the carrier's evidence once it has any. Three statuses come from a person at Fax for Agents: ``refunding`` (a refund is on its way to the card), ``refunded`` (the whole charge went back) and ``canceled`` (the order was canceled and the hold on the card released, nothing charged).""" + """One order of the one-time send. The field ``next`` is what the caller does now: ``checkout`` (pay), ``confirm`` (click the mailed link), ``wait`` (read again later) or ``done``. Money is integer micro-USD. The field ``captured_micro`` is what the card was charged, written only once the payment provider confirmed it. The field ``fax`` is the fax job once the order was released, with the carrier's evidence once it has any. Three statuses come from a person at Fax for Agents. With ``refunding`` a refund is on its way to the card, and with ``refunded`` the whole charge went back. With ``canceled`` the order was canceled and the hold on the card released, so nothing was charged.""" id: str status: Literal["draft", "checkout_open", "authorized", "awaiting_confirmation", "released", "capturing", "canceling", "captured", "released_hold", "expired", "refused", "settle_failed", "refunding", "refunded", "canceled"] @@ -1621,6 +1621,8 @@ class Subscription(_Response): stripe_subscription_id: str stripe_price_id: str | None cancel_at_period_end: bool + cancel_at: str | None = Field(None, description="When Stripe is set to end the subscription. A cancel in the billing portal sets it to the end of the period and leaves cancel_at_period_end false.") + ends_at: str | None = Field(None, description="When the subscription ends without being charged again. That is cancel_at when it comes no later than current_period_end, or current_period_end after a cancel at the period's end. Null while it renews.") current_period_end: str | None entitled: bool created_at: str diff --git a/tests/test_async.py b/tests/test_async.py index d68c411..456375b 100644 --- a/tests/test_async.py +++ b/tests/test_async.py @@ -315,3 +315,34 @@ async def test_async_records_export_created_range_and_workspace_plan( } api.get("/v1/subscriptions").respond(200, json={"items": [], "workspace": False}) assert (await aclient.billing.list_subscriptions()).plan is None + + +async def test_async_subscription_end_and_second_checkout( + aclient: AsyncClient, api: respx.MockRouter +) -> None: + """API 1.21.2 on the async client: ends_at on a subscription and the reason of a second checkout.""" + end = "2026-12-16T23:23:27.000Z" + item = { + "id": "sub_1", + "product": "workspace_monthly", + "status": "active", + "stripe_subscription_id": "sub_fixture", + "stripe_price_id": "price_workspace_monthly_test", + "cancel_at_period_end": True, + "cancel_at": None, + "ends_at": end, + "current_period_end": end, + "entitled": True, + "created_at": "2026-11-16T23:23:27.000Z", + "updated_at": "2026-11-16T23:23:27.000Z", + "canceled_at": None, + } + api.get("/v1/subscriptions").respond(200, json={"items": [item], "workspace": True}) + listed = await aclient.billing.list_subscriptions() + assert listed.items[0].ends_at == end and listed.items[0].cancel_at is None + api.post("/v1/subscriptions/checkout").respond( + 409, json=error("conflict", "already active", details={"reason": "plan_active"}) + ) + with pytest.raises(ConflictError) as exc: + await aclient.billing.create_subscription_checkout() + assert exc.value.reason == "plan_active" diff --git a/tests/test_client.py b/tests/test_client.py index 02d2e13..43fae1d 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -1243,6 +1243,93 @@ def test_the_subscription_list_carries_the_workspace_plan(client: Client, api: r models.WorkspacePlan.model_validate({k: v for k, v in workspace_plan().items() if k != "export_open"}) +def subscription(**over: object) -> dict[str, object]: + """A subscription as ``sub_json`` of billing/subscriptions.py writes it at API 1.21.2.""" + return { + "id": "sub_1", + "product": "workspace_monthly", + "status": "active", + "stripe_subscription_id": "sub_fixture", + "stripe_price_id": "price_workspace_monthly_test", + "cancel_at_period_end": False, + "cancel_at": None, + "ends_at": None, + "current_period_end": "2026-12-16T23:23:27.000Z", + "entitled": True, + "created_at": "2026-11-16T23:23:27.000Z", + "updated_at": "2026-11-16T23:23:27.000Z", + "canceled_at": None, + **over, + } + + +def test_a_subscription_says_when_it_ends(client: Client, api: respx.MockRouter) -> None: + """API 1.21.2: cancel_at and ends_at. A cancel in the billing portal sets cancel_at, not the flag.""" + end = "2026-12-16T23:23:27.000Z" + renewing = {k: v for k, v in subscription().items() if k not in ("cancel_at", "ends_at")} + route = api.get("/v1/subscriptions") + route.side_effect = [ + httpx.Response( + 200, + json={ + "items": [subscription(cancel_at=end, ends_at=end), subscription(id="sub_2")], + "workspace": True, + "plan": workspace_plan(), + }, + ), + httpx.Response(200, json={"items": [renewing], "workspace": True}), + ] + ending, renews = client.billing.list_subscriptions().items + assert ending.cancel_at_period_end is False + assert ending.cancel_at == end and ending.ends_at == end + assert renews.cancel_at is None and renews.ends_at is None + older = client.billing.list_subscriptions().items[0] + assert older.cancel_at is None and older.ends_at is None and older.entitled is True + + +def test_the_plan_is_never_bought_twice(client: Client, api: respx.MockRouter) -> None: + """API 1.21.2: a second checkout of the plan answers 409 conflict, and details.reason says why.""" + page = "https://checkout.stripe.com/c/pay/cs_test_fixture" + route = api.post("/v1/subscriptions/checkout") + route.side_effect = [ + httpx.Response( + 409, + json=error( + "conflict", + "The Agent workspace is already active for this organization.", + details={"reason": "plan_active"}, + ), + ), + httpx.Response( + 409, + json=error( + "conflict", + "A payment page for the Agent workspace is already open.", + details={"reason": "checkout_open", "url": page, "expires_at": "2026-11-17T23:23:27.000Z"}, + ), + ), + httpx.Response( + 201, + json={"url": page, "stripe_session_id": "cs_test_fixture", "product": "workspace_monthly"}, + ), + ] + with pytest.raises(ConflictError) as active: + client.billing.create_subscription_checkout() + assert active.value.code == "conflict" and active.value.reason == "plan_active" + assert active.value.state is None and active.value.retryable is False + with pytest.raises(ConflictError) as open_page: + client.billing.create_subscription_checkout() + assert open_page.value.reason == "checkout_open" + assert open_page.value.details["url"] == page + assert open_page.value.details["expires_at"] == "2026-11-17T23:23:27.000Z" + assert client.billing.create_subscription_checkout().url == page + assert len(route.calls) == 3 + # a refusal with no details, or a reason that is not a string, has no reason + assert ConflictError(status=409, code="quote_consumed", message="used").reason is None + assert ConflictError(status=409, code="conflict", message="x", details={"reason": 7}).reason is None + assert ConflictError(status=409, code="conflict", message="x", details=["plan_active"]).reason is None + + def test_the_number_the_workspace_pays_for(client: Client, api: respx.MockRouter) -> None: """API 1.21.0: included_with_workspace marks the number whose monthly charge the plan pays.""" route = api.get("/v1/numbers/num_1") diff --git a/tests/test_one_time.py b/tests/test_one_time.py index 11a56b2..d242d49 100644 --- a/tests/test_one_time.py +++ b/tests/test_one_time.py @@ -13,6 +13,7 @@ from faxforagents import ( AsyncClient, Client, + ConflictError, InvalidRequestError, NotFoundError, PaymentRequiredError, @@ -277,6 +278,22 @@ def test_get_by_token_and_confirm(keyless: Client, api: respx.MockRouter) -> Non assert json.loads(route.calls.last.request.content) == {"token": "mail-token"} +def test_the_link_of_a_canceled_order(keyless: Client, api: respx.MockRouter) -> None: + """API 1.21.2: the confirm link of a canceled order reads link_canceled, and confirms no more.""" + canceled = {**CASES["by_token"], "state": "link_canceled", "status": "canceled"} + api.post("/v1/one-time-sends/by-token").respond(200, json=canceled) + summary = keyless.one_time_sends.read_by_token("mail-token") + assert summary.state == "link_canceled" and summary.status == "canceled" + with pytest.raises(ValueError): + models.OneTimeConfirmSummary.model_validate({**canceled, "state": "link_withdrawn"}) + api.post(f"/v1/one-time-sends/{ORDER}/confirm").respond( + 409, json=error("link_canceled", "this order was canceled, and the hold on the card is released") + ) + with pytest.raises(ConflictError) as exc: + keyless.one_time_sends.confirm(summary.order_id, token="mail-token") + assert exc.value.code == "link_canceled" and exc.value.status == 409 + + def test_resend_confirmation(keyless: Client, api: respx.MockRouter) -> None: route = api.post(f"/v1/one-time-sends/{ORDER}/resend-confirmation").respond( 200, json=CASES["awaiting_confirmation"]