From 62f2a6b92411df2902c3fc03c8822ae30cad01ea Mon Sep 17 00:00:00 2001 From: bensynapse <118375461+bensynapse@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:24:21 +0200 Subject: [PATCH 1/3] Version 0.8.0: the spec at API 1.20.8, top-up cancel and cover check The saved spec follows the public document at API 1.20.8. It was merged three ways, with the public document at 1.20.6 as the base. Five fields the spec declared itself are now in the public document, whose declarations replace them. billing.cancel_topup_session and one_time_sends.check_cover are new on both clients. The statement methods take type, and kind keeps working. The rotate_api_key docstring names the ConflictError of an expired key. Tests cover each new method and parameter. --- CHANGELOG.md | 25 ++ README.md | 15 +- pyproject.toml | 2 +- spec/openapi.yaml | 600 ++++++++++++++++++++++++++----- src/faxforagents/__init__.py | 2 +- src/faxforagents/async_client.py | 75 +++- src/faxforagents/client.py | 73 +++- src/faxforagents/models.py | 213 +++++++---- tests/conftest.py | 20 ++ tests/test_async.py | 39 +- tests/test_client.py | 115 +++++- tests/test_one_time.py | 45 ++- tests/test_surface.py | 2 + 13 files changed, 1041 insertions(+), 185 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0204035..928d26c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,30 @@ # Changelog +## 0.8.0 (2026-11-15) + +Follows API 1.20.8. The saved spec has 163 operations and the models are regenerated from it. +Every operation has a method on both clients. + +New: `billing.cancel_topup_session(topup_session_id)` closes the hosted Checkout of an open top-up and returns it with status `canceled`. +Canceling a setup payment also turns off the auto top-up that waited on it. Scope `billing:write`, never an agent key. +A top-up that was paid, declined or charged off session raises `ConflictError`, with its status in `details["status"]`. +New: `one_time_sends.check_cover(...)` takes the cover fields typed so far and says whether the message fits on the cover page. It needs no key. +It returns the new model `OneTimeCoverRoom` with `fits`, `message_chars`, `lines_left` and `fits_chars`. Nothing is stored. + +New parameter: `billing.statement`, `billing.iter_statement` and `billing.statement_csv` take `type`, the type each line shows. +`kind` still works. It is the same filter by its older name, and two different types in both raise `InvalidRequestError`. + +Changed: five fields that the saved spec declared itself now follow the public document. +`Quote.policy_evaluation` is a `PolicyVerdict` and `PolicyEvaluation.usage` a `PolicyUsage`. Both were dicts, so read them as attributes, such as `usage.day_jobs`. +`Quote.pricing` is `per_page` or `one_time`, with `per_page` as the default. `PolicyEvaluation.decision` is `allow` or `deny`. +`FaxJob.approval_id` and `FaxJob.policy_version_id` keep their type. `FaxJob.route_paused` is new and false by default. + +`identity.rotate_api_key` on a key that expired raises `ConflictError` with `details["reason"]` set to `key_expired`. Create a new key to replace it. +`PaymentReceipt.pdf_url` is `None` for an automatic top-up, which has no invoice. Its `url` still opens the receipt. +A statement line of a hold or a release names what it was for in `ref_type`: `fax_job`, `extraction` or `number_order`. +The card of a one-time order is held, not authorized, in the docstrings and the model descriptions. +New models `OneTimeCoverCheck`, `OneTimeCoverRoom`, `PolicyVerdict` and `PolicyUsage`. Other model names, fields and optionality are kept. + ## 0.7.0 (2026-11-15) Follows API 1.20.6. The saved spec has 161 operations and the models are regenerated from it. diff --git a/README.md b/README.md index 6dcbbd4..b5bb715 100644 --- a/README.md +++ b/README.md @@ -84,10 +84,12 @@ The same in async form, with `AsyncClient` and `await` on every call. - `documents.create_upload(filename=..., size_bytes=...)` needs no `content_type`. The API reads the type from the filename and refuses a filename of another format at once with `unsupported_format`. - `billing.statement()` reads the wallet one line per event, with the balance after each line. - `billing.statement_csv()` returns the same lines as CSV text. + `type=` keeps one type of line, and `kind=`, its older name, still works. `billing.statement_csv()` + returns the same lines as CSV text. - `faxes.list(q=...)` finds a fax by its number or by the start of its id. `documents.list(q=...)` finds a document by file name, or a received fax's file by the sender's number. - `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. - `faxes.wait(fax_id)` and `approvals.wait(approval_id)` poll with a timeout. - `verify_webhook(secret, headers, body)` checks the Standard Webhooks signature on a delivery. - Models are pydantic v2, generated from the public OpenAPI document. Money is an integer count of @@ -115,7 +117,7 @@ each call needs. | `ffa.faxes` | `create`, `list`, `iter`, `get`, `wait`, `list_events`, `list_attempts`, `get_receipt`, `get_receipt_pdf`, `cancel` | | `ffa.webhooks` | `list`, `create`, `update`, `delete`, `rotate_secret`, `test`, `list_deliveries`, `get_delivery`, `replay_delivery` | | `ffa.events` | `list`, `iter` | -| `ffa.billing` | `balance`, `list_ledger`, `iter_ledger`, `statement`, `iter_statement`, `statement_csv`, `iter_topup_sessions`, `iter_invoices`, settings, top-ups, auto top-ups, budgets, `delete_budget`, `usage`, exports, invoices, `get_invoice_receipt`, `get_topup_receipt`, subscriptions, `create_portal_session` | +| `ffa.billing` | `balance`, `list_ledger`, `iter_ledger`, `statement`, `iter_statement`, `statement_csv`, `iter_topup_sessions`, `iter_invoices`, settings, top-ups, `cancel_topup_session`, auto top-ups, budgets, `delete_budget`, `usage`, exports, invoices, `get_invoice_receipt`, `get_topup_receipt`, subscriptions, `create_portal_session` | | `ffa.platform` | `capabilities`, `service_status` | | `ffa.sandbox` | `list_scenarios`, `create_scenario`, `create_inbound_fax`, `reset` | | `ffa.approvals` | `request`, `request_help`, `list`, `iter`, `get`, `wait`, `approve`, `reject`, `revoke` | @@ -127,7 +129,7 @@ each call needs. | `ffa.organizations` | `list`, `current`, `update_current`, `request_data_export`, `request_data_deletion`, `list_data_requests`, `withdraw_data_deletion`, `download_export_archive` | | `ffa.members` | `list`, `update`, `remove`, `list_invitations`, `invite`, `resend_invitation`, `link_invitation`, `revoke_invitation` | | `ffa.oauth` | `list_grants`, `iter_grants`, `revoke_grant` | -| `ffa.one_time_sends` | `config`, `preview`, `create`, `create_from_quote`, `list`, `iter`, `get`, `get_page`, `wait`, `checkout`, `read_by_token`, `confirm`, `resend_confirmation`, `get_receipt_pdf` | +| `ffa.one_time_sends` | `config`, `preview`, `check_cover`, `create`, `create_from_quote`, `list`, `iter`, `get`, `get_page`, `wait`, `checkout`, `read_by_token`, `confirm`, `resend_confirmation`, `get_receipt_pdf` | `ffa.request("GET", "/v1/anything")` reaches an operation the resources do not cover yet. @@ -217,8 +219,8 @@ with Client(keyless=True) as ffa: # no API key: only one_time_se ``` `order.next` names the step that is waiting: `checkout`, `confirm`, `wait` or `done`. `wait` polls until -`done`, or until the step you pass as `until`. The card is authorized at checkout and charged only when -the carrier confirms delivery. +`done`, or until the step you pass as `until`. The card is held at checkout and charged only for the +pages the carrier confirms. The status token goes in the `X-FFA-Order-Token` header. It reads the order, opens its checkout, mails the confirmation again and downloads the receipt. A client with a live key of the order's organization @@ -310,9 +312,10 @@ ruff check src tests && mypy src sh scripts/truthcheck.sh ``` -`spec/openapi.yaml` follows the public document at API version 1.20.6 and keeps the schemas of the earlier live documents. +`spec/openapi.yaml` follows the public document at API version 1.20.8 and keeps the schemas of the earlier live documents. The two validation error schemas are the exception. 0.5.0 removed them because the server never sent that shape. 0.6.0 removed two cost fields of an extraction, because the server stopped sending them. +0.8.0 replaced five fields it had declared itself with the public ones, such as `Quote.policy_evaluation`. It also retains earlier public model names and route-documented response additions. To refresh it, merge the live schemas while preserving existing declarations, then run `uv run python scripts/gen_models.py`. Keep new response fields optional so older payloads and existing callers remain valid. diff --git a/pyproject.toml b/pyproject.toml index 7e02028..dbc6604 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "faxforagents" -version = "0.7.0" +version = "0.8.0" 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 fd4f96b..f069078 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.20.6. +# Fax for Agents API, refreshed from the public document of https://github.com/faxforagents/openapi at API 1.20.8. # All earlier schemas are kept. Existing SDK routes, model names and serializer additions are retained. openapi: 3.1.0 info: @@ -26,7 +26,7 @@ info: x-logo: url: https://faxforagents.com/brand/logo-512.png altText: Fax for Agents - version: 1.20.6 + version: 1.20.8 servers: - url: https://api.faxforagents.com description: Production (live and test keys) @@ -202,8 +202,9 @@ paths: tags: - identity summary: Rotate an API key and preserve its expiry - description: The replacement keeps the original expires_at, including no expiry. The old secret works for - up to 24 hours, capped by its existing expiry. + description: 'The replacement keeps the original expires_at, including no expiry. The old secret works for + up to 24 hours, capped by its existing expiry. Once a key expired, rotation answers 409: create a new one + to replace it.' operationId: rotate_api_key parameters: - name: key_id @@ -235,7 +236,13 @@ paths: '404': $ref: '#/components/responses/NotFound' '409': - $ref: '#/components/responses/Conflict' + description: 'The key expired, so it cannot be rotated (conflict, with details.reason key_expired and + details.expires_at). Create a new key to replace it. Also idempotency_key_conflict: the Idempotency-Key + was used with a different body.' + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorEnvelope' '410': $ref: '#/components/responses/Gone' '422': @@ -2255,7 +2262,10 @@ paths: tags: - billing summary: 'The wallet statement: one line per event with the balance after it, newest first' - description: The customer's reading of the wallet. ``GET /v1/ledger`` stays the double-entry record. + description: 'One line per event on the wallet, signed the way the balance moved. type filters the lines by + the type they carry. kind is the same filter by its older name, and both at once answer 422 unless they + agree. A hold and its release name what they were for in ref_type: fax_job, extraction or number_order. + GET /v1/ledger keeps the reference as it was booked, fax_job for every hold.' operationId: get_statement parameters: - name: cursor @@ -2276,6 +2286,19 @@ paths: minimum: 1 default: 50 title: Limit + - name: type + in: query + required: false + schema: + anyOf: + - type: string + pattern: ^(topup|fax|received_fax|number|extraction|release|refund|dispute|credit|adjustment|other)$ + - type: 'null' + description: 'Only the lines whose type is this one: topup, fax, received_fax, number, extraction, release, + refund, dispute, credit, adjustment, other.' + title: Type + description: 'Only the lines whose type is this one: topup, fax, received_fax, number, extraction, release, + refund, dispute, credit, adjustment, other.' - name: kind in: query required: false @@ -2284,11 +2307,11 @@ paths: - type: string pattern: ^(topup|fax|received_fax|number|extraction|release|refund|dispute|credit|adjustment|other)$ - type: 'null' - description: 'One kind of line: topup, fax, received_fax, number, extraction, release, refund, dispute, - credit, adjustment, other.' + description: The same filter as type, by the name it had before 2026-11-15. Sent with type, it has to + name the same type. title: Kind - description: 'One kind of line: topup, fax, received_fax, number, extraction, release, refund, dispute, - credit, adjustment, other.' + description: The same filter as type, by the name it had before 2026-11-15. Sent with type, it has to name + the same type. - name: from in: query required: false @@ -2346,8 +2369,26 @@ paths: tags: - billing summary: 'The wallet statement as CSV: every line the filters select' + description: 'One line per event on the wallet, signed the way the balance moved. type filters the lines by + the type they carry. kind is the same filter by its older name, and both at once answer 422 unless they + agree. A hold and its release name what they were for in ref_type: fax_job, extraction or number_order. + GET /v1/ledger keeps the reference as it was booked, fax_job for every hold. The file''s columns for them + are reference_type and reference_id.' operationId: get_statement_csv parameters: + - name: type + in: query + required: false + schema: + anyOf: + - type: string + pattern: ^(topup|fax|received_fax|number|extraction|release|refund|dispute|credit|adjustment|other)$ + - type: 'null' + description: 'Only the lines whose type is this one: topup, fax, received_fax, number, extraction, release, + refund, dispute, credit, adjustment, other.' + title: Type + description: 'Only the lines whose type is this one: topup, fax, received_fax, number, extraction, release, + refund, dispute, credit, adjustment, other.' - name: kind in: query required: false @@ -2356,11 +2397,11 @@ paths: - type: string pattern: ^(topup|fax|received_fax|number|extraction|release|refund|dispute|credit|adjustment|other)$ - type: 'null' - description: 'One kind of line: topup, fax, received_fax, number, extraction, release, refund, dispute, - credit, adjustment, other.' + description: The same filter as type, by the name it had before 2026-11-15. Sent with type, it has to + name the same type. title: Kind - description: 'One kind of line: topup, fax, received_fax, number, extraction, release, refund, dispute, - credit, adjustment, other.' + description: The same filter as type, by the name it had before 2026-11-15. Sent with type, it has to name + the same type. - name: from in: query required: false @@ -2652,6 +2693,69 @@ paths: mutating: false idempotency_key: false agent_key_allowed: true + /v1/topup-sessions/{topup_session_id}/cancel: + post: + tags: + - billing + summary: Cancel an open top-up, so its hosted Checkout can no longer be paid + description: Closes the Checkout of a manual or setup top-up that is still open and answers the session with + status canceled. Canceling a setup payment also turns off the auto top-up that waited on it. A top-up already + canceled or expired is answered as it is. One that was paid, declined or charged off session answers 409. + operationId: cancel_topup_session + parameters: + - name: topup_session_id + in: path + required: true + schema: + type: string + title: Topup Session Id + - name: Idempotency-Key + in: header + required: false + schema: + type: string + maxLength: 255 + description: 'Replay the first successful response for the same request within 24 hours. Reusing the idempotency + header with a different request returns 409 idempotency_key_conflict. Responses include Idempotent-Replayed: + true on replay.' + responses: + '200': + description: Successful Response + content: + application/json: + schema: + $ref: '#/components/schemas/TopupSession' + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + description: 'The top-up has no open Checkout to cancel: it was paid, declined or charged off session + (conflict, with details.status). details.reason is paid when it was paid before the cancel. Also idempotency_key_conflict: + the Idempotency-Key was used with a different body.' + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorEnvelope' + '410': + $ref: '#/components/responses/Gone' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + '503': + $ref: '#/components/responses/ServiceUnavailable' + security: + - bearerAuth: [] + - apiKeyHeader: [] + x-required-scope: billing:write + x-llm: + scope: billing:write + mutating: true + idempotency_key: true + agent_key_allowed: false /v1/topup-sessions/{topup_session_id}/receipt: get: tags: @@ -7661,8 +7765,9 @@ paths: description: 'Reads a file (or text) exactly as the create would and answers its page count and its first page as a small picture, or the create''s own refusal: too_many_pages, encrypted_pdf, unsupported_format, document_too_large and the other document codes. The price of the document follows from the count and the - route of GET /one-time-sends/config. Nothing is stored: no order, no account, no file. No credential is - needed. Idempotency-Key is accepted but ignored: the call changes nothing, so a repeat reads the file again.' + route of GET /v1/one-time-sends/config. Nothing is stored: no order, no account, no file. No credential + is needed. Idempotency-Key is accepted but ignored: the call changes nothing, so a repeat reads the file + again.' operationId: preview_one_time_document requestBody: content: @@ -7727,6 +7832,43 @@ paths: idempotency_key: false agent_key_allowed: true key_optional: true + /v1/one-time-sends/cover-checks: + post: + tags: + - one-time-sends + summary: Measure the room the cover sheet leaves for its message, before an order is made + description: |- + Lays out the cover sheet exactly as the create would, with the fields given so far, and answers whether the message fits on its one page and how many more lines fit, or how much of it fits when it runs over. The create refuses a cover that does not fit with invalid_request on cover. This call says so while the message is written. Every field may be empty. Nothing is stored and no credential is needed. Idempotency-Key is accepted but ignored: the call changes nothing. + + No API key is needed. + operationId: create_one_time_cover_check + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OneTimeCoverCheck' + required: true + responses: + '200': + description: Successful Response + content: + application/json: + schema: + $ref: '#/components/schemas/OneTimeCoverRoom' + '413': + $ref: '#/components/responses/PayloadTooLarge' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + '503': + $ref: '#/components/responses/ServiceUnavailable' + security: [] + x-llm: + scope: none + mutating: false + idempotency_key: false + agent_key_allowed: true /v1/one-time-sends: post: tags: @@ -8399,10 +8541,11 @@ paths: tags: - one-time-sends summary: Open the card payment of a one-time order - description: 'Answers the hosted payment page of the order. The card is authorized there, not charged: it - is charged when the carrier confirms delivery. A second call answers the same page while it can still be - paid, and a new one after it expired. An order whose aup_accepted is false needs {"accept_aup": true} in - the body once, from the status token or a session: the person who pays accepts the policy, never a key.' + description: 'Answers the hosted payment page of the order. The card is held there, not charged. It is charged + only for the pages the carrier confirms, and the rest of the hold is released. A second call answers the + same page while it can still be paid, and a new one after it expired. An order whose aup_accepted is false + needs {"accept_aup": true} in the body once, from the status token or a session: the person who pays accepts + the policy, never a key.' operationId: create_one_time_checkout parameters: - name: one_time_order_id @@ -8492,7 +8635,7 @@ paths: mutating: true idempotency_key: true agent_key_allowed: true - hint: The card is authorized on the hosted page and charged only when the carrier confirms delivery. A person + hint: The card is held on the hosted page and charged only for the pages the carrier confirms. A person pays, never the agent. order_token: true /v1/one-time-sends/{one_time_order_id}/confirm: @@ -9005,6 +9148,7 @@ components: - archived - keys_revoked title: AgentArchived + description: 'What archiving an agent did: it is disabled for good and out of the list, and its keys are revoked.' AgentCreate: properties: name: @@ -9144,6 +9288,7 @@ components: - countries - prefixes title: AlreadyAllowed + description: A number of a draft's allowed_destinations that one of its countries or prefixes already allows. ApiKey: properties: id: @@ -9399,6 +9544,8 @@ components: - page_count - state title: ApprovalDocument + description: 'The document a send request binds, as it is now: its name, its pages and whether a send can + use it.' ApprovalRequest: properties: id: @@ -10078,6 +10225,7 @@ components: - deleted - archived title: BudgetRemoved + description: 'What removing a budget did: deleted when it never charged a hold, archived when it has history.' Capabilities: properties: environment: @@ -10163,6 +10311,9 @@ components: additionalProperties: true type: object title: One Time + description: 'One fax paid by card on this server. enabled: orders are taken here. published: the price + card offers the product. routes: the routes sold one fax at a time, empty while not enabled. max_document_pages: + the most document pages one order takes. Prices are in GET /v1/one-time-sends/config.' additionalProperties: true type: object required: @@ -10385,6 +10536,7 @@ components: required: - items title: DataRequestList + description: The organization's export and deletion requests, each with where it stands. Deleted: properties: id: @@ -10407,6 +10559,7 @@ components: webhook_id: type: string title: Webhook Id + description: The destination the event is sent to. webhook_url: anyOf: - type: string @@ -10416,45 +10569,59 @@ components: event_id: type: string title: Event Id + description: The event sent. The webhook-id header carries the same id. event_type: type: string title: Event Type + description: The event's type, such as fax.delivered. attempt: type: integer title: Attempt + description: How many attempts were made so far. status: type: string title: Status + description: 'pending: an attempt is due or waits for its time. delivered: the destination answered 2xx. + exhausted: every attempt of the schedule failed. failed: it stopped early, because the destination was + deleted or paused, or its address was refused.' response_status: anyOf: - type: integer - type: 'null' title: Response Status + description: The HTTP status of the last attempt's answer. Null before an attempt, or when none came. error: anyOf: - type: string - type: 'null' title: Error + description: Why the last attempt failed, in words. Null once delivered. duration_ms: anyOf: - type: integer - type: 'null' title: Duration Ms + description: How long the last attempt took, in milliseconds. replay_of: anyOf: - type: string - type: 'null' title: Replay Of + description: The delivery this one sends again (POST /v1/webhook-deliveries/{delivery_id}/replay). Null + for a first delivery. schedule_s: items: type: integer type: array title: Schedule S + description: The wait before each attempt, in seconds after the one before. The first attempt waits 0 + seconds. next_attempt_at: anyOf: - type: string - type: 'null' title: Next Attempt At + description: When the next attempt is due. Null once the delivery has ended. created_at: type: string title: Created At @@ -10463,6 +10630,7 @@ components: - type: string - type: 'null' title: Delivered At + description: When the destination answered 2xx. Null until then. additionalProperties: true type: object required: @@ -10481,6 +10649,7 @@ components: - created_at - delivered_at title: Delivery + description: 'One delivery of an event to a webhook destination: its attempts so far and the last answer.' DeliveryDetail: properties: id: @@ -10489,6 +10658,7 @@ components: webhook_id: type: string title: Webhook Id + description: The destination the event is sent to. webhook_url: anyOf: - type: string @@ -10498,45 +10668,59 @@ components: event_id: type: string title: Event Id + description: The event sent. The webhook-id header carries the same id. event_type: type: string title: Event Type + description: The event's type, such as fax.delivered. attempt: type: integer title: Attempt + description: How many attempts were made so far. status: type: string title: Status + description: 'pending: an attempt is due or waits for its time. delivered: the destination answered 2xx. + exhausted: every attempt of the schedule failed. failed: it stopped early, because the destination was + deleted or paused, or its address was refused.' response_status: anyOf: - type: integer - type: 'null' title: Response Status + description: The HTTP status of the last attempt's answer. Null before an attempt, or when none came. error: anyOf: - type: string - type: 'null' title: Error + description: Why the last attempt failed, in words. Null once delivered. duration_ms: anyOf: - type: integer - type: 'null' title: Duration Ms + description: How long the last attempt took, in milliseconds. replay_of: anyOf: - type: string - type: 'null' title: Replay Of + description: The delivery this one sends again (POST /v1/webhook-deliveries/{delivery_id}/replay). Null + for a first delivery. schedule_s: items: type: integer type: array title: Schedule S + description: The wait before each attempt, in seconds after the one before. The first attempt waits 0 + seconds. next_attempt_at: anyOf: - type: string - type: 'null' title: Next Attempt At + description: When the next attempt is due. Null once the delivery has ended. created_at: type: string title: Created At @@ -10545,6 +10729,7 @@ components: - type: string - type: 'null' title: Delivered At + description: When the destination answered 2xx. Null until then. webhook_deleted: type: boolean title: Webhook Deleted @@ -10583,6 +10768,7 @@ components: - request_headers - payload title: DeliveryDetail + description: One delivery with the headers and the body that every attempt sends. DeliveryPage: properties: items: @@ -10649,10 +10835,14 @@ components: - type: string - type: 'null' title: Converted From + description: The name of the image this PDF was converted from, as the person gave it. filename is the + PDF's own name. Null for a document that was not an image. received: anyOf: - $ref: '#/components/schemas/DocumentReceived' - type: 'null' + description: Set in the list (GET /v1/documents) on the file of a received fax, source inbound. It names + the inbox item, the sender as the sending machine gave it, and the time. Null everywhere else. upload_id: anyOf: - type: string @@ -10769,6 +10959,7 @@ components: - type: integer - type: 'null' title: Total + description: How many documents the filters match in all, across every page. additionalProperties: true type: object required: @@ -10837,6 +11028,7 @@ components: required: - filename title: DocumentUpdate + description: A new file name for a document. DocumentValidation: properties: id: @@ -10929,6 +11121,9 @@ components: retryable: type: boolean title: Retryable + description: 'True when the failure passes on its own: the same call, sent again unchanged after a short + wait, is expected to work. False when the same call gets the same answer until the request or the resource + changes.' correlation_id: anyOf: - type: string @@ -11484,6 +11679,21 @@ components: - type: string - type: 'null' title: Client Reference + approval_id: + anyOf: + - type: string + - type: 'null' + title: Approval Id + description: 'The approval request a person approved for this send. Null when another path authorized + it: a delegated policy (policy_version_id), a test key no policy binds, or the payer''s confirmation + of a one-time order.' + policy_version_id: + anyOf: + - type: string + - type: 'null' + title: Policy Version Id + description: The version of the delegated policy that allowed this send. A version never changes, so it + shows the limits the send was allowed under. Null when no policy decided the send. attempt_count: type: integer title: Attempt Count @@ -11520,18 +11730,12 @@ components: anyOf: - $ref: '#/components/schemas/OneTimeJob' - type: 'null' - approval_id: - type: - - string - - 'null' - description: Returned by GET /v1/faxes/{fax_id}. Declared here until the public schema includes it. - x-sdk-route: GET /v1/faxes/{fax_id} - policy_version_id: - type: - - string - - 'null' - description: Returned by GET /v1/faxes/{fax_id}. Declared here until the public schema includes it. - x-sdk-route: GET /v1/faxes/{fax_id} + route_paused: + type: boolean + title: Route Paused + description: An operator has paused sends on this fax's route while the fax waits for a line (queued or + between tries). It goes out when the route is resumed. Read when the fax is read, not stored. + default: false additionalProperties: true type: object required: @@ -11586,6 +11790,8 @@ components: provider: sandbox provider_ref: sbx_311dd5d5bc5dfd76 client_reference: null + approval_id: null + policy_version_id: null attempt_count: 1 created_at: '2026-11-14T19:58:38.794Z' updated_at: '2026-11-14T19:58:38.910Z' @@ -11603,6 +11809,7 @@ components: remote_station_id: SBX-OK one_time_order_id: null one_time: null + route_paused: false FaxJobPage: properties: items: @@ -11732,6 +11939,7 @@ components: amount_micro: type: integer title: Amount Micro + description: What the received pages were charged, in micro-USD. 0 on the sandbox. default: 0 note: anyOf: @@ -11768,6 +11976,8 @@ components: - type: string - type: 'null' title: File Deleted At + description: When the file of this fax was deleted. media_status is then deleted and there is no download. + Null while the file is kept. duration_secs: anyOf: - type: integer @@ -11827,6 +12037,7 @@ components: amount_micro: type: integer title: Amount Micro + description: What the received pages were charged, in micro-USD. 0 on the sandbox. default: 0 note: anyOf: @@ -11863,6 +12074,8 @@ components: - type: string - type: 'null' title: File Deleted At + description: When the file of this fax was deleted. media_status is then deleted and there is no download. + Null while the file is kept. duration_secs: anyOf: - type: integer @@ -11966,6 +12179,7 @@ components: amount_micro: type: integer title: Amount Micro + description: What the received pages were charged, in micro-USD. 0 on the sandbox. default: 0 note: anyOf: @@ -12055,6 +12269,7 @@ components: unread: type: integer title: Unread + description: The faxes nobody has opened yet in this environment, whatever the filters. default: 0 additionalProperties: true type: object @@ -12254,6 +12469,7 @@ components: - url - expires_at title: InvitationLink + description: A new link for an open invitation, shown once, which replaces the old link. InvitationList: properties: items: @@ -12827,8 +13043,9 @@ components: title: OneTimeAttempts description: |- The tries of an order's fax while it is still going out. A busy line or one that does not answer - is dialed again (``max`` tries in all, about ``retry_delay_seconds`` apart). ``last_failure_code`` is - why the last finished try did not get through, null when no try has ended. + is dialed again, up to ``max`` tries in all, about ``retry_delay_seconds`` apart. The field + ``last_failure_code`` says why the last finished try did not get through. It is null when no try has + ended. OneTimeCard: properties: last4: @@ -12943,9 +13160,10 @@ components: - terms_url title: OneTimeConfig description: |- - What the public send page and an agent read before an order: whether the product is open here, the - card the order will be priced from (present only while open), the document limits and the policy the - sender accepts. Prices are integer micro-USD; the dollar figure is the client's to format. + What the public send page and an agent read before an order. It says whether the product is open + here, and while it is open it gives the card the order will be priced from. It also gives the document + limits and the policy the sender accepts. Prices are integer micro-USD, and the client formats the + dollar figure. OneTimeConfirm: properties: token: @@ -13049,6 +13267,87 @@ components: description: |- ``signed_in`` says whether this browser now holds a session for the payer; ``me`` is then the same object ``GET /v1/auth/me`` answers (the CSRF token included). + OneTimeCoverCheck: + properties: + sender_name: + anyOf: + - type: string + maxLength: 1000 + - type: 'null' + title: Sender Name + description: Printed in the From line. + email: + anyOf: + - type: string + maxLength: 1000 + - type: 'null' + title: Email + description: Printed in the From line. + to: + anyOf: + - type: string + maxLength: 100 + - type: 'null' + title: To + description: The destination, when one is typed. + to_name: + anyOf: + - type: string + maxLength: 1000 + - type: 'null' + title: To Name + subject: + anyOf: + - type: string + maxLength: 1000 + - type: 'null' + title: Subject + message: + anyOf: + - type: string + maxLength: 8000 + - type: 'null' + title: Message + additionalProperties: false + type: object + title: OneTimeCoverCheck + description: |- + The fields a one-time order prints on its cover sheet, as a form holds them before the order exists. + Every field may be empty. The limits of the create apply (cover.to_name 120 characters, cover.subject + 200, cover.message 2,000). + OneTimeCoverRoom: + properties: + fits: + type: boolean + title: Fits + description: The cover with this message fits on its one page. + message_chars: + type: integer + title: Message Chars + description: The length of the message as it will be printed. + lines_left: + anyOf: + - type: integer + - type: 'null' + title: Lines Left + description: How many more lines of message text fit on the page. Null when the message is empty, since + the first line also brings its heading, and when it does not fit. + fits_chars: + anyOf: + - type: integer + - type: 'null' + title: Fits Chars + description: 'When the message runs over: how much of its start fits with the same line breaks. Null when + it fits, and when the page is full without any message.' + additionalProperties: true + type: object + required: + - fits + - message_chars + title: OneTimeCoverRoom + description: |- + How the message sits on the one cover page, measured as the create measures it. Nothing is stored + and no order is made. OneTimeFromQuote: properties: quote_id: @@ -13123,8 +13422,9 @@ components: - thumbnail_png_base64 title: OneTimeInspection description: |- - What a file would be as a one-time order's document: its page count, and its first page as a small - PNG (base64, null when this server cannot draw one). Nothing is stored and no order is made. + What a file would be as a one-time order's document: its page count and its first page as a small + PNG. The PNG is base64, or null when this server cannot draw one. Nothing is stored and no order is + made. OneTimeJob: properties: order_id: @@ -13217,7 +13517,7 @@ components: required: - order_id title: OneTimeJob - description: 'The order behind a fax job that a one-time send made: what was authorized, what was charged.' + description: 'The order behind a fax job that a one-time send made: what was held on the card, what was charged.' OneTimeOrder: properties: id: @@ -13301,9 +13601,9 @@ components: document_deleted: type: boolean title: Document Deleted - description: 'True once no copy of the document is held: it was deleted after the send, by the retention - period or by its owner, or the order ended before it was released and the uploaded file was removed. - The order, the fax and the carrier evidence stay; they hold no document content.' + description: True once no copy of the document is held. It was deleted after the send, by the retention + period or by its owner. Or the order ended before its release and the uploaded file was removed. The + order, the fax and the carrier evidence stay, and they hold no document content. default: false document_expires_at: anyOf: @@ -13430,8 +13730,8 @@ components: anyOf: - $ref: '#/components/schemas/OneTimeAttempts' - type: 'null' - description: 'The tries of the order''s fax while it has not ended: how many were made, of how many, and - why the last one did not get through. Null before the fax exists and once it ended.' + description: The tries of the order's fax while it has not ended. It says how many were made, of how many, + and why the last one did not get through. Null before the fax exists and once it ended. preview: anyOf: - $ref: '#/components/schemas/OneTimePreview' @@ -13481,10 +13781,10 @@ components: - updated_at title: OneTimeOrder description: |- - One order of the one-time send. ``next`` is what the caller does now: ``checkout`` (open the - payment), ``confirm`` (the payer clicks the link in the mail), ``wait`` (nothing to do; read again) or - ``done``. Money is integer micro-USD. ``captured_micro`` is what the card was charged, written only - once the payment provider confirmed it. ``fax`` is the fax job once the order was released, with the + 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. OneTimeOrderCreated: properties: @@ -13569,9 +13869,9 @@ components: document_deleted: type: boolean title: Document Deleted - description: 'True once no copy of the document is held: it was deleted after the send, by the retention - period or by its owner, or the order ended before it was released and the uploaded file was removed. - The order, the fax and the carrier evidence stay; they hold no document content.' + description: True once no copy of the document is held. It was deleted after the send, by the retention + period or by its owner. Or the order ended before its release and the uploaded file was removed. The + order, the fax and the carrier evidence stay, and they hold no document content. default: false document_expires_at: anyOf: @@ -13694,8 +13994,8 @@ components: anyOf: - $ref: '#/components/schemas/OneTimeAttempts' - type: 'null' - description: 'The tries of the order''s fax while it has not ended: how many were made, of how many, and - why the last one did not get through. Null before the fax exists and once it ended.' + description: The tries of the order's fax while it has not ended. It says how many were made, of how many, + and why the last one did not get through. Null before the fax exists and once it ended. preview: anyOf: - $ref: '#/components/schemas/OneTimePreview' @@ -13855,9 +14155,10 @@ components: - estimated_wait_minutes title: OneTimeQueue description: |- - The wait for a carrier line. ``queued`` is true when a fax sent now, or this order's waiting fax, - is estimated to wait more than ten minutes for a line: the order is kept and sent in turn, never - dropped. The minutes are an estimate from the number of faxes ahead and the carrier's line count. + The wait for a carrier line. The field ``queued`` is true when a fax sent now, or this order's + waiting fax, is estimated to wait over ten minutes for a line. The order is kept and sent in turn, + never dropped. The minutes are an estimate from the number of faxes ahead and the carrier's line + count. OneTimeRoute: properties: label: @@ -14008,7 +14309,9 @@ components: - type: string - type: 'null' title: Pdf Url - description: The same receipt as a PDF. + description: 'The same receipt as a PDF, where Stripe has one: the receipt of a paid invoice, which a + top-up paid in Checkout has. Null for a charge without an invoice, such as an automatic top-up: its + receipt is the page at url.' amount_micro: type: integer title: Amount Micro @@ -14137,25 +14440,33 @@ components: properties: decision: type: string + enum: + - allow + - deny title: Decision rule: anyOf: - type: string - type: 'null' title: Rule + description: The rule that failed first when a policy denied the plan. Null on allow, and when no policy + binds the caller. reason: type: string title: Reason + description: Why, in one sentence. policy_id: anyOf: - type: string - type: 'null' title: Policy Id + description: The policy that allowed the plan, or the first one that denied it. Null when none binds. policy_version_id: anyOf: - type: string - type: 'null' title: Policy Version Id + description: The version of that policy that decided. policy_name: anyOf: - type: string @@ -14166,12 +14477,25 @@ components: - type: integer - type: 'null' title: Version + managed: + anyOf: + - type: string + - type: 'null' + title: Managed + description: connected_apps when the organization's auto-send setting decided, else null. denials: items: additionalProperties: true type: object type: array title: Denials + description: Every policy that denied the plan, each with its policy_id, policy_version_id, decision, + rule and reason. Empty on allow. + usage: + anyOf: + - $ref: '#/components/schemas/PolicyUsage' + - type: 'null' + description: 'On allow: the deciding policy''s counters for the day and the month before this send.' plan: additionalProperties: true type: object @@ -14201,14 +14525,6 @@ components: title: Approval Required description: 'What a send of this plan by that caller would need: true when a person has to approve it. false when a policy allows it, and for a test send by a caller no policy binds.' - usage: - type: - - object - - 'null' - additionalProperties: - type: integer - description: Returned by POST /v1/policy-evaluations when a bound policy has usage. - x-sdk-route: POST /v1/policy-evaluations additionalProperties: true type: object required: @@ -14222,6 +14538,9 @@ components: - denials - plan title: PolicyEvaluation + description: |- + A dry run: the verdict for one planned send, the plan as the server read it, and what a send of it + would need. Nothing is sent. PolicyEvaluationCreate: properties: quote_id: @@ -14303,6 +14622,7 @@ components: required: - already_allowed title: PolicyRuleCheck + description: Which of a draft's numbers its countries or prefixes already allow. PolicyRuleCheckCreate: properties: allowed_destinations: @@ -14311,21 +14631,25 @@ components: type: array maxItems: 500 title: Allowed Destinations + description: The draft's exact E.164 numbers. allowed_countries: items: type: string type: array maxItems: 300 title: Allowed Countries + description: The draft's ISO 3166-1 alpha-2 country codes, such as US or GB. allowed_country_prefixes: items: type: string type: array maxItems: 300 title: Allowed Country Prefixes + description: The draft's dialing prefixes, written as the rate card routes on them, such as +44. additionalProperties: false type: object title: PolicyRuleCheckCreate + description: The three destination lists of a draft policy, to check against each other. PolicyUpdate: properties: name: @@ -14355,6 +14679,104 @@ components: additionalProperties: false type: object title: PolicyUpdate + PolicyUsage: + properties: + day_jobs: + type: integer + title: Day Jobs + day_amount_micro: + type: integer + title: Day Amount Micro + month_jobs: + type: integer + title: Month Jobs + month_amount_micro: + type: integer + title: Month Amount Micro + additionalProperties: true + type: object + required: + - day_jobs + - day_amount_micro + - month_jobs + - month_amount_micro + title: PolicyUsage + description: What the deciding policy had counted before the send it was asked about, in UTC periods. + PolicyVerdict: + properties: + decision: + type: string + enum: + - allow + - deny + title: Decision + rule: + anyOf: + - type: string + - type: 'null' + title: Rule + description: The rule that failed first when a policy denied the plan. Null on allow, and when no policy + binds the caller. + reason: + type: string + title: Reason + description: Why, in one sentence. + policy_id: + anyOf: + - type: string + - type: 'null' + title: Policy Id + description: The policy that allowed the plan, or the first one that denied it. Null when none binds. + policy_version_id: + anyOf: + - type: string + - type: 'null' + title: Policy Version Id + description: The version of that policy that decided. + policy_name: + anyOf: + - type: string + - type: 'null' + title: Policy Name + version: + anyOf: + - type: integer + - type: 'null' + title: Version + managed: + anyOf: + - type: string + - type: 'null' + title: Managed + description: connected_apps when the organization's auto-send setting decided, else null. + denials: + items: + additionalProperties: true + type: object + type: array + title: Denials + description: Every policy that denied the plan, each with its policy_id, policy_version_id, decision, + rule and reason. Empty on allow. + usage: + anyOf: + - $ref: '#/components/schemas/PolicyUsage' + - type: 'null' + description: 'On allow: the deciding policy''s counters for the day and the month before this send.' + additionalProperties: true + type: object + required: + - decision + - rule + - reason + - policy_id + - policy_version_id + - policy_name + - version + - denials + title: PolicyVerdict + description: |- + One evaluation of the delegated policies that bind a caller: the first policy that allows the plan, + or every policy that denies it. PolicyVersion: properties: id: @@ -14616,6 +15038,16 @@ components: type: integer title: Per Page Micro default: 0 + pricing: + type: string + enum: + - per_page + - one_time + title: Pricing + description: 'per_page: priced from the rate card, paid from the wallet and sent with POST /v1/faxes. + one_time: the quote of a one-time order, priced at the card''s price for the order. Only the order sends + it, and POST /v1/faxes refuses it with quote_pricing_mismatch.' + default: per_page route_label: type: string title: Route Label @@ -14642,6 +15074,12 @@ components: authorization_required: type: boolean title: Authorization Required + policy_evaluation: + anyOf: + - $ref: '#/components/schemas/PolicyVerdict' + - type: 'null' + description: The dry run of the delegated policies that bind the caller, made with the quote. Null when + no policy binds the caller. The send evaluates the policies again, with their counters locked. route_paused: type: boolean title: Route Paused @@ -14668,18 +15106,6 @@ components: created_at: type: string title: Created At - pricing: - type: string - description: Returned by POST /v1/fax-quotes. Declared here until the public schema includes it. - x-sdk-route: POST /v1/fax-quotes - policy_evaluation: - type: - - object - - 'null' - description: Returned by GET /v1/fax-quotes/{quote_id}. Declared here until the public schema includes - it. - x-sdk-route: GET /v1/fax-quotes/{quote_id} - additionalProperties: true additionalProperties: true type: object required: @@ -14718,12 +15144,14 @@ components: currency: USD price_version: launch-v3 per_page_micro: 0 + pricing: per_page route_label: United States and Canada cover: null quality: fine sender_name: null delete_after_send: false authorization_required: false + policy_evaluation: null route_paused: false warnings: - code: sandbox @@ -14893,9 +15321,9 @@ components: - $ref: '#/components/schemas/OneTimeJob' - type: 'null' description: Set on the receipt of a fax that a one-time order paid for. It names the order, its status, - the card and the amount the card was authorized for. captured_micro in it is the amount charged, written - once the payment provider confirmed the capture. For a card order read the money here. Null for a fax - paid from the wallet. + the card and the amount held on the card. captured_micro in it is the amount charged, written once the + payment provider confirmed the capture. For a card order read the money here. Null for a fax paid from + the wallet. additionalProperties: true type: object required: @@ -15327,6 +15755,7 @@ components: - adjustment - other title: Type + description: What the line is, in one word. The type filter of the statement takes these values. description: type: string title: Description @@ -15344,11 +15773,16 @@ components: - type: string - type: 'null' title: Ref Type + description: 'What ref_id is. A hold or its release names what it was for: fax_job, extraction or number_order. + Other lines name what they were booked against, such as stripe_payment_intent for a top-up or inbox_item + for a received fax.' ref_id: anyOf: - type: string - type: 'null' title: Ref Id + description: The id of that object, such as fax_..., ext_..., nord_... or inb_..., or the payment's id + at the card processor. Null when the line names none. additionalProperties: true type: object required: @@ -15361,6 +15795,7 @@ components: - ref_type - ref_id title: StatementLine + description: One event on the wallet, signed the way the balance moved, with the balance after it. StatementPage: properties: items: @@ -15378,6 +15813,7 @@ components: required: - items title: StatementPage + description: A page of the wallet statement, newest line first. Subscription: properties: id: diff --git a/src/faxforagents/__init__.py b/src/faxforagents/__init__.py index 5921c66..d98c7aa 100644 --- a/src/faxforagents/__init__.py +++ b/src/faxforagents/__init__.py @@ -18,7 +18,7 @@ from __future__ import annotations -__version__ = "0.7.0" +__version__ = "0.8.0" 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 95aa5a2..8cafd5a 100644 --- a/src/faxforagents/async_client.py +++ b/src/faxforagents/async_client.py @@ -76,7 +76,10 @@ async def create_api_key( ) async def rotate_api_key(self, key_id: str, *, idempotency_key: str | None = None) -> m.ApiKeyWithSecret: - """A new secret. The old one works 24 more hours. Scope: key:admin.""" + """A new secret. The old one works 24 more hours. Scope: key:admin. + + A key that expired cannot be rotated. It raises ``ConflictError`` with ``details["reason"]`` + ``key_expired``. Create a new key to replace it.""" return await self._h.request( "POST", f"/v1/api-keys/{key_id}/rotate", model=m.ApiKeyWithSecret, idempotency_key=idempotency_key ) @@ -481,6 +484,7 @@ def iter_ledger(self, *, limit: int | None = None) -> AsyncIterator[m.LedgerEntr async def statement( self, *, + type: str | None = None, kind: str | None = None, from_: str | None = None, to: str | None = None, @@ -490,30 +494,38 @@ async def statement( """The wallet statement, newest first: one line per event with the balance after it. Scope: billing:read. - ``kind`` keeps one kind of line: topup, fax, received_fax, number, extraction, release, refund, - dispute, credit, adjustment or other. ``from_`` and ``to`` are UTC days, YYYY-MM-DD, both - included. ``list_ledger`` stays the double-entry record.""" - params = {"kind": kind, "from": from_, "to": to, "cursor": cursor, "limit": limit} + ``type`` keeps the lines of one type, as each line shows it. The types are topup, fax, + received_fax, number, extraction, release, refund, dispute, credit, adjustment and other. + ``kind`` is the same filter by its older name. Two different types in both raise + ``InvalidRequestError``. ``from_`` and ``to`` are UTC days, YYYY-MM-DD, both included. + ``list_ledger`` stays the double-entry record.""" + params = {"type": type, "kind": kind, "from": from_, "to": to, "cursor": cursor, "limit": limit} return await self._h.request("GET", "/v1/statement", model=m.StatementPage, params=params) def iter_statement( self, *, + type: str | None = None, kind: str | None = None, from_: str | None = None, to: str | None = None, limit: int | None = None, ) -> AsyncIterator[m.StatementLine]: """Every statement line the filters select, following next_cursor.""" - return apaginate(self.statement, {"kind": kind, "from_": from_, "to": to, "limit": limit}) + filters = {"type": type, "kind": kind, "from_": from_, "to": to, "limit": limit} + return apaginate(self.statement, filters) async def statement_csv( - self, *, kind: str | None = None, from_: str | None = None, to: str | None = None + self, + *, + type: str | None = None, + kind: str | None = None, + from_: str | None = None, + to: str | None = None, ) -> str: """The statement as CSV text, every line the filters select in one answer. Scope: billing:read.""" - data = await self._h.request( - "GET", "/v1/statement.csv", params={"kind": kind, "from": from_, "to": to} - ) + params = {"type": type, "kind": kind, "from": from_, "to": to} + data = await self._h.request("GET", "/v1/statement.csv", params=params) return bytes(data).decode("utf-8") async def get_settings(self) -> m.BillingSettings: @@ -558,9 +570,26 @@ async def get_topup_session(self, topup_session_id: str) -> m.TopupSession: """Read a top-up session. Scope: billing:read.""" return await self._h.request("GET", f"/v1/topup-sessions/{topup_session_id}", model=m.TopupSession) + async def cancel_topup_session( + self, topup_session_id: str, *, idempotency_key: str | None = None + ) -> m.TopupSession: + """Cancel an open top-up, so nobody can pay its hosted Checkout any more. It reads ``canceled``. + Scope: billing:write, never an agent key. + + Canceling a setup payment also turns off the auto top-up that waited on it. A top-up already + canceled or expired comes back as it is. One that was paid, declined or charged off session + raises ``ConflictError``, with the top-up's status in ``details["status"]``.""" + return await self._h.request( + "POST", + f"/v1/topup-sessions/{topup_session_id}/cancel", + model=m.TopupSession, + idempotency_key=idempotency_key, + ) + async def get_topup_receipt(self, topup_session_id: str) -> m.PaymentReceipt: """The payment receipt of a paid top-up, an automatic one included. ``url`` is the hosted - receipt. ``ConflictError`` while the top-up is not paid. Scope: billing:read.""" + receipt. ``pdf_url`` is ``None`` for an automatic top-up, which has no invoice and no PDF. + ``ConflictError`` while the top-up is not paid. Scope: billing:read.""" return await self._h.request( "GET", f"/v1/topup-sessions/{topup_session_id}/receipt", model=m.PaymentReceipt ) @@ -1578,6 +1607,30 @@ async def preview( files={"file": (name, data, ctype)}, ) + async def check_cover( + self, + *, + sender_name: str | None = None, + email: str | None = None, + to: str | None = None, + to_name: str | None = None, + subject: str | None = None, + message: str | None = None, + ) -> m.OneTimeCoverRoom: + """Measure the room the cover sheet leaves for its message, before an order is made. Nothing is + stored. It works without an API key. + + Pass the cover fields typed so far, as ``create`` takes them, and leave out the rest. ``fits`` + says whether the message fits on the one cover page, and ``lines_left`` how many more lines + fit. When it runs over, ``fits_chars`` is how much of its start fits. ``create`` refuses a + cover that does not fit.""" + body = m.OneTimeCoverCheck( + sender_name=sender_name, email=email, to=to, to_name=to_name, subject=subject, message=message + ) + return await self._h.request( + "POST", "/v1/one-time-sends/cover-checks", model=m.OneTimeCoverRoom, json=body + ) + async def create( self, *, diff --git a/src/faxforagents/client.py b/src/faxforagents/client.py index 074eeaf..b351bd5 100644 --- a/src/faxforagents/client.py +++ b/src/faxforagents/client.py @@ -125,7 +125,10 @@ def create_api_key( ) def rotate_api_key(self, key_id: str, *, idempotency_key: str | None = None) -> m.ApiKeyWithSecret: - """A new secret. The old one works 24 more hours. Scope: key:admin.""" + """A new secret. The old one works 24 more hours. Scope: key:admin. + + A key that expired cannot be rotated. It raises ``ConflictError`` with ``details["reason"]`` + ``key_expired``. Create a new key to replace it.""" return self._h.request( "POST", f"/v1/api-keys/{key_id}/rotate", model=m.ApiKeyWithSecret, idempotency_key=idempotency_key ) @@ -522,6 +525,7 @@ def iter_ledger(self, *, limit: int | None = None) -> Iterator[m.LedgerEntry]: def statement( self, *, + type: str | None = None, kind: str | None = None, from_: str | None = None, to: str | None = None, @@ -531,30 +535,38 @@ def statement( """The wallet statement, newest first: one line per event with the balance after it. Scope: billing:read. - ``kind`` keeps one kind of line: topup, fax, received_fax, number, extraction, release, refund, - dispute, credit, adjustment or other. ``from_`` and ``to`` are UTC days, YYYY-MM-DD, both - included. ``list_ledger`` stays the double-entry record.""" - params = {"kind": kind, "from": from_, "to": to, "cursor": cursor, "limit": limit} + ``type`` keeps the lines of one type, as each line shows it. The types are topup, fax, + received_fax, number, extraction, release, refund, dispute, credit, adjustment and other. + ``kind`` is the same filter by its older name. Two different types in both raise + ``InvalidRequestError``. ``from_`` and ``to`` are UTC days, YYYY-MM-DD, both included. + ``list_ledger`` stays the double-entry record.""" + params = {"type": type, "kind": kind, "from": from_, "to": to, "cursor": cursor, "limit": limit} return self._h.request("GET", "/v1/statement", model=m.StatementPage, params=params) def iter_statement( self, *, + type: str | None = None, kind: str | None = None, from_: str | None = None, to: str | None = None, limit: int | None = None, ) -> Iterator[m.StatementLine]: """Every statement line the filters select, following next_cursor.""" - return paginate( - lambda p: self.statement(**p), {"kind": kind, "from_": from_, "to": to, "limit": limit} - ) + filters = {"type": type, "kind": kind, "from_": from_, "to": to, "limit": limit} + return paginate(lambda p: self.statement(**p), filters) def statement_csv( - self, *, kind: str | None = None, from_: str | None = None, to: str | None = None + self, + *, + type: str | None = None, + kind: str | None = None, + from_: str | None = None, + to: str | None = None, ) -> str: """The statement as CSV text, every line the filters select in one answer. Scope: billing:read.""" - data = self._h.request("GET", "/v1/statement.csv", params={"kind": kind, "from": from_, "to": to}) + params = {"type": type, "kind": kind, "from": from_, "to": to} + data = self._h.request("GET", "/v1/statement.csv", params=params) return bytes(data).decode("utf-8") def get_settings(self) -> m.BillingSettings: @@ -595,9 +607,26 @@ def get_topup_session(self, topup_session_id: str) -> m.TopupSession: """Read a top-up session. Scope: billing:read.""" return self._h.request("GET", f"/v1/topup-sessions/{topup_session_id}", model=m.TopupSession) + def cancel_topup_session( + self, topup_session_id: str, *, idempotency_key: str | None = None + ) -> m.TopupSession: + """Cancel an open top-up, so nobody can pay its hosted Checkout any more. It reads ``canceled``. + Scope: billing:write, never an agent key. + + Canceling a setup payment also turns off the auto top-up that waited on it. A top-up already + canceled or expired comes back as it is. One that was paid, declined or charged off session + raises ``ConflictError``, with the top-up's status in ``details["status"]``.""" + return self._h.request( + "POST", + f"/v1/topup-sessions/{topup_session_id}/cancel", + model=m.TopupSession, + idempotency_key=idempotency_key, + ) + def get_topup_receipt(self, topup_session_id: str) -> m.PaymentReceipt: """The payment receipt of a paid top-up, an automatic one included. ``url`` is the hosted - receipt. ``ConflictError`` while the top-up is not paid. Scope: billing:read.""" + receipt. ``pdf_url`` is ``None`` for an automatic top-up, which has no invoice and no PDF. + ``ConflictError`` while the top-up is not paid. Scope: billing:read.""" return self._h.request( "GET", f"/v1/topup-sessions/{topup_session_id}/receipt", model=m.PaymentReceipt ) @@ -1589,6 +1618,28 @@ def preview( files={"file": (name, data, ctype)}, ) + def check_cover( + self, + *, + sender_name: str | None = None, + email: str | None = None, + to: str | None = None, + to_name: str | None = None, + subject: str | None = None, + message: str | None = None, + ) -> m.OneTimeCoverRoom: + """Measure the room the cover sheet leaves for its message, before an order is made. Nothing is + stored. It works without an API key. + + Pass the cover fields typed so far, as ``create`` takes them, and leave out the rest. ``fits`` + says whether the message fits on the one cover page, and ``lines_left`` how many more lines + fit. When it runs over, ``fits_chars`` is how much of its start fits. ``create`` refuses a + cover that does not fit.""" + body = m.OneTimeCoverCheck( + sender_name=sender_name, email=email, to=to, to_name=to_name, subject=subject, message=message + ) + return self._h.request("POST", "/v1/one-time-sends/cover-checks", model=m.OneTimeCoverRoom, json=body) + def create( self, *, diff --git a/src/faxforagents/models.py b/src/faxforagents/models.py index 0129b99..c26d30d 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.20.6). Do not edit by hand. +GENERATED by scripts/gen_models.py from spec/openapi.yaml (API version 1.20.8). 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. """ @@ -242,6 +242,8 @@ class AgentActivityPage(_Response): class AgentArchived(_Response): + """What archiving an agent did: it is disabled for good and out of the list, and its keys are revoked.""" + id: str deleted: bool = Field(..., description="Always false: an agent has history and its row is kept.") archived: bool @@ -275,6 +277,8 @@ class AgentUpdate(_Request): class AlreadyAllowed(_Response): + """A number of a draft's allowed_destinations that one of its countries or prefixes already allows.""" + number: str countries: list[str] = Field(..., description="The listed countries whose route serves this number.") prefixes: list[str] = Field(..., description="The listed prefixes this number's route carries.") @@ -392,6 +396,8 @@ class ApprovalDecision(_Request): class ApprovalDocument(_Response): + """The document a send request binds, as it is now: its name, its pages and whether a send can use it.""" + id: str filename: str | None = Field(..., description="The file's name; null when the document row is gone.") page_count: int | None @@ -566,6 +572,8 @@ class BudgetPatch(_Request): class BudgetRemoved(_Response): + """What removing a budget did: deleted when it never charged a hold, archived when it has history.""" + id: str deleted: bool = Field(..., description="True when the budget never charged a hold and its row is gone.") archived: bool = Field(..., description="True when the budget has history: disabled and hidden, row kept.") @@ -590,7 +598,7 @@ class Capabilities(_Response): extraction: bool | None = None extraction_pricing: dict[str, Any] | None = Field(None, description="What POST /v1/extractions charges, in micro-units. page_micro is for every page read. escalated_page_micro is added for a page the stronger model reads again. max_pages is the most pages one extraction reads. Sandbox extractions are free.") limits: dict[str, int] - one_time: dict[str, Any] | None = None + one_time: dict[str, Any] | None = Field(None, description="One fax paid by card on this server. enabled: orders are taken here. published: the price card offers the product. routes: the routes sold one fax at a time, empty while not enabled. max_document_pages: the most document pages one order takes. Prices are in GET /v1/one-time-sends/config.") class ClassificationCreate(_Request): @@ -659,6 +667,8 @@ class DataRequest(_Response): class DataRequestList(_Response): + """The organization's export and deletion requests, each with where it stands.""" + items: list[DataRequest] @@ -668,39 +678,43 @@ class Deleted(_Response): class Delivery(_Response): + """One delivery of an event to a webhook destination: its attempts so far and the last answer.""" + id: str - webhook_id: str + webhook_id: str = Field(..., description="The destination the event is sent to.") webhook_url: str | None = Field(None, description="The destination's URL, kept after the destination is deleted.") - event_id: str - event_type: str - attempt: int - status: str - response_status: int | None - error: str | None - duration_ms: int | None - replay_of: str | None - schedule_s: list[int] - next_attempt_at: str | None + event_id: str = Field(..., description="The event sent. The webhook-id header carries the same id.") + event_type: str = Field(..., description="The event's type, such as fax.delivered.") + attempt: int = Field(..., description="How many attempts were made so far.") + status: str = Field(..., description="pending: an attempt is due or waits for its time. delivered: the destination answered 2xx. exhausted: every attempt of the schedule failed. failed: it stopped early, because the destination was deleted or paused, or its address was refused.") + response_status: int | None = Field(..., description="The HTTP status of the last attempt's answer. Null before an attempt, or when none came.") + error: str | None = Field(..., description="Why the last attempt failed, in words. Null once delivered.") + duration_ms: int | None = Field(..., description="How long the last attempt took, in milliseconds.") + replay_of: str | None = Field(..., description="The delivery this one sends again (POST /v1/webhook-deliveries/{delivery_id}/replay). Null for a first delivery.") + schedule_s: list[int] = Field(..., description="The wait before each attempt, in seconds after the one before. The first attempt waits 0 seconds.") + next_attempt_at: str | None = Field(..., description="When the next attempt is due. Null once the delivery has ended.") created_at: str - delivered_at: str | None + delivered_at: str | None = Field(..., description="When the destination answered 2xx. Null until then.") class DeliveryDetail(_Response): + """One delivery with the headers and the body that every attempt sends.""" + id: str - webhook_id: str + webhook_id: str = Field(..., description="The destination the event is sent to.") webhook_url: str | None = Field(None, description="The destination's URL, kept after the destination is deleted.") - event_id: str - event_type: str - attempt: int - status: str - response_status: int | None - error: str | None - duration_ms: int | None - replay_of: str | None - schedule_s: list[int] - next_attempt_at: str | None + event_id: str = Field(..., description="The event sent. The webhook-id header carries the same id.") + event_type: str = Field(..., description="The event's type, such as fax.delivered.") + attempt: int = Field(..., description="How many attempts were made so far.") + status: str = Field(..., description="pending: an attempt is due or waits for its time. delivered: the destination answered 2xx. exhausted: every attempt of the schedule failed. failed: it stopped early, because the destination was deleted or paused, or its address was refused.") + response_status: int | None = Field(..., description="The HTTP status of the last attempt's answer. Null before an attempt, or when none came.") + error: str | None = Field(..., description="Why the last attempt failed, in words. Null once delivered.") + duration_ms: int | None = Field(..., description="How long the last attempt took, in milliseconds.") + replay_of: str | None = Field(..., description="The delivery this one sends again (POST /v1/webhook-deliveries/{delivery_id}/replay). Null for a first delivery.") + schedule_s: list[int] = Field(..., description="The wait before each attempt, in seconds after the one before. The first attempt waits 0 seconds.") + next_attempt_at: str | None = Field(..., description="When the next attempt is due. Null once the delivery has ended.") created_at: str - delivered_at: str | None + delivered_at: str | None = Field(..., description="When the destination answered 2xx. Null until then.") webhook_deleted: bool = Field(..., description="True when the destination was deleted since.") request_headers: dict[str, str] = Field(..., description="The headers every attempt carries. webhook-id is the event id. webhook-timestamp and webhook-signature are made at each attempt and are not stored, so their values here say what they hold. The signing secret is never returned.") payload: dict[str, Any] = Field(..., description="The JSON body that is sent, the same at every attempt.") @@ -732,8 +746,8 @@ class Document(_Response): render_status: str render_reason: str | None validation: dict[str, Any] - converted_from: str | None = None - received: DocumentReceived | None = None + converted_from: str | None = Field(None, description="The name of the image this PDF was converted from, as the person gave it. filename is the PDF's own name. Null for a document that was not an image.") + received: DocumentReceived | None = Field(None, description="Set in the list (GET /v1/documents) on the file of a received fax, source inbound. It names the inbox item, the sender as the sending machine gave it, and the time. Null everywhere else.") upload_id: str | None created_at: str expires_at: str | None @@ -753,7 +767,7 @@ class DocumentCreate(_Request): class DocumentPage(_Response): items: list[Document] next_cursor: str | None = None - total: int | None = None + total: int | None = Field(None, description="How many documents the filters match in all, across every page.") class PagePreview(_Response): @@ -772,6 +786,8 @@ class DocumentPages(_Response): class DocumentUpdate(_Request): + """A new file name for a document.""" + filename: str = Field(..., description="The new file name. The stored file is a PDF: a name without .pdf gets it added.") @@ -811,7 +827,7 @@ class EffectivePolicies(_Response): class ErrorBody(_Response): code: str = Field(..., description="A stable code such as invalid_token, scope_missing, not_found, quote_expired, insufficient_balance, approval_required, rate_limited, live_provider_unavailable, one_time_unavailable.") message: str = Field(..., description="One sentence a person can act on.") - retryable: bool + retryable: bool = Field(..., description="True when the failure passes on its own: the same call, sent again unchanged after a short wait, is expected to work. False when the same call gets the same answer until the request or the resource changes.") correlation_id: str | None = Field(None, description="The X-Request-Id of the request. Quote it when you write to hello@faxforagents.com.") details: Any | None = Field(None, description="Code-specific fields, for example details.scope on scope_missing.") @@ -929,7 +945,7 @@ class OneTimeCard(_Response): class OneTimeJob(_Response): - """The order behind a fax job that a one-time send made: what was authorized, what was charged.""" + """The order behind a fax job that a one-time send made: what was held on the card, what was charged.""" order_id: str status: Literal["draft", "checkout_open", "authorized", "awaiting_confirmation", "released", "capturing", "canceling", "captured", "released_hold", "expired", "refused", "settle_failed"] | None = None @@ -971,6 +987,8 @@ class FaxJob(_Response): provider: str provider_ref: str | None client_reference: str | None + approval_id: str | None = Field(None, description="The approval request a person approved for this send. Null when another path authorized it: a delegated policy (policy_version_id), a test key no policy binds, or the payer's confirmation of a one-time order.") + policy_version_id: str | None = Field(None, description="The version of the delegated policy that allowed this send. A version never changes, so it shows the limits the send was allowed under. Null when no policy decided the send.") attempt_count: int created_at: str updated_at: str @@ -979,10 +997,7 @@ class FaxJob(_Response): evidence: dict[str, Any] | None = Field(None, description="The carrier's evidence once delivered or partial; null before.") one_time_order_id: str | None = Field(None, description="The one-time order this fax was paid by; null for a wallet fax.") one_time: OneTimeJob | None = None - # Returned by GET /v1/faxes/{fax_id}. - approval_id: str | None = Field(None, description="Returned by GET /v1/faxes/{fax_id}. Declared here until the public schema includes it.") - # Returned by GET /v1/faxes/{fax_id}. - policy_version_id: str | None = Field(None, description="Returned by GET /v1/faxes/{fax_id}. Declared here until the public schema includes it.") + route_paused: bool = Field(False, description="An operator has paused sends on this fax's route while the fax waits for a line (queued or between tries). It goes out when the route is resumed. Read when the fax is read, not stored.") class FaxJobPage(_Response): @@ -1018,14 +1033,14 @@ class InboxItem(_Response): status: str document_id: str | None received_at: str - amount_micro: int = 0 + amount_micro: int = Field(0, description="What the received pages were charged, in micro-USD. 0 on the sandbox.") note: str | None = None environment: Literal["live", "test"] = "live" number_id: str | None = None project_id: str | None = None partial_content: bool = False media_status: str = "stored" - file_deleted_at: str | None = None + file_deleted_at: str | None = Field(None, description="When the file of this fax was deleted. media_status is then deleted and there is no download. Null while the file is kept.") duration_secs: int | None = None provider: str = "" read_at: str | None = None @@ -1040,14 +1055,14 @@ class InboxItemDetail(_Response): status: str document_id: str | None received_at: str - amount_micro: int = 0 + amount_micro: int = Field(0, description="What the received pages were charged, in micro-USD. 0 on the sandbox.") note: str | None = None environment: Literal["live", "test"] = "live" number_id: str | None = None project_id: str | None = None partial_content: bool = False media_status: str = "stored" - file_deleted_at: str | None = None + file_deleted_at: str | None = Field(None, description="When the file of this fax was deleted. media_status is then deleted and there is no download. Null while the file is kept.") duration_secs: int | None = None provider: str = "" read_at: str | None = None @@ -1065,7 +1080,7 @@ class InboxItemSummary(_Response): status: str document_id: str | None received_at: str - amount_micro: int = 0 + amount_micro: int = Field(0, description="What the received pages were charged, in micro-USD. 0 on the sandbox.") note: str | None = None # Returned by POST /v1/sandbox/inbound-faxes. environment: Literal["live", "test"] | None = Field(None, description="Returned by POST /v1/sandbox/inbound-faxes.") @@ -1090,7 +1105,7 @@ class InboxItemSummary(_Response): class InboxPage(_Response): items: list[InboxItem] next_cursor: str | None = None - unread: int = 0 + unread: int = Field(0, description="The faxes nobody has opened yet in this environment, whatever the filters.") class InboxUpdate(_Request): @@ -1139,6 +1154,8 @@ class InvitationCreate(_Request): class InvitationLink(_Response): + """A new link for an open invitation, shown once, which replaces the old link.""" + id: str url: str = Field(..., description="The new invitation link. Shown once.") expires_at: str @@ -1314,7 +1331,7 @@ class OAuthRedirect(_Response): class OneTimeAttempts(_Response): - """The tries of an order's fax while it is still going out. A busy line or one that does not answer is dialed again (``max`` tries in all, about ``retry_delay_seconds`` apart). ``last_failure_code`` is why the last finished try did not get through, null when no try has ended.""" + """The tries of an order's fax while it is still going out. A busy line or one that does not answer is dialed again, up to ``max`` tries in all, about ``retry_delay_seconds`` apart. The field ``last_failure_code`` says why the last finished try did not get through. It is null when no try has ended.""" made: int max: int @@ -1332,7 +1349,7 @@ class OneTimeCheckout(_Response): class OneTimeQueue(_Response): - """The wait for a carrier line. ``queued`` is true when a fax sent now, or this order's waiting fax, is estimated to wait more than ten minutes for a line: the order is kept and sent in turn, never dropped. The minutes are an estimate from the number of faxes ahead and the carrier's line count.""" + """The wait for a carrier line. The field ``queued`` is true when a fax sent now, or this order's waiting fax, is estimated to wait over ten minutes for a line. The order is kept and sent in turn, never dropped. The minutes are an estimate from the number of faxes ahead and the carrier's line count.""" queued: bool jobs_ahead: int @@ -1349,7 +1366,7 @@ class OneTimeRoute(_Response): class OneTimeConfig(_Response): - """What the public send page and an agent read before an order: whether the product is open here, the card the order will be priced from (present only while open), the document limits and the policy the sender accepts. Prices are integer micro-USD; the dollar figure is the client's to format.""" + """What the public send page and an agent read before an order. It says whether the product is open here, and while it is open it gives the card the order will be priced from. It also gives the document limits and the policy the sender accepts. Prices are integer micro-USD, and the client formats the dollar figure.""" enabled: bool reason: str | None = None @@ -1404,7 +1421,7 @@ class OneTimePrice(_Response): class OneTimeOrder(_Response): - """One order of the one-time send. ``next`` is what the caller does now: ``checkout`` (open the payment), ``confirm`` (the payer clicks the link in the mail), ``wait`` (nothing to do; read again) or ``done``. Money is integer micro-USD. ``captured_micro`` is what the card was charged, written only once the payment provider confirmed it. ``fax`` is the fax job once the order was released, with the carrier's evidence once it has any.""" + """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.""" id: str status: Literal["draft", "checkout_open", "authorized", "awaiting_confirmation", "released", "capturing", "canceling", "captured", "released_hold", "expired", "refused", "settle_failed"] @@ -1421,7 +1438,7 @@ class OneTimeOrder(_Response): document_sha256: str document_id: str | None delete_after_send: bool = Field(False, description="The sender asked for the document and the transmitted copy to be deleted the moment the fax ends in delivered, partial or failed.") - document_deleted: bool = Field(False, description="True once no copy of the document is held: it was deleted after the send, by the retention period or by its owner, or the order ended before it was released and the uploaded file was removed. The order, the fax and the carrier evidence stay; they hold no document content.") + document_deleted: bool = Field(False, description="True once no copy of the document is held. It was deleted after the send, by the retention period or by its owner. Or the order ended before its release and the uploaded file was removed. The order, the fax and the carrier evidence stay, and they hold no document content.") document_expires_at: str | None = Field(None, description="When the retention period deletes the stored document. Null before the release and once the document is deleted.") price: OneTimePrice amount_micro: int @@ -1446,7 +1463,7 @@ class OneTimeOrder(_Response): status_url: str | None = Field(None, description="The order's page for the person who pays or confirms, with a fresh status token. Present on a read by a key or session of the order's organization while the order is not done.") warnings: list[dict[str, Any]] | None = None fax: dict[str, Any] | None = Field(None, description="The fax job (the FaxJob shape) once the order was released; null before.") - attempts: OneTimeAttempts | None = Field(None, description="The tries of the order's fax while it has not ended: how many were made, of how many, and why the last one did not get through. Null before the fax exists and once it ended.") + attempts: OneTimeAttempts | None = Field(None, description="The tries of the order's fax while it has not ended. It says how many were made, of how many, and why the last one did not get through. Null before the fax exists and once it ended.") preview: OneTimePreview | None = Field(None, description="Whether the order's pages can be looked at (the cover sheet and the document). Present on the read of one order; null in a list and in the create's answer.") created_at: str updated_at: str @@ -1460,6 +1477,26 @@ class OneTimeConfirmed(_Response): me: dict[str, Any] | None = None +class OneTimeCoverCheck(_Request): + """The fields a one-time order prints on its cover sheet, as a form holds them before the order exists. Every field may be empty. The limits of the create apply (cover.to_name 120 characters, cover.subject 200, cover.message 2,000).""" + + sender_name: str | None = Field(None, description="Printed in the From line.") + email: str | None = Field(None, description="Printed in the From line.") + to: str | None = Field(None, description="The destination, when one is typed.") + to_name: str | None = None + subject: str | None = None + message: str | None = None + + +class OneTimeCoverRoom(_Response): + """How the message sits on the one cover page, measured as the create measures it. Nothing is stored and no order is made.""" + + fits: bool = Field(..., description="The cover with this message fits on its one page.") + message_chars: int = Field(..., description="The length of the message as it will be printed.") + lines_left: int | None = Field(None, description="How many more lines of message text fit on the page. Null when the message is empty, since the first line also brings its heading, and when it does not fit.") + fits_chars: int | None = Field(None, description="When the message runs over: how much of its start fits with the same line breaks. Null when it fits, and when the page is full without any message.") + + class OneTimeFromQuote(_Request): quote_id: str sender_name: str = Field(..., description="Printed on the cover sheet. 2 to 120 characters.") @@ -1471,7 +1508,7 @@ class OneTimeFromQuote(_Request): class OneTimeInspection(_Response): - """What a file would be as a one-time order's document: its page count, and its first page as a small PNG (base64, null when this server cannot draw one). Nothing is stored and no order is made.""" + """What a file would be as a one-time order's document: its page count and its first page as a small PNG. The PNG is base64, or null when this server cannot draw one. Nothing is stored and no order is made.""" document_pages: int thumbnail_png_base64: str | None @@ -1496,7 +1533,7 @@ class OneTimeOrderCreated(_Response): document_sha256: str document_id: str | None delete_after_send: bool = Field(False, description="The sender asked for the document and the transmitted copy to be deleted the moment the fax ends in delivered, partial or failed.") - document_deleted: bool = Field(False, description="True once no copy of the document is held: it was deleted after the send, by the retention period or by its owner, or the order ended before it was released and the uploaded file was removed. The order, the fax and the carrier evidence stay; they hold no document content.") + document_deleted: bool = Field(False, description="True once no copy of the document is held. It was deleted after the send, by the retention period or by its owner. Or the order ended before its release and the uploaded file was removed. The order, the fax and the carrier evidence stay, and they hold no document content.") document_expires_at: str | None = Field(None, description="When the retention period deletes the stored document. Null before the release and once the document is deleted.") price: OneTimePrice amount_micro: int @@ -1521,7 +1558,7 @@ class OneTimeOrderCreated(_Response): status_url: str warnings: list[dict[str, Any]] | None = None fax: dict[str, Any] | None = Field(None, description="The fax job (the FaxJob shape) once the order was released; null before.") - attempts: OneTimeAttempts | None = Field(None, description="The tries of the order's fax while it has not ended: how many were made, of how many, and why the last one did not get through. Null before the fax exists and once it ended.") + attempts: OneTimeAttempts | None = Field(None, description="The tries of the order's fax while it has not ended. It says how many were made, of how many, and why the last one did not get through. Null before the fax exists and once it ended.") preview: OneTimePreview | None = Field(None, description="Whether the order's pages can be looked at (the cover sheet and the document). Present on the read of one order; null in a list and in the create's answer.") created_at: str updated_at: str @@ -1598,7 +1635,7 @@ class PasskeyRegisterVerify(_Request): class PaymentReceipt(_Response): url: str = Field(..., description="Stripe's hosted receipt for the payment. It says what was paid and when.") - pdf_url: str | None = Field(None, description="The same receipt as a PDF.") + pdf_url: str | None = Field(None, description="The same receipt as a PDF, where Stripe has one: the receipt of a paid invoice, which a top-up paid in Checkout has. Null for a charge without an invoice, such as an automatic top-up: its receipt is the page at url.") amount_micro: int amount_refunded_micro: int currency: str @@ -1615,22 +1652,33 @@ class PolicyCreate(_Request): enabled: bool = True +class PolicyUsage(_Response): + """What the deciding policy had counted before the send it was asked about, in UTC periods.""" + + day_jobs: int + day_amount_micro: int + month_jobs: int + month_amount_micro: int + + class PolicyEvaluation(_Response): - decision: str - rule: str | None - reason: str - policy_id: str | None - policy_version_id: str | None + """A dry run: the verdict for one planned send, the plan as the server read it, and what a send of it would need. Nothing is sent.""" + + decision: Literal["allow", "deny"] + rule: str | None = Field(..., description="The rule that failed first when a policy denied the plan. Null on allow, and when no policy binds the caller.") + reason: str = Field(..., description="Why, in one sentence.") + policy_id: str | None = Field(..., description="The policy that allowed the plan, or the first one that denied it. Null when none binds.") + policy_version_id: str | None = Field(..., description="The version of that policy that decided.") policy_name: str | None version: int | None - denials: list[dict[str, Any]] + managed: str | None = Field(None, description="connected_apps when the organization's auto-send setting decided, else null.") + denials: list[dict[str, Any]] = Field(..., description="Every policy that denied the plan, each with its policy_id, policy_version_id, decision, rule and reason. Empty on allow.") + usage: PolicyUsage | None = Field(None, description="On allow: the deciding policy's counters for the day and the month before this send.") plan: dict[str, Any] executed: bool = False subject: str | None = Field(None, description="The caller the plan was evaluated for: the calling principal, or the key, agent or connected app the request named.") under_policy: bool | None = Field(None, description="Whether any policy binds that caller. false with decision deny means no policy applies, not that a policy refused the plan.") approval_required: bool | None = Field(None, description="What a send of this plan by that caller would need: true when a person has to approve it. false when a policy allows it, and for a test send by a caller no policy binds.") - # Returned by POST /v1/policy-evaluations. - usage: dict[str, int] | None = Field(None, description="Returned by POST /v1/policy-evaluations when a bound policy has usage.") class PolicyEvaluationCreate(_Request): @@ -1648,13 +1696,17 @@ class PolicyList(_Response): class PolicyRuleCheck(_Response): + """Which of a draft's numbers its countries or prefixes already allow.""" + already_allowed: list[AlreadyAllowed] = Field(..., description="The listed numbers a listed country or prefix allows anyway. A destination passes a policy when it matches any of the three lists, so for these numbers the number list adds nothing.") class PolicyRuleCheckCreate(_Request): - allowed_destinations: list[str] | None = None - allowed_countries: list[str] | None = None - allowed_country_prefixes: list[str] | None = None + """The three destination lists of a draft policy, to check against each other.""" + + allowed_destinations: list[str] | None = Field(None, description="The draft's exact E.164 numbers.") + allowed_countries: list[str] | None = Field(None, description="The draft's ISO 3166-1 alpha-2 country codes, such as US or GB.") + allowed_country_prefixes: list[str] | None = Field(None, description="The draft's dialing prefixes, written as the rate card routes on them, such as +44.") class PolicyUpdate(_Request): @@ -1664,6 +1716,21 @@ class PolicyUpdate(_Request): enabled: bool | None = None +class PolicyVerdict(_Response): + """One evaluation of the delegated policies that bind a caller: the first policy that allows the plan, or every policy that denies it.""" + + decision: Literal["allow", "deny"] + rule: str | None = Field(..., description="The rule that failed first when a policy denied the plan. Null on allow, and when no policy binds the caller.") + reason: str = Field(..., description="Why, in one sentence.") + policy_id: str | None = Field(..., description="The policy that allowed the plan, or the first one that denied it. Null when none binds.") + policy_version_id: str | None = Field(..., description="The version of that policy that decided.") + policy_name: str | None + version: int | None + managed: str | None = Field(None, description="connected_apps when the organization's auto-send setting decided, else null.") + denials: list[dict[str, Any]] = Field(..., description="Every policy that denied the plan, each with its policy_id, policy_version_id, decision, rule and reason. Empty on allow.") + usage: PolicyUsage | None = Field(None, description="On allow: the deciding policy's counters for the day and the month before this send.") + + class PolicyVersion(_Response): id: str policy_id: str @@ -1760,22 +1827,20 @@ class Quote(_Response): currency: str price_version: str per_page_micro: int = 0 + pricing: Literal["per_page", "one_time"] = Field("per_page", description="per_page: priced from the rate card, paid from the wallet and sent with POST /v1/faxes. one_time: the quote of a one-time order, priced at the card's price for the order. Only the order sends it, and POST /v1/faxes refuses it with quote_pricing_mismatch.") route_label: str = "" cover: dict[str, Any] | None quality: str = "fine" sender_name: str | None = None delete_after_send: bool = False authorization_required: bool + policy_evaluation: PolicyVerdict | None = Field(None, description="The dry run of the delegated policies that bind the caller, made with the quote. Null when no policy binds the caller. The send evaluates the policies again, with their counters locked.") route_paused: bool = Field(False, description="An operator has paused sends on this quote's route. A fax sent now is accepted and stays queued until the route is resumed. Read when the quote is answered, not stored.") warnings: list[dict[str, Any]] expires_at: str expired: bool consumed_by_job_id: str | None created_at: str - # Returned by POST /v1/fax-quotes. - pricing: str | None = Field(None, description="Returned by POST /v1/fax-quotes. Declared here until the public schema includes it.") - # Returned by GET /v1/fax-quotes/{quote_id}. - policy_evaluation: dict[str, Any] | None = Field(None, description="Returned by GET /v1/fax-quotes/{quote_id}. Declared here until the public schema includes it.") class QuoteCreate(_Request): @@ -1826,7 +1891,7 @@ class Receipt(_Response): note: str generated_at: str seller: Seller | None = Field(None, description="The company that issues the receipt.") - one_time: OneTimeJob | None = Field(None, description="Set on the receipt of a fax that a one-time order paid for. It names the order, its status, the card and the amount the card was authorized for. captured_micro in it is the amount charged, written once the payment provider confirmed the capture. For a card order read the money here. Null for a fax paid from the wallet.") + one_time: OneTimeJob | None = Field(None, description="Set on the receipt of a fax that a one-time order paid for. It names the order, its status, the card and the amount held on the card. captured_micro in it is the amount charged, written once the payment provider confirmed the capture. For a card order read the money here. Null for a fax paid from the wallet.") class ReconcileResult(_Response): @@ -1998,17 +2063,21 @@ class SignedUrl(_Response): class StatementLine(_Response): + """One event on the wallet, signed the way the balance moved, with the balance after it.""" + id: str created_at: str - type: Literal["topup", "fax", "received_fax", "number", "extraction", "release", "refund", "dispute", "credit", "adjustment", "other"] + type: Literal["topup", "fax", "received_fax", "number", "extraction", "release", "refund", "dispute", "credit", "adjustment", "other"] = Field(..., description="What the line is, in one word. The type filter of the statement takes these values.") description: str = Field(..., description="What happened, in plain words. Never an account name.") amount_micro: int = Field(..., description="Signed the way the wallet moved: positive is money in.") balance_after_micro: int = Field(..., description="The available balance right after this line.") - ref_type: str | None - ref_id: str | None + ref_type: str | None = Field(..., description="What ref_id is. A hold or its release names what it was for: fax_job, extraction or number_order. Other lines name what they were booked against, such as stripe_payment_intent for a top-up or inbox_item for a received fax.") + ref_id: str | None = Field(..., description="The id of that object, such as fax_..., ext_..., nord_... or inb_..., or the payment's id at the card processor. Null when the line names none.") class StatementPage(_Response): + """A page of the wallet statement, newest line first.""" + items: list[StatementLine] next_cursor: str | None = None @@ -2403,6 +2472,8 @@ class faxforagents__auth__schemas__Me(_Response): "OneTimePrice", "OneTimeOrder", "OneTimeConfirmed", + "OneTimeCoverCheck", + "OneTimeCoverRoom", "OneTimeFromQuote", "OneTimeInspection", "OneTimeOrderCreated", @@ -2419,12 +2490,14 @@ class faxforagents__auth__schemas__Me(_Response): "PasskeyRegisterVerify", "PaymentReceipt", "PolicyCreate", + "PolicyUsage", "PolicyEvaluation", "PolicyEvaluationCreate", "PolicyList", "PolicyRuleCheck", "PolicyRuleCheckCreate", "PolicyUpdate", + "PolicyVerdict", "PolicyVersion", "PolicyVersionList", "PortOrder", diff --git a/tests/conftest.py b/tests/conftest.py index 9a9048d..0d276ee 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -150,3 +150,23 @@ def api_key_with_secret(**over: Any) -> dict[str, Any]: "secret": "ffa_test_" + "a" * 43, } return {**base, **over} + + +def topup_session(**over: Any) -> dict[str, Any]: + base = { + "id": "tus_" + "8" * 32, + "environment": "live", + "kind": "manual", + "amount_micro": 25_000_000, + "currency": "USD", + "status": "open", + "url": "https://checkout.example.test/c/pay_1", + "stripe_session_id": "cs_test_1", + "stripe_payment_intent_id": None, + "auto_topup_id": None, + "error": None, + "created_at": "2026-11-15T09:00:00Z", + "expires_at": "2026-11-16T09:00:00Z", + "completed_at": None, + } + return {**base, **over} diff --git a/tests/test_async.py b/tests/test_async.py index 7cdff42..87df24e 100644 --- a/tests/test_async.py +++ b/tests/test_async.py @@ -6,7 +6,7 @@ import respx from faxforagents import AsyncClient -from tests.conftest import api_key_with_secret, fax_job, quote +from tests.conftest import api_key_with_secret, fax_job, quote, topup_session async def test_async_send_and_wait(aclient: AsyncClient, api: respx.MockRouter) -> None: @@ -220,3 +220,40 @@ async def test_async_filters_and_one_time_reads(aclient: AsyncClient, api: respx ) assert await aclient.one_time_sends.get_page("oto_1", 2) == b"\x89PNG" assert "x-ffa-order-token" not in page.calls.last.request.headers + + +async def test_async_topup_cancel_statement_type_and_cover_check( + aclient: AsyncClient, api: respx.MockRouter +) -> None: + import json + + tid = topup_session()["id"] + cancel = api.post(f"/v1/topup-sessions/{tid}/cancel").respond( + 200, json=topup_session(kind="setup", status="canceled") + ) + assert (await aclient.billing.cancel_topup_session(tid)).status == "canceled" + assert len(cancel.calls.last.request.headers["idempotency-key"]) == 36 + line = { + "id": "led_1", + "created_at": "2026-11-15T09:00:00Z", + "type": "adjustment", + "description": "Refund of the failed fax, as agreed", + "amount_micro": 39_000, + "balance_after_micro": 100_039_000, + "ref_type": "billing_adjustment", + "ref_id": "adj_1", + } + route = api.get("/v1/statement").respond(200, json={"items": [line], "next_cursor": None}) + ids = [item.id async for item in aclient.billing.iter_statement(type="adjustment")] + assert ids == ["led_1"] and dict(route.calls.last.request.url.params) == {"type": "adjustment"} + assert (await aclient.billing.statement(kind="adjustment")).items[0].type == "adjustment" + assert dict(route.calls.last.request.url.params) == {"kind": "adjustment"} + csv = api.get("/v1/statement.csv").respond(200, content=b"date\n", headers={"content-type": "text/csv"}) + assert await aclient.billing.statement_csv(type="adjustment") == "date\n" + assert dict(csv.calls.last.request.url.params) == {"type": "adjustment"} + cover = api.post("/v1/one-time-sends/cover-checks").respond( + 200, json={"fits": True, "message_chars": 5, "lines_left": 30, "fits_chars": None} + ) + room = await aclient.one_time_sends.check_cover(subject="Form", message="Hello") + assert room.fits is True and room.lines_left == 30 + assert json.loads(cover.calls.last.request.content) == {"subject": "Form", "message": "Hello"} diff --git a/tests/test_client.py b/tests/test_client.py index f561468..b58cf38 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -21,7 +21,7 @@ ScopeError, ServerError, ) -from tests.conftest import BASE, KEY, api_key_with_secret, document, error, fax_job, quote +from tests.conftest import BASE, KEY, api_key_with_secret, document, error, fax_job, quote, topup_session def test_bearer_header_and_user_agent(client: Client, api: respx.MockRouter) -> None: @@ -957,3 +957,116 @@ def test_used_approvals_and_closing_a_help_request(client: Client, api: respx.Mo assert json.loads(reject.calls.last.request.content) == {} client.approvals.reject("apr_1", reason="wrong number") assert json.loads(reject.calls.last.request.content) == {"reason": "wrong number"} + + +def test_cancel_an_open_topup(client: Client, api: respx.MockRouter) -> None: + """API 1.20.8: the hosted Checkout of an open top-up closes, and the session reads canceled.""" + tid = topup_session()["id"] + route = api.post(f"/v1/topup-sessions/{tid}/cancel") + route.side_effect = [ + httpx.Response(200, json=topup_session(status="canceled")), + httpx.Response( + 409, + json=error( + "conflict", "this top-up has no open Checkout to cancel", details={"status": "completed"} + ), + ), + ] + canceled = client.billing.cancel_topup_session(tid, idempotency_key="k-cancel") + assert canceled.status == "canceled" and canceled.id == tid + sent = route.calls.last.request + assert sent.headers["idempotency-key"] == "k-cancel" and sent.content == b"" + with pytest.raises(ConflictError) as exc: + client.billing.cancel_topup_session(tid) + assert exc.value.code == "conflict" and exc.value.details == {"status": "completed"} + assert len(route.calls) == 2 + + +def test_the_statement_filters_by_type_and_kind_still_works(client: Client, api: respx.MockRouter) -> None: + """API 1.20.8: type is the filter, kind is its older name, and two different types answer 422.""" + hold = statement_line(id="led_3", type="release", ref_type="extraction", ref_id="ext_1") + route = api.get("/v1/statement") + route.side_effect = [ + httpx.Response(200, json={"items": [statement_line(type="refund")], "next_cursor": None}), + httpx.Response(200, json={"items": [hold], "next_cursor": None}), + httpx.Response(200, json={"items": [], "next_cursor": None}), + httpx.Response( + 422, + json=error( + "invalid_request", + "type and kind are one filter: send one of them, or the same type in both", + details={"fields": ["type", "kind"]}, + ), + ), + ] + assert client.billing.statement(type="refund").items[0].type == "refund" + assert dict(route.calls[0].request.url.params) == {"type": "refund"} + released = list(client.billing.iter_statement(type="release", limit=5)) + assert released[0].ref_type == "extraction" and released[0].ref_id == "ext_1" + assert dict(route.calls[1].request.url.params) == {"type": "release", "limit": "5"} + assert client.billing.statement(kind="fax").items == [] + assert dict(route.calls[2].request.url.params) == {"kind": "fax"} + with pytest.raises(InvalidRequestError) as exc: + client.billing.statement(type="fax", kind="topup") + assert exc.value.details == {"fields": ["type", "kind"]} + assert dict(route.calls[3].request.url.params) == {"type": "fax", "kind": "topup"} + csv = api.get("/v1/statement.csv").respond( + 200, content=b"date,type\n", headers={"content-type": "text/csv"} + ) + assert client.billing.statement_csv(type="refund", from_="2026-11-01") == "date,type\n" + assert dict(csv.calls.last.request.url.params) == {"type": "refund", "from": "2026-11-01"} + + +def test_an_expired_key_is_not_rotated(client: Client, api: respx.MockRouter) -> None: + """API 1.20.8: the replacement would keep the past expiry, so the rotation answers 409.""" + details = {"reason": "key_expired", "expires_at": "2026-11-01T00:00:00Z"} + route = api.post("/v1/api-keys/key_1/rotate").respond( + 409, json=error("conflict", "this key expired, so it cannot be rotated", details=details) + ) + with pytest.raises(ConflictError) as exc: + client.identity.rotate_api_key("key_1") + assert exc.value.status == 409 and exc.value.details == details + assert len(route.calls) == 1 + + +def test_the_quote_and_the_job_name_their_policy(client: Client, api: respx.MockRouter) -> None: + """API 1.20.8: a quote carries its pricing and the policy dry run, a job what authorized it.""" + usage = {"day_jobs": 3, "day_amount_micro": 117_000, "month_jobs": 40, "month_amount_micro": 1_560_000} + verdict = {**evaluation(version=2), "managed": None, "usage": usage} + verdict.pop("plan") + route = api.post("/v1/fax-quotes") + route.side_effect = [ + httpx.Response(201, json=quote(pricing="one_time", policy_evaluation=verdict)), + httpx.Response(201, json=quote()), + ] + priced = client.quotes.create(document_id="doc_" + "2" * 32, to="+15550000001") + assert priced.pricing == "one_time" and priced.policy_evaluation is not None + assert priced.policy_evaluation.decision == "allow" and priced.policy_evaluation.version == 2 + assert priced.policy_evaluation.usage is not None and priced.policy_evaluation.usage.day_jobs == 3 + older = client.quotes.create(document_id="doc_" + "2" * 32, to="+15550000001") + assert older.pricing == "per_page" and older.policy_evaluation is None + job_id = fax_job()["id"] + get = api.get(f"/v1/faxes/{job_id}") + get.side_effect = [ + httpx.Response(200, json=fax_job(approval_id="apr_1", policy_version_id=None, route_paused=True)), + httpx.Response(200, json=fax_job()), + ] + job = client.faxes.get(job_id) + assert job.approval_id == "apr_1" and job.policy_version_id is None and job.route_paused is True + plain = client.faxes.get(job_id) + assert plain.approval_id is None and plain.route_paused is False + api.post("/v1/policy-evaluations").respond(200, json=evaluation(managed="connected_apps", usage=usage)) + result = client.policies.evaluate(to="+15550000001", document_id="doc_" + "2" * 32) + assert result.managed == "connected_apps" and result.usage is not None + assert result.usage.month_amount_micro == 1_560_000 + + +def test_an_automatic_topup_receipt_has_no_pdf(client: Client, api: respx.MockRouter) -> None: + """API 1.20.8: a charge without an invoice has a receipt page and no PDF.""" + tid = topup_session(kind="auto")["id"] + api.get(f"/v1/topup-sessions/{tid}/receipt").respond( + 200, + json=receipt(pdf_url=None, topup_session_id=tid, url="https://pay.example.test/receipts/payment/1"), + ) + found = client.billing.get_topup_receipt(tid) + assert found.pdf_url is None and found.url.endswith("/receipts/payment/1") diff --git a/tests/test_one_time.py b/tests/test_one_time.py index 62ca2f5..c2d4ccd 100644 --- a/tests/test_one_time.py +++ b/tests/test_one_time.py @@ -10,7 +10,14 @@ import pytest import respx -from faxforagents import AsyncClient, Client, InvalidRequestError, NotFoundError, PaymentRequiredError +from faxforagents import ( + AsyncClient, + Client, + InvalidRequestError, + NotFoundError, + PaymentRequiredError, + ServerError, +) from tests.conftest import BASE, KEY, error CASES: dict[str, Any] = { @@ -419,3 +426,39 @@ def test_a_page_of_the_order_as_png(keyless: Client, api: respx.MockRouter) -> N api.get(f"/v1/one-time-sends/{ORDER}/pages/9").respond(404, json=error("not_found", "cannot be shown")) with pytest.raises(NotFoundError): keyless.one_time_sends.get_page(ORDER, 9, order_token=TOKEN) + + +def test_cover_check_measures_the_message_with_no_key(keyless: Client, api: respx.MockRouter) -> None: + """API 1.20.8: the room on the cover sheet while the message is typed. Nothing is stored.""" + route = api.post("/v1/one-time-sends/cover-checks") + route.side_effect = [ + httpx.Response(200, json={"fits": True, "message_chars": 11, "lines_left": 24, "fits_chars": None}), + httpx.Response( + 200, json={"fits": False, "message_chars": 2400, "lines_left": None, "fits_chars": 1980} + ), + httpx.Response(200, json={"fits": True, "message_chars": 0, "lines_left": None, "fits_chars": None}), + ] + room = keyless.one_time_sends.check_cover( + sender_name="Dana Example", to="+12025550123", message="Hello there" + ) + assert room.fits is True and room.lines_left == 24 and room.fits_chars is None + sent = route.calls[0].request + assert json.loads(sent.content) == { + "sender_name": "Dana Example", + "to": "+12025550123", + "message": "Hello there", + } + assert "authorization" not in sent.headers + over = keyless.one_time_sends.check_cover(message="x" * 2400) + assert over.fits is False and over.lines_left is None and over.fits_chars == 1980 + assert keyless.one_time_sends.check_cover().message_chars == 0 + assert json.loads(route.calls[2].request.content) == {} + + +def test_cover_check_is_refused_while_one_time_sends_are_off(keyless: Client, api: respx.MockRouter) -> None: + api.post("/v1/one-time-sends/cover-checks").respond( + 503, json=error("one_time_unavailable", "one-time sends are switched off on this server") + ) + with pytest.raises(ServerError) as exc: + keyless.one_time_sends.check_cover(message="hi") + assert exc.value.status == 503 and exc.value.code == "one_time_unavailable" diff --git a/tests/test_surface.py b/tests/test_surface.py index bb4095e..214699e 100644 --- a/tests/test_surface.py +++ b/tests/test_surface.py @@ -112,6 +112,7 @@ def test_every_operation_has_a_method() -> None: "create_topup_session": "billing.create_topup_session", "list_topup_sessions": "billing.list_topup_sessions", "get_topup_session": "billing.get_topup_session", + "cancel_topup_session": "billing.cancel_topup_session", "get_topup_receipt": "billing.get_topup_receipt", "list_auto_topups": "billing.list_auto_topups", "create_auto_topup": "billing.create_auto_topup", @@ -214,6 +215,7 @@ def test_every_operation_has_a_method() -> None: "revoke_oauth_grant": "oauth.revoke_grant", "get_one_time_config": "one_time_sends.config", "preview_one_time_document": "one_time_sends.preview", + "create_one_time_cover_check": "one_time_sends.check_cover", "create_one_time_order": "one_time_sends.create", "create_one_time_order_from_quote": "one_time_sends.create_from_quote", "list_one_time_orders": "one_time_sends.list", From 382bed4f30cba63b34760dcda91639f92a41f811 Mon Sep 17 00:00:00 2001 From: bensynapse <118375461+bensynapse@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:29:55 +0200 Subject: [PATCH 2/3] Say the card is held in the checkout docstring one_time_sends.checkout said the card is authorized at checkout. API 1.20.8 says it is held and charged only for the pages that arrive. --- src/faxforagents/async_client.py | 4 ++-- src/faxforagents/client.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/faxforagents/async_client.py b/src/faxforagents/async_client.py index 8cafd5a..70a7b6e 100644 --- a/src/faxforagents/async_client.py +++ b/src/faxforagents/async_client.py @@ -1778,8 +1778,8 @@ async def checkout( ) -> m.OneTimeCheckout: """Open the hosted card payment and return its ``checkout_url``. Scope with a key: fax:send. - The card is authorized on that page and charged only when the carrier confirms delivery. A - second call answers the same page while it can still be paid. + The card is held on that page and charged only for the pages the carrier confirms. The rest of + the hold is released. A second call answers the same page while it can still be paid. An order whose ``aup_accepted`` is false needs ``accept_aup=True`` once: the person who pays accepts the acceptable use policy and the terms. The server takes it with ``order_token`` or a diff --git a/src/faxforagents/client.py b/src/faxforagents/client.py index b351bd5..be226fd 100644 --- a/src/faxforagents/client.py +++ b/src/faxforagents/client.py @@ -1787,8 +1787,8 @@ def checkout( ) -> m.OneTimeCheckout: """Open the hosted card payment and return its ``checkout_url``. Scope with a key: fax:send. - The card is authorized on that page and charged only when the carrier confirms delivery. A - second call answers the same page while it can still be paid. + The card is held on that page and charged only for the pages the carrier confirms. The rest of + the hold is released. A second call answers the same page while it can still be paid. An order whose ``aup_accepted`` is false needs ``accept_aup=True`` once: the person who pays accepts the acceptable use policy and the terms. The server takes it with ``order_token`` or a From ccf9c25382900efa75910f75e783a9eaddaa00c2 Mon Sep 17 00:00:00 2001 From: bensynapse <118375461+bensynapse@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:16:35 +0200 Subject: [PATCH 3/3] Take the spec at API 1.20.9 and state the payment rule The saved spec follows the public document at API 1.20.9, which changed only wording. The checkout docstring says a failed fax costs nothing. A fax that stops part way costs the price of the pages the carrier confirms. The README and the CHANGELOG say the same. The version stays 0.8.0. --- CHANGELOG.md | 3 ++- README.md | 6 +++--- spec/openapi.yaml | 18 +++++++++--------- src/faxforagents/async_client.py | 5 +++-- src/faxforagents/client.py | 5 +++-- src/faxforagents/models.py | 2 +- 6 files changed, 21 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 928d26c..cb74e4f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## 0.8.0 (2026-11-15) -Follows API 1.20.8. The saved spec has 163 operations and the models are regenerated from it. +Follows API 1.20.9. The saved spec has 163 operations and the models are regenerated from it. Every operation has a method on both clients. New: `billing.cancel_topup_session(topup_session_id)` closes the hosted Checkout of an open top-up and returns it with status `canceled`. @@ -23,6 +23,7 @@ Changed: five fields that the saved spec declared itself now follow the public d `PaymentReceipt.pdf_url` is `None` for an automatic top-up, which has no invoice. Its `url` still opens the receipt. A statement line of a hold or a release names what it was for in `ref_type`: `fax_job`, `extraction` or `number_order`. The card of a one-time order is held, not authorized, in the docstrings and the model descriptions. +`one_time_sends.checkout` states the payment rule of API 1.20.9. A failed fax costs nothing, and a fax that stops part way costs the price of the pages the carrier confirms. New models `OneTimeCoverCheck`, `OneTimeCoverRoom`, `PolicyVerdict` and `PolicyUsage`. Other model names, fields and optionality are kept. ## 0.7.0 (2026-11-15) diff --git a/README.md b/README.md index b5bb715..6ad319a 100644 --- a/README.md +++ b/README.md @@ -219,8 +219,8 @@ with Client(keyless=True) as ffa: # no API key: only one_time_se ``` `order.next` names the step that is waiting: `checkout`, `confirm`, `wait` or `done`. `wait` polls until -`done`, or until the step you pass as `until`. The card is held at checkout and charged only for the -pages the carrier confirms. +`done`, or until the step you pass as `until`. The card is held at checkout. A failed fax costs nothing, +and a fax that stops part way costs the price of the pages the carrier confirms. The status token goes in the `X-FFA-Order-Token` header. It reads the order, opens its checkout, mails the confirmation again and downloads the receipt. A client with a live key of the order's organization @@ -312,7 +312,7 @@ ruff check src tests && mypy src sh scripts/truthcheck.sh ``` -`spec/openapi.yaml` follows the public document at API version 1.20.8 and keeps the schemas of the earlier live documents. +`spec/openapi.yaml` follows the public document at API version 1.20.9 and keeps the schemas of the earlier live documents. The two validation error schemas are the exception. 0.5.0 removed them because the server never sent that shape. 0.6.0 removed two cost fields of an extraction, because the server stopped sending them. 0.8.0 replaced five fields it had declared itself with the public ones, such as `Quote.policy_evaluation`. diff --git a/spec/openapi.yaml b/spec/openapi.yaml index f069078..1bd592b 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.20.8. +# Fax for Agents API, refreshed from the public document of https://github.com/faxforagents/openapi at API 1.20.9. # All earlier schemas are kept. Existing SDK routes, model names and serializer additions are retained. openapi: 3.1.0 info: @@ -26,7 +26,7 @@ info: x-logo: url: https://faxforagents.com/brand/logo-512.png altText: Fax for Agents - version: 1.20.8 + version: 1.20.9 servers: - url: https://api.faxforagents.com description: Production (live and test keys) @@ -8541,11 +8541,11 @@ paths: tags: - one-time-sends summary: Open the card payment of a one-time order - description: 'Answers the hosted payment page of the order. The card is held there, not charged. It is charged - only for the pages the carrier confirms, and the rest of the hold is released. A second call answers the - same page while it can still be paid, and a new one after it expired. An order whose aup_accepted is false - needs {"accept_aup": true} in the body once, from the status token or a session: the person who pays accepts - the policy, never a key.' + description: 'Answers the hosted payment page of the order. The card is held there, not charged. A failed + fax costs nothing. A fax that stops part way is charged the price of the pages the carrier confirms, and + the rest of the hold is released. A second call answers the same page while it can still be paid, and a + new one after it expired. An order whose aup_accepted is false needs {"accept_aup": true} in the body once, + from the status token or a session: the person who pays accepts the policy, never a key.' operationId: create_one_time_checkout parameters: - name: one_time_order_id @@ -8635,8 +8635,8 @@ paths: mutating: true idempotency_key: true agent_key_allowed: true - hint: The card is held on the hosted page and charged only for the pages the carrier confirms. A person - pays, never the agent. + hint: The card is held on the hosted page. A failed fax costs nothing, and a fax that stops part way costs + the price of the pages the carrier confirms. A person pays, never the agent. order_token: true /v1/one-time-sends/{one_time_order_id}/confirm: post: diff --git a/src/faxforagents/async_client.py b/src/faxforagents/async_client.py index 70a7b6e..71f84b9 100644 --- a/src/faxforagents/async_client.py +++ b/src/faxforagents/async_client.py @@ -1778,8 +1778,9 @@ async def checkout( ) -> m.OneTimeCheckout: """Open the hosted card payment and return its ``checkout_url``. Scope with a key: fax:send. - The card is held on that page and charged only for the pages the carrier confirms. The rest of - the hold is released. A second call answers the same page while it can still be paid. + The card is held on that page, not charged. A failed fax costs nothing. A fax that stops part + way is charged the price of the pages the carrier confirms, and the rest of the hold is released. + A second call answers the same page while it can still be paid. An order whose ``aup_accepted`` is false needs ``accept_aup=True`` once: the person who pays accepts the acceptable use policy and the terms. The server takes it with ``order_token`` or a diff --git a/src/faxforagents/client.py b/src/faxforagents/client.py index be226fd..4d8f09f 100644 --- a/src/faxforagents/client.py +++ b/src/faxforagents/client.py @@ -1787,8 +1787,9 @@ def checkout( ) -> m.OneTimeCheckout: """Open the hosted card payment and return its ``checkout_url``. Scope with a key: fax:send. - The card is held on that page and charged only for the pages the carrier confirms. The rest of - the hold is released. A second call answers the same page while it can still be paid. + The card is held on that page, not charged. A failed fax costs nothing. A fax that stops part + way is charged the price of the pages the carrier confirms, and the rest of the hold is released. + A second call answers the same page while it can still be paid. An order whose ``aup_accepted`` is false needs ``accept_aup=True`` once: the person who pays accepts the acceptable use policy and the terms. The server takes it with ``order_token`` or a diff --git a/src/faxforagents/models.py b/src/faxforagents/models.py index c26d30d..d24150a 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.20.8). Do not edit by hand. +GENERATED by scripts/gen_models.py from spec/openapi.yaml (API version 1.20.9). 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. """