diff --git a/CHANGELOG.md b/CHANGELOG.md index e01de0b..0204035 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,38 @@ # Changelog +## 0.7.0 (2026-11-15) + +Follows API 1.20.6. The saved spec has 161 operations and the models are regenerated from it. +Every operation has a method on both clients. + +New: `billing.statement(kind=..., from_=..., to=...)` reads the wallet statement, one line per event with the balance after it. +`billing.iter_statement` follows `next_cursor`, and `billing.statement_csv` returns the same lines as CSV text. Scope `billing:read`. +New: `documents.rename(document_id, filename=...)`. A name without `.pdf` gets it added. Scope `document:write`. +New: `webhooks.get_delivery(delivery_id)` returns `DeliveryDetail`, with the headers and the JSON body that were sent. +New: `billing.delete_budget(budget_id)`. A budget that never charged a hold is deleted, and one with history is archived. +New: `agents.archive(agent_id)` revokes the agent's keys and takes it out of the list. Its name is free again. +New: `numbers.dismiss_order(order_id)` puts a failed number order away. Any other order raises `ConflictError`. +New: `policies.check_rules(...)` names the numbers of a draft's `allowed_destinations` that a listed country or prefix already allows. It writes nothing. +New: `members.resend_invitation` mails an open invitation again. `members.link_invitation` answers a new link once, for you to hand over. Both stop the old link. +New: `organizations.list_data_requests()` and `organizations.withdraw_data_deletion(request_id)`. +New: `one_time_sends.preview(file=...)` or `preview(text=...)` counts the pages of a document before any order exists, with no key. +New: `one_time_sends.get_page(order_id, page_number)` returns one page of an order as PNG bytes. Page 1 is the cover sheet. + +New parameters: `faxes.list` and `faxes.iter` take `q`, a fax number or the start of a job id. +`documents.list` and `documents.iter` take `source`, `exclude_source` and `q`. `inbox.list` and `inbox.iter` take `archived`. +`agents.list` and `billing.list_budgets` take `include_archived`. `policies.evaluate` takes `key_id`, `agent_id` or `connection_id`. + +Changed: `approvals.reject` no longer needs `reason`. A help request closes without one. A send request still needs it, and the API answers 422 without it. +`approvals.list(status="used")` finds the approvals a send consumed. They read `approved`, and `consumed_by_job_id` names the fax. +Before API 1.20.6 such an approval read `expired` once its time had passed. + +New fields, among them `DocumentPage.total`, `InboxPage.unread`, `Balance.held_jobs`, `Quote.route_paused` and `Document.converted_from`. +`Receipt` has `seller`, `provider_ref` and `sender_name`. `ApprovalRequest` has `document`, `requested_by_name` and `decided_by_name`. +18 new models, among them `StatementPage`, `StatementLine`, `PolicyRuleCheck`, `DeliveryDetail` and `OneTimeInspection`. + +The API now refuses an organization name over 80 characters with 422. It took 200 before. +Nothing is removed. Other model names, fields and optionality are kept. + ## 0.6.1 (2026-11-15) Follows API 1.20.5. The saved spec has 147 operations and the models are regenerated from it. diff --git a/README.md b/README.md index ee36a61..6dcbbd4 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,11 @@ The same in async form, with `AsyncClient` and `await` on every call. document. An image becomes gray letter pages. - `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. +- `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. - `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 @@ -105,24 +110,24 @@ each call needs. | Resource | Calls | |---|---| | `ffa.identity` | `me`, `list_api_keys`, `create_api_key`, `rotate_api_key`, `revoke_api_key` | -| `ffa.documents` | `create`, `upload`, `create_upload`, `put_upload_content`, `complete_upload`, `cancel_upload`, `list`, `iter`, `get`, `delete`, `get_validation`, `get_download`, `download`, `list_pages` | +| `ffa.documents` | `create`, `upload`, `create_upload`, `put_upload_content`, `complete_upload`, `cancel_upload`, `list`, `iter`, `get`, `rename`, `delete`, `get_validation`, `get_download`, `download`, `list_pages` | | `ffa.quotes` | `create`, `get` | | `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`, `replay_delivery` | +| `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`, `iter_topup_sessions`, `iter_invoices`, settings, top-ups, auto top-ups, budgets, `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, 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` | -| `ffa.policies` | `list`, `create`, `effective`, `get_auto_send`, `set_auto_send`, `get`, `update`, `list_versions`, `evaluate` | -| `ffa.agents` | `list`, `create`, `get`, `update`, `create_key`, `activity` | +| `ffa.policies` | `list`, `create`, `effective`, `get_auto_send`, `set_auto_send`, `get`, `update`, `list_versions`, `evaluate`, `check_rules` | +| `ffa.agents` | `list`, `create`, `get`, `update`, `archive`, `create_key`, `activity` | | `ffa.inbox` | `list`, `iter`, `get`, `update`, `delete`, `get_download`, `download` | -| `ffa.numbers` | `coverage`, `inventory`, `create_order`, `list_orders`, `get_order`, `list`, `get`, `update`, `release`, `check_portability`, `list_port_orders`, `create_port_order`, `get_port_order`, `create_port_out_request`, `verify_sender` | +| `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`, `download_export_archive` | -| `ffa.members` | `list`, `update`, `remove`, `list_invitations`, `invite`, `revoke_invitation` | +| `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`, `create`, `create_from_quote`, `list`, `iter`, `get`, `wait`, `checkout`, `read_by_token`, `confirm`, `resend_confirmation`, `get_receipt_pdf` | +| `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.request("GET", "/v1/anything")` reaches an operation the resources do not cover yet. @@ -133,7 +138,7 @@ only when the carrier's evidence is on the attempt, and `fax.evidence` holds it. `unknown` never retransmit on their own. Whether to resend is a human decision. Sandbox destinations: `+15550000001` delivered, `+15550000002` busy then delivered, `+15550000003` -partial, `+15550000004` no answer, `+15550000005` unknown, `+15550000006` provider timeout, +partial (a one-page fax ends failed), `+15550000004` no answer, `+15550000005` unknown, `+15550000006` provider timeout, `+15550000007` invalid number. Any other `+1` number is delivered. ## Errors @@ -305,7 +310,7 @@ ruff check src tests && mypy src sh scripts/truthcheck.sh ``` -`spec/openapi.yaml` follows the public document at API version 1.20.5 and keeps the schemas of the earlier live documents. +`spec/openapi.yaml` follows the public document at API version 1.20.6 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. It also retains earlier public model names and route-documented response additions. diff --git a/pyproject.toml b/pyproject.toml index 3f52a60..7e02028 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "faxforagents" -version = "0.6.1" +version = "0.7.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 9ce72e6..fd4f96b 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.5. +# Fax for Agents API, refreshed from the public document of https://github.com/faxforagents/openapi at API 1.20.6. # 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.5 + version: 1.20.6 servers: - url: https://api.faxforagents.com description: Production (live and test keys) @@ -622,6 +622,51 @@ paths: minimum: 1 default: 50 title: Limit + - name: source + in: query + required: false + schema: + anyOf: + - enum: + - upload + - image + - text + - markdown + - html + - inbound + type: string + - type: 'null' + description: Only documents of this source; "inbound" is the files of received faxes. + title: Source + description: Only documents of this source; "inbound" is the files of received faxes. + - name: exclude_source + in: query + required: false + schema: + anyOf: + - enum: + - upload + - image + - text + - markdown + - html + - inbound + type: string + - type: 'null' + description: Leave this source out; "inbound" lists the documents you made. + title: Exclude Source + description: Leave this source out; "inbound" lists the documents you made. + - name: q + in: query + required: false + schema: + anyOf: + - type: string + maxLength: 255 + - type: 'null' + description: Part of a file name, or of the sender's number for a received fax. + title: Q + description: Part of a file name, or of the sender's number for a received fax. responses: '200': description: Successful Response @@ -695,6 +740,65 @@ paths: mutating: false idempotency_key: false agent_key_allowed: true + patch: + tags: + - documents + summary: Rename a document + operationId: rename_document + parameters: + - name: document_id + in: path + required: true + schema: + type: string + title: Document 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.' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/DocumentUpdate' + responses: + '200': + description: Successful Response + content: + application/json: + schema: + $ref: '#/components/schemas/Document' + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/Conflict' + '410': + $ref: '#/components/responses/Gone' + '413': + $ref: '#/components/responses/PayloadTooLarge' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + security: + - bearerAuth: [] + - apiKeyHeader: [] + x-required-scope: document:write + x-llm: + scope: document:write + mutating: true + idempotency_key: true + agent_key_allowed: true delete: tags: - documents @@ -1181,6 +1285,22 @@ paths: title: Idempotency Key description: Find the send job using its Idempotency-Key. This lookup requires the stored replay record. An empty result does not prove no fax was sent. + - name: q + in: query + required: false + schema: + anyOf: + - type: string + minLength: 1 + maxLength: 64 + - type: 'null' + 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.' + title: Q + 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: cursor in: query required: false @@ -1879,6 +1999,47 @@ paths: mutating: false idempotency_key: false agent_key_allowed: false + /v1/webhook-deliveries/{delivery_id}: + get: + tags: + - webhooks + summary: One delivery with the body that was sent (no secrets) + operationId: get_webhook_delivery + parameters: + - name: delivery_id + in: path + required: true + schema: + type: string + title: Delivery Id + responses: + '200': + description: Successful Response + content: + application/json: + schema: + $ref: '#/components/schemas/DeliveryDetail' + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + '410': + $ref: '#/components/responses/Gone' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + security: + - bearerAuth: [] + - apiKeyHeader: [] + x-required-scope: webhook:admin + x-llm: + scope: webhook:admin + mutating: false + idempotency_key: false + agent_key_allowed: false /v1/webhook-deliveries/{delivery_id}/replay: post: tags: @@ -2089,6 +2250,169 @@ paths: mutating: false idempotency_key: false agent_key_allowed: true + /v1/statement: + get: + 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. + operationId: get_statement + parameters: + - name: cursor + in: query + required: false + schema: + anyOf: + - type: string + maxLength: 64 + - type: 'null' + title: Cursor + - name: limit + in: query + required: false + schema: + type: integer + maximum: 200 + minimum: 1 + default: 50 + title: Limit + - name: kind + in: query + required: false + schema: + anyOf: + - 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.' + title: Kind + description: 'One kind of line: topup, fax, received_fax, number, extraction, release, refund, dispute, + credit, adjustment, other.' + - 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: + application/json: + schema: + $ref: '#/components/schemas/StatementPage' + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + '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: billing:read + x-llm: + scope: billing:read + mutating: false + idempotency_key: false + agent_key_allowed: true + /v1/statement.csv: + get: + tags: + - billing + summary: 'The wallet statement as CSV: every line the filters select' + operationId: get_statement_csv + parameters: + - name: kind + in: query + required: false + schema: + anyOf: + - 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.' + title: Kind + description: 'One kind of line: topup, fax, received_fax, number, extraction, release, refund, dispute, + credit, adjustment, other.' + - 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': + $ref: '#/components/responses/Forbidden' + '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: billing:read + x-llm: + scope: billing:read + mutating: false + idempotency_key: false + agent_key_allowed: true /v1/billing-settings: get: tags: @@ -2524,6 +2848,16 @@ paths: - billing summary: Spending caps of this environment operationId: list_budgets + parameters: + - name: include_archived + in: query + required: false + schema: + type: boolean + description: Also list removed budgets with history. + default: false + title: Include Archived + description: Also list removed budgets with history. responses: '200': description: Successful Response @@ -2537,6 +2871,8 @@ paths: $ref: '#/components/responses/Forbidden' '410': $ref: '#/components/responses/Gone' + '422': + $ref: '#/components/responses/UnprocessableContent' '429': $ref: '#/components/responses/TooManyRequests' '404': @@ -2667,6 +3003,57 @@ paths: mutating: true idempotency_key: true agent_key_allowed: false + delete: + tags: + - billing + summary: 'Remove a cap: deleted when it never charged a hold, archived when it has history' + operationId: delete_budget + parameters: + - name: budget_id + in: path + required: true + schema: + type: string + title: Budget 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/BudgetRemoved' + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/Conflict' + '410': + $ref: '#/components/responses/Gone' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + security: + - bearerAuth: [] + - apiKeyHeader: [] + x-required-scope: billing:write + x-llm: + scope: billing:write + mutating: true + idempotency_key: true + agent_key_allowed: false /v1/usage: get: tags: @@ -3641,6 +4028,96 @@ paths: mutating: true idempotency_key: true agent_key_allowed: false + /v1/organizations/current/data-requests: + get: + tags: + - organizations + summary: The organization's export and deletion requests and where each stands + operationId: list_data_requests + responses: + '200': + description: Successful Response + content: + application/json: + schema: + $ref: '#/components/schemas/DataRequestList' + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + '410': + $ref: '#/components/responses/Gone' + '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: account:read + x-llm: + scope: account:read + mutating: false + idempotency_key: false + agent_key_allowed: true + /v1/organizations/current/deletion-requests/{request_id}: + delete: + tags: + - organizations + summary: Withdraw an open deletion request (owner) + description: Works while the request is open. Once a person at Fax for Agents has started the deletion the + organization answers 410 to every call, this one included. + operationId: withdraw_data_deletion + parameters: + - name: request_id + in: path + required: true + schema: + type: string + title: Request 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/DataRequest' + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/Conflict' + '410': + $ref: '#/components/responses/Gone' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + security: + - bearerAuth: [] + - apiKeyHeader: [] + x-required-scope: org:admin + x-llm: + scope: org:admin + mutating: true + idempotency_key: true + agent_key_allowed: false /v1/organization/export-archives/{token}: get: tags: @@ -3922,6 +4399,112 @@ paths: mutating: true idempotency_key: true agent_key_allowed: false + /v1/invitations/{invitation_id}/resend: + post: + tags: + - members + summary: 'Send an open invitation again: a new link for 7 days, and the old link stops working' + operationId: resend_invitation + parameters: + - name: invitation_id + in: path + required: true + schema: + type: string + title: Invitation 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/Invitation' + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/Conflict' + '410': + $ref: '#/components/responses/Gone' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + security: + - bearerAuth: [] + - apiKeyHeader: [] + x-required-scope: member:admin + x-llm: + scope: member:admin + mutating: true + idempotency_key: true + agent_key_allowed: false + /v1/invitations/{invitation_id}/link: + post: + tags: + - members + summary: Make a new link for an open invitation, to hand over yourself (the old link stops working) + description: 'No mail is sent. The link is shown once, like a key''s secret: the server keeps only its hash. + It joins the organization only for a person signed in with the invited address.' + operationId: link_invitation + parameters: + - name: invitation_id + in: path + required: true + schema: + type: string + title: Invitation 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/InvitationLink' + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/Conflict' + '410': + $ref: '#/components/responses/Gone' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + security: + - bearerAuth: [] + - apiKeyHeader: [] + x-required-scope: member:admin + x-llm: + scope: member:admin + mutating: true + idempotency_key: true + agent_key_allowed: false /v1/invitations/{invitation_id}: delete: tags: @@ -4045,7 +4628,11 @@ paths: anyOf: - type: string - type: 'null' + description: pending, approved, used, rejected, revoked or expired. used finds the approvals a send consumed; + their status reads approved and consumed_by_job_id names the fax. title: Status + description: pending, approved, used, rejected, revoked or expired. used finds the approvals a send consumed; + their status reads approved and consumed_by_job_id names the fax. - name: cursor in: query required: false @@ -4200,7 +4787,7 @@ paths: post: tags: - approvals - summary: Reject with a reason + summary: Reject with a reason (a help request closes without one) operationId: reject_request parameters: - name: approval_id @@ -4316,6 +4903,54 @@ paths: mutating: true idempotency_key: true agent_key_allowed: false + /v1/policy-rule-checks: + post: + tags: + - policies + summary: Check a draft's destination lists against each other. Writes nothing + description: 'For the editor of a policy: which numbers of allowed_destinations are already allowed by one + of allowed_countries or allowed_country_prefixes. Routed with the rate card, the way an evaluation routes + a destination. Entries that are not numbers the card serves are left out. Nothing is stored and no policy + is read. Idempotency-Key is accepted but ignored: a repeat checks the lists again.' + operationId: create_policy_rule_check + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/PolicyRuleCheckCreate' + required: true + responses: + '200': + description: Successful Response + content: + application/json: + schema: + $ref: '#/components/schemas/PolicyRuleCheck' + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + '413': + $ref: '#/components/responses/PayloadTooLarge' + '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: policy:read + x-llm: + scope: policy:read + mutating: false + idempotency_key: false + agent_key_allowed: true /v1/policies: get: tags: @@ -4728,7 +5363,7 @@ paths: post: tags: - policies - summary: 'Dry run: would the calling key''s policies allow this send? Never executes' + summary: 'Dry run: would the policies of the caller, or of a named key, agent or app, allow this send?' operationId: create_policy_evaluation requestBody: required: true @@ -4785,6 +5420,16 @@ paths: - agents summary: List agent identities operationId: list_agents + parameters: + - name: include_archived + in: query + required: false + schema: + type: boolean + description: Also list archived agents. + default: false + title: Include Archived + description: Also list archived agents. responses: '200': description: Successful Response @@ -4798,6 +5443,8 @@ paths: $ref: '#/components/responses/Forbidden' '410': $ref: '#/components/responses/Gone' + '422': + $ref: '#/components/responses/UnprocessableContent' '429': $ref: '#/components/responses/TooManyRequests' '404': @@ -4968,11 +5615,62 @@ paths: mutating: true idempotency_key: true agent_key_allowed: false + delete: + tags: + - agents + summary: 'Archive an agent: its keys are revoked, it leaves the list and its name is free again' + operationId: archive_agent + parameters: + - name: agent_id + in: path + required: true + schema: + type: string + title: Agent 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/AgentArchived' + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/Conflict' + '410': + $ref: '#/components/responses/Gone' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + security: + - bearerAuth: [] + - apiKeyHeader: [] + x-required-scope: agent:admin + x-llm: + scope: agent:admin + mutating: true + idempotency_key: true + agent_key_allowed: false /v1/agents/{agent_id}/keys: post: tags: - agents - summary: Mint a key for the agent (bounded scopes, secret shown once) + summary: Create a key for the agent (bounded scopes, secret shown once) operationId: create_agent_key parameters: - name: agent_id @@ -5122,6 +5820,16 @@ paths: type: string - type: 'null' title: Status + - name: archived + in: query + required: false + schema: + anyOf: + - type: boolean + - type: 'null' + description: false leaves archived faxes out; true lists only those. + title: Archived + description: false leaves archived faxes out; true lists only those. responses: '200': description: Successful Response @@ -5259,7 +5967,7 @@ paths: delete: tags: - inbox - summary: Delete a received fax + summary: 'Delete a received fax: its file and the text read from it' operationId: delete_inbox_item parameters: - name: inbox_id @@ -5654,6 +6362,60 @@ paths: mutating: false idempotency_key: false agent_key_allowed: true + /v1/number-orders/{order_id}/dismissals: + post: + tags: + - numbers + summary: Put a failed number order away + description: Sets dismissed_at on an order that failed. The order stays in the list. An order that did not + fail answers 409 conflict. + operationId: dismiss_number_order + parameters: + - name: order_id + in: path + required: true + schema: + type: string + title: Order 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/NumberOrder' + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/Conflict' + '410': + $ref: '#/components/responses/Gone' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + security: + - bearerAuth: [] + - apiKeyHeader: [] + x-required-scope: number:buy + x-llm: + scope: number:buy + mutating: true + idempotency_key: true + agent_key_allowed: false /v1/numbers: get: tags: @@ -6891,6 +7653,80 @@ paths: agent_key_allowed: true hint: Read enabled first. The routes and their prices are present only while the product is open here. description: No API key is needed. + /v1/one-time-sends/preview: + post: + tags: + - one-time-sends + summary: Count the pages of a document before an order is made + 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.' + operationId: preview_one_time_document + requestBody: + content: + multipart/form-data: + schema: + properties: + file: + type: string + format: binary + description: 'The document: PDF, PNG, JPEG or TIFF. Send this or text.' + text: + type: string + description: The text of the fax, in place of a file. + text_format: + type: string + enum: + - text + - markdown + type: object + application/json: + schema: + properties: + text: + type: string + description: The text of the fax. + text_format: + type: string + enum: + - text + - markdown + type: object + required: + - text + required: true + responses: + '200': + description: Successful Response + content: + application/json: + schema: + $ref: '#/components/schemas/OneTimeInspection' + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + '413': + $ref: '#/components/responses/PayloadTooLarge' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + '503': + $ref: '#/components/responses/ServiceUnavailable' + security: + - {} + - bearerAuth: [] + - apiKeyHeader: [] + x-required-scope: fax:send + x-llm: + scope: fax:send + mutating: false + idempotency_key: false + agent_key_allowed: true + key_optional: true /v1/one-time-sends: post: tags: @@ -7490,6 +8326,74 @@ paths: idempotency_key: false agent_key_allowed: true order_token: true + /v1/one-time-sends/{one_time_order_id}/pages/{page_number}: + get: + tags: + - one-time-sends + summary: 'One page of a one-time order as a picture: the cover sheet, then the document' + description: Page 1 is the cover sheet. Before the fax is released the cover is drawn from the order as it + will be printed, and the other pages from the uploaded document. After the release the pages are the file + that went to the carrier. order.preview says how many pages can be asked for. 404 not_found for a page that + does not exist or a copy that is no longer held (deleted after the send, or after its retention). A key + or session of the order's organization may read it, and so may the status token, as the header or as ?t=. + operationId: get_one_time_order_page + parameters: + - name: one_time_order_id + in: path + required: true + schema: + type: string + title: One Time Order Id + - name: page_number + in: path + required: true + schema: + type: integer + title: Page Number + - name: t + in: query + required: false + schema: + anyOf: + - type: string + - type: 'null' + description: The status token, when no header carries it. + title: T + description: The status token, when no header carries it. + - name: X-FFA-Order-Token + in: header + required: false + schema: + type: string + description: The status token of the order, for a caller without a key or a session. + responses: + '200': + description: The page as a PNG + content: + image/png: {} + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + '410': + $ref: '#/components/responses/Gone' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + security: + - bearerAuth: [] + - apiKeyHeader: [] + - orderToken: [] + x-required-scope: fax:read + x-llm: + scope: fax:read + mutating: false + idempotency_key: false + agent_key_allowed: true + order_token: true /v1/one-time-sends/{one_time_order_id}/checkout: post: tags: @@ -7988,6 +8892,12 @@ components: - type: string - type: 'null' title: Disabled At + archived_at: + anyOf: + - type: string + - type: 'null' + title: Archived At + description: 'Set on an archived agent: disabled for good and left out of the list.' additionalProperties: true type: object required: @@ -8015,6 +8925,11 @@ components: actor: type: string title: Actor + actor_label: + type: string + title: Actor Label + description: 'The actor in words: a member''s email, the agent''s name, an API key''s prefix.' + default: unknown action: type: string title: Action @@ -8067,6 +8982,29 @@ components: required: - items title: AgentActivityPage + AgentArchived: + properties: + id: + type: string + title: Id + deleted: + type: boolean + title: Deleted + description: 'Always false: an agent has history and its row is kept.' + archived: + type: boolean + title: Archived + keys_revoked: + type: integer + title: Keys Revoked + additionalProperties: true + type: object + required: + - id + - deleted + - archived + - keys_revoked + title: AgentArchived AgentCreate: properties: name: @@ -8181,7 +9119,31 @@ components: title: Contact Email additionalProperties: false type: object - title: AgentUpdate + title: AgentUpdate + AlreadyAllowed: + properties: + number: + type: string + title: Number + countries: + items: + type: string + type: array + title: Countries + description: The listed countries whose route serves this number. + prefixes: + items: + type: string + type: array + title: Prefixes + description: The listed prefixes this number's route carries. + additionalProperties: true + type: object + required: + - number + - countries + - prefixes + title: AlreadyAllowed ApiKey: properties: id: @@ -8404,6 +9366,39 @@ components: additionalProperties: false type: object title: ApprovalDecision + ApprovalDocument: + properties: + id: + type: string + title: Id + filename: + anyOf: + - type: string + - type: 'null' + title: Filename + description: The file's name; null when the document row is gone. + page_count: + anyOf: + - type: integer + - type: 'null' + title: Page Count + state: + type: string + enum: + - available + - deleted + - changed + title: State + description: 'available: the document is the one the request binds. deleted: it was deleted. changed: + its sha256 is no longer the bound one. A send with this approval is refused in the last two.' + additionalProperties: true + type: object + required: + - id + - filename + - page_count + - state + title: ApprovalDocument ApprovalRequest: properties: id: @@ -8441,11 +9436,29 @@ components: requested_by: type: string title: Requested By + requested_by_name: + anyOf: + - type: string + - type: 'null' + title: Requested By Name + description: 'The requester as people read it: the key''s label, the agent''s name, the connected app''s + name or the person''s address. null when the actor has no row in the organization any more.' decided_by: anyOf: - type: string - type: 'null' title: Decided By + decided_by_name: + anyOf: + - type: string + - type: 'null' + title: Decided By Name + description: The decider, named the same way. + document: + anyOf: + - $ref: '#/components/schemas/ApprovalDocument' + - type: 'null' + description: The document a send request binds (bound.document_id). null for a help request. reason: anyOf: - type: string @@ -8816,6 +9829,12 @@ components: held_micro: type: integer title: Held Micro + held_jobs: + type: integer + title: Held Jobs + description: 'How many fax jobs still have their hold in place: queued, sending, or ended unknown and + waiting for a reconcile. Their holds add up to held_micro.' + default: 0 top_up_url: anyOf: - type: string @@ -8835,6 +9854,7 @@ components: currency: USD available_micro: 100000000 held_micro: 0 + held_jobs: 0 top_up_url: https://app.faxforagents.com/app/billing BillingSettings: properties: @@ -8948,6 +9968,12 @@ components: updated_at: type: string title: Updated At + archived_at: + anyOf: + - type: string + - type: 'null' + title: Archived At + description: Set on a removed budget that has history. It is disabled for good. additionalProperties: true type: object required: @@ -9032,6 +10058,26 @@ components: additionalProperties: false type: object title: BudgetPatch + BudgetRemoved: + properties: + id: + type: string + title: Id + deleted: + type: boolean + title: Deleted + description: True when the budget never charged a hold and its row is gone. + archived: + type: boolean + title: Archived + description: 'True when the budget has history: disabled and hidden, row kept.' + additionalProperties: true + type: object + required: + - id + - deleted + - archived + title: BudgetRemoved Capabilities: properties: environment: @@ -9082,6 +10128,19 @@ components: title: Scopes description: 'Every scope the platform defines, the list a new key is made from. It is not what the calling credential holds: GET /v1/me returns that under scopes.' + default_scopes: + items: + type: string + type: array + title: Default Scopes + description: The scopes a key gets when POST /v1/api-keys names none. + admin_scopes: + items: + type: string + type: array + title: Admin Scopes + 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: type: boolean title: Approvals @@ -9272,6 +10331,60 @@ components: - excluded - note title: Coverage + DataRequest: + properties: + id: + type: string + title: Id + kind: + type: string + enum: + - export + - deletion + title: Kind + status: + type: string + enum: + - open + - closed + - withdrawn + title: Status + description: open until a person at Fax for Agents answers it; withdrawn by an owner; else closed. + created_at: + type: string + title: Created At + due_at: + type: string + title: Due At + description: '30 days after the request: when it is answered at the latest.' + closed_at: + anyOf: + - type: string + - type: 'null' + title: Closed At + additionalProperties: true + type: object + required: + - id + - kind + - status + - created_at + - due_at + - closed_at + title: DataRequest + description: An export or deletion request of the organization and where it stands. + DataRequestList: + properties: + items: + items: + $ref: '#/components/schemas/DataRequest' + type: array + title: Items + additionalProperties: true + type: object + required: + - items + title: DataRequestList Deleted: properties: id: @@ -9294,6 +10407,12 @@ components: webhook_id: type: string title: Webhook Id + webhook_url: + anyOf: + - type: string + - type: 'null' + title: Webhook Url + description: The destination's URL, kept after the destination is deleted. event_id: type: string title: Event Id @@ -9362,6 +10481,108 @@ components: - created_at - delivered_at title: Delivery + DeliveryDetail: + properties: + id: + type: string + title: Id + webhook_id: + type: string + title: Webhook Id + webhook_url: + anyOf: + - type: string + - type: 'null' + title: Webhook Url + description: The destination's URL, kept after the destination is deleted. + event_id: + type: string + title: Event Id + event_type: + type: string + title: Event Type + attempt: + type: integer + title: Attempt + status: + type: string + title: Status + response_status: + anyOf: + - type: integer + - type: 'null' + title: Response Status + error: + anyOf: + - type: string + - type: 'null' + title: Error + duration_ms: + anyOf: + - type: integer + - type: 'null' + title: Duration Ms + replay_of: + anyOf: + - type: string + - type: 'null' + title: Replay Of + schedule_s: + items: + type: integer + type: array + title: Schedule S + next_attempt_at: + anyOf: + - type: string + - type: 'null' + title: Next Attempt At + created_at: + type: string + title: Created At + delivered_at: + anyOf: + - type: string + - type: 'null' + title: Delivered At + webhook_deleted: + type: boolean + title: Webhook Deleted + description: True when the destination was deleted since. + request_headers: + additionalProperties: + type: string + type: object + title: Request Headers + 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: + additionalProperties: true + type: object + title: Payload + description: The JSON body that is sent, the same at every attempt. + additionalProperties: true + type: object + required: + - id + - webhook_id + - event_id + - event_type + - attempt + - status + - response_status + - error + - duration_ms + - replay_of + - schedule_s + - next_attempt_at + - created_at + - delivered_at + - webhook_deleted + - request_headers + - payload + title: DeliveryDetail DeliveryPage: properties: items: @@ -9423,6 +10644,15 @@ components: additionalProperties: true type: object title: Validation + converted_from: + anyOf: + - type: string + - type: 'null' + title: Converted From + received: + anyOf: + - $ref: '#/components/schemas/DocumentReceived' + - type: 'null' upload_id: anyOf: - type: string @@ -9475,6 +10705,8 @@ components: render_reason: null validation: warnings: [] + converted_from: null + received: null upload_id: up_01a1dba3f80475159f9195dc92d38428 created_at: '2026-11-14T19:58:38.630Z' expires_at: '2026-12-14T19:58:38.739Z' @@ -9532,6 +10764,11 @@ components: - type: string - type: 'null' title: Next Cursor + total: + anyOf: + - type: integer + - type: 'null' + title: Total additionalProperties: true type: object required: @@ -9567,6 +10804,39 @@ components: - render_reason - items title: DocumentPages + DocumentReceived: + properties: + inbox_item_id: + type: string + title: Inbox Item Id + from: + anyOf: + - type: string + - type: 'null' + title: From + received_at: + type: string + title: Received At + additionalProperties: true + type: object + required: + - inbox_item_id + - received_at + title: DocumentReceived + description: The received fax a document is the file of. + DocumentUpdate: + properties: + filename: + type: string + maxLength: 255 + minLength: 1 + title: Filename + description: 'The new file name. The stored file is a PDF: a name without .pdf gets it added.' + additionalProperties: false + type: object + required: + - filename + title: DocumentUpdate DocumentValidation: properties: id: @@ -10493,6 +11763,11 @@ components: type: string title: Media Status default: stored + file_deleted_at: + anyOf: + - type: string + - type: 'null' + title: File Deleted At duration_secs: anyOf: - type: integer @@ -10583,6 +11858,11 @@ components: type: string title: Media Status default: stored + file_deleted_at: + anyOf: + - type: string + - type: 'null' + title: File Deleted At duration_secs: anyOf: - type: integer @@ -10643,6 +11923,7 @@ components: project_id: proj_01a1dba3f790751897c1a738a5631341 partial_content: false media_status: stored + file_deleted_at: null duration_secs: null provider: sandbox read_at: null @@ -10771,6 +12052,10 @@ components: - type: string - type: 'null' title: Next Cursor + unread: + type: integer + title: Unread + default: 0 additionalProperties: true type: object required: @@ -10792,11 +12077,13 @@ components: project_id: proj_01a1dba3f790751897c1a738a5631341 partial_content: false media_status: stored + file_deleted_at: null duration_secs: null provider: sandbox read_at: null expires_at: '2027-02-12T19:58:39.009Z' next_cursor: null + unread: 1 InboxUpdate: properties: status: @@ -10824,6 +12111,7 @@ components: - type: string - type: 'null' title: Locality + description: 'The area that was searched for. Null in test: test numbers are made up and have no city.' items: items: $ref: '#/components/schemas/InventoryNumber' @@ -10870,6 +12158,11 @@ components: setup_micro: type: integer title: Setup Micro + owned: + type: boolean + title: Owned + description: True when your organization already holds this number. An order of it is refused. + default: false additionalProperties: true type: object required: @@ -10940,8 +12233,27 @@ components: additionalProperties: false type: object required: - - email - title: InvitationCreate + - email + title: InvitationCreate + InvitationLink: + properties: + id: + type: string + title: Id + url: + type: string + title: Url + description: The new invitation link. Shown once. + expires_at: + type: string + title: Expires At + additionalProperties: true + type: object + required: + - id + - url + - expires_at + title: InvitationLink InvitationList: properties: items: @@ -11387,6 +12699,12 @@ components: - type: string - type: 'null' title: Completed At + dismissed_at: + anyOf: + - type: string + - type: 'null' + title: Dismissed At + description: When a person put this failed order away. Null until then. additionalProperties: true type: object required: @@ -11477,6 +12795,40 @@ components: additionalProperties: false type: object title: NumberUpdate + OneTimeAttempts: + properties: + made: + type: integer + title: Made + max: + type: integer + title: Max + last_failure_code: + anyOf: + - type: string + - type: 'null' + title: Last Failure Code + last_finished_at: + anyOf: + - type: string + - type: 'null' + title: Last Finished At + retry_delay_seconds: + type: integer + title: Retry Delay Seconds + additionalProperties: true + type: object + required: + - made + - max + - last_failure_code + - last_finished_at + - retry_delay_seconds + 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. OneTimeCard: properties: last4: @@ -11748,6 +13100,31 @@ components: - quote_id - sender_name title: OneTimeFromQuote + OneTimeInspection: + properties: + document_pages: + type: integer + title: Document Pages + thumbnail_png_base64: + anyOf: + - type: string + - type: 'null' + title: Thumbnail Png Base64 + warnings: + items: + additionalProperties: true + type: object + type: array + title: Warnings + additionalProperties: true + type: object + required: + - document_pages + - 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. OneTimeJob: properties: order_id: @@ -11797,6 +13174,44 @@ components: anyOf: - $ref: '#/components/schemas/OneTimeCard' - type: 'null' + sender_name: + anyOf: + - type: string + - type: 'null' + title: Sender Name + description: 'On a receipt: the sender''s name.' + email: + anyOf: + - type: string + - type: 'null' + title: Email + description: 'On a receipt: the address the order was made with.' + authorized_at: + anyOf: + - type: string + - type: 'null' + title: Authorized At + description: 'On a receipt: when the card was held.' + settled_at: + anyOf: + - type: string + - type: 'null' + title: Settled At + description: 'On a receipt: when the payment provider confirmed the charge, or the release.' + failure_code: + anyOf: + - type: string + - type: 'null' + title: Failure Code + description: 'On a receipt: why the order ended unpaid.' + price: + anyOf: + - additionalProperties: + type: integer + type: object + - type: 'null' + title: Price + description: 'On a receipt: flat_micro, included_pages and extra_page_micro the amount follows from.' additionalProperties: true type: object required: @@ -12011,6 +13426,18 @@ components: - type: 'null' title: Fax description: The fax job (the FaxJob shape) once the order was released; null before. + attempts: + 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.' + preview: + anyOf: + - $ref: '#/components/schemas/OneTimePreview' + - type: 'null' + 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: type: string title: Created At @@ -12263,6 +13690,18 @@ components: - type: 'null' title: Fax description: The fax job (the FaxJob shape) once the order was released; null before. + attempts: + 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.' + preview: + anyOf: + - $ref: '#/components/schemas/OneTimePreview' + - type: 'null' + 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: type: string title: Created At @@ -12331,6 +13770,35 @@ components: required: - items title: OneTimeOrderPage + OneTimePreview: + properties: + state: + type: string + enum: + - draft + - sent + - deleted + - unavailable + title: State + pages: + type: integer + title: Pages + cover_pages: + type: integer + title: Cover Pages + additionalProperties: true + type: object + required: + - state + - pages + - cover_pages + title: OneTimePreview + description: |- + Whether the pages of an order can be looked at, and how many. ``draft``: the cover sheet as it + will be printed and the uploaded document, before the fax is released. ``sent``: the file that went + to the carrier, cover sheet first. ``deleted``: no copy is held any more (the sender asked for the + deletion, the retention ended, or the order ended before a fax was made). ``unavailable``: nothing + to show right now. Page ``n`` is ``GET /v1/one-time-sends/{id}/pages/{n}``, 1 to ``pages``. OneTimePrice: properties: price_version: @@ -12372,6 +13840,13 @@ components: estimated_wait_minutes: type: integer title: Estimated Wait Minutes + paused: + type: boolean + title: Paused + description: An operator has paused sends on this route. A fax to it is kept and goes out when the route + is resumed; no time can be estimated. A one-time order that is not sent within 48 hours of its release + is canceled and the card is not charged. + default: false additionalProperties: true type: object required: @@ -12458,7 +13933,7 @@ components: properties: name: type: string - maxLength: 200 + maxLength: 80 minLength: 1 title: Name additionalProperties: false @@ -12482,6 +13957,13 @@ components: - member - viewer title: Role + suspended_at: + anyOf: + - type: string + - type: 'null' + title: Suspended At + description: Set while a review has paused sending for the whole organization. A send answers `account_suspended` + until it is cleared. Reads keep working. additionalProperties: true type: object required: @@ -12698,6 +14180,27 @@ components: type: boolean title: Executed default: false + subject: + anyOf: + - type: string + - type: 'null' + title: Subject + description: 'The caller the plan was evaluated for: the calling principal, or the key, agent or connected + app the request named.' + under_policy: + anyOf: + - type: boolean + - type: 'null' + title: Under Policy + description: Whether any policy binds that caller. false with decision deny means no policy applies, not + that a policy refused the plan. + approval_required: + anyOf: + - type: boolean + - 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.' usage: type: - object @@ -12748,6 +14251,29 @@ components: maxLength: 32 - type: 'null' title: From + key_id: + anyOf: + - type: string + pattern: ^[a-z]{2,8}_[0-9a-f]{32}$ + - type: 'null' + title: Key Id + description: Evaluate as this API key of your organization instead of the caller, in the key's environment. + Choose at most one of key_id, agent_id and connection_id. + agent_id: + anyOf: + - type: string + pattern: ^[a-z]{2,8}_[0-9a-f]{32}$ + - type: 'null' + title: Agent Id + description: Evaluate as this agent of your organization (bindings to single keys excluded). + connection_id: + anyOf: + - type: string + pattern: ^[a-z]{2,8}_[0-9a-f]{32}$ + - type: 'null' + title: Connection Id + description: Evaluate as this connected app (an OAuth grant, GET /v1/oauth/grants), in the connection's + environment. A signed-in person may name their own. additionalProperties: false type: object title: PolicyEvaluationCreate @@ -12763,6 +14289,43 @@ components: required: - items title: PolicyList + PolicyRuleCheck: + properties: + already_allowed: + items: + $ref: '#/components/schemas/AlreadyAllowed' + type: array + title: Already Allowed + 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. + additionalProperties: true + type: object + required: + - already_allowed + title: PolicyRuleCheck + PolicyRuleCheckCreate: + properties: + allowed_destinations: + items: + type: string + type: array + maxItems: 500 + title: Allowed Destinations + allowed_countries: + items: + type: string + type: array + maxItems: 300 + title: Allowed Countries + allowed_country_prefixes: + items: + type: string + type: array + maxItems: 300 + title: Allowed Country Prefixes + additionalProperties: false + type: object + title: PolicyRuleCheckCreate PolicyUpdate: properties: name: @@ -12821,6 +14384,12 @@ components: created_by: type: string title: Created By + created_by_name: + anyOf: + - type: string + - type: 'null' + title: Created By Name + description: 'Who wrote the version as people read it: a person''s address or a key''s label.' created_at: type: string title: Created At @@ -13073,6 +14642,12 @@ components: authorization_required: type: boolean title: Authorization Required + route_paused: + type: boolean + title: Route Paused + 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. + default: false warnings: items: additionalProperties: true @@ -13149,6 +14724,7 @@ components: sender_name: null delete_after_send: false authorization_required: false + route_paused: false warnings: - code: sandbox message: 'test key: sandbox provider, not charged' @@ -13239,6 +14815,12 @@ components: - type: string - type: 'null' title: From + sender_name: + anyOf: + - type: string + - type: 'null' + title: Sender Name + description: The sender name the fax was sent with, when one was given. document_sha256: type: string title: Document Sha256 @@ -13270,6 +14852,12 @@ components: provider: type: string title: Provider + provider_ref: + anyOf: + - type: string + - type: 'null' + title: Provider Ref + description: The carrier's own reference for the last attempt, when it gave one. created_at: type: string title: Created At @@ -13295,6 +14883,11 @@ components: generated_at: type: string title: Generated At + seller: + anyOf: + - $ref: '#/components/schemas/Seller' + - type: 'null' + description: The company that issues the receipt. one_time: anyOf: - $ref: '#/components/schemas/OneTimeJob' @@ -13331,6 +14924,7 @@ components: failure_code: null to: '+15550000001' from: null + sender_name: null document_sha256: c00b74dede1923d27ba294643d5e79cb5454089e3f1b7b151cc46aa520a2410f transmitted_sha256: 9f18c276fb5160f70fecb50f8e53768a7aa631e3e2a140447d3cb4f0377eb6e4 billable_pages: 2 @@ -13340,6 +14934,7 @@ components: captured_micro: 0 currency: USD provider: sandbox + provider_ref: sbx_311dd5d5bc5dfd76 created_at: '2026-11-14T19:58:38.794Z' completed_at: '2026-11-14T19:58:38.910Z' evidence: @@ -13376,6 +14971,11 @@ components: finished_at: '2026-11-14T19:58:38.907Z' note: Delivery evidence as the carrier reported it. It is not legal proof of acceptance by the recipient. generated_at: '2026-11-14T19:58:38.943Z' + seller: + name: JSB Holdings LLC + address: 8 The Green, Dover, DE 19901, US + product: Fax for Agents + email: hello@faxforagents.com one_time: null ReleaseRequest: properties: @@ -13402,6 +15002,17 @@ components: message: type: string title: Message + id: + anyOf: + - type: string + - type: 'null' + title: Id + description: The request, as `GET .../data-requests` lists it. + created_at: + anyOf: + - type: string + - type: 'null' + title: Created At additionalProperties: true type: object required: @@ -13554,6 +15165,29 @@ components: - name - schema title: SchemaCreate + Seller: + properties: + name: + type: string + title: Name + address: + type: string + title: Address + product: + type: string + title: Product + email: + type: string + title: Email + additionalProperties: true + type: object + required: + - name + - address + - product + - email + title: Seller + description: The company a receipt is issued by. SenderVerification: properties: id: @@ -13670,6 +15304,80 @@ components: - expires_at - content_type title: SignedUrl + StatementLine: + properties: + id: + type: string + title: Id + created_at: + type: string + title: Created At + type: + type: string + enum: + - topup + - fax + - received_fax + - number + - extraction + - release + - refund + - dispute + - credit + - adjustment + - other + title: Type + description: + type: string + title: Description + description: What happened, in plain words. Never an account name. + amount_micro: + type: integer + title: Amount Micro + description: 'Signed the way the wallet moved: positive is money in.' + balance_after_micro: + type: integer + title: Balance After Micro + description: The available balance right after this line. + ref_type: + anyOf: + - type: string + - type: 'null' + title: Ref Type + ref_id: + anyOf: + - type: string + - type: 'null' + title: Ref Id + additionalProperties: true + type: object + required: + - id + - created_at + - type + - description + - amount_micro + - balance_after_micro + - ref_type + - ref_id + title: StatementLine + StatementPage: + properties: + items: + items: + $ref: '#/components/schemas/StatementLine' + type: array + title: Items + next_cursor: + anyOf: + - type: string + - type: 'null' + title: Next Cursor + additionalProperties: true + type: object + required: + - items + title: StatementPage Subscription: properties: id: @@ -14221,6 +15929,12 @@ components: status: type: string title: Status + failing: + type: boolean + title: Failing + description: True when the latest delivery this destination was sent did not get a 2xx answer. It turns + false with the next delivery that does. + default: false previous_secret_expires_at: anyOf: - type: string @@ -14252,6 +15966,7 @@ components: - fax.delivered - fax.failed status: active + failing: false previous_secret_expires_at: null created_at: '2026-11-14T19:58:39.486Z' updated_at: '2026-11-14T19:58:39.486Z' @@ -14350,6 +16065,12 @@ components: status: type: string title: Status + failing: + type: boolean + title: Failing + description: True when the latest delivery this destination was sent did not get a 2xx answer. It turns + false with the next delivery that does. + default: false previous_secret_expires_at: anyOf: - type: string @@ -14386,6 +16107,7 @@ components: - fax.delivered - fax.failed status: active + failing: false previous_secret_expires_at: null created_at: '2026-11-14T19:58:39.486Z' updated_at: '2026-11-14T19:58:39.486Z' diff --git a/src/faxforagents/__init__.py b/src/faxforagents/__init__.py index 5449f3d..5921c66 100644 --- a/src/faxforagents/__init__.py +++ b/src/faxforagents/__init__.py @@ -18,7 +18,7 @@ from __future__ import annotations -__version__ = "0.6.1" +__version__ = "0.7.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 88aa676..95aa5a2 100644 --- a/src/faxforagents/async_client.py +++ b/src/faxforagents/async_client.py @@ -175,20 +175,58 @@ async def upload( await self.complete_upload(session.id, sha256=hashlib.sha256(data).hexdigest()) return await self.create(upload_id=session.id, filename=name) - async def list(self, *, cursor: str | None = None, limit: int | None = None) -> m.DocumentPage: - """Documents, newest first. Scope: document:read.""" - return await self._h.request( - "GET", "/v1/documents", model=m.DocumentPage, params={"cursor": cursor, "limit": limit} - ) + async def list( + self, + *, + source: str | None = None, + exclude_source: str | None = None, + q: str | None = None, + cursor: str | None = None, + limit: int | None = None, + ) -> m.DocumentPage: + """Documents, newest first. ``total`` counts every document that matches. Scope: document:read. - def iter(self, *, limit: int | None = None) -> AsyncIterator[m.Document]: - """Every document, following next_cursor.""" - return apaginate(self.list, {"limit": limit}) + ``source`` keeps one source: upload, image, text, markdown, html or inbound, the files of received + faxes. ``exclude_source`` leaves one out. ``q`` finds part of a file name, or of the sender's number + for a received fax.""" + params = { + "source": source, + "exclude_source": exclude_source, + "q": q, + "cursor": cursor, + "limit": limit, + } + return await self._h.request("GET", "/v1/documents", model=m.DocumentPage, params=params) + + def iter( + self, + *, + source: str | None = None, + exclude_source: str | None = None, + q: str | None = None, + limit: int | None = None, + ) -> AsyncIterator[m.Document]: + """Every document that matches, following next_cursor.""" + params = {"source": source, "exclude_source": exclude_source, "q": q, "limit": limit} + return apaginate(self.list, params) async def get(self, document_id: str) -> m.Document: """Hash, pages and validation state. Scope: document:read.""" return await self._h.request("GET", f"/v1/documents/{document_id}", model=m.Document) + async def rename( + self, document_id: str, *, filename: str, idempotency_key: str | None = None + ) -> m.Document: + """Give a document a new file name. A name without ``.pdf`` gets it added. Scope: document:write.""" + body = m.DocumentUpdate(filename=filename) + return await self._h.request( + "PATCH", + f"/v1/documents/{document_id}", + model=m.Document, + json=body, + idempotency_key=idempotency_key, + ) + async def delete(self, document_id: str, *, idempotency_key: str | None = None) -> m.Deleted: """Delete the document, its bytes and its previews. Scope: document:write.""" return await self._h.request( @@ -267,21 +305,33 @@ async def list( self, *, state: str | None = None, + q: str | None = None, idempotency_key: str | None = None, cursor: str | None = None, limit: int | None = None, ) -> m.FaxJobPage: """Fax jobs, newest first. Scope: fax:read. + ``q`` finds faxes by destination or by id. Text that starts with ``fax_`` is the start of a job + id. Anything else is read as a fax number in any spelling. It combines with ``state``. + ``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. """ - params = {"state": state, "idempotency_key": idempotency_key, "cursor": cursor, "limit": limit} + params = { + "state": state, + "q": q, + "idempotency_key": idempotency_key, + "cursor": cursor, + "limit": limit, + } return await self._h.request("GET", "/v1/faxes", model=m.FaxJobPage, params=params) - def iter(self, *, state: str | None = None, limit: int | None = None) -> AsyncIterator[m.FaxJob]: - """Every fax job, following next_cursor.""" - return apaginate(self.list, {"state": state, "limit": limit}) + def iter( + self, *, state: str | None = None, q: 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}) async def get(self, fax_id: str) -> m.FaxJob: """The job with its evidence once delivered or partial. Scope: fax:read.""" @@ -383,6 +433,11 @@ async def list_deliveries( params = {"webhook_id": webhook_id, "event_id": event_id, "cursor": cursor, "limit": limit} return await self._h.request("GET", "/v1/webhook-deliveries", model=m.DeliveryPage, params=params) + async def get_delivery(self, delivery_id: str) -> m.DeliveryDetail: + """One delivery with the headers and the JSON body that were sent. The signing secret is never in + it. Scope: webhook:admin.""" + return await self._h.request("GET", f"/v1/webhook-deliveries/{delivery_id}", model=m.DeliveryDetail) + async def replay_delivery(self, delivery_id: str, *, idempotency_key: str | None = None) -> m.Delivery: """Deliver the event again with the same event id. Scope: webhook:admin.""" return await self._h.request( @@ -423,6 +478,44 @@ def iter_ledger(self, *, limit: int | None = None) -> AsyncIterator[m.LedgerEntr """Every ledger entry, following next_cursor.""" return apaginate(self.list_ledger, {"limit": limit}) + async def statement( + self, + *, + kind: str | None = None, + from_: str | None = None, + to: str | None = None, + cursor: str | None = None, + limit: int | None = None, + ) -> m.StatementPage: + """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} + return await self._h.request("GET", "/v1/statement", model=m.StatementPage, params=params) + + def iter_statement( + self, + *, + 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}) + + async def statement_csv( + self, *, 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} + ) + return bytes(data).decode("utf-8") + async def get_settings(self) -> m.BillingSettings: """Billing settings of the organization. Scope: billing:read.""" return await self._h.request("GET", "/v1/billing-settings", model=m.BillingSettings) @@ -489,9 +582,11 @@ async def delete_auto_topup(self, auto_topup_id: str, *, idempotency_key: str | "DELETE", f"/v1/auto-topups/{auto_topup_id}", model=m.Deleted, idempotency_key=idempotency_key ) - async def list_budgets(self) -> m.BudgetList: - """Spending caps of this environment. Scope: billing:read.""" - return await self._h.request("GET", "/v1/budgets", model=m.BudgetList) + async def list_budgets(self, *, include_archived: bool | None = None) -> m.BudgetList: + """Spending caps of this environment. ``include_archived=True`` adds the removed caps that have + history. Scope: billing:read.""" + params = {"include_archived": include_archived} + return await self._h.request("GET", "/v1/budgets", model=m.BudgetList, params=params) async def create_budget(self, *, idempotency_key: str | None = None, **fields: Any) -> m.Budget: """A daily or monthly cap for the organization, a project or an agent. Scope: billing:write.""" @@ -509,6 +604,13 @@ async def patch_budget( "PATCH", f"/v1/budgets/{budget_id}", model=m.Budget, json=body, idempotency_key=idempotency_key ) + async def delete_budget(self, budget_id: str, *, idempotency_key: str | None = None) -> m.BudgetRemoved: + """Remove a cap. One that never charged a hold is deleted, one with history is archived. + Scope: billing:write, never an agent key.""" + return await self._h.request( + "DELETE", f"/v1/budgets/{budget_id}", model=m.BudgetRemoved, idempotency_key=idempotency_key + ) + async def usage( self, *, @@ -656,7 +758,10 @@ async def request_help( async def list( self, *, status: str | None = None, cursor: str | None = None, limit: int | None = None ) -> m.ApprovalRequestPage: - """Requests, pending first. Scope: approval:read.""" + """Requests, pending first. Scope: approval:read. + + ``status`` is pending, approved, used, rejected, revoked or expired. ``used`` finds the approvals a + send consumed. They read ``approved``, and ``consumed_by_job_id`` names the fax.""" params = {"status": status, "cursor": cursor, "limit": limit} return await self._h.request( "GET", "/v1/approval-requests", model=m.ApprovalRequestPage, params=params @@ -697,9 +802,10 @@ async def approve( ) async def reject( - self, approval_id: str, *, reason: str, idempotency_key: str | None = None + self, approval_id: str, *, reason: str | None = None, idempotency_key: str | None = None ) -> m.ApprovalRequest: - """Reject with a reason. Scope: approval:decide.""" + """Reject with a reason. A help request closes without one, a send request needs it. + Scope: approval:decide.""" body = m.ApprovalDecision(reason=reason) return await self._h.request( "POST", @@ -801,16 +907,53 @@ async def evaluate( document_id: str | None = None, to: str | None = None, from_: str | None = None, + key_id: str | None = None, + agent_id: str | None = None, + connection_id: str | None = None, ) -> m.PolicyEvaluation: - """Dry run: would this key's policies allow the send? Never executes. Scope: policy:read.""" - body = {"quote_id": quote_id, "document_id": document_id, "to": to, "from": from_} + """Dry run: would the policies allow the send? Never executes. Scope: policy:read. + + With none of ``key_id``, ``agent_id`` or ``connection_id`` the plan is evaluated for the calling + key. Pass one of them to evaluate it for another key, agent or connected app of the organization. + The answer names that caller in ``subject`` and says in ``approval_required`` whether a person + would have to approve the send.""" + body = { + "quote_id": quote_id, + "document_id": document_id, + "to": to, + "from": from_, + "key_id": key_id, + "agent_id": agent_id, + "connection_id": connection_id, + } return await self._h.request("POST", "/v1/policy-evaluations", model=m.PolicyEvaluation, json=body) + async def check_rules( + self, + *, + allowed_destinations: Sequence[str] | None = None, + allowed_countries: Sequence[str] | None = None, + allowed_country_prefixes: Sequence[str] | None = None, + ) -> m.PolicyRuleCheck: + """Check the destination lists of a draft policy against each other. Writes nothing. + Scope: policy:read. + + ``already_allowed`` names the numbers of ``allowed_destinations`` that a listed country or prefix + allows anyway. For those numbers the number list adds nothing.""" + lists = { + "allowed_destinations": allowed_destinations, + "allowed_countries": allowed_countries, + "allowed_country_prefixes": allowed_country_prefixes, + } + body = {name: list(values) for name, values in lists.items() if values is not None} + return await self._h.request("POST", "/v1/policy-rule-checks", model=m.PolicyRuleCheck, json=body) + class Agents(_Resource): - async def list(self) -> m.AgentList: - """Agent identities. Scope: agent:read.""" - return await self._h.request("GET", "/v1/agents", model=m.AgentList) + async def list(self, *, include_archived: bool | None = None) -> m.AgentList: + """Agent identities. ``include_archived=True`` adds the archived ones. Scope: agent:read.""" + params = {"include_archived": include_archived} + return await self._h.request("GET", "/v1/agents", model=m.AgentList, params=params) async def create(self, *, idempotency_key: str | None = None, **fields: Any) -> m.Agent: """Register an agent identity. Scope: agent:admin, never an agent key.""" @@ -830,6 +973,13 @@ async def update(self, agent_id: str, *, idempotency_key: str | None = None, **c "PATCH", f"/v1/agents/{agent_id}", model=m.Agent, json=body, idempotency_key=idempotency_key ) + async def archive(self, agent_id: str, *, idempotency_key: str | None = None) -> m.AgentArchived: + """Archive an agent for good. Its keys are revoked, it leaves the list and its name is free again. + Scope: agent:admin, never an agent key.""" + return await self._h.request( + "DELETE", f"/v1/agents/{agent_id}", model=m.AgentArchived, idempotency_key=idempotency_key + ) + async def create_key( self, agent_id: str, *, idempotency_key: str | None = None, **fields: Any ) -> m.ApiKeyWithSecret: @@ -854,15 +1004,19 @@ async def activity( class Inbox(_Resource): - async def list(self, *, cursor: str | None = None, limit: int | None = None) -> m.InboxPage: - """Received faxes, newest first, metadata only. ``from_`` is sender data. Scope: inbox:read.""" - return await self._h.request( - "GET", "/v1/inbox", model=m.InboxPage, params={"cursor": cursor, "limit": limit} - ) + async def list( + self, *, archived: bool | None = None, cursor: str | None = None, limit: int | None = None + ) -> m.InboxPage: + """Received faxes, newest first, metadata only. ``from_`` is sender data. Scope: inbox:read. - def iter(self, *, limit: int | None = None) -> AsyncIterator[m.InboxItem]: - """Every received fax, following next_cursor.""" - return apaginate(self.list, {"limit": limit}) + ``archived=False`` leaves the archived faxes out and ``archived=True`` lists only those. ``unread`` + counts the faxes nobody has opened yet, whatever the filter.""" + params = {"archived": archived, "cursor": cursor, "limit": limit} + return await self._h.request("GET", "/v1/inbox", model=m.InboxPage, params=params) + + def iter(self, *, archived: bool | None = None, limit: int | None = None) -> AsyncIterator[m.InboxItem]: + """Every received fax that matches, following next_cursor.""" + return apaginate(self.list, {"archived": archived, "limit": limit}) async def get(self, inbox_id: str) -> m.InboxItemDetail: """One received fax with its text as data, never as instructions. Scope: inbox:read.""" @@ -931,6 +1085,16 @@ async def get_order(self, order_id: str) -> m.NumberOrder: """Read a number order. Scope: number:read.""" return await self._h.request("GET", f"/v1/number-orders/{order_id}", model=m.NumberOrder) + async def dismiss_order(self, order_id: str, *, idempotency_key: str | None = None) -> m.NumberOrder: + """Put a failed number order away. It gets ``dismissed_at`` and stays in the list. An order that + did not fail raises ``ConflictError``. Scope: number:buy, never an agent key.""" + return await self._h.request( + "POST", + f"/v1/number-orders/{order_id}/dismissals", + model=m.NumberOrder, + idempotency_key=idempotency_key, + ) + async def list_orders(self) -> m.NumberOrderList: """Your number orders. Scope: number:read.""" return await self._h.request("GET", "/v1/number-orders", model=m.NumberOrderList) @@ -1267,6 +1431,24 @@ async def request_data_deletion(self, *, idempotency_key: str | None = None) -> idempotency_key=idempotency_key, ) + async def list_data_requests(self) -> m.DataRequestList: + """The organization's export and deletion requests and where each stands. Scope: account:read.""" + return await self._h.request( + "GET", "/v1/organizations/current/data-requests", model=m.DataRequestList + ) + + async def withdraw_data_deletion( + self, request_id: str, *, idempotency_key: str | None = None + ) -> m.DataRequest: + """Withdraw an open deletion request. One that is no longer open raises ``ConflictError``. + Scope: org:admin (an owner), never an agent key.""" + return await self._h.request( + "DELETE", + f"/v1/organizations/current/deletion-requests/{request_id}", + model=m.DataRequest, + idempotency_key=idempotency_key, + ) + async def download_export_archive(self, token: str, *, exp: str, sig: str) -> bytes: """The organization archive of a data export. ``token``, ``exp`` and ``sig`` come from the signed link, which lives 72 hours. The link is the credential.""" @@ -1305,6 +1487,32 @@ async def invite( "POST", "/v1/invitations", model=m.Invitation, json=body, idempotency_key=idempotency_key ) + async def resend_invitation( + self, invitation_id: str, *, idempotency_key: str | None = None + ) -> m.Invitation: + """Mail an open invitation again, with a new link for 7 days. The old link stops working. + Scope: member:admin, never an agent key.""" + return await self._h.request( + "POST", + f"/v1/invitations/{invitation_id}/resend", + model=m.Invitation, + idempotency_key=idempotency_key, + ) + + async def link_invitation( + self, invitation_id: str, *, idempotency_key: str | None = None + ) -> m.InvitationLink: + """A new link for an open invitation, to hand over yourself. No mail is sent, the old link stops + working and ``url`` is shown once. Scope: member:admin, never an agent key. + + The link joins the organization only for a person signed in with the invited address.""" + return await self._h.request( + "POST", + f"/v1/invitations/{invitation_id}/link", + model=m.InvitationLink, + idempotency_key=idempotency_key, + ) + async def revoke_invitation(self, invitation_id: str, *, idempotency_key: str | None = None) -> None: """Withdraw an invitation. Scope: member:admin, never an agent key.""" await self._h.request("DELETE", f"/v1/invitations/{invitation_id}", idempotency_key=idempotency_key) @@ -1338,6 +1546,38 @@ async def config(self) -> m.OneTimeConfig: """Whether one-time sends are open, with the card and the limits. No key needed.""" return await self._h.request("GET", "/v1/one-time-sends/config", model=m.OneTimeConfig) + async def preview( + self, + *, + file: bytes | str | Path | None = None, + filename: str | None = None, + content_type: str | None = None, + text: str | None = None, + text_format: str | None = None, + ) -> m.OneTimeInspection: + """Count the pages of a document before an order is made. Nothing is stored. It works without an + API key. + + Pass exactly one of ``file`` or ``text``, as for ``create``. The answer has ``document_pages`` and + the first page as a small PNG in ``thumbnail_png_base64``. A file the create would refuse raises + the same error here, such as ``too_many_pages`` or ``encrypted_pdf``. With a key: fax:send.""" + if (file is None) == (text is None): + raise ValueError("pass exactly one of file or text") + if file is None: + return await self._h.request( + "POST", + "/v1/one-time-sends/preview", + model=m.OneTimeInspection, + json={"text": text, "text_format": text_format}, + ) + name, data, ctype = one_time_file(file, filename, content_type) + return await self._h.request( + "POST", + "/v1/one-time-sends/preview", + model=m.OneTimeInspection, + files={"file": (name, data, ctype)}, + ) + async def create( self, *, @@ -1550,6 +1790,17 @@ async def resend_confirmation( idempotency_key=idempotency_key, ) + async def get_page(self, order_id: str, page_number: int, *, order_token: str | None = None) -> bytes: + """One page of the order as PNG bytes. Page 1 is the cover sheet, then the document follows. + + ``preview.pages`` on the order says how many pages there are. A page that is not held any more + raises ``NotFoundError``. Read it with a key of the order's organization (scope fax:read) or with + ``order_token``.""" + data = await self._h.request( + "GET", f"/v1/one-time-sends/{order_id}/pages/{page_number}", headers=token_header(order_token) + ) + return bytes(data) + async def get_receipt_pdf(self, order_id: str, *, order_token: str | None = None) -> bytes: """The receipt of the order's fax as a one-page PDF. 409 while the fax has not ended.""" data = await self._h.request( diff --git a/src/faxforagents/client.py b/src/faxforagents/client.py index 159f0af..074eeaf 100644 --- a/src/faxforagents/client.py +++ b/src/faxforagents/client.py @@ -224,20 +224,56 @@ def upload( self.complete_upload(session.id, sha256=hashlib.sha256(data).hexdigest()) return self.create(upload_id=session.id, filename=name) - def list(self, *, cursor: str | None = None, limit: int | None = None) -> m.DocumentPage: - """Documents, newest first. Scope: document:read.""" - return self._h.request( - "GET", "/v1/documents", model=m.DocumentPage, params={"cursor": cursor, "limit": limit} - ) + def list( + self, + *, + source: str | None = None, + exclude_source: str | None = None, + q: str | None = None, + cursor: str | None = None, + limit: int | None = None, + ) -> m.DocumentPage: + """Documents, newest first. ``total`` counts every document that matches. Scope: document:read. - def iter(self, *, limit: int | None = None) -> Iterator[m.Document]: - """Every document, following next_cursor.""" - return paginate(lambda p: self.list(**p), {"limit": limit}) + ``source`` keeps one source: upload, image, text, markdown, html or inbound, the files of received + faxes. ``exclude_source`` leaves one out. ``q`` finds part of a file name, or of the sender's number + for a received fax.""" + params = { + "source": source, + "exclude_source": exclude_source, + "q": q, + "cursor": cursor, + "limit": limit, + } + return self._h.request("GET", "/v1/documents", model=m.DocumentPage, params=params) + + def iter( + self, + *, + source: str | None = None, + exclude_source: str | None = None, + q: str | None = None, + limit: int | None = None, + ) -> Iterator[m.Document]: + """Every document that matches, following next_cursor.""" + params = {"source": source, "exclude_source": exclude_source, "q": q, "limit": limit} + return paginate(lambda p: self.list(**p), params) def get(self, document_id: str) -> m.Document: """Hash, pages and validation state. Scope: document:read.""" return self._h.request("GET", f"/v1/documents/{document_id}", model=m.Document) + def rename(self, document_id: str, *, filename: str, idempotency_key: str | None = None) -> m.Document: + """Give a document a new file name. A name without ``.pdf`` gets it added. Scope: document:write.""" + body = m.DocumentUpdate(filename=filename) + return self._h.request( + "PATCH", + f"/v1/documents/{document_id}", + model=m.Document, + json=body, + idempotency_key=idempotency_key, + ) + def delete(self, document_id: str, *, idempotency_key: str | None = None) -> m.Deleted: """Delete the document, its bytes and its previews. Scope: document:write.""" return self._h.request( @@ -314,21 +350,33 @@ def list( self, *, state: str | None = None, + q: str | None = None, idempotency_key: str | None = None, cursor: str | None = None, limit: int | None = None, ) -> m.FaxJobPage: """Fax jobs, newest first. Scope: fax:read. + ``q`` finds faxes by destination or by id. Text that starts with ``fax_`` is the start of a job + id. Anything else is read as a fax number in any spelling. It combines with ``state``. + ``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. """ - params = {"state": state, "idempotency_key": idempotency_key, "cursor": cursor, "limit": limit} + params = { + "state": state, + "q": q, + "idempotency_key": idempotency_key, + "cursor": cursor, + "limit": limit, + } return self._h.request("GET", "/v1/faxes", model=m.FaxJobPage, params=params) - def iter(self, *, state: str | None = None, limit: int | None = None) -> Iterator[m.FaxJob]: - """Every fax job, following next_cursor.""" - return paginate(lambda p: self.list(**p), {"state": state, "limit": limit}) + def iter( + self, *, state: str | None = None, q: 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}) def get(self, fax_id: str) -> m.FaxJob: """The job with its evidence once delivered or partial. Scope: fax:read.""" @@ -426,6 +474,11 @@ def list_deliveries( params = {"webhook_id": webhook_id, "event_id": event_id, "cursor": cursor, "limit": limit} return self._h.request("GET", "/v1/webhook-deliveries", model=m.DeliveryPage, params=params) + def get_delivery(self, delivery_id: str) -> m.DeliveryDetail: + """One delivery with the headers and the JSON body that were sent. The signing secret is never in + it. Scope: webhook:admin.""" + return self._h.request("GET", f"/v1/webhook-deliveries/{delivery_id}", model=m.DeliveryDetail) + def replay_delivery(self, delivery_id: str, *, idempotency_key: str | None = None) -> m.Delivery: """Deliver the event again with the same event id. Scope: webhook:admin.""" return self._h.request( @@ -466,6 +519,44 @@ def iter_ledger(self, *, limit: int | None = None) -> Iterator[m.LedgerEntry]: """Every ledger entry, following next_cursor.""" return paginate(lambda p: self.list_ledger(**p), {"limit": limit}) + def statement( + self, + *, + kind: str | None = None, + from_: str | None = None, + to: str | None = None, + cursor: str | None = None, + limit: int | None = None, + ) -> m.StatementPage: + """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} + return self._h.request("GET", "/v1/statement", model=m.StatementPage, params=params) + + def iter_statement( + self, + *, + 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} + ) + + def statement_csv( + self, *, 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}) + return bytes(data).decode("utf-8") + def get_settings(self) -> m.BillingSettings: """Billing settings of the organization. Scope: billing:read.""" return self._h.request("GET", "/v1/billing-settings", model=m.BillingSettings) @@ -528,9 +619,11 @@ def delete_auto_topup(self, auto_topup_id: str, *, idempotency_key: str | None = "DELETE", f"/v1/auto-topups/{auto_topup_id}", model=m.Deleted, idempotency_key=idempotency_key ) - def list_budgets(self) -> m.BudgetList: - """Spending caps of this environment. Scope: billing:read.""" - return self._h.request("GET", "/v1/budgets", model=m.BudgetList) + def list_budgets(self, *, include_archived: bool | None = None) -> m.BudgetList: + """Spending caps of this environment. ``include_archived=True`` adds the removed caps that have + history. Scope: billing:read.""" + params = {"include_archived": include_archived} + return self._h.request("GET", "/v1/budgets", model=m.BudgetList, params=params) def create_budget(self, *, idempotency_key: str | None = None, **fields: Any) -> m.Budget: """A daily or monthly cap for the organization, a project or an agent. Scope: billing:write.""" @@ -546,6 +639,13 @@ def patch_budget(self, budget_id: str, *, idempotency_key: str | None = None, ** "PATCH", f"/v1/budgets/{budget_id}", model=m.Budget, json=body, idempotency_key=idempotency_key ) + def delete_budget(self, budget_id: str, *, idempotency_key: str | None = None) -> m.BudgetRemoved: + """Remove a cap. One that never charged a hold is deleted, one with history is archived. + Scope: billing:write, never an agent key.""" + return self._h.request( + "DELETE", f"/v1/budgets/{budget_id}", model=m.BudgetRemoved, idempotency_key=idempotency_key + ) + def usage( self, *, @@ -689,7 +789,10 @@ def request_help( def list( self, *, status: str | None = None, cursor: str | None = None, limit: int | None = None ) -> m.ApprovalRequestPage: - """Requests, pending first. Scope: approval:read.""" + """Requests, pending first. Scope: approval:read. + + ``status`` is pending, approved, used, rejected, revoked or expired. ``used`` finds the approvals a + send consumed. They read ``approved``, and ``consumed_by_job_id`` names the fax.""" params = {"status": status, "cursor": cursor, "limit": limit} return self._h.request("GET", "/v1/approval-requests", model=m.ApprovalRequestPage, params=params) @@ -724,9 +827,10 @@ def approve( ) def reject( - self, approval_id: str, *, reason: str, idempotency_key: str | None = None + self, approval_id: str, *, reason: str | None = None, idempotency_key: str | None = None ) -> m.ApprovalRequest: - """Reject with a reason. Scope: approval:decide.""" + """Reject with a reason. A help request closes without one, a send request needs it. + Scope: approval:decide.""" body = m.ApprovalDecision(reason=reason) return self._h.request( "POST", @@ -826,16 +930,53 @@ def evaluate( document_id: str | None = None, to: str | None = None, from_: str | None = None, + key_id: str | None = None, + agent_id: str | None = None, + connection_id: str | None = None, ) -> m.PolicyEvaluation: - """Dry run: would this key's policies allow the send? Never executes. Scope: policy:read.""" - body = {"quote_id": quote_id, "document_id": document_id, "to": to, "from": from_} + """Dry run: would the policies allow the send? Never executes. Scope: policy:read. + + With none of ``key_id``, ``agent_id`` or ``connection_id`` the plan is evaluated for the calling + key. Pass one of them to evaluate it for another key, agent or connected app of the organization. + The answer names that caller in ``subject`` and says in ``approval_required`` whether a person + would have to approve the send.""" + body = { + "quote_id": quote_id, + "document_id": document_id, + "to": to, + "from": from_, + "key_id": key_id, + "agent_id": agent_id, + "connection_id": connection_id, + } return self._h.request("POST", "/v1/policy-evaluations", model=m.PolicyEvaluation, json=body) + def check_rules( + self, + *, + allowed_destinations: Sequence[str] | None = None, + allowed_countries: Sequence[str] | None = None, + allowed_country_prefixes: Sequence[str] | None = None, + ) -> m.PolicyRuleCheck: + """Check the destination lists of a draft policy against each other. Writes nothing. + Scope: policy:read. + + ``already_allowed`` names the numbers of ``allowed_destinations`` that a listed country or prefix + allows anyway. For those numbers the number list adds nothing.""" + lists = { + "allowed_destinations": allowed_destinations, + "allowed_countries": allowed_countries, + "allowed_country_prefixes": allowed_country_prefixes, + } + body = {name: list(values) for name, values in lists.items() if values is not None} + return self._h.request("POST", "/v1/policy-rule-checks", model=m.PolicyRuleCheck, json=body) + class Agents(_Resource): - def list(self) -> m.AgentList: - """Agent identities. Scope: agent:read.""" - return self._h.request("GET", "/v1/agents", model=m.AgentList) + def list(self, *, include_archived: bool | None = None) -> m.AgentList: + """Agent identities. ``include_archived=True`` adds the archived ones. Scope: agent:read.""" + params = {"include_archived": include_archived} + return self._h.request("GET", "/v1/agents", model=m.AgentList, params=params) def create(self, *, idempotency_key: str | None = None, **fields: Any) -> m.Agent: """Register an agent identity. Scope: agent:admin, never an agent key.""" @@ -855,6 +996,13 @@ def update(self, agent_id: str, *, idempotency_key: str | None = None, **changes "PATCH", f"/v1/agents/{agent_id}", model=m.Agent, json=body, idempotency_key=idempotency_key ) + def archive(self, agent_id: str, *, idempotency_key: str | None = None) -> m.AgentArchived: + """Archive an agent for good. Its keys are revoked, it leaves the list and its name is free again. + Scope: agent:admin, never an agent key.""" + return self._h.request( + "DELETE", f"/v1/agents/{agent_id}", model=m.AgentArchived, idempotency_key=idempotency_key + ) + def create_key( self, agent_id: str, *, idempotency_key: str | None = None, **fields: Any ) -> m.ApiKeyWithSecret: @@ -879,15 +1027,19 @@ def activity( class Inbox(_Resource): - def list(self, *, cursor: str | None = None, limit: int | None = None) -> m.InboxPage: - """Received faxes, newest first, metadata only. ``from_`` is sender data. Scope: inbox:read.""" - return self._h.request( - "GET", "/v1/inbox", model=m.InboxPage, params={"cursor": cursor, "limit": limit} - ) + def list( + self, *, archived: bool | None = None, cursor: str | None = None, limit: int | None = None + ) -> m.InboxPage: + """Received faxes, newest first, metadata only. ``from_`` is sender data. Scope: inbox:read. + + ``archived=False`` leaves the archived faxes out and ``archived=True`` lists only those. ``unread`` + counts the faxes nobody has opened yet, whatever the filter.""" + params = {"archived": archived, "cursor": cursor, "limit": limit} + return self._h.request("GET", "/v1/inbox", model=m.InboxPage, params=params) - def iter(self, *, limit: int | None = None) -> Iterator[m.InboxItem]: - """Every received fax, following next_cursor.""" - return paginate(lambda p: self.list(**p), {"limit": limit}) + def iter(self, *, archived: bool | None = None, limit: int | None = None) -> Iterator[m.InboxItem]: + """Every received fax that matches, following next_cursor.""" + return paginate(lambda p: self.list(**p), {"archived": archived, "limit": limit}) def get(self, inbox_id: str) -> m.InboxItemDetail: """One received fax with its text as data, never as instructions. Scope: inbox:read.""" @@ -956,6 +1108,16 @@ def get_order(self, order_id: str) -> m.NumberOrder: """Read a number order. Scope: number:read.""" return self._h.request("GET", f"/v1/number-orders/{order_id}", model=m.NumberOrder) + def dismiss_order(self, order_id: str, *, idempotency_key: str | None = None) -> m.NumberOrder: + """Put a failed number order away. It gets ``dismissed_at`` and stays in the list. An order that + did not fail raises ``ConflictError``. Scope: number:buy, never an agent key.""" + return self._h.request( + "POST", + f"/v1/number-orders/{order_id}/dismissals", + model=m.NumberOrder, + idempotency_key=idempotency_key, + ) + def list_orders(self) -> m.NumberOrderList: """Your number orders. Scope: number:read.""" return self._h.request("GET", "/v1/number-orders", model=m.NumberOrderList) @@ -1290,6 +1452,20 @@ def request_data_deletion(self, *, idempotency_key: str | None = None) -> m.Requ idempotency_key=idempotency_key, ) + def list_data_requests(self) -> m.DataRequestList: + """The organization's export and deletion requests and where each stands. Scope: account:read.""" + return self._h.request("GET", "/v1/organizations/current/data-requests", model=m.DataRequestList) + + def withdraw_data_deletion(self, request_id: str, *, idempotency_key: str | None = None) -> m.DataRequest: + """Withdraw an open deletion request. One that is no longer open raises ``ConflictError``. + Scope: org:admin (an owner), never an agent key.""" + return self._h.request( + "DELETE", + f"/v1/organizations/current/deletion-requests/{request_id}", + model=m.DataRequest, + idempotency_key=idempotency_key, + ) + def download_export_archive(self, token: str, *, exp: str, sig: str) -> bytes: """The organization archive of a data export. ``token``, ``exp`` and ``sig`` come from the signed link, which lives 72 hours. The link is the credential.""" @@ -1326,6 +1502,28 @@ def invite(self, *, email: str, role: str = "member", idempotency_key: str | Non "POST", "/v1/invitations", model=m.Invitation, json=body, idempotency_key=idempotency_key ) + def resend_invitation(self, invitation_id: str, *, idempotency_key: str | None = None) -> m.Invitation: + """Mail an open invitation again, with a new link for 7 days. The old link stops working. + Scope: member:admin, never an agent key.""" + return self._h.request( + "POST", + f"/v1/invitations/{invitation_id}/resend", + model=m.Invitation, + idempotency_key=idempotency_key, + ) + + def link_invitation(self, invitation_id: str, *, idempotency_key: str | None = None) -> m.InvitationLink: + """A new link for an open invitation, to hand over yourself. No mail is sent, the old link stops + working and ``url`` is shown once. Scope: member:admin, never an agent key. + + The link joins the organization only for a person signed in with the invited address.""" + return self._h.request( + "POST", + f"/v1/invitations/{invitation_id}/link", + model=m.InvitationLink, + idempotency_key=idempotency_key, + ) + def revoke_invitation(self, invitation_id: str, *, idempotency_key: str | None = None) -> None: """Withdraw an invitation. Scope: member:admin, never an agent key.""" self._h.request("DELETE", f"/v1/invitations/{invitation_id}", idempotency_key=idempotency_key) @@ -1359,6 +1557,38 @@ def config(self) -> m.OneTimeConfig: """Whether one-time sends are open, with the card and the limits. No key needed.""" return self._h.request("GET", "/v1/one-time-sends/config", model=m.OneTimeConfig) + def preview( + self, + *, + file: bytes | str | Path | None = None, + filename: str | None = None, + content_type: str | None = None, + text: str | None = None, + text_format: str | None = None, + ) -> m.OneTimeInspection: + """Count the pages of a document before an order is made. Nothing is stored. It works without an + API key. + + Pass exactly one of ``file`` or ``text``, as for ``create``. The answer has ``document_pages`` and + the first page as a small PNG in ``thumbnail_png_base64``. A file the create would refuse raises + the same error here, such as ``too_many_pages`` or ``encrypted_pdf``. With a key: fax:send.""" + if (file is None) == (text is None): + raise ValueError("pass exactly one of file or text") + if file is None: + return self._h.request( + "POST", + "/v1/one-time-sends/preview", + model=m.OneTimeInspection, + json={"text": text, "text_format": text_format}, + ) + name, data, ctype = one_time_file(file, filename, content_type) + return self._h.request( + "POST", + "/v1/one-time-sends/preview", + model=m.OneTimeInspection, + files={"file": (name, data, ctype)}, + ) + def create( self, *, @@ -1569,6 +1799,17 @@ def resend_confirmation( idempotency_key=idempotency_key, ) + def get_page(self, order_id: str, page_number: int, *, order_token: str | None = None) -> bytes: + """One page of the order as PNG bytes. Page 1 is the cover sheet, then the document follows. + + ``preview.pages`` on the order says how many pages there are. A page that is not held any more + raises ``NotFoundError``. Read it with a key of the order's organization (scope fax:read) or with + ``order_token``.""" + data = self._h.request( + "GET", f"/v1/one-time-sends/{order_id}/pages/{page_number}", headers=token_header(order_token) + ) + return bytes(data) + def get_receipt_pdf(self, order_id: str, *, order_token: str | None = None) -> bytes: """The receipt of the order's fax as a one-page PDF. 409 while the fax has not ended.""" data = self._h.request( diff --git a/src/faxforagents/models.py b/src/faxforagents/models.py index 12e6caf..0129b99 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.5). Do not edit by hand. +GENERATED by scripts/gen_models.py from spec/openapi.yaml (API version 1.20.6). 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. """ @@ -50,6 +50,7 @@ class OrganizationSummary(_Response): id: str name: str role: Literal["owner", "admin", "member", "viewer"] + suspended_at: str | None = Field(None, description="Set while a review has paused sending for the whole organization. A send answers `account_suspended` until it is cleared. Reads keep working.") class Accepted(_Response): @@ -220,11 +221,13 @@ class Agent(_Response): created_at: str updated_at: str disabled_at: str | None + archived_at: str | None = Field(None, description="Set on an archived agent: disabled for good and left out of the list.") class AgentActivity(_Response): id: str actor: str + actor_label: str = Field("unknown", description="The actor in words: a member's email, the agent's name, an API key's prefix.") action: str resource_type: str resource_id: str | None @@ -238,6 +241,13 @@ class AgentActivityPage(_Response): next_cursor: str | None = None +class AgentArchived(_Response): + id: str + deleted: bool = Field(..., description="Always false: an agent has history and its row is kept.") + archived: bool + keys_revoked: int + + class AgentCreate(_Request): name: str purpose: str | None = Field(None, description="Shown to humans, never evaluated.") @@ -264,6 +274,12 @@ class AgentUpdate(_Request): contact_email: str | None = None +class AlreadyAllowed(_Response): + 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.") + + class AnalyticsJourneys(_Response): computed_at: str days: int @@ -375,6 +391,13 @@ class ApprovalDecision(_Request): reason: str | None = None +class ApprovalDocument(_Response): + id: str + filename: str | None = Field(..., description="The file's name; null when the document row is gone.") + page_count: int | None + state: Literal["available", "deleted", "changed"] = Field(..., description="available: the document is the one the request binds. deleted: it was deleted. changed: its sha256 is no longer the bound one. A send with this approval is refused in the last two.") + + class ApprovalRequest(_Response): id: str kind: Literal["send", "help"] @@ -383,7 +406,10 @@ class ApprovalRequest(_Response): bound: dict[str, Any] message: str | None requested_by: str + requested_by_name: str | None = Field(None, description="The requester as people read it: the key's label, the agent's name, the connected app's name or the person's address. null when the actor has no row in the organization any more.") decided_by: str | None + decided_by_name: str | None = Field(None, description="The decider, named the same way.") + document: ApprovalDocument | None = Field(None, description="The document a send request binds (bound.document_id). null for a help request.") reason: str | None consumed_by_job_id: str | None created_at: str @@ -486,6 +512,7 @@ class Balance(_Response): currency: str available_micro: int held_micro: int + held_jobs: int = Field(0, description="How many fax jobs still have their hold in place: queued, sending, or ended unknown and waiting for a reconcile. Their holds add up to held_micro.") top_up_url: str | None = Field(None, description="The dashboard page where a person adds funds to the wallet. A key cannot top up.") @@ -518,6 +545,7 @@ class Budget(_Response): resets_at: str created_at: str updated_at: str + archived_at: str | None = Field(None, description="Set on a removed budget that has history. It is disabled for good.") class BudgetCreate(_Request): @@ -537,6 +565,12 @@ class BudgetPatch(_Request): status: Literal["active", "disabled"] | None = None +class BudgetRemoved(_Response): + 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.") + + class Capabilities(_Response): environment: Literal["live", "test"] provider: str @@ -550,6 +584,8 @@ class Capabilities(_Response): price_version: str rates: dict[str, Any] scopes: list[str] = Field(..., description="Every scope the platform defines, the list a new key is made from. It is not what the calling credential holds: GET /v1/me returns that under scopes.") + default_scopes: list[str] | None = Field(None, description="The scopes a key gets when POST /v1/api-keys names none.") + 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.") @@ -611,6 +647,21 @@ class Coverage(_Response): note: str | None +class DataRequest(_Response): + """An export or deletion request of the organization and where it stands.""" + + id: str + kind: Literal["export", "deletion"] + status: Literal["open", "closed", "withdrawn"] = Field(..., description="open until a person at Fax for Agents answers it; withdrawn by an owner; else closed.") + created_at: str + due_at: str = Field(..., description="30 days after the request: when it is answered at the latest.") + closed_at: str | None + + +class DataRequestList(_Response): + items: list[DataRequest] + + class Deleted(_Response): id: str deleted: bool = True @@ -619,6 +670,25 @@ class Deleted(_Response): class Delivery(_Response): id: str webhook_id: str + 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 + created_at: str + delivered_at: str | None + + +class DeliveryDetail(_Response): + id: str + webhook_id: str + 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 @@ -631,6 +701,9 @@ class Delivery(_Response): next_attempt_at: str | None created_at: str delivered_at: str | None + 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.") class DeliveryPage(_Response): @@ -638,6 +711,14 @@ class DeliveryPage(_Response): next_cursor: str | None = None +class DocumentReceived(_Response): + """The received fax a document is the file of.""" + + inbox_item_id: str + from_: str | None = Field(None, alias="from") + received_at: str + + class Document(_Response): id: str environment: Literal["live", "test"] @@ -651,6 +732,8 @@ class Document(_Response): render_status: str render_reason: str | None validation: dict[str, Any] + converted_from: str | None = None + received: DocumentReceived | None = None upload_id: str | None created_at: str expires_at: str | None @@ -670,6 +753,7 @@ class DocumentCreate(_Request): class DocumentPage(_Response): items: list[Document] next_cursor: str | None = None + total: int | None = None class PagePreview(_Response): @@ -687,6 +771,10 @@ class DocumentPages(_Response): items: list[PagePreview] +class DocumentUpdate(_Request): + filename: str = Field(..., description="The new file name. The stored file is a PDF: a name without .pdf gets it added.") + + class DocumentValidation(_Response): id: str status: str @@ -850,6 +938,12 @@ class OneTimeJob(_Response): refunded_micro: int | None = Field(None, description="What was refunded to the card after the charge, in micro-units.") document_pages: int | None = Field(None, description="The pages of the order's document. The cover sheet is not counted.") card: OneTimeCard | None = None + sender_name: str | None = Field(None, description="On a receipt: the sender's name.") + email: str | None = Field(None, description="On a receipt: the address the order was made with.") + authorized_at: str | None = Field(None, description="On a receipt: when the card was held.") + settled_at: str | None = Field(None, description="On a receipt: when the payment provider confirmed the charge, or the release.") + failure_code: str | None = Field(None, description="On a receipt: why the order ended unpaid.") + price: dict[str, int] | None = Field(None, description="On a receipt: flat_micro, included_pages and extra_page_micro the amount follows from.") class FaxJob(_Response): @@ -931,6 +1025,7 @@ class InboxItem(_Response): project_id: str | None = None partial_content: bool = False media_status: str = "stored" + file_deleted_at: str | None = None duration_secs: int | None = None provider: str = "" read_at: str | None = None @@ -952,6 +1047,7 @@ class InboxItemDetail(_Response): project_id: str | None = None partial_content: bool = False media_status: str = "stored" + file_deleted_at: str | None = None duration_secs: int | None = None provider: str = "" read_at: str | None = None @@ -994,6 +1090,7 @@ class InboxItemSummary(_Response): class InboxPage(_Response): items: list[InboxItem] next_cursor: str | None = None + unread: int = 0 class InboxUpdate(_Request): @@ -1014,12 +1111,13 @@ class InventoryNumber(_Response): monthly_micro: int currency: str setup_micro: int + owned: bool = Field(False, description="True when your organization already holds this number. An order of it is refused.") class Inventory(_Response): country: str number_type: str - locality: str | None + locality: str | None = Field(..., description="The area that was searched for. Null in test: test numbers are made up and have no city.") items: list[InventoryNumber] recurring_period: str note: str @@ -1040,6 +1138,12 @@ class InvitationCreate(_Request): role: Literal["owner", "admin", "member", "viewer"] = "member" +class InvitationLink(_Response): + id: str + url: str = Field(..., description="The new invitation link. Shown once.") + expires_at: str + + class InvitationList(_Response): items: list[Invitation] @@ -1155,6 +1259,7 @@ class NumberOrder(_Response): error: str | None created_at: str completed_at: str | None + dismissed_at: str | None = Field(None, description="When a person put this failed order away. Null until then.") class NumberOrderCreate(_Request): @@ -1208,6 +1313,16 @@ class OAuthRedirect(_Response): redirect_to: str = Field(..., description="Where the browser goes next: the client's registered redirect URI.") +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.""" + + made: int + max: int + last_failure_code: str | None + last_finished_at: str | None + retry_delay_seconds: int + + class OneTimeCheckout(_Response): order_id: str checkout_url: str @@ -1222,6 +1337,7 @@ class OneTimeQueue(_Response): queued: bool jobs_ahead: int estimated_wait_minutes: int + paused: bool = Field(False, description="An operator has paused sends on this route. A fax to it is kept and goes out when the route is resumed; no time can be estimated. A one-time order that is not sent within 48 hours of its release is canceled and the card is not charged.") class OneTimeRoute(_Response): @@ -1270,6 +1386,14 @@ class OneTimeConfirmSummary(_Response): confirm_deadline_at: str | None +class OneTimePreview(_Response): + """Whether the pages of an order can be looked at, and how many. ``draft``: the cover sheet as it will be printed and the uploaded document, before the fax is released. ``sent``: the file that went to the carrier, cover sheet first. ``deleted``: no copy is held any more (the sender asked for the deletion, the retention ended, or the order ended before a fax was made). ``unavailable``: nothing to show right now. Page ``n`` is ``GET /v1/one-time-sends/{id}/pages/{n}``, 1 to ``pages``.""" + + state: Literal["draft", "sent", "deleted", "unavailable"] + pages: int + cover_pages: int + + class OneTimePrice(_Response): price_version: str currency: str @@ -1322,6 +1446,8 @@ 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.") + 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 @@ -1344,6 +1470,14 @@ class OneTimeFromQuote(_Request): delete_after_send: bool | None = Field(None, description="Delete the document and the transmitted copy the moment the fax ends in delivered, partial or failed. The order, the receipt and the carrier evidence stay; they hold no document content. A fax that ends unknown keeps the document until the carrier reports, or until the retention period ends. Left out, the quote's own delete_after_send applies.") +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.""" + + document_pages: int + thumbnail_png_base64: str | None + warnings: list[dict[str, Any]] | None = None + + 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.""" @@ -1387,6 +1521,8 @@ 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.") + 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 status_token: str @@ -1490,6 +1626,9 @@ class PolicyEvaluation(_Response): denials: list[dict[str, Any]] 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.") @@ -1499,12 +1638,25 @@ class PolicyEvaluationCreate(_Request): document_id: str | None = Field(None, description="Or plan: this document ...") to: str | None = Field(None, description="... to this E.164 destination.") from_: str | None = Field(None, alias="from") + key_id: str | None = Field(None, description="Evaluate as this API key of your organization instead of the caller, in the key's environment. Choose at most one of key_id, agent_id and connection_id.") + agent_id: str | None = Field(None, description="Evaluate as this agent of your organization (bindings to single keys excluded).") + connection_id: str | None = Field(None, description="Evaluate as this connected app (an OAuth grant, GET /v1/oauth/grants), in the connection's environment. A signed-in person may name their own.") class PolicyList(_Response): items: list[Policy] +class PolicyRuleCheck(_Response): + 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 + + class PolicyUpdate(_Request): name: str | None = None purpose: str | None = None @@ -1521,6 +1673,7 @@ class PolicyVersion(_Response): enabled: bool rules: dict[str, Any] created_by: str + created_by_name: str | None = Field(None, description="Who wrote the version as people read it: a person's address or a key's label.") created_at: str @@ -1613,6 +1766,7 @@ class Quote(_Response): sender_name: str | None = None delete_after_send: bool = False authorization_required: bool + 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 @@ -1639,12 +1793,22 @@ class Reauth(_Request): credential: dict[str, Any] | None = None +class Seller(_Response): + """The company a receipt is issued by.""" + + name: str + address: str + product: str + email: str + + class Receipt(_Response): fax_job_id: str state: str failure_code: str | None to: str from_: str | None = Field(None, alias="from") + sender_name: str | None = Field(None, description="The sender name the fax was sent with, when one was given.") document_sha256: str transmitted_sha256: str | None billable_pages: int @@ -1654,12 +1818,14 @@ class Receipt(_Response): captured_micro: int currency: str provider: str + provider_ref: str | None = Field(None, description="The carrier's own reference for the last attempt, when it gave one.") created_at: str completed_at: str | None evidence: dict[str, Any] | None attempts: list[Attempt] 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.") @@ -1686,6 +1852,8 @@ class Requested(_Response): requested: bool kind: Literal["export", "deletion"] message: str + id: str | None = Field(None, description="The request, as `GET .../data-requests` lists it.") + created_at: str | None = None class ReviewAccessAction(_Request): @@ -1829,6 +1997,22 @@ class SignedUrl(_Response): content_type: str +class StatementLine(_Response): + id: str + created_at: str + type: Literal["topup", "fax", "received_fax", "number", "extraction", "release", "refund", "dispute", "credit", "adjustment", "other"] + 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 + + +class StatementPage(_Response): + items: list[StatementLine] + next_cursor: str | None = None + + class Subscription(_Response): id: str product: str @@ -1978,6 +2162,7 @@ class Webhook(_Response): description: str | None event_types: list[str] status: str + failing: bool = Field(False, description="True when the latest delivery this destination was sent did not get a 2xx answer. It turns false with the next delivery that does.") previous_secret_expires_at: str | None created_at: str updated_at: str @@ -2011,6 +2196,7 @@ class WebhookWithSecret(_Response): description: str | None event_types: list[str] status: str + failing: bool = Field(False, description="True when the latest delivery this destination was sent did not get a 2xx answer. It turns false with the next delivery that does.") previous_secret_expires_at: str | None created_at: str updated_at: str @@ -2097,10 +2283,12 @@ class faxforagents__auth__schemas__Me(_Response): "Agent", "AgentActivity", "AgentActivityPage", + "AgentArchived", "AgentCreate", "AgentKeyCreate", "AgentList", "AgentUpdate", + "AlreadyAllowed", "AnalyticsJourneys", "AnalyticsOrganization", "AnalyticsSource", @@ -2111,6 +2299,7 @@ class faxforagents__auth__schemas__Me(_Response): "ApiKeyList", "ApiKeyWithSecret", "ApprovalDecision", + "ApprovalDocument", "ApprovalRequest", "ApprovalRequestCreate", "ApprovalRequestPage", @@ -2130,6 +2319,7 @@ class faxforagents__auth__schemas__Me(_Response): "BudgetCreate", "BudgetList", "BudgetPatch", + "BudgetRemoved", "Capabilities", "ClassificationCreate", "Client", @@ -2137,14 +2327,19 @@ class faxforagents__auth__schemas__Me(_Response): "Correction", "CorrectionCreate", "Coverage", + "DataRequest", + "DataRequestList", "Deleted", "Delivery", + "DeliveryDetail", "DeliveryPage", + "DocumentReceived", "Document", "DocumentCreate", "DocumentPage", "PagePreview", "DocumentPages", + "DocumentUpdate", "DocumentValidation", "Policy", "EffectivePolicies", @@ -2175,6 +2370,7 @@ class faxforagents__auth__schemas__Me(_Response): "Inventory", "Invitation", "InvitationCreate", + "InvitationLink", "InvitationList", "Invoice", "InvoicePage", @@ -2196,16 +2392,19 @@ class faxforagents__auth__schemas__Me(_Response): "OAuthConsent", "OAuthConsentDecision", "OAuthRedirect", + "OneTimeAttempts", "OneTimeCheckout", "OneTimeQueue", "OneTimeRoute", "OneTimeConfig", "OneTimeConfirm", "OneTimeConfirmSummary", + "OneTimePreview", "OneTimePrice", "OneTimeOrder", "OneTimeConfirmed", "OneTimeFromQuote", + "OneTimeInspection", "OneTimeOrderCreated", "OneTimeOrderPage", "Organization", @@ -2223,6 +2422,8 @@ class faxforagents__auth__schemas__Me(_Response): "PolicyEvaluation", "PolicyEvaluationCreate", "PolicyList", + "PolicyRuleCheck", + "PolicyRuleCheckCreate", "PolicyUpdate", "PolicyVersion", "PolicyVersionList", @@ -2239,6 +2440,7 @@ class faxforagents__auth__schemas__Me(_Response): "Quote", "QuoteCreate", "Reauth", + "Seller", "Receipt", "ReconcileResult", "ReconciliationReport", @@ -2266,6 +2468,8 @@ class faxforagents__auth__schemas__Me(_Response): "SessionOut", "SessionList", "SignedUrl", + "StatementLine", + "StatementPage", "Subscription", "SubscriptionCheckout", "SubscriptionList", diff --git a/tests/test_async.py b/tests/test_async.py index 2c02926..7cdff42 100644 --- a/tests/test_async.py +++ b/tests/test_async.py @@ -142,3 +142,81 @@ async def test_async_receipts_and_an_upload_without_a_type( session = await aclient.documents.create_upload(filename="scan.png", size_bytes=9) assert session.content_type == "image/png" assert b"content_type" not in create.calls.last.request.content + + +async def test_async_statement_pages_and_csv(aclient: AsyncClient, api: respx.MockRouter) -> None: + line = { + "id": "led_1", + "created_at": "2026-11-15T09:00:00Z", + "type": "fax", + "description": "Fax to +15550000001", + "amount_micro": -39_000, + "balance_after_micro": 99_961_000, + "ref_type": "fax_job", + "ref_id": "fax_1", + } + route = api.get("/v1/statement") + route.side_effect = [ + httpx.Response(200, json={"items": [line], "next_cursor": "led_1"}), + httpx.Response(200, json={"items": [{**line, "id": "led_0"}], "next_cursor": None}), + ] + ids = [item.id async for item in aclient.billing.iter_statement(from_="2026-11-01")] + assert ids == ["led_1", "led_0"] + assert dict(route.calls[0].request.url.params) == {"from": "2026-11-01"} + assert dict(route.calls[1].request.url.params) == {"from": "2026-11-01", "cursor": "led_1"} + api.get("/v1/statement.csv").respond(200, content=b"date,amount\n", headers={"content-type": "text/csv"}) + assert await aclient.billing.statement_csv(kind="fax") == "date,amount\n" + + +async def test_async_new_writes(aclient: AsyncClient, api: respx.MockRouter) -> None: + import json + + from tests.conftest import document + + doc_id = document()["id"] + rename = api.patch(f"/v1/documents/{doc_id}").respond(200, json=document(filename="lease.pdf")) + assert (await aclient.documents.rename(doc_id, filename="lease")).filename == "lease.pdf" + assert json.loads(rename.calls.last.request.content) == {"filename": "lease"} + api.delete("/v1/agents/agent_1").respond( + 200, json={"id": "agent_1", "deleted": False, "archived": True, "keys_revoked": 1} + ) + assert (await aclient.agents.archive("agent_1")).keys_revoked == 1 + api.delete("/v1/budgets/bud_1").respond(200, json={"id": "bud_1", "deleted": True, "archived": False}) + assert (await aclient.billing.delete_budget("bud_1")).deleted is True + check = api.post("/v1/policy-rule-checks").respond(200, json={"already_allowed": []}) + assert (await aclient.policies.check_rules(allowed_country_prefixes=["+1"])).already_allowed == [] + assert json.loads(check.calls.last.request.content) == {"allowed_country_prefixes": ["+1"]} + link = {"id": "inv_1", "url": "https://app.example.test/join/x", "expires_at": "2026-11-22T00:00:00Z"} + api.post("/v1/invitations/inv_1/link").respond(200, json=link) + assert (await aclient.members.link_invitation("inv_1")).url.endswith("/join/x") + withdrawn = { + "id": "orq_1", + "kind": "deletion", + "status": "withdrawn", + "created_at": "2026-11-15T09:00:00Z", + "due_at": "2026-12-15T09:00:00Z", + "closed_at": "2026-11-15T10:00:00Z", + } + api.delete("/v1/organizations/current/deletion-requests/orq_1").respond(200, json=withdrawn) + assert (await aclient.organizations.withdraw_data_deletion("orq_1")).status == "withdrawn" + api.get("/v1/organizations/current/data-requests").respond(200, json={"items": [withdrawn]}) + assert (await aclient.organizations.list_data_requests()).items[0].id == "orq_1" + + +async def test_async_filters_and_one_time_reads(aclient: AsyncClient, api: respx.MockRouter) -> None: + faxes = api.get("/v1/faxes").respond(200, json={"items": [fax_job()], "next_cursor": None}) + assert len([job async for job in aclient.faxes.iter(q="+15550000001")]) == 1 + assert dict(faxes.calls.last.request.url.params) == {"q": "+15550000001"} + inbox = api.get("/v1/inbox").respond(200, json={"items": [], "next_cursor": None, "unread": 0}) + assert (await aclient.inbox.list(archived=True)).unread == 0 + assert dict(inbox.calls.last.request.url.params) == {"archived": "true"} + preview = api.post("/v1/one-time-sends/preview").respond( + 200, json={"document_pages": 1, "thumbnail_png_base64": None} + ) + assert (await aclient.one_time_sends.preview(text="Hello")).document_pages == 1 + assert preview.calls.last.request.headers["authorization"].startswith("Bearer ffa_test_") + page = api.get("/v1/one-time-sends/oto_1/pages/2").respond( + 200, content=b"\x89PNG", headers={"content-type": "image/png"} + ) + 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 diff --git a/tests/test_client.py b/tests/test_client.py index 48eb327..f561468 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -628,3 +628,332 @@ def test_an_early_receipt_names_the_fax_state(client: Client, api: respx.MockRou client.faxes.get_receipt("fax_y") assert exc.value.state == "active" and exc.value.code == "conflict" and exc.value.retryable is False assert ConflictError(status=409, code="quote_consumed", message="used").state is None + + +def statement_line(**over: object) -> dict[str, object]: + return { + "id": "led_" + "7" * 32, + "created_at": "2026-11-15T09:00:00Z", + "type": "topup", + "description": "Top-up", + "amount_micro": 25_000_000, + "balance_after_micro": 125_000_000, + "ref_type": "topup_session", + "ref_id": "tus_1", + **over, + } + + +def test_statement_pages_filters_and_csv(client: Client, api: respx.MockRouter) -> None: + """API 1.20.6: one line per wallet event with the balance after it, as JSON pages or as CSV.""" + route = api.get("/v1/statement") + route.side_effect = [ + httpx.Response(200, json={"items": [statement_line()], "next_cursor": "led_9"}), + httpx.Response(200, json={"items": [statement_line(id="led_2", type="fax")], "next_cursor": "led_2"}), + httpx.Response(200, json={"items": [statement_line(id="led_1", type="fax")], "next_cursor": None}), + ] + page = client.billing.statement(kind="topup", from_="2026-11-01", to="2026-11-15", limit=10) + assert page.items[0].balance_after_micro == 125_000_000 and page.next_cursor == "led_9" + sent = route.calls[0].request.url.params + assert dict(sent) == {"kind": "topup", "from": "2026-11-01", "to": "2026-11-15", "limit": "10"} + assert "idempotency-key" not in route.calls[0].request.headers + assert [line.id for line in client.billing.iter_statement(kind="fax")] == ["led_2", "led_1"] + assert dict(route.calls[1].request.url.params) == {"kind": "fax"} + assert dict(route.calls[2].request.url.params) == {"kind": "fax", "cursor": "led_2"} + csv = api.get("/v1/statement.csv").respond( + 200, content=b"date,type,amount\n2026-11-15,topup,25.00\n", headers={"content-type": "text/csv"} + ) + text = client.billing.statement_csv(to="2026-11-15") + assert text.splitlines() == ["date,type,amount", "2026-11-15,topup,25.00"] + assert dict(csv.calls.last.request.url.params) == {"to": "2026-11-15"} + + +def test_document_rename_and_the_list_filters(client: Client, api: respx.MockRouter) -> None: + """API 1.20.6: PATCH renames a document. The list filters by source and text and answers total.""" + doc_id = document()["id"] + patch = api.patch(f"/v1/documents/{doc_id}").respond(200, json=document(filename="contract.pdf")) + renamed = client.documents.rename(doc_id, filename="contract", idempotency_key="k-rename") + assert renamed.filename == "contract.pdf" + assert json.loads(patch.calls.last.request.content) == {"filename": "contract"} + assert patch.calls.last.request.headers["idempotency-key"] == "k-rename" + listed = api.get("/v1/documents") + listed.side_effect = [ + httpx.Response(200, json={"items": [document(source="inbound")], "next_cursor": None, "total": 1}), + httpx.Response(200, json={"items": [], "next_cursor": None, "total": 0}), + ] + page = client.documents.list(source="inbound", q="+1415") + assert page.total == 1 and page.items[0].source == "inbound" + assert dict(listed.calls[0].request.url.params) == {"source": "inbound", "q": "+1415"} + assert list(client.documents.iter(exclude_source="inbound", limit=5)) == [] + assert dict(listed.calls[1].request.url.params) == {"exclude_source": "inbound", "limit": "5"} + + +def test_fax_search_by_number_or_job_id(client: Client, api: respx.MockRouter) -> None: + route = api.get("/v1/faxes") + route.side_effect = [ + httpx.Response(200, json={"items": [fax_job(state="failed")], "next_cursor": None}), + httpx.Response(200, json={"items": [fax_job()], "next_cursor": None}), + ] + page = client.faxes.list(q="fax_1111", state="failed") + assert page.items[0].state == "failed" + assert dict(route.calls[0].request.url.params) == {"state": "failed", "q": "fax_1111"} + assert len(list(client.faxes.iter(q="(555) 000-0001"))) == 1 + assert route.calls[1].request.url.params["q"] == "(555) 000-0001" + + +def test_one_webhook_delivery_with_what_was_sent(client: Client, api: respx.MockRouter) -> None: + detail = { + "id": "dlv_1", + "webhook_id": "wh_1", + "webhook_url": "https://example.com/hooks/fax", + "event_id": "evt_1", + "event_type": "fax.delivered", + "attempt": 1, + "status": "delivered", + "response_status": 200, + "error": None, + "duration_ms": 84, + "replay_of": None, + "schedule_s": [0, 60, 300], + "next_attempt_at": None, + "created_at": "2026-11-15T09:00:00Z", + "delivered_at": "2026-11-15T09:00:01Z", + "webhook_deleted": False, + "request_headers": {"webhook-id": "evt_1", "content-type": "application/json"}, + "payload": {"type": "fax.delivered", "data": {"id": "fax_1"}}, + } + api.get("/v1/webhook-deliveries/dlv_1").respond(200, json=detail) + got = client.webhooks.get_delivery("dlv_1") + assert got.request_headers["webhook-id"] == "evt_1" and got.payload["type"] == "fax.delivered" + assert got.webhook_url == "https://example.com/hooks/fax" and got.webhook_deleted is False + + +def budget(**over: object) -> dict[str, object]: + return { + "id": "bud_1", + "environment": "test", + "scope": "organization", + "project_id": None, + "agent_id": None, + "period": "monthly", + "limit_micro": 10_000_000, + "spent_micro": 0, + "remaining_micro": 10_000_000, + "status": "active", + "resets_at": "2026-12-01T00:00:00Z", + "created_at": "2026-11-01T00:00:00Z", + "updated_at": "2026-11-01T00:00:00Z", + **over, + } + + +def test_budget_removal_and_the_archived_list(client: Client, api: respx.MockRouter) -> None: + removed = api.delete("/v1/budgets/bud_1").respond( + 200, json={"id": "bud_1", "deleted": False, "archived": True} + ) + gone = client.billing.delete_budget("bud_1") + assert gone.archived is True and gone.deleted is False + assert len(removed.calls.last.request.headers["idempotency-key"]) == 36 + listed = api.get("/v1/budgets") + listed.side_effect = [ + httpx.Response(200, json={"items": [budget(archived_at="2026-11-15T09:00:00Z")]}), + httpx.Response(200, json={"items": []}), + ] + assert client.billing.list_budgets(include_archived=True).items[0].archived_at + assert dict(listed.calls[0].request.url.params) == {"include_archived": "true"} + client.billing.list_budgets() + assert dict(listed.calls[1].request.url.params) == {} + + +def test_agent_archive_and_the_archived_list(client: Client, api: respx.MockRouter) -> None: + route = api.delete("/v1/agents/agent_1").respond( + 200, json={"id": "agent_1", "deleted": False, "archived": True, "keys_revoked": 2} + ) + archived = client.agents.archive("agent_1", idempotency_key="k-archive") + assert archived.keys_revoked == 2 and archived.archived is True + assert route.calls.last.request.headers["idempotency-key"] == "k-archive" + listed = api.get("/v1/agents").respond(200, json={"items": []}) + assert client.agents.list(include_archived=True).items == [] + assert dict(listed.calls.last.request.url.params) == {"include_archived": "true"} + + +def number_order(**over: object) -> dict[str, object]: + return { + "id": "nor_1", + "environment": "test", + "status": "failed", + "e164": "+15550001000", + "country": "US", + "number_type": "local", + "number_id": None, + "number": None, + "provider": "sandbox", + "recurring_charge_micro": 2_000_000, + "recurring_period": "month", + "first_month_hold_micro": 2_000_000, + "currency": "USD", + "error": "Sandbox carrier refused this number order.", + "created_at": "2026-11-15T09:00:00Z", + "completed_at": "2026-11-15T09:00:05Z", + **over, + } + + +def test_number_order_dismissal(client: Client, api: respx.MockRouter) -> None: + """API 1.20.6: a failed order is put away. Any other order answers 409 conflict.""" + route = api.post("/v1/number-orders/nor_1/dismissals") + route.side_effect = [ + httpx.Response(200, json=number_order(dismissed_at="2026-11-15T10:00:00Z")), + httpx.Response(409, json=error("conflict", "this order did not fail")), + ] + order = client.numbers.dismiss_order("nor_1") + assert order.dismissed_at == "2026-11-15T10:00:00Z" and order.status == "failed" + assert route.calls[0].request.content == b"" + assert len(route.calls[0].request.headers["idempotency-key"]) == 36 + with pytest.raises(ConflictError): + client.numbers.dismiss_order("nor_1") + + +def evaluation(**over: object) -> dict[str, object]: + return { + "decision": "allow", + "rule": None, + "reason": "allowed by policy", + "policy_id": "pol_1", + "policy_version_id": "polv_1", + "policy_name": "US only", + "version": 1, + "denials": [], + "plan": {"to": "+15550000001"}, + **over, + } + + +def test_policy_rule_check_and_an_evaluation_for_an_agent(client: Client, api: respx.MockRouter) -> None: + check = api.post("/v1/policy-rule-checks").respond( + 200, json={"already_allowed": [{"number": "+14155550100", "countries": ["US"], "prefixes": []}]} + ) + found = client.policies.check_rules( + allowed_destinations=("+14155550100", "+447700900123"), allowed_countries=["US"] + ) + assert found.already_allowed[0].number == "+14155550100" and found.already_allowed[0].countries == ["US"] + assert json.loads(check.calls.last.request.content) == { + "allowed_destinations": ["+14155550100", "+447700900123"], + "allowed_countries": ["US"], + } + evaluate = api.post("/v1/policy-evaluations").respond( + 200, json=evaluation(subject="agent_1", under_policy=True, approval_required=False) + ) + result = client.policies.evaluate(to="+15550000001", document_id="doc_" + "2" * 32, agent_id="agent_1") + assert result.subject == "agent_1" and result.under_policy is True and result.approval_required is False + assert json.loads(evaluate.calls.last.request.content) == { + "to": "+15550000001", + "document_id": "doc_" + "2" * 32, + "agent_id": "agent_1", + } + + +def invitation(**over: object) -> dict[str, object]: + return { + "id": "inv_1", + "email": "sam@example.com", + "role": "member", + "invited_by": "user_1", + "created_at": "2026-11-15T09:00:00Z", + "expires_at": "2026-11-22T09:00:00Z", + "accepted_at": None, + **over, + } + + +def test_invitation_resend_and_a_link_to_hand_over(client: Client, api: respx.MockRouter) -> None: + resend = api.post("/v1/invitations/inv_1/resend").respond(200, json=invitation()) + assert client.members.resend_invitation("inv_1").expires_at == "2026-11-22T09:00:00Z" + assert len(resend.calls.last.request.headers["idempotency-key"]) == 36 + link = api.post("/v1/invitations/inv_1/link").respond( + 200, + json={ + "id": "inv_1", + "url": "https://app.example.test/join/abc", + "expires_at": "2026-11-22T09:00:00Z", + }, + ) + made = client.members.link_invitation("inv_1", idempotency_key="k-link") + assert made.url == "https://app.example.test/join/abc" + assert link.calls.last.request.headers["idempotency-key"] == "k-link" + + +def data_request(**over: object) -> dict[str, object]: + return { + "id": "orq_1", + "kind": "deletion", + "status": "open", + "created_at": "2026-11-15T09:00:00Z", + "due_at": "2026-12-15T09:00:00Z", + "closed_at": None, + **over, + } + + +def test_data_requests_and_withdrawing_a_deletion(client: Client, api: respx.MockRouter) -> None: + api.get("/v1/organizations/current/data-requests").respond( + 200, json={"items": [data_request(), data_request(id="orq_2", kind="export", status="closed")]} + ) + listed = client.organizations.list_data_requests() + assert [(r.kind, r.status) for r in listed.items] == [("deletion", "open"), ("export", "closed")] + route = api.delete("/v1/organizations/current/deletion-requests/orq_1") + route.side_effect = [ + httpx.Response(200, json=data_request(status="withdrawn", closed_at="2026-11-15T10:00:00Z")), + httpx.Response( + 409, json=error("conflict", "not open any more", details={"reason": "request_closed"}) + ), + ] + assert client.organizations.withdraw_data_deletion("orq_1").status == "withdrawn" + with pytest.raises(ConflictError) as exc: + client.organizations.withdraw_data_deletion("orq_1") + assert exc.value.details == {"reason": "request_closed"} + + +def test_inbox_archived_filter_and_the_unread_count(client: Client, api: respx.MockRouter) -> None: + route = api.get("/v1/inbox").respond(200, json={"items": [], "next_cursor": None, "unread": 3}) + page = client.inbox.list(archived=False) + assert page.unread == 3 + assert dict(route.calls.last.request.url.params) == {"archived": "false"} + assert list(client.inbox.iter(archived=True)) == [] + assert dict(route.calls.last.request.url.params) == {"archived": "true"} + + +def approval(**over: object) -> dict[str, object]: + return { + "id": "apr_1", + "kind": "help", + "status": "rejected", + "quote_id": None, + "bound": {}, + "message": "Which number should I use?", + "requested_by": "key_1", + "decided_by": "user_1", + "reason": None, + "consumed_by_job_id": None, + "created_at": "2026-11-15T09:00:00Z", + "expires_at": "2026-11-16T09:00:00Z", + "decided_at": "2026-11-15T09:05:00Z", + **over, + } + + +def test_used_approvals_and_closing_a_help_request(client: Client, api: respx.MockRouter) -> None: + """API 1.20.6: a used approval reads approved, and a help request closes without a reason.""" + used = approval( + kind="send", status="approved", quote_id="quote_1", consumed_by_job_id="fax_1", requested_by_name="ci" + ) + listed = api.get("/v1/approval-requests").respond(200, json={"items": [used], "next_cursor": None}) + page = client.approvals.list(status="used") + assert page.items[0].status == "approved" and page.items[0].consumed_by_job_id == "fax_1" + assert page.items[0].requested_by_name == "ci" + assert dict(listed.calls.last.request.url.params) == {"status": "used"} + reject = api.post("/v1/approval-requests/apr_1/reject").respond(200, json=approval()) + assert client.approvals.reject("apr_1").status == "rejected" + 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"} diff --git a/tests/test_one_time.py b/tests/test_one_time.py index cefc238..62ca2f5 100644 --- a/tests/test_one_time.py +++ b/tests/test_one_time.py @@ -10,7 +10,7 @@ import pytest import respx -from faxforagents import AsyncClient, Client, NotFoundError, PaymentRequiredError +from faxforagents import AsyncClient, Client, InvalidRequestError, NotFoundError, PaymentRequiredError from tests.conftest import BASE, KEY, error CASES: dict[str, Any] = { @@ -379,3 +379,43 @@ async def test_async_flow(api: respx.MockRouter) -> None: assert done.next == "done" assert read.calls.last.request.headers["x-ffa-order-token"] == TOKEN assert "authorization" not in read.calls.last.request.headers + + +INSPECTION = {"document_pages": 3, "thumbnail_png_base64": "iVBORw0KGgo=", "warnings": []} + + +def test_preview_counts_pages_with_no_key_and_stores_nothing(keyless: Client, api: respx.MockRouter) -> None: + """API 1.20.6: the page count of a file or a text before any order exists.""" + route = api.post("/v1/one-time-sends/preview").respond(200, json=INSPECTION) + found = keyless.one_time_sends.preview(text="# Hello", text_format="markdown") + assert found.document_pages == 3 and found.thumbnail_png_base64 == "iVBORw0KGgo=" + sent = route.calls.last.request + assert json.loads(sent.content) == {"text": "# Hello", "text_format": "markdown"} + assert "authorization" not in sent.headers + keyless.one_time_sends.preview(file=b"%PDF-1.7", filename="letter.pdf") + upload = route.calls.last.request + assert upload.headers["content-type"].startswith("multipart/form-data") + assert b'filename="letter.pdf"' in upload.content and b"application/pdf" in upload.content + with pytest.raises(ValueError, match="exactly one"): + keyless.one_time_sends.preview() + with pytest.raises(ValueError, match="exactly one"): + keyless.one_time_sends.preview(file=b"%PDF", text="both") + + +def test_preview_raises_the_refusal_of_the_create(keyless: Client, api: respx.MockRouter) -> None: + api.post("/v1/one-time-sends/preview").respond(422, json=error("too_many_pages", "20 pages at most")) + with pytest.raises(InvalidRequestError) as exc: + keyless.one_time_sends.preview(file=b"%PDF", filename="long.pdf") + assert exc.value.code == "too_many_pages" + + +def test_a_page_of_the_order_as_png(keyless: Client, api: respx.MockRouter) -> None: + png = b"\x89PNG\r\n\x1a\n" + b"0" * 16 + route = api.get(f"/v1/one-time-sends/{ORDER}/pages/1").respond( + 200, content=png, headers={"content-type": "image/png"} + ) + assert keyless.one_time_sends.get_page(ORDER, 1, order_token=TOKEN) == png + assert route.calls.last.request.headers["x-ffa-order-token"] == TOKEN + 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) diff --git a/tests/test_surface.py b/tests/test_surface.py index 5f1761f..bb4095e 100644 --- a/tests/test_surface.py +++ b/tests/test_surface.py @@ -76,6 +76,7 @@ def test_every_operation_has_a_method() -> None: "create_document": "documents.create", "list_documents": "documents.list", "get_document": "documents.get", + "rename_document": "documents.rename", "delete_document": "documents.delete", "get_document_validation": "documents.get_validation", "get_document_download": "documents.get_download", @@ -99,10 +100,13 @@ def test_every_operation_has_a_method() -> None: "rotate_webhook_secret": "webhooks.rotate_secret", "test_webhook": "webhooks.test", "list_webhook_deliveries": "webhooks.list_deliveries", + "get_webhook_delivery": "webhooks.get_delivery", "replay_webhook_delivery": "webhooks.replay_delivery", "list_events": "events.list", "get_balance": "billing.balance", "list_ledger": "billing.list_ledger", + "get_statement": "billing.statement", + "get_statement_csv": "billing.statement_csv", "get_billing_settings": "billing.get_settings", "patch_billing_settings": "billing.patch_settings", "create_topup_session": "billing.create_topup_session", @@ -115,6 +119,7 @@ def test_every_operation_has_a_method() -> None: "list_budgets": "billing.list_budgets", "create_budget": "billing.create_budget", "patch_budget": "billing.patch_budget", + "delete_budget": "billing.delete_budget", "get_usage": "billing.usage", "create_usage_export": "billing.create_usage_export", "get_usage_export": "billing.get_usage_export", @@ -146,10 +151,12 @@ def test_every_operation_has_a_method() -> None: "update_policy": "policies.update", "list_policy_versions": "policies.list_versions", "create_policy_evaluation": "policies.evaluate", + "create_policy_rule_check": "policies.check_rules", "list_agents": "agents.list", "create_agent": "agents.create", "get_agent": "agents.get", "update_agent": "agents.update", + "archive_agent": "agents.archive", "create_agent_key": "agents.create_key", "get_agent_activity": "agents.activity", "list_inbox": "inbox.list", @@ -163,6 +170,7 @@ def test_every_operation_has_a_method() -> None: "create_number_order": "numbers.create_order", "list_number_orders": "numbers.list_orders", "get_number_order": "numbers.get_order", + "dismiss_number_order": "numbers.dismiss_order", "list_numbers": "numbers.list", "get_number": "numbers.get", "update_number": "numbers.update", @@ -191,20 +199,26 @@ def test_every_operation_has_a_method() -> None: "update_current_organization": "organizations.update_current", "request_data_export": "organizations.request_data_export", "request_data_deletion": "organizations.request_data_deletion", + "list_data_requests": "organizations.list_data_requests", + "withdraw_data_deletion": "organizations.withdraw_data_deletion", "download_export_archive": "organizations.download_export_archive", "list_members": "members.list", "update_member": "members.update", "remove_member": "members.remove", "list_invitations": "members.list_invitations", "create_invitation": "members.invite", + "resend_invitation": "members.resend_invitation", + "link_invitation": "members.link_invitation", "revoke_invitation": "members.revoke_invitation", "list_oauth_grants": "oauth.list_grants", "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_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", "get_one_time_order": "one_time_sends.get", + "get_one_time_order_page": "one_time_sends.get_page", "get_one_time_order_by_token": "one_time_sends.get_by_token", "read_one_time_order_by_token": "one_time_sends.read_by_token", "create_one_time_checkout": "one_time_sends.checkout",