From 2a322160c2942965e5d86393b9cacfb3f89c0f51 Mon Sep 17 00:00:00 2001 From: bensynapse <118375461+bensynapse@users.noreply.github.com> Date: Mon, 16 Nov 2026 21:31:51 +0200 Subject: [PATCH 1/2] Version 0.11.0: the spec at API 1.21.0 and the records export The saved spec follows the public document at API 1.21.0, merged three ways from 1.20.11. All 16 changes applied with no conflict. SubscriptionList.plan stays optional as a local edit. The models are regenerated. WorkspacePlan is new, and there are 175 in all. organizations.fax_history_csv and organizations.audit_csv return the records export as CSV text. faxes.list and faxes.iter take created_after and created_before. Docstrings name live_amount_micro, the workspace plan and the refund statuses of a one-time order. The shared fixtures gain the new serializer fields, and eight new tests cover the new surface. The README and the CHANGELOG say what changed. --- CHANGELOG.md | 29 +++ README.md | 18 +- pyproject.toml | 2 +- spec/openapi.yaml | 335 ++++++++++++++++++++++++++++++- src/faxforagents/__init__.py | 2 +- src/faxforagents/async_client.py | 68 ++++++- src/faxforagents/client.py | 68 ++++++- src/faxforagents/models.py | 51 +++-- tests/fixtures/README.md | 5 + tests/fixtures/one-time.json | 6 + tests/fixtures/responses.json | 3 + tests/test_async.py | 33 ++- tests/test_client.py | 130 ++++++++++++ tests/test_one_time.py | 21 ++ tests/test_surface.py | 2 + 15 files changed, 735 insertions(+), 38 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 22f9953..fc0cee9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,34 @@ # Changelog +## 0.11.0 (2026-11-16) + +Follows API 1.21.0. The saved spec has 165 operations and 175 schemas, and the models are regenerated from it. +Every operation has a method on both clients. Nothing is removed. + +New methods: `organizations.fax_history_csv` and `organizations.audit_csv`, the records export of the Agent workspace plan. +Each returns CSV text for a range of UTC days, `from_` and `to`, both included, as `billing.statement_csv` does. +The fax history needs `fax:read` and `inbox:read`. The audit trail needs `org:admin` and refuses an agent's key. +Without the plan, or more than 30 days after it ended, both raise `ScopeError` with the code `workspace_required`. + +New parameters: `faxes.list` and `faxes.iter` take `created_after` and `created_before`, ISO 8601 times. +The start is included and the end is left out. A start after the end raises `InvalidRequestError`. +Left out, no query parameter is sent, so the request is the same as in 0.10.0. + +New fields: + +- `Quote.live_amount_micro` is what the same fax costs with a live key. A test quote is free, so this is its live price. + It is `None` when the rate card changed since the quote, and from an older server. +- `SubscriptionList.plan` is the new model `WorkspacePlan`: the request limits, the included number, the keep times and whether the export is open. + The public document requires it. The saved spec leaves it optional, so an older payload still parses. +- `Number.included_with_workspace` is true for the number whose monthly charge the Agent workspace pays. It defaults to `False`. +- `OneTimeOrder.refund_pending_micro` and `OneTimeOrderCreated.refund_pending_micro` hold a refund the payment provider has not confirmed yet. + They default to 0. + +One-time orders have three new statuses, set by a person at Fax for Agents: `refunding`, `refunded` and `canceled`. +`refunded` and `canceled` read `next` `done`, so `one_time_sends.wait` returns on them. `refunding` reads `next` `wait`. + +Descriptions say test where they said sandbox. `Capabilities.limits` names the request limit, 3000 a minute with the plan and 600 without. + ## 0.10.0 (2026-11-16) Follows API 1.20.11, as 0.9.1 did. The saved spec has 163 operations and the models are regenerated from it. diff --git a/README.md b/README.md index ad872d9..60d74ed 100644 --- a/README.md +++ b/README.md @@ -88,6 +88,12 @@ The same in async form, with `AsyncClient` and `await` on every call. 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. +- `faxes.list(created_after=..., created_before=...)` keeps the jobs created in a time range, given in + ISO 8601. The start is included and the end is left out. +- `organizations.fax_history_csv()` and `organizations.audit_csv()` return the records export of the + Agent workspace plan as CSV text, for a range of UTC days. Without the plan they raise `ScopeError` + with the code `workspace_required`. +- A test quote is free. Its `live_amount_micro` says what the same fax costs with a live key. - `one_time_sends.preview(file=...)` counts the pages of a document before any order exists, with no key. `one_time_sends.check_cover(message=...)` says whether a cover message fits on its page. - `billing.get_topup_session(id, check_checkout=True)` asks Stripe about the hosted Checkout of an open @@ -129,7 +135,7 @@ each call needs. | `ffa.inbox` | `list`, `iter`, `get`, `update`, `delete`, `get_download`, `download` | | `ffa.numbers` | `coverage`, `inventory`, `create_order`, `list_orders`, `get_order`, `dismiss_order`, `list`, `get`, `update`, `release`, `check_portability`, `list_port_orders`, `create_port_order`, `get_port_order`, `create_port_out_request`, `verify_sender` | | `ffa.extractions` | `create`, `list`, `iter`, `get`, `correct`, `classify`, `list_classifications`, `iter_classifications`, `get_classification`, `summarize`, `list_summaries`, `iter_summaries`, `get_summary`, `list_schemas`, `create_schema`, `get_schema` | -| `ffa.organizations` | `list`, `current`, `update_current`, `request_data_export`, `request_data_deletion`, `list_data_requests`, `withdraw_data_deletion`, `download_export_archive` | +| `ffa.organizations` | `list`, `current`, `update_current`, `request_data_export`, `request_data_deletion`, `list_data_requests`, `withdraw_data_deletion`, `download_export_archive`, `fax_history_csv`, `audit_csv` | | `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`, `check_cover`, `create`, `create_from_quote`, `list`, `iter`, `get`, `get_page`, `wait`, `checkout`, `read_by_token`, `confirm`, `resend_confirmation`, `get_receipt_pdf` | @@ -225,6 +231,11 @@ with Client(keyless=True) as ffa: # no API key: only one_time_se `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. +A person at Fax for Agents can refund an order or release the hold on its card. The order then reads +`refunding` until the refund is confirmed and `refunded` after. It reads `canceled` when the hold was +released and nothing was charged. `refund_pending_micro` is a refund the payment provider has not +confirmed yet. + 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 needs no token. A test key is refused: an order is always live. @@ -300,7 +311,7 @@ Every command takes `--json` for the raw answer. ## Prices Price card launch-v3 is effective from 2026-11-12. $0.039 per page sent, $0.019 per page received. -$2 per number per month, $19 per month for the Agent workspace. Sandbox pages cost 0. +$2 per number per month, $19 per month for the Agent workspace. With a test key, every page costs 0. `ffa.platform.capabilities()` returns the card in force. One fax by card has its own price: `ffa.one_time_sends.config()` returns it. @@ -315,13 +326,14 @@ ruff check src tests && mypy src sh scripts/truthcheck.sh ``` -`spec/openapi.yaml` follows the public document at API version 1.20.11. It has the same 163 operations and no schema that document lacks. +`spec/openapi.yaml` follows the public document at API version 1.21.0. It has the same 165 operations and no schema that document lacks. It also declares fields a route returns beyond the public schemas, in `InboxItemSummary` and `ExtractionPage`. 0.5.0 removed the two validation error schemas, because the server never sent that shape. 0.6.0 removed two cost fields of an extraction, because the server stopped sending them. 0.8.0 replaced five fields it had declared itself with the public ones, such as `Quote.policy_evaluation`. 0.9.0 leaves `Delivery.webhook_deleted` optional, where the public document requires it. 0.10.0 removed the 70 schemas of earlier server documents that no operation reaches, such as those of the admin console. +0.11.0 leaves `SubscriptionList.plan` optional, where the public document requires it. `scripts/gen_models.py` writes a model only for a schema an operation reaches, through its paths, a shared response or a field. If a refresh brings in a schema that no operation reaches, it gets no model and `tests/test_removed_models.py` fails. To refresh it, merge the public document while preserving existing declarations, then run `uv run python scripts/gen_models.py`. diff --git a/pyproject.toml b/pyproject.toml index b761a02..803aa1f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "faxforagents" -version = "0.10.0" +version = "0.11.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 cb88753..baf1ec6 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.11. +# Fax for Agents API, refreshed from the public document of https://github.com/faxforagents/openapi at API 1.21.0. # An operation reaches every schema here. 0.10.0 dropped 70 earlier schemas that no operation reached. # Existing SDK routes, model names and serializer additions are retained. openapi: 3.1.0 @@ -27,7 +27,7 @@ info: x-logo: url: https://faxforagents.com/brand/logo-512.png altText: Fax for Agents - version: 1.20.11 + version: 1.21.0 servers: - url: https://api.faxforagents.com description: Production (live and test keys) @@ -1298,6 +1298,10 @@ paths: tags: - faxes summary: List fax jobs, newest first + description: 'Fax jobs of the credential''s organization and environment, newest first, in pages of `limit`. + Every filter combines with the others and with `cursor`: pass the same filters with the `next_cursor` of + the page before. `created_after` and `created_before` narrow the list to the jobs created in a time range, + the start included and the end left out. A range whose start is after its end is refused with 422 invalid_request.' operationId: list_faxes parameters: - name: state @@ -1338,6 +1342,36 @@ paths: description: 'Find faxes by destination or by id. Text that starts with fax_ is the beginning of a job id. Anything else is read as a fax number in any spelling: its digits are looked for anywhere in the destination. Combines with state.' + - name: created_after + in: query + required: false + schema: + anyOf: + - type: string + format: date-time + - type: 'null' + description: Only jobs created at or after this time. ISO 8601, for example 2026-11-16T00:00:00Z. A time + without an offset is read as UTC. Combines with created_before, the other filters and cursor. + examples: + - '2026-11-16T00:00:00Z' + title: Created After + description: Only jobs created at or after this time. ISO 8601, for example 2026-11-16T00:00:00Z. A time + without an offset is read as UTC. Combines with created_before, the other filters and cursor. + - name: created_before + in: query + required: false + schema: + anyOf: + - type: string + format: date-time + - type: 'null' + description: Only jobs created before this time, which is left out. ISO 8601, for example 2026-11-17T00:00:00Z. + A time without an offset is read as UTC. With created_after, a range that starts after it ends is refused. + examples: + - '2026-11-17T00:00:00Z' + title: Created Before + description: Only jobs created before this time, which is left out. ISO 8601, for example 2026-11-17T00:00:00Z. + A time without an offset is read as UTC. With created_after, a range that starts after it ends is refused. - name: cursor in: query required: false @@ -4374,6 +4408,147 @@ paths: agent_key_allowed: true description: 'No API key: the `exp` and `sig` query values come from the signed URL the API minted. The link lives 72 hours.' + /v1/records/faxes.csv: + get: + tags: + - organizations + summary: 'The fax history as CSV: every fax sent and received in the range' + description: 'One line per fax of the key''s environment, sent and received, oldest first. A sent fax counts + by when it was created and a received one by when it arrived. The lines carry what each fax cost the wallet, + never the document or its text. A range of more than 20000 lines answers 422: choose fewer days. Needs the + scopes fax:read and inbox:read.' + operationId: get_fax_history_csv + parameters: + - name: from + in: query + required: false + schema: + anyOf: + - type: string + - type: 'null' + description: First UTC day, YYYY-MM-DD, included. + title: From + description: First UTC day, YYYY-MM-DD, included. + - name: to + in: query + required: false + schema: + anyOf: + - type: string + - type: 'null' + description: Last UTC day, YYYY-MM-DD, included. + title: To + description: Last UTC day, YYYY-MM-DD, included. + responses: + '200': + description: Successful Response + content: + text/csv: + schema: + type: string + '401': + $ref: '#/components/responses/Unauthorized' + '403': + description: error.code is workspace_required while the organization's Agent workspace plan is not active + and ended more than 30 days ago, or never started. error.details.ended_at is when it ended and error.details.closed_at + when the export closed. scope_missing names a scope the credential lacks. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorEnvelope' + '410': + $ref: '#/components/responses/Gone' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + '404': + description: Not an id of this organization, or it was deleted (not_found). + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorEnvelope' + security: + - bearerAuth: [] + - apiKeyHeader: [] + x-required-scope: fax:read + x-llm: + scope: fax:read + mutating: false + idempotency_key: false + agent_key_allowed: true + hint: Needs inbox:read as well as fax:read. The answer is CSV text. Without the Agent workspace plan it + is 403 workspace_required. + /v1/records/audit.csv: + get: + tags: + - organizations + summary: 'The audit trail as CSV: every action on the organization in the range' + description: 'One line per audit row of the organization, oldest first: when, who (actor and a label), what + (action), on what (resource_type and resource_id) and the row''s data as JSON. Never a document''s content. + A range of more than 20000 lines answers 422: choose fewer days. Needs the scope org:admin, which an owner + has. An agent is refused.' + operationId: get_audit_csv + parameters: + - name: from + in: query + required: false + schema: + anyOf: + - type: string + - type: 'null' + description: First UTC day, YYYY-MM-DD, included. + title: From + description: First UTC day, YYYY-MM-DD, included. + - name: to + in: query + required: false + schema: + anyOf: + - type: string + - type: 'null' + description: Last UTC day, YYYY-MM-DD, included. + title: To + description: Last UTC day, YYYY-MM-DD, included. + responses: + '200': + description: Successful Response + content: + text/csv: + schema: + type: string + '401': + $ref: '#/components/responses/Unauthorized' + '403': + description: error.code is workspace_required while the organization's Agent workspace plan is not active + and ended more than 30 days ago, or never started. error.details.ended_at is when it ended and error.details.closed_at + when the export closed. scope_missing names a scope the credential lacks, and an agent gets agent_forbidden. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorEnvelope' + '410': + $ref: '#/components/responses/Gone' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + '404': + description: Not an id of this organization, or it was deleted (not_found). + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorEnvelope' + security: + - bearerAuth: [] + - apiKeyHeader: [] + x-required-scope: org:admin + x-llm: + scope: org:admin + mutating: false + idempotency_key: false + agent_key_allowed: false + hint: The answer is CSV text. Without the Agent workspace plan it is 403 workspace_required. /v1/members: get: tags: @@ -8280,6 +8455,9 @@ paths: - expired - refused - settle_failed + - refunding + - refunded + - canceled type: string - type: 'null' title: Status @@ -10433,12 +10611,16 @@ components: title: Extraction Pricing 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. + With a test key, extractions are free. limits: additionalProperties: type: integer type: object title: Limits + description: 'requests_per_minute is the limit of the calling credential: 3000 while the organization''s + Agent workspace is active, 600 otherwise. The RateLimit-Limit header of every answer says the same. + The other keys are the life of a quote and of a download link in seconds, and the largest HTML document + in bytes.' one_time: additionalProperties: true type: object @@ -12077,7 +12259,7 @@ components: amount_micro: type: integer title: Amount Micro - description: What the received pages were charged, in micro-USD. 0 on the sandbox. + description: What the received pages were charged, in micro-USD. 0 in test. default: 0 note: anyOf: @@ -12175,7 +12357,7 @@ components: amount_micro: type: integer title: Amount Micro - description: What the received pages were charged, in micro-USD. 0 on the sandbox. + description: What the received pages were charged, in micro-USD. 0 in test. default: 0 note: anyOf: @@ -12317,7 +12499,7 @@ components: amount_micro: type: integer title: Amount Micro - description: What the received pages were charged, in micro-USD. 0 on the sandbox. + description: What the received pages were charged, in micro-USD. 0 in test. default: 0 note: anyOf: @@ -12927,6 +13109,13 @@ components: currency: type: string title: Currency + included_with_workspace: + type: boolean + title: Included With Workspace + description: 'True while the organization''s Agent workspace pays this number''s monthly charge: the oldest + live local number, pending or active, while the plan is active. Its renewals then take nothing from + the wallet. When the plan ends, the next renewal charges monthly_micro.' + default: false order_id: anyOf: - type: string @@ -13036,7 +13225,8 @@ components: first_month_hold_micro: type: integer title: First Month Hold Micro - description: Held now, captured when the number activates. + description: 'Held now, captured when the number activates. 0 for a test number, and 0 when the Agent + workspace pays the first month: the number''s included_with_workspace is then true.' currency: type: string title: Currency @@ -13342,6 +13532,9 @@ components: - expired - refused - settle_failed + - refunding + - refunded + - canceled title: Status to: type: string @@ -13590,6 +13783,9 @@ components: - expired - refused - settle_failed + - refunding + - refunded + - canceled - type: 'null' title: Status amount_micro: @@ -13682,6 +13878,9 @@ components: - expired - refused - settle_failed + - refunding + - refunded + - canceled title: Status next: type: string @@ -13770,6 +13969,12 @@ components: description: What was refunded to the card after the charge, in micro-units, as the ledger holds it. Zero when nothing was refunded. captured_micro stays what was charged. default: 0 + refund_pending_micro: + type: integer + title: Refund Pending Micro + description: A refund on its way to the card that the payment provider has not confirmed yet, in micro-units, + while the order is refunding. Zero otherwise. + default: 0 card: anyOf: - $ref: '#/components/schemas/OneTimeCard' @@ -13929,7 +14134,9 @@ components: ``confirm`` (click the mailed link), ``wait`` (read again later) or ``done``. Money is integer micro-USD. The field ``captured_micro`` is what the card was charged, written only once the payment provider confirmed it. The field ``fax`` is the fax job once the order was released, with the - carrier's evidence once it has any. + carrier's evidence once it has any. Three statuses come from a person at Fax for Agents: ``refunding`` + (a refund is on its way to the card), ``refunded`` (the whole charge went back) and ``canceled`` (the + order was canceled and the hold on the card released, nothing charged). OneTimeOrderCreated: properties: id: @@ -13950,6 +14157,9 @@ components: - expired - refused - settle_failed + - refunding + - refunded + - canceled title: Status next: type: string @@ -14038,6 +14248,12 @@ components: description: What was refunded to the card after the charge, in micro-units, as the ledger holds it. Zero when nothing was refunded. captured_micro stays what was charged. default: 0 + refund_pending_micro: + type: integer + title: Refund Pending Micro + description: A refund on its way to the card that the payment provider has not confirmed yet, in micro-units, + while the order is refunding. Zero otherwise. + default: 0 card: anyOf: - $ref: '#/components/schemas/OneTimeCard' @@ -14671,7 +14887,8 @@ components: - type: 'null' 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.' + false when a policy allows it, and for a test send by a caller no policy binds. It is false for a signed-in + owner''s own live send too, which needs no approval.' additionalProperties: true type: object required: @@ -15183,6 +15400,16 @@ components: amount_micro: type: integer title: Amount Micro + live_amount_micro: + anyOf: + - type: integer + - type: 'null' + title: Live Amount Micro + description: What the same fax costs with a live key, in micro-units. It is the billable pages at the + live rate of the destination, priced by the rule a live quote uses. A test quote is free (amount_micro + 0), and this field says what the fax would cost live. On a live quote it equals amount_micro. Null when + the rate card in force is not the one the quote was priced on (price_version) or no longer serves the + destination. currency: type: string title: Currency @@ -15296,6 +15523,7 @@ components: cover_pages: 0 billable_pages: 2 amount_micro: 0 + live_amount_micro: 78000 currency: USD price_version: launch-v3 per_page_micro: 0 @@ -16053,6 +16281,8 @@ components: workspace: type: boolean title: Workspace + plan: + $ref: '#/components/schemas/WorkspacePlan' next_cursor: anyOf: - type: string @@ -16719,6 +16949,93 @@ components: created_at: '2026-11-14T19:58:39.486Z' updated_at: '2026-11-14T19:58:39.486Z' secret: whsec_... + WorkspacePlan: + properties: + active: + type: boolean + title: Active + description: 'The plan is active: a subscription is active, trialing or past due.' + credit_micro: + type: integer + title: Credit Micro + description: The fax credit each paid invoice of the plan adds to the live wallet. + records_keep_days: + type: integer + title: Records Keep Days + description: How long live documents and received faxes are kept while the plan is active. + document_keep_days: + type: integer + title: Document Keep Days + description: How long a document is kept without the plan. + inbox_keep_days: + type: integer + title: Inbox Keep Days + description: How long a received fax is kept without the plan. + requests_per_minute: + type: integer + title: Requests Per Minute + description: The request limit of each credential of the organization now. + plan_requests_per_minute: + type: integer + title: Plan Requests Per Minute + description: The request limit of each credential while the plan is active. + standard_requests_per_minute: + type: integer + title: Standard Requests Per Minute + description: The request limit of each credential without it. + included_numbers: + type: integer + title: Included Numbers + description: Local numbers whose monthly charge the plan pays. + included_number_id: + anyOf: + - type: string + - type: 'null' + title: Included Number Id + description: 'The number the plan pays for now: the oldest live local number, while the plan is active.' + included_number: + anyOf: + - type: string + - type: 'null' + title: Included Number + description: That number, E.164. + ended_at: + anyOf: + - type: string + - type: 'null' + title: Ended At + description: When the plan last ended. Null while it is active or if it never was. + cleanup_at: + anyOf: + - type: string + - type: 'null' + title: Cleanup At + description: When records older than the standard time (30 days for a document, 90 for a received fax) + are deleted after the plan ended. Null while the plan is active. + export_open: + type: boolean + title: Export Open + description: 'GET /v1/records/faxes.csv and /v1/records/audit.csv answer: while the plan is active and + until cleanup_at.' + additionalProperties: true + type: object + required: + - active + - credit_micro + - records_keep_days + - document_keep_days + - inbox_keep_days + - requests_per_minute + - plan_requests_per_minute + - standard_requests_per_minute + - included_numbers + - included_number_id + - included_number + - ended_at + - cleanup_at + - export_open + title: WorkspacePlan + description: What the Agent workspace gives and where the organization stands with it. InsufficientBalance: title: InsufficientBalance description: The error envelope of 402 insufficient_balance, with its details written out. diff --git a/src/faxforagents/__init__.py b/src/faxforagents/__init__.py index b83fedd..2c9c961 100644 --- a/src/faxforagents/__init__.py +++ b/src/faxforagents/__init__.py @@ -18,7 +18,7 @@ from __future__ import annotations -__version__ = "0.10.0" +__version__ = "0.11.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 75729b0..0c7d5bc 100644 --- a/src/faxforagents/async_client.py +++ b/src/faxforagents/async_client.py @@ -272,7 +272,10 @@ async def create( ) -> m.Quote: """The exact price of one document to one E.164 destination, valid ten minutes. Scope: fax:quote. - ``quality`` picks the resolution: standard, fine (the default), superfine or ultra. Same price.""" + ``quality`` picks the resolution: standard, fine (the default), superfine or ultra. Same price. + + A test quote is free, and ``live_amount_micro`` says what the same fax costs with a live key. It is + ``None`` when the rate card changed since the quote, or from a server older than API 1.21.0.""" body: dict[str, Any] = {"document_id": document_id, "to": to, "from": from_, "cover": cover} if quality is not None: body["quality"] = quality @@ -310,6 +313,8 @@ async def list( state: str | None = None, q: str | None = None, idempotency_key: str | None = None, + created_after: str | None = None, + created_before: str | None = None, cursor: str | None = None, limit: int | None = None, ) -> m.FaxJobPage: @@ -320,21 +325,41 @@ async def list( ``idempotency_key`` finds the send made with that Idempotency-Key. It is a filter here, not a header. An empty result does not prove no fax was sent. + + ``created_after`` and ``created_before`` keep the jobs created in a time range. The start is + included and the end is left out. Both are ISO 8601, such as ``2026-11-16T00:00:00Z``, and a time + without an offset is read as UTC. A start after the end raises ``InvalidRequestError``. Every + filter combines with the others. Needs API 1.21.0. """ params = { "state": state, "q": q, "idempotency_key": idempotency_key, + "created_after": created_after, + "created_before": created_before, "cursor": cursor, "limit": limit, } return await self._h.request("GET", "/v1/faxes", model=m.FaxJobPage, params=params) def iter( - self, *, state: str | None = None, q: str | None = None, limit: int | None = None + self, + *, + state: str | None = None, + q: str | None = None, + created_after: str | None = None, + created_before: str | None = None, + limit: int | None = None, ) -> AsyncIterator[m.FaxJob]: """Every fax job that matches, following next_cursor.""" - return apaginate(self.list, {"state": state, "q": q, "limit": limit}) + filters = { + "state": state, + "q": q, + "created_after": created_after, + "created_before": created_before, + "limit": limit, + } + return apaginate(self.list, filters) async def get(self, fax_id: str) -> m.FaxJob: """The job with its evidence once delivered or partial. Scope: fax:read.""" @@ -716,7 +741,11 @@ async def create_subscription_checkout( ) async def list_subscriptions(self) -> m.SubscriptionList: - """Subscriptions and the workspace entitlement. Scope: billing:read.""" + """Subscriptions and the workspace entitlement. Scope: billing:read. + + ``plan`` says what the Agent workspace gives and where the organization stands with it: the + request limit, the included number, how long records are kept and whether the records export is + open. It is ``None`` from a server older than API 1.21.0.""" return await self._h.request("GET", "/v1/subscriptions", model=m.SubscriptionList) async def create_portal_session(self, *, idempotency_key: str | None = None) -> m.PortalSession: @@ -1505,6 +1534,30 @@ async def download_export_archive(self, token: str, *, exp: str, sig: str) -> by ) return bytes(data) + async def fax_history_csv(self, *, from_: str | None = None, to: str | None = None) -> str: + """The fax history as CSV text: one line per fax of this key's environment, sent and received, + oldest first. Each line says what the fax cost, never what the document says. + Scope: fax:read and inbox:read. + + ``from_`` and ``to`` are UTC days, YYYY-MM-DD, both included. A range of more than 20000 lines + raises ``InvalidRequestError``: ask for fewer days. The export comes with the Agent workspace plan. + Without the plan, or more than 30 days after it ended, it raises ``ScopeError`` with the code + ``workspace_required``. Needs API 1.21.0.""" + data = await self._h.request("GET", "/v1/records/faxes.csv", params={"from": from_, "to": to}) + return bytes(data).decode("utf-8") + + async def audit_csv(self, *, from_: str | None = None, to: str | None = None) -> str: + """The audit trail as CSV text: one line per audit row of the organization, oldest first. It + names who did what to which resource, never a document's content. + Scope: org:admin, never an agent key. + + ``from_`` and ``to`` are UTC days, YYYY-MM-DD, both included. A range of more than 20000 lines + raises ``InvalidRequestError``: ask for fewer days. The export comes with the Agent workspace plan. + Without the plan, or more than 30 days after it ended, it raises ``ScopeError`` with the code + ``workspace_required``. Needs API 1.21.0.""" + data = await self._h.request("GET", "/v1/records/audit.csv", params={"from": from_, "to": to}) + return bytes(data).decode("utf-8") + class Members(_Resource): async def list(self) -> m.MemberList: @@ -1763,7 +1816,12 @@ def iter(self, *, status: str | None = None, limit: int | None = None) -> AsyncI async def get(self, order_id: str, *, order_token: str | None = None) -> m.OneTimeOrder: """The order: its status, the step that is waiting in ``next``, and the fax once released. - Read it with a key of the order's organization (scope fax:read) or with ``order_token``.""" + Read it with a key of the order's organization (scope fax:read) or with ``order_token``. + + A person at Fax for Agents can refund an order or release the hold on its card. The order then + reads ``refunding`` with ``next`` ``wait``, and ``refunded`` once the whole charge went back. It + reads ``canceled`` when the hold was released and nothing was charged. ``refund_pending_micro`` is + a refund the payment provider has not confirmed yet. These statuses need API 1.21.0.""" return await self._h.request( "GET", f"/v1/one-time-sends/{order_id}", model=m.OneTimeOrder, headers=token_header(order_token) ) diff --git a/src/faxforagents/client.py b/src/faxforagents/client.py index f7deaed..24d99f6 100644 --- a/src/faxforagents/client.py +++ b/src/faxforagents/client.py @@ -317,7 +317,10 @@ def create( ) -> m.Quote: """The exact price of one document to one E.164 destination, valid ten minutes. Scope: fax:quote. - ``quality`` picks the resolution: standard, fine (the default), superfine or ultra. Same price.""" + ``quality`` picks the resolution: standard, fine (the default), superfine or ultra. Same price. + + A test quote is free, and ``live_amount_micro`` says what the same fax costs with a live key. It is + ``None`` when the rate card changed since the quote, or from a server older than API 1.21.0.""" body: dict[str, Any] = {"document_id": document_id, "to": to, "from": from_, "cover": cover} if quality is not None: body["quality"] = quality @@ -355,6 +358,8 @@ def list( state: str | None = None, q: str | None = None, idempotency_key: str | None = None, + created_after: str | None = None, + created_before: str | None = None, cursor: str | None = None, limit: int | None = None, ) -> m.FaxJobPage: @@ -365,21 +370,41 @@ def list( ``idempotency_key`` finds the send made with that Idempotency-Key. It is a filter here, not a header. An empty result does not prove no fax was sent. + + ``created_after`` and ``created_before`` keep the jobs created in a time range. The start is + included and the end is left out. Both are ISO 8601, such as ``2026-11-16T00:00:00Z``, and a time + without an offset is read as UTC. A start after the end raises ``InvalidRequestError``. Every + filter combines with the others. Needs API 1.21.0. """ params = { "state": state, "q": q, "idempotency_key": idempotency_key, + "created_after": created_after, + "created_before": created_before, "cursor": cursor, "limit": limit, } return self._h.request("GET", "/v1/faxes", model=m.FaxJobPage, params=params) def iter( - self, *, state: str | None = None, q: str | None = None, limit: int | None = None + self, + *, + state: str | None = None, + q: str | None = None, + created_after: str | None = None, + created_before: str | None = None, + limit: int | None = None, ) -> Iterator[m.FaxJob]: """Every fax job that matches, following next_cursor.""" - return paginate(lambda p: self.list(**p), {"state": state, "q": q, "limit": limit}) + filters = { + "state": state, + "q": q, + "created_after": created_after, + "created_before": created_before, + "limit": limit, + } + return paginate(lambda p: self.list(**p), filters) def get(self, fax_id: str) -> m.FaxJob: """The job with its evidence once delivered or partial. Scope: fax:read.""" @@ -745,7 +770,11 @@ def create_subscription_checkout(self, *, idempotency_key: str | None = None) -> ) def list_subscriptions(self) -> m.SubscriptionList: - """Subscriptions and the workspace entitlement. Scope: billing:read.""" + """Subscriptions and the workspace entitlement. Scope: billing:read. + + ``plan`` says what the Agent workspace gives and where the organization stands with it: the + request limit, the included number, how long records are kept and whether the records export is + open. It is ``None`` from a server older than API 1.21.0.""" return self._h.request("GET", "/v1/subscriptions", model=m.SubscriptionList) def create_portal_session(self, *, idempotency_key: str | None = None) -> m.PortalSession: @@ -1520,6 +1549,30 @@ def download_export_archive(self, token: str, *, exp: str, sig: str) -> bytes: ) return bytes(data) + def fax_history_csv(self, *, from_: str | None = None, to: str | None = None) -> str: + """The fax history as CSV text: one line per fax of this key's environment, sent and received, + oldest first. Each line says what the fax cost, never what the document says. + Scope: fax:read and inbox:read. + + ``from_`` and ``to`` are UTC days, YYYY-MM-DD, both included. A range of more than 20000 lines + raises ``InvalidRequestError``: ask for fewer days. The export comes with the Agent workspace plan. + Without the plan, or more than 30 days after it ended, it raises ``ScopeError`` with the code + ``workspace_required``. Needs API 1.21.0.""" + data = self._h.request("GET", "/v1/records/faxes.csv", params={"from": from_, "to": to}) + return bytes(data).decode("utf-8") + + def audit_csv(self, *, from_: str | None = None, to: str | None = None) -> str: + """The audit trail as CSV text: one line per audit row of the organization, oldest first. It + names who did what to which resource, never a document's content. + Scope: org:admin, never an agent key. + + ``from_`` and ``to`` are UTC days, YYYY-MM-DD, both included. A range of more than 20000 lines + raises ``InvalidRequestError``: ask for fewer days. The export comes with the Agent workspace plan. + Without the plan, or more than 30 days after it ended, it raises ``ScopeError`` with the code + ``workspace_required``. Needs API 1.21.0.""" + data = self._h.request("GET", "/v1/records/audit.csv", params={"from": from_, "to": to}) + return bytes(data).decode("utf-8") + class Members(_Resource): def list(self) -> m.MemberList: @@ -1770,7 +1823,12 @@ def iter(self, *, status: str | None = None, limit: int | None = None) -> Iterat def get(self, order_id: str, *, order_token: str | None = None) -> m.OneTimeOrder: """The order: its status, the step that is waiting in ``next``, and the fax once released. - Read it with a key of the order's organization (scope fax:read) or with ``order_token``.""" + Read it with a key of the order's organization (scope fax:read) or with ``order_token``. + + A person at Fax for Agents can refund an order or release the hold on its card. The order then + reads ``refunding`` with ``next`` ``wait``, and ``refunded`` once the whole charge went back. It + reads ``canceled`` when the hold was released and nothing was charged. ``refund_pending_micro`` is + a refund the payment provider has not confirmed yet. These statuses need API 1.21.0.""" return self._h.request( "GET", f"/v1/one-time-sends/{order_id}", model=m.OneTimeOrder, headers=token_header(order_token) ) diff --git a/src/faxforagents/models.py b/src/faxforagents/models.py index e851579..736a6d3 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.11). Do not edit by hand. +GENERATED by scripts/gen_models.py from spec/openapi.yaml (API version 1.21.0). 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. """ @@ -334,8 +334,8 @@ class Capabilities(_Response): admin_scopes: list[str] | None = Field(None, description="The scopes that administer the organization: keys, webhooks, billing, members, policies, agents, approval decisions and number purchases. An agent's own key never carries one.") approvals: bool 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] + 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. With a test key, extractions are free.") + limits: dict[str, int] = Field(..., description="requests_per_minute is the limit of the calling credential: 3000 while the organization's Agent workspace is active, 600 otherwise. The RateLimit-Limit header of every answer says the same. The other keys are the life of a quote and of a download link in seconds, and the largest HTML document in bytes.") 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.") @@ -669,7 +669,7 @@ class OneTimeJob(_Response): """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 + status: Literal["draft", "checkout_open", "authorized", "awaiting_confirmation", "released", "capturing", "canceling", "captured", "released_hold", "expired", "refused", "settle_failed", "refunding", "refunded", "canceled"] | None = None amount_micro: int | None = None captured_micro: int | None = None refunded_micro: int | None = Field(None, description="What was refunded to the card after the charge, in micro-units.") @@ -754,7 +754,7 @@ class InboxItem(_Response): status: str document_id: str | None received_at: str - amount_micro: int = Field(0, description="What the received pages were charged, in micro-USD. 0 on the sandbox.") + amount_micro: int = Field(0, description="What the received pages were charged, in micro-USD. 0 in test.") note: str | None = None environment: Literal["live", "test"] = "live" number_id: str | None = None @@ -776,7 +776,7 @@ class InboxItemDetail(_Response): status: str document_id: str | None received_at: str - amount_micro: int = Field(0, description="What the received pages were charged, in micro-USD. 0 on the sandbox.") + amount_micro: int = Field(0, description="What the received pages were charged, in micro-USD. 0 in test.") note: str | None = None environment: Literal["live", "test"] = "live" number_id: str | None = None @@ -801,7 +801,7 @@ class InboxItemSummary(_Response): status: str document_id: str | None received_at: str - amount_micro: int = Field(0, description="What the received pages were charged, in micro-USD. 0 on the sandbox.") + amount_micro: int = Field(0, description="What the received pages were charged, in micro-USD. 0 in test.") 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.") @@ -964,6 +964,7 @@ class Number(_Response): provider: str monthly_micro: int currency: str + included_with_workspace: bool = Field(False, description="True while the organization's Agent workspace pays this number's monthly charge: the oldest live local number, pending or active, while the plan is active. Its renewals then take nothing from the wallet. When the plan ends, the next renewal charges monthly_micro.") order_id: str | None created_at: str activated_at: str | None @@ -987,7 +988,7 @@ class NumberOrder(_Response): provider: str recurring_charge_micro: int = Field(..., description="Charged every month on the activation day.") recurring_period: str - first_month_hold_micro: int = Field(..., description="Held now, captured when the number activates.") + first_month_hold_micro: int = Field(..., description="Held now, captured when the number activates. 0 for a test number, and 0 when the Agent workspace pays the first month: the number's included_with_workspace is then true.") currency: str error: str | None created_at: str @@ -1076,7 +1077,7 @@ class OneTimeConfirmSummary(_Response): order_id: str state: Literal["ok", "link_used", "link_expired"] - status: Literal["draft", "checkout_open", "authorized", "awaiting_confirmation", "released", "capturing", "canceling", "captured", "released_hold", "expired", "refused", "settle_failed"] + status: Literal["draft", "checkout_open", "authorized", "awaiting_confirmation", "released", "capturing", "canceling", "captured", "released_hold", "expired", "refused", "settle_failed", "refunding", "refunded", "canceled"] to: str sender_name: str email: str @@ -1104,10 +1105,10 @@ class OneTimePrice(_Response): class OneTimeOrder(_Response): - """One order of the one-time send. The field ``next`` is what the caller does now: ``checkout`` (pay), ``confirm`` (click the mailed link), ``wait`` (read again later) or ``done``. Money is integer micro-USD. The field ``captured_micro`` is what the card was charged, written only once the payment provider confirmed it. The field ``fax`` is the fax job once the order was released, with the carrier's evidence once it has any.""" + """One order of the one-time send. The field ``next`` is what the caller does now: ``checkout`` (pay), ``confirm`` (click the mailed link), ``wait`` (read again later) or ``done``. Money is integer micro-USD. The field ``captured_micro`` is what the card was charged, written only once the payment provider confirmed it. The field ``fax`` is the fax job once the order was released, with the carrier's evidence once it has any. Three statuses come from a person at Fax for Agents: ``refunding`` (a refund is on its way to the card), ``refunded`` (the whole charge went back) and ``canceled`` (the order was canceled and the hold on the card released, nothing charged).""" id: str - status: Literal["draft", "checkout_open", "authorized", "awaiting_confirmation", "released", "capturing", "canceling", "captured", "released_hold", "expired", "refused", "settle_failed"] + status: Literal["draft", "checkout_open", "authorized", "awaiting_confirmation", "released", "capturing", "canceling", "captured", "released_hold", "expired", "refused", "settle_failed", "refunding", "refunded", "canceled"] next: Literal["checkout", "confirm", "wait", "done"] environment: Literal["live", "test"] source: Literal["web", "api", "mcp"] @@ -1127,6 +1128,7 @@ class OneTimeOrder(_Response): amount_micro: int captured_micro: int refunded_micro: int = Field(0, description="What was refunded to the card after the charge, in micro-units, as the ledger holds it. Zero when nothing was refunded. captured_micro stays what was charged.") + refund_pending_micro: int = Field(0, description="A refund on its way to the card that the payment provider has not confirmed yet, in micro-units, while the order is refunding. Zero otherwise.") card: OneTimeCard | None checkout_url: str | None checkout_expires_at: str | None @@ -1202,7 +1204,7 @@ class OneTimeOrderCreated(_Response): """The create answer: the order plus the status token. The token reads this one order, opens its checkout and asks for the confirmation mail again, with no key and no session, for seven days. Send it as ``X-FFA-Order-Token`` (or ``?t=``). ``status_url`` is the order's page in the app with the token.""" id: str - status: Literal["draft", "checkout_open", "authorized", "awaiting_confirmation", "released", "capturing", "canceling", "captured", "released_hold", "expired", "refused", "settle_failed"] + status: Literal["draft", "checkout_open", "authorized", "awaiting_confirmation", "released", "capturing", "canceling", "captured", "released_hold", "expired", "refused", "settle_failed", "refunding", "refunded", "canceled"] next: Literal["checkout", "confirm", "wait", "done"] environment: Literal["live", "test"] source: Literal["web", "api", "mcp"] @@ -1222,6 +1224,7 @@ class OneTimeOrderCreated(_Response): amount_micro: int captured_micro: int refunded_micro: int = Field(0, description="What was refunded to the card after the charge, in micro-units, as the ledger holds it. Zero when nothing was refunded. captured_micro stays what was charged.") + refund_pending_micro: int = Field(0, description="A refund on its way to the card that the payment provider has not confirmed yet, in micro-units, while the order is refunding. Zero otherwise.") card: OneTimeCard | None checkout_url: str | None checkout_expires_at: str | None @@ -1321,7 +1324,7 @@ class PolicyEvaluation(_Response): 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.") + 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. It is false for a signed-in owner's own live send too, which needs no approval.") class PolicyEvaluationCreate(_Request): @@ -1444,6 +1447,7 @@ class Quote(_Response): cover_pages: int billable_pages: int amount_micro: int + live_amount_micro: int | None = Field(None, description="What the same fax costs with a live key, in micro-units. It is the billable pages at the live rate of the destination, priced by the rule a live quote uses. A test quote is free (amount_micro 0), and this field says what the fax would cost live. On a live quote it equals amount_micro. Null when the rate card in force is not the one the quote was priced on (price_version) or no longer serves the destination.") currency: str price_version: str per_page_micro: int = 0 @@ -1630,9 +1634,29 @@ class SubscriptionCheckout(_Response): product: str +class WorkspacePlan(_Response): + """What the Agent workspace gives and where the organization stands with it.""" + + active: bool = Field(..., description="The plan is active: a subscription is active, trialing or past due.") + credit_micro: int = Field(..., description="The fax credit each paid invoice of the plan adds to the live wallet.") + records_keep_days: int = Field(..., description="How long live documents and received faxes are kept while the plan is active.") + document_keep_days: int = Field(..., description="How long a document is kept without the plan.") + inbox_keep_days: int = Field(..., description="How long a received fax is kept without the plan.") + requests_per_minute: int = Field(..., description="The request limit of each credential of the organization now.") + plan_requests_per_minute: int = Field(..., description="The request limit of each credential while the plan is active.") + standard_requests_per_minute: int = Field(..., description="The request limit of each credential without it.") + included_numbers: int = Field(..., description="Local numbers whose monthly charge the plan pays.") + included_number_id: str | None = Field(..., description="The number the plan pays for now: the oldest live local number, while the plan is active.") + included_number: str | None = Field(..., description="That number, E.164.") + ended_at: str | None = Field(..., description="When the plan last ended. Null while it is active or if it never was.") + cleanup_at: str | None = Field(..., description="When records older than the standard time (30 days for a document, 90 for a received fax) are deleted after the plan ended. Null while the plan is active.") + export_open: bool = Field(..., description="GET /v1/records/faxes.csv and /v1/records/audit.csv answer: while the plan is active and until cleanup_at.") + + class SubscriptionList(_Response): items: list[Subscription] workspace: bool + plan: WorkspacePlan | None = None next_cursor: str | None = None @@ -1935,6 +1959,7 @@ class WebhookWithSecret(_Response): "StatementPage", "Subscription", "SubscriptionCheckout", + "WorkspacePlan", "SubscriptionList", "SummaryCreate", "TopupCreate", diff --git a/tests/fixtures/README.md b/tests/fixtures/README.md index e42a2c5..2e47a57 100644 --- a/tests/fixtures/README.md +++ b/tests/fixtures/README.md @@ -19,6 +19,9 @@ At API 1.20.0, server revision `3c06d076f0f5cfe477c42b71857cbdda9767884e`, the n The extraction page loses `cost_micro`, which `ocr/service.py` no longer sends. At API 1.20.10, server revision `da29794e1fb66a7f1486680a08a5d16402aee435`, the top-up session gains `checkout_status` from `billing/wallet.py`. It is null unless a read of an open top-up asks with `check_checkout=true`. +At API 1.21.0, server revision `a8e44c1174b926e359d9625847d4e347b98290cb`, the quote gains `live_amount_micro` from `billing/quotes.py`. +It is null for these test quotes, priced on launch-v1 while the card in force is launch-v3. +The number gains `included_with_workspace` from `numbers/service.py`, false for a test number. ## One-time sends (`one-time.json`) @@ -28,3 +31,5 @@ The other cases follow the serializers `order_json` and `job_block` in `onetime/ They are synthetic examples, not captured traffic: no order was created and no card was charged to make them. The tests add the API 1.17.0 fields (`queue`, `aup_accepted`, `status_url`, `top_up_url`) on top of these cases. Ids, addresses, the token and the checkout address are test values. +At API 1.21.0, server revision `a8e44c1174b926e359d9625847d4e347b98290cb`, each order gains `refund_pending_micro` from `onetime/service.py`. +It is 0 for an order that is not refunding. diff --git a/tests/fixtures/one-time.json b/tests/fixtures/one-time.json index 3c34163..90a6d62 100644 --- a/tests/fixtures/one-time.json +++ b/tests/fixtures/one-time.json @@ -71,6 +71,7 @@ "amount_micro": 2490000, "captured_micro": 0, "refunded_micro": 0, + "refund_pending_micro": 0, "card": null, "checkout_url": null, "checkout_expires_at": null, @@ -129,6 +130,7 @@ "amount_micro": 2490000, "captured_micro": 0, "refunded_micro": 0, + "refund_pending_micro": 0, "card": null, "checkout_url": null, "checkout_expires_at": null, @@ -185,6 +187,7 @@ "amount_micro": 2490000, "captured_micro": 0, "refunded_micro": 0, + "refund_pending_micro": 0, "card": null, "checkout_url": "https://checkout.example.test/c/pay/cs_test_1", "checkout_expires_at": "2026-11-12T09:31:00Z", @@ -241,6 +244,7 @@ "amount_micro": 2490000, "captured_micro": 0, "refunded_micro": 0, + "refund_pending_micro": 0, "card": { "last4": "4242", "brand": "visa" @@ -300,6 +304,7 @@ "amount_micro": 2490000, "captured_micro": 2490000, "refunded_micro": 0, + "refund_pending_micro": 0, "card": { "last4": "4242", "brand": "visa" @@ -538,6 +543,7 @@ "amount_micro": 2490000, "captured_micro": 2490000, "refunded_micro": 0, + "refund_pending_micro": 0, "card": { "last4": "4242", "brand": "visa" diff --git a/tests/fixtures/responses.json b/tests/fixtures/responses.json index 0541227..3f41e9b 100644 --- a/tests/fixtures/responses.json +++ b/tests/fixtures/responses.json @@ -90,6 +90,7 @@ "cover_pages": 0, "billable_pages": 1, "amount_micro": 0, + "live_amount_micro": null, "currency": "USD", "price_version": "launch-v1", "cover": null, @@ -118,6 +119,7 @@ "cover_pages": 0, "billable_pages": 1, "amount_micro": 0, + "live_amount_micro": null, "currency": "USD", "price_version": "launch-v1", "cover": null, @@ -183,6 +185,7 @@ "provider": "sandbox", "monthly_micro": 0, "currency": "USD", + "included_with_workspace": false, "order_id": "nord_1", "created_at": "2026-11-02T00:00:00Z", "activated_at": "2026-11-02T00:00:00Z", diff --git a/tests/test_async.py b/tests/test_async.py index dffa5c8..d68c411 100644 --- a/tests/test_async.py +++ b/tests/test_async.py @@ -6,7 +6,7 @@ import pytest import respx -from faxforagents import AsyncClient, ConflictError +from faxforagents import AsyncClient, ConflictError, ScopeError from tests.conftest import api_key_with_secret, delivery, error, fax_job, quote, topup_session @@ -284,3 +284,34 @@ async def test_async_topup_checkout_read_and_a_deleted_webhook( with pytest.raises(ConflictError) as exc: await aclient.webhooks.replay_delivery("dlv_1") assert exc.value.details == {"reason": "webhook_deleted"} + + +async def test_async_records_export_created_range_and_workspace_plan( + aclient: AsyncClient, api: respx.MockRouter +) -> None: + """API 1.21.0 on the async client: the records export, the created range and the plan.""" + history = api.get("/v1/records/faxes.csv").respond( + 200, content=b"direction,id\ninbound,inb_1\n", headers={"content-type": "text/csv"} + ) + text = await aclient.organizations.fax_history_csv(from_="2026-11-16", to="2026-11-16") + assert text == "direction,id\ninbound,inb_1\n" + assert dict(history.calls.last.request.url.params) == {"from": "2026-11-16", "to": "2026-11-16"} + api.get("/v1/records/audit.csv").respond( + 403, json=error("workspace_required", details={"ended_at": None}) + ) + with pytest.raises(ScopeError) as exc: + await aclient.organizations.audit_csv() + assert exc.value.code == "workspace_required" + listed = api.get("/v1/faxes") + listed.side_effect = [ + httpx.Response(200, json={"items": [fax_job(id="fax_a")], "next_cursor": "c2"}), + httpx.Response(200, json={"items": [fax_job(id="fax_b")], "next_cursor": None}), + ] + ids = [job.id async for job in aclient.faxes.iter(created_before="2026-11-17T00:00:00Z")] + assert ids == ["fax_a", "fax_b"] + assert dict(listed.calls[1].request.url.params) == { + "created_before": "2026-11-17T00:00:00Z", + "cursor": "c2", + } + api.get("/v1/subscriptions").respond(200, json={"items": [], "workspace": False}) + assert (await aclient.billing.list_subscriptions()).plan is None diff --git a/tests/test_client.py b/tests/test_client.py index 2b646c3..02d2e13 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -20,6 +20,7 @@ RateLimitedError, ScopeError, ServerError, + models, ) from tests.conftest import ( BASE, @@ -1122,3 +1123,132 @@ def test_a_delivery_to_a_deleted_webhook_is_not_replayed(client: Client, api: re client.webhooks.replay_delivery("dlv_1") assert exc.value.code == "conflict" and exc.value.details == details assert len(replay.calls) == 1 + + +def test_the_fax_list_takes_a_created_range(client: Client, api: respx.MockRouter) -> None: + """API 1.21.0: created_after is included and created_before left out. A reversed range answers 422.""" + later = fax_job(id="fax_" + "9" * 32) + route = api.get("/v1/faxes") + route.side_effect = [ + httpx.Response(200, json={"items": [fax_job()], "next_cursor": "c2"}), + httpx.Response(200, json={"items": [fax_job()], "next_cursor": "c2"}), + httpx.Response(200, json={"items": [later], "next_cursor": None}), + httpx.Response(422, json=error("invalid_request", "created_after is after created_before")), + ] + page = client.faxes.list( + created_after="2026-11-16T00:00:00Z", created_before="2026-11-17T00:00:00Z", state="delivered" + ) + assert page.next_cursor == "c2" + assert dict(route.calls[0].request.url.params) == { + "state": "delivered", + "created_after": "2026-11-16T00:00:00Z", + "created_before": "2026-11-17T00:00:00Z", + } + ids = [job.id for job in client.faxes.iter(created_after="2026-11-16T00:00:00Z")] + assert ids == [fax_job()["id"], later["id"]] + assert dict(route.calls[1].request.url.params) == {"created_after": "2026-11-16T00:00:00Z"} + assert dict(route.calls[2].request.url.params) == { + "created_after": "2026-11-16T00:00:00Z", + "cursor": "c2", + } + with pytest.raises(InvalidRequestError) as exc: + client.faxes.list(created_after="2026-11-17T00:00:00Z", created_before="2026-11-16T00:00:00Z") + assert exc.value.status == 422 and exc.value.code == "invalid_request" + + +def test_a_test_quote_names_its_live_price(client: Client, api: respx.MockRouter) -> None: + """API 1.21.0: a test quote is free and live_amount_micro is what the same fax costs live.""" + route = api.post("/v1/fax-quotes") + older = quote() + route.side_effect = [ + httpx.Response(201, json=quote(price_version="launch-v3", billable_pages=2, live_amount_micro=78000)), + httpx.Response(201, json=quote(live_amount_micro=None)), + httpx.Response(201, json=older), + ] + priced = client.quotes.create(document_id="doc_" + "2" * 32, to="+15550000001") + assert priced.amount_micro == 0 and priced.live_amount_micro == 78000 + unknown = client.quotes.create(document_id="doc_" + "2" * 32, to="+15550000001") + assert unknown.live_amount_micro is None + assert "live_amount_micro" not in older + assert client.quotes.create(document_id="doc_" + "2" * 32, to="+15550000001").live_amount_micro is None + + +def test_the_records_export_is_csv_text(client: Client, api: respx.MockRouter) -> None: + """API 1.21.0: the fax history and the audit trail of the Agent workspace plan, as CSV.""" + faxes = api.get("/v1/records/faxes.csv").respond( + 200, + content=b"direction,id,created_at\noutbound,fax_1,2026-11-16T09:00:00Z\n", + headers={"content-type": "text/csv; charset=utf-8"}, + ) + text = client.organizations.fax_history_csv(from_="2026-11-01", to="2026-11-16") + assert text.splitlines() == ["direction,id,created_at", "outbound,fax_1,2026-11-16T09:00:00Z"] + sent = faxes.calls.last.request + assert dict(sent.url.params) == {"from": "2026-11-01", "to": "2026-11-16"} + assert sent.method == "GET" and "idempotency-key" not in sent.headers + audit = api.get("/v1/records/audit.csv").respond( + 200, + content="created_at,actor_label\n2026-11-16,Dana Ö\n".encode(), + headers={"content-type": "text/csv"}, + ) + assert client.organizations.audit_csv() == "created_at,actor_label\n2026-11-16,Dana Ö\n" + assert audit.calls.last.request.url.query == b"" + + +def test_the_records_export_needs_the_workspace_plan(client: Client, api: respx.MockRouter) -> None: + """API 1.21.0: without the plan, or 30 days after it ended, the export answers 403 workspace_required.""" + details = {"ended_at": "2026-10-01T00:00:00Z", "closed_at": "2026-10-31T00:00:00Z"} + api.get("/v1/records/faxes.csv").respond(403, json=error("workspace_required", details=details)) + with pytest.raises(ScopeError) as exc: + client.organizations.fax_history_csv(from_="2026-09-01") + assert exc.value.code == "workspace_required" and exc.value.details == details + api.get("/v1/records/audit.csv").respond(403, json=error("scope_missing", details={"scope": "org:admin"})) + with pytest.raises(ScopeError) as missing: + client.organizations.audit_csv(to="2026-11-16") + assert missing.value.code == "scope_missing" and missing.value.details == {"scope": "org:admin"} + + +def workspace_plan(**over: object) -> dict[str, object]: + return { + "active": True, + "credit_micro": 10_000_000, + "records_keep_days": 365, + "document_keep_days": 30, + "inbox_keep_days": 90, + "requests_per_minute": 3000, + "plan_requests_per_minute": 3000, + "standard_requests_per_minute": 600, + "included_numbers": 1, + "included_number_id": "num_1", + "included_number": "+15550001001", + "ended_at": None, + "cleanup_at": None, + "export_open": True, + **over, + } + + +def test_the_subscription_list_carries_the_workspace_plan(client: Client, api: respx.MockRouter) -> None: + """API 1.21.0: plan says what the Agent workspace gives. An older server sends no plan.""" + route = api.get("/v1/subscriptions") + route.side_effect = [ + httpx.Response(200, json={"items": [], "workspace": True, "plan": workspace_plan()}), + httpx.Response(200, json={"items": [], "workspace": False}), + ] + listed = client.billing.list_subscriptions() + assert listed.plan is not None and listed.plan.export_open is True + assert listed.plan.requests_per_minute == 3000 and listed.plan.standard_requests_per_minute == 600 + assert listed.plan.included_number_id == "num_1" and listed.plan.ended_at is None + assert client.billing.list_subscriptions().plan is None + with pytest.raises(ValueError): + models.WorkspacePlan.model_validate({k: v for k, v in workspace_plan().items() if k != "export_open"}) + + +def test_the_number_the_workspace_pays_for(client: Client, api: respx.MockRouter) -> None: + """API 1.21.0: included_with_workspace marks the number whose monthly charge the plan pays.""" + route = api.get("/v1/numbers/num_1") + route.side_effect = [ + httpx.Response(200, json=number(included_with_workspace=True)), + httpx.Response(200, json=number()), + ] + assert client.numbers.get("num_1").included_with_workspace is True + assert client.numbers.get("num_1").included_with_workspace is False diff --git a/tests/test_one_time.py b/tests/test_one_time.py index cf37e68..11a56b2 100644 --- a/tests/test_one_time.py +++ b/tests/test_one_time.py @@ -17,6 +17,7 @@ NotFoundError, PaymentRequiredError, ServerError, + models, ) from tests.conftest import BASE, KEY, error @@ -478,3 +479,23 @@ def test_cover_check_refuses_a_field_over_the_limit_of_the_create( keyless.one_time_sends.check_cover(message="x" * 2001) assert exc.value.status == 422 and exc.value.details == {"field": "cover"} assert len(json.loads(route.calls.last.request.content)["message"]) == 2001 + + +def test_a_refunded_or_canceled_order_is_done(keyless: Client, api: respx.MockRouter) -> None: + """API 1.21.0: a person at Fax for Agents refunds an order or releases its hold. Refunding waits.""" + paid = CASES["captured"]["captured_micro"] + refunding = {**CASES["captured"], "status": "refunding", "next": "wait", "refund_pending_micro": paid} + refunded = {**CASES["captured"], "status": "refunded", "next": "done", "refunded_micro": paid} + route = api.get(f"/v1/one-time-sends/{ORDER}").mock( + side_effect=[httpx.Response(200, json=refunding), httpx.Response(200, json=refunded)] + ) + order = keyless.one_time_sends.wait(ORDER, order_token=TOKEN, interval=0.0) + assert order.status == "refunded" and order.next == "done" + assert order.refunded_micro == paid and order.refund_pending_micro == 0 + assert route.call_count == 2 + first = models.OneTimeOrder.model_validate(refunding) + assert first.status == "refunding" and first.refund_pending_micro == paid + canceled = {**CASES["awaiting_confirmation"], "status": "canceled", "next": "done"} + assert models.OneTimeOrder.model_validate(canceled).captured_micro == 0 + older = {k: v for k, v in CASES["captured"].items() if k != "refund_pending_micro"} + assert models.OneTimeOrder.model_validate(older).refund_pending_micro == 0 diff --git a/tests/test_surface.py b/tests/test_surface.py index 214699e..da93fc6 100644 --- a/tests/test_surface.py +++ b/tests/test_surface.py @@ -203,6 +203,8 @@ def test_every_operation_has_a_method() -> None: "list_data_requests": "organizations.list_data_requests", "withdraw_data_deletion": "organizations.withdraw_data_deletion", "download_export_archive": "organizations.download_export_archive", + "get_fax_history_csv": "organizations.fax_history_csv", + "get_audit_csv": "organizations.audit_csv", "list_members": "members.list", "update_member": "members.update", "remove_member": "members.remove", From 8a798717b44a3471b78b43acb4aaa1b56b02e48d Mon Sep 17 00:00:00 2001 From: bensynapse <118375461+bensynapse@users.noreply.github.com> Date: Mon, 16 Nov 2026 21:38:33 +0200 Subject: [PATCH 2/2] Split the plan sentence of list_subscriptions in two The writing lint counts 31 words in it, once its double backticks are read as code. Both clients get the same two sentences. The meaning is unchanged. --- src/faxforagents/async_client.py | 6 +++--- src/faxforagents/client.py | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/faxforagents/async_client.py b/src/faxforagents/async_client.py index 0c7d5bc..0de740b 100644 --- a/src/faxforagents/async_client.py +++ b/src/faxforagents/async_client.py @@ -743,9 +743,9 @@ async def create_subscription_checkout( async def list_subscriptions(self) -> m.SubscriptionList: """Subscriptions and the workspace entitlement. Scope: billing:read. - ``plan`` says what the Agent workspace gives and where the organization stands with it: the - request limit, the included number, how long records are kept and whether the records export is - open. It is ``None`` from a server older than API 1.21.0.""" + ``plan`` says what the Agent workspace gives and where the organization stands with it. It names + the request limit, the included number, how long records are kept and whether the records export + is open. It is ``None`` from a server older than API 1.21.0.""" return await self._h.request("GET", "/v1/subscriptions", model=m.SubscriptionList) async def create_portal_session(self, *, idempotency_key: str | None = None) -> m.PortalSession: diff --git a/src/faxforagents/client.py b/src/faxforagents/client.py index 24d99f6..498ac8e 100644 --- a/src/faxforagents/client.py +++ b/src/faxforagents/client.py @@ -772,9 +772,9 @@ def create_subscription_checkout(self, *, idempotency_key: str | None = None) -> def list_subscriptions(self) -> m.SubscriptionList: """Subscriptions and the workspace entitlement. Scope: billing:read. - ``plan`` says what the Agent workspace gives and where the organization stands with it: the - request limit, the included number, how long records are kept and whether the records export is - open. It is ``None`` from a server older than API 1.21.0.""" + ``plan`` says what the Agent workspace gives and where the organization stands with it. It names + the request limit, the included number, how long records are kept and whether the records export + is open. It is ``None`` from a server older than API 1.21.0.""" return self._h.request("GET", "/v1/subscriptions", model=m.SubscriptionList) def create_portal_session(self, *, idempotency_key: str | None = None) -> m.PortalSession: