{"openapi":"3.0.3","info":{"title":"Poppelo API","description":"The Poppelo API: submit purchase orders and supplier invoices in any format, follow them through extraction and review, approve or reject them, and receive webhooks as they move. The web app is one client of this API; everything it does, the API does.\n\n## Authentication\nSend a tenant API key in the `X-API-Key` header. Create keys in Settings › API keys (or `POST /api/v1/tenants/{tenantId}/api-keys`); a key is shown once. Each key carries permission scopes (`orders:read`, `orders:write`, `review:write`, …; `*` is full access) and a call outside them is refused with 403. The web app authenticates with a session cookie instead; cookie-authenticated writes must come from the application origin.\n\n## Tenant id\nAlmost every route is under `/api/v1/tenants/{tenantId}/…`, and a key only works for its own tenant. Find it with `GET /api/v1/me`: any valid credential answers with its `tenantId`, `principalType` and, for an API key, its id, name and permissions. Settings › Developers shows the same id.\n\n## Errors\nEvery error is `{ \"error\": { \"code\", \"message\", \"details?\", \"correlationId?\" } }` (the `Error` schema). `code` is one of a fixed catalogue, listed as the enum on `Error.error.code`; branch on it, never on `message`. `VALIDATION_ERROR` (400) carries `details` as an array of problems. Quote `correlationId` to support.\n\n## The core flow\n1. `POST /api/v1/tenants/{tenantId}/orders` with a base64 `document` (or a `documentUrl`) answers 202 with an `envelopeId`. `channelId` is optional: without it the document goes to the account's API channel. Structured order lines (no document) go to `POST …/orders/manual`; supplier invoices to `POST …/invoices`; files up to 25 MB to the multipart `POST …/upload`.\n2. Follow it with `GET /api/v1/tenants/{tenantId}/envelopes/{envelopeId}` (or a webhook). Stop polling when `resting` is true (exported, manual_handling, rejected, failed). `awaitingHuman` is true while a person must act (in_review, pending_export, manual_handling). `orderId` is set once the document has been read.\n3. An order in review is approved with `POST …/review/{envelopeId}/approve` (optionally with corrections) or rejected with `POST …/review/{envelopeId}/reject`.\n\n## Idempotency\nSubmissions accept an `Idempotency-Key` header (or an `idempotencyKey` body field). A retry with the same key and body returns the original envelope; the same key with a different body is refused with 409 `IDEMPOTENCY_KEY_REUSED`. Use one key per source document, so a network retry never creates a duplicate order.\n\n## Lists and pagination\nPaged lists answer `{ \"data\": [...], \"pagination\": { \"page\", \"pageSize\", \"total\", \"totalPages\" } }` and take `page` (1-based) and `pageSize` (max 200; the default is 20 for orders, invoices, review and audit, 50 for reference data and webhook deliveries). `pagination.estimated` is true when `total` is an estimate (over 10,000 rows); page further back with `createdBefore` set to the last row's `createdAt`. `limit` and `offset` are deprecated aliases. Reference data and webhook deliveries also repeat `total`, `limit` and `offset` at the top level. Short lists (webhooks, users, API keys, rules, profiles) answer `{ \"data\": [...] }` with no paging. A few lists use a cursor: golden data answers `{ \"data\", \"nextCursor\" }` and takes `cursor`. Channels answer `{ \"channels\": [...] }`. Read the response schema of each operation for its exact shape.\n\n## Webhooks\nRegister an HTTPS URL with `POST /api/v1/tenants/{tenantId}/webhooks` and choose events (for example `envelope.in_review`, `envelope.approved`, `envelope.exported`, `envelope.failed`). Each delivery is a POST with the JSON body `{ \"event\", \"timestamp\", \"data\", \"id\", \"attempt\" }` and these headers:\n- `X-Poppelo-Signature`: hex HMAC-SHA256 of `\"{X-Poppelo-Timestamp}.{raw body}\"` with the subscription's signing secret.\n- `X-Poppelo-Timestamp`: Unix seconds when the delivery was signed. Reject a delivery more than five minutes old.\n- `X-Poppelo-Event`: the event name.\n- `X-Poppelo-Delivery-Id`: stable across retries of the same delivery; use it to ignore duplicates.\n\nVerify the signature over the raw body before parsing it, and compare in constant time after checking the lengths match. The older `X-OrderFlow-Signature`, `-Timestamp`, `-Event` and `-Delivery-Id` headers are deprecated: they are still sent with the same values for one more release and then stop. Switch to the `X-Poppelo-*` names. A delivery that does not get a 2xx is retried with backoff.\n\n## Rate limits\n`X-RateLimit-Limit`, `X-RateLimit-Remaining` and `X-RateLimit-Reset` (seconds) describe your plan's per-minute limit; `X-RateLimit-IP-Limit`, `-Remaining` and `-Reset` describe the per-IP backstop. Refusals are 429 `TENANT_RATE_LIMIT_EXCEEDED` (plan limit), 429 `RATE_LIMIT_EXCEEDED` (per-IP backstop), 429 `TENANT_CAPACITY_EXCEEDED` (too many concurrent requests) and 503 `SERVICE_BUSY`; each carries `Retry-After`.\n\n## Timestamps\nEvery timestamp is ISO 8601 in UTC (`2026-11-21T14:03:12.481Z`).\n\nWhat changed in the API is listed at https://www.poppelo.com/developers/changelog.","version":"1.0.0"},"components":{"securitySchemes":{"apiKey":{"type":"apiKey","name":"X-API-Key","in":"header","description":"Tenant-scoped API key"},"sessionCookie":{"type":"apiKey","name":"authjs.session-token","in":"cookie","description":"Web-app session cookie (`__Secure-authjs.session-token` over HTTPS). Cookie-authenticated writes must come from the application origin."},"sessionBearer":{"type":"http","scheme":"bearer","description":"The same web session token sent as `Authorization: Bearer <token>`."},"scimBearer":{"type":"http","scheme":"bearer","description":"A tenant's SCIM directory token (pop_scim_…), shown once when the directory is created. Only the /api/v1/scim/v2 routes accept it."},"provisioningToken":{"type":"apiKey","name":"x-provisioning-token","in":"header","description":"Platform credential issued by Poppelo to partners that provision tenants headlessly. Distinct from the tenant-scoped X-API-Key; see the provisioning tag."}},"schemas":{"Error":{"type":"object","description":"Every error the API sends has this shape.","properties":{"error":{"type":"object","properties":{"code":{"type":"string","enum":["ACCESS_DENIED","ADD_PAYMENT_METHOD","ALERT_NOT_FOUND","ALREADY_ACTIVE","ALREADY_IN_ENVIRONMENT","ALREADY_MEMBER","ALREADY_OFFBOARDING","ALREADY_OWNER","API_ERROR","API_KEY_REVOKED","APPROVAL_NEEDS_ACKNOWLEDGEMENT","APP_IN_USE","APP_MISMATCH","APP_NOT_FOUND","AUTONOMY_GRANT_REQUIRES_PERSON","AUTONOMY_NOT_ELIGIBLE","BAD_REQUEST","BILLING_UNAVAILABLE","BUSINESS_CHOICE_REQUIRED","CANNOT_DEMOTE_OWNER","CHANNEL_EXISTS","CHANNEL_NOT_FOUND","CHANNEL_UNAVAILABLE","CHECKOUT_IN_PROGRESS","CLIENT_ID_TAKEN","CONFIRMATION_MISMATCH","CONFIRMATION_REQUIRED","CONFLICT","CONNECTION_TEST_FAILED","CONNECTION_VERIFICATION_FAILED","CONNECTOR_ALREADY_ASSIGNED","CONNECTOR_ID_REQUIRED","CONNECTOR_NEEDS_RECONNECT","CONNECTOR_NOT_CONNECTED","CONNECTOR_NOT_FOUND","CONNECTOR_ROLE_MISMATCH","CORRECTION_APPLY_FAILED","CORRECTION_INVALID","CREDENTIALS_MISSING","CREDENTIAL_STORAGE_FAILED","CSRF_ORIGIN_REJECTED","CUSTOMER_NOT_FOUND","DAILY_BUDGET_EXCEEDED","DESTINATION_ALREADY_ATTEMPTED","DESTINATION_CHOICE_REQUIRED","DESTINATION_DEFAULT_REQUIRED","DESTINATION_POLICY_CONFLICT","DESTINATION_ROLE_MISMATCH","DOCUMENT_FETCH_FAILED","DOCUMENT_NOT_FOUND","DOCUMENT_REQUIRED","DOMAIN_TAKEN","DOMAIN_VERIFICATION_FAILED","DUPLICATE_INVOICE","DUPLICATE_RULE_ID","ECONNREFUSED","ECONNRESET","ECONOMIC_SAFETY_REFUSED","EMAIL_BELONGS_TO_ANOTHER_TENANT","ENCRYPTION_KEY_REQUIRED","ENOTFOUND","ENTITY_IN_USE","ENTITY_NAME_TAKEN","ENTITY_NOT_FOUND","ENVIRONMENT_NOT_APPLICABLE","EXPORT_FAILED","EXPORT_TOO_LARGE","FINDING_NOT_FOUND","FORBIDDEN","GOLDEN_EVAL_ALREADY_RUNNING","GOLDEN_EVAL_NO_EXAMPLES","GONE","GRACE_PERIOD_EXPIRED","HINT_BUDGET_EXCEEDED","HINT_REQUIRES_PARTNER","IDEMPOTENCY_KEY_EXPIRED","IDEMPOTENCY_KEY_REUSED","INSUFFICIENT_CONTRIBUTORS","INSUFFICIENT_SCOPE","INTERNAL","INTERNAL_ERROR","INVALID_APP","INVALID_CONFIRMATION_TOKEN","INVALID_CORRECTION_FIELD","INVALID_CURSOR","INVALID_DATE","INVALID_DESTINATION_CHOICE","INVALID_DOCUMENT_URL","INVALID_ENDPOINT_URL","INVALID_HMAC","INVALID_IMAP_HOST","INVALID_LINK","INVALID_MATCH_VALUE","INVALID_PAYLOAD","INVALID_PERMISSIONS","INVALID_PROVIDER","INVALID_QUICKBOOKS_REFERENCE","INVALID_REQUEST","INVALID_RULE_TARGET","INVALID_SFTP_HOST","INVALID_SHOP_DOMAIN","INVALID_SIGNATURE","INVALID_STATE","INVALID_TENANT","INVALID_TIMEZONE","INVOICE_TOTAL_MISMATCH","KEY_ALREADY_ISSUED","LIMIT_EXCEEDED","LINE_COUNT_EXCEEDS_LIMIT","LINK_ALREADY_USED","LINK_EXPIRED","LOCKED","MALWARE_DETECTED","MALWARE_SCAN_UNAVAILABLE","MANUAL_HANDLING_SYSTEM_HOLD","MFA_REQUIRED","MICROSOFT_ACCOUNT_NOT_SUPPORTED","MICROSOFT_ADMIN_APPROVAL_REQUIRED","MICROSOFT_APP_NOT_IN_DIRECTORY","MISSING_SIGNATURE","MULTIPLE_CONNECTORS","MULTI_PO_MERGED","NOT_AN_ACCOUNTING_CONNECTOR","NOT_AN_INVOICE","NOT_AN_INVOICE_RESUBMIT","NOT_AN_ORDER","NOT_AN_ORDER_USE_REPROCESS","NOT_A_PROPOSED_CUSTOMER","NOT_A_QUICKBOOKS_CONNECTOR","NOT_CONFIGURED","NOT_CURRENT_OWNER","NOT_FOUND","NOT_IN_MANUAL_HANDLING","NOT_REVIEWABLE","NOT_TEXT_EXTRACTABLE","NO_CUSTOMER","NO_CUSTOMER_PROPOSAL","NO_DOCUMENT","NO_TENANT","OAUTH_AUTHORIZATION_REQUEST_EXPIRED","OAUTH_AUTHORIZATION_REQUEST_NOT_FOUND","OAUTH_CONSENT_CANCELLED","OAUTH_CONSENT_USER_MISMATCH","OAUTH_DENIED","OAUTH_FORWARDING_REQUIRED","OAUTH_GRANT_NOT_FOUND","OAUTH_ROUTE_NOT_ALLOWED","OAUTH_SCOPE_NOT_ALLOWED","OAUTH_TOKEN_INVALID","ONBOARDING_STEP_ORDER","ORDER_ALREADY_POSTED","ORDER_HAS_NO_LINES","ORDER_NOT_FOUND","OUTBOX_ROW_NOT_CANCELLED","OVERRIDE_REASON_REQUIRED","OWNER_CANNOT_BE_MOVED","PAGE_TOO_DEEP","PARSE_ERROR","PARTNER_NOT_FOUND","PAYLOAD_TOO_LARGE","PERMISSION_ESCALATION","PLAN_CHANGE_NEEDS_CHECKOUT","PLAN_LIMIT_EXCEEDED","PLAN_NOT_BILLABLE","POSTED_MONEY_MISMATCH","POSTING_BLOCKED","POSTING_DECISION_REQUIRED","POSTING_SETTING_NOT_SUPPORTED","PREPROCESS_FAILED","PROCESSING_ERROR","PROVIDER_NOT_CONFIGURED","PROVIDER_UNAVAILABLE","PROVISIONING_FAILED","QBO_ACCESS_DENIED","QBO_AUTH_EXPIRED","QBO_CUSTOMER_INACTIVE","QBO_DUPLICATE_DOC_NUMBER","QBO_ERROR","QBO_ITEM_NOT_FOUND","QBO_THROTTLED","QBO_VALIDATION","QUICKBOOKS_ACCOUNTS_UNAVAILABLE","QUICKBOOKS_COMPANY_NOT_SUPPORTED","QUICKBOOKS_UNAVAILABLE","RATE_LIMIT_EXCEEDED","RECONNECT","REVISION_CANCELLATION_CONFIRMATION_REQUIRED","REVISION_NOTHING_TO_CANCEL","REVISION_UPDATE_HAS_NO_LINES","ROUTED_TO_FILE_EXPORT","RULE_CONFLICT","RULE_NOT_FOUND","RULE_NOT_PROPOSED","SCIM_DIRECTORY_EXISTS","SCIM_NOT_CONFIGURED","SEAT_LIMIT_REACHED","SERVICE_UNAVAILABLE","SESSION_MISMATCH","SHOPIFY_ACCESS_DENIED","SHOPIFY_AUTH","SHOPIFY_LOCATION_REQUIRED","SHOPIFY_RATE_LIMITED","SHOPIFY_SHOP_FROZEN","SHOPIFY_SHOP_LOCKED","SHOPIFY_SHOP_NOT_FOUND","SHOPIFY_STORE_NOT_FOUND","SHOPIFY_UNREACHABLE","SHOPIFY_USER_ERROR","SHOPIFY_VARIANT_NOT_FOUND","SHOP_ALREADY_BOUND","SHOP_DOMAIN_MISMATCH","SIGNUP_ALREADY_MEMBER","SSO_ACS_ERROR","SSO_AUTHORIZE_ERROR","SSO_DISABLED","SSO_ENFORCED_OFF_DOMAIN","SSO_ENFORCEMENT_UNVERIFIED","SSO_OFF_DOMAIN_ADMINS","SSO_OIDC_ERROR","SSO_PRECONDITION_FAILED","SSO_SELECTOR_REQUIRED","SSO_UNAVAILABLE","STALE_PARKED","STORAGE_KEY_OUT_OF_SCOPE","STORAGE_UNAVAILABLE","STRIPE_ERROR","SUBSCRIPTION_REQUIRED","SYNC_ALREADY_RUNNING","SYNC_CONFIG_AMBIGUOUS","SYNC_FAILED","SYNC_NOT_CONFIGURED","TARGET_NOT_ACTIVE","TARGET_NOT_ELIGIBLE","TARGET_NOT_FOUND","TENANT_CAPACITY_EXCEEDED","TENANT_CONTEXT_REQUIRED","TENANT_NOT_FOUND","TENANT_OFFBOARDED","TENANT_OFFBOARDING","TENANT_RATE_LIMIT_EXCEEDED","TENANT_SUSPENDED","THROTTLED","TIMEOUT","TOKEN_EXCHANGE_FAILED","TOOL_NOT_AVAILABLE","TOPIC_MISMATCH","UNAUTHORIZED","UNKNOWN_LINE_ITEM","UNKNOWN_OUTCOME","UNKNOWN_QUEUE","UNSUPPORTED_CHANNEL_TYPE","UNSUPPORTED_CONNECTOR_TYPE","UNSUPPORTED_DOCUMENT_TYPE","UNSUPPORTED_MATCH_KEY","UNSUPPORTED_MEDIA_TYPE","UNSUPPORTED_OMS_TYPE","UNSUPPORTED_TOPIC","USER_DEACTIVATED","VALIDATION_ERROR","WEBHOOK_INACTIVE","WHOLE_UNITS_REQUIRED"],"description":"A machine-readable code from the error-code catalogue. Branch on this, not on message."},"message":{"type":"string","description":"One sentence for a person."},"details":{"description":"Structured facts about the refusal: for VALIDATION_ERROR an array of { path, message, code }; for a 409 gate, what to resend.","anyOf":[{"type":"object","additionalProperties":true},{"type":"array","items":{"type":"object","additionalProperties":true}}]},"correlationId":{"type":"string","description":"The request id (or envelope/order id) to quote to support."}},"required":["code","message"]}},"required":["error"],"example":{"error":{"code":"DOCUMENT_REQUIRED","message":"Provide either document (base64) or documentUrl.","correlationId":"req-7f3a9c"}}}},"responses":{"BadRequest":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"Unauthorized":{"description":"No valid credential: UNAUTHORIZED. Send X-API-Key (or a web session); a revoked or expired key is refused the same way.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"Forbidden":{"description":"The credential is valid but may not do this: FORBIDDEN or ACCESS_DENIED (the key lacks the permission scope, or the role is too low, or the tenant in the path is not the key's tenant), TENANT_SUSPENDED for writes on a suspended account, MFA_REQUIRED for a session that owes a passkey.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"NotFound":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"Conflict":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"UnsupportedMediaType":{"description":"UNSUPPORTED_MEDIA_TYPE: the document is not in a supported format. Convert it to PDF, XLSX, DOCX, CSV, PNG or JPEG.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"UnprocessableEntity":{"description":"The request is well formed but its values cannot be used, for example INVALID_PERMISSIONS on an API key.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"TooManyRequests":{"description":"TENANT_RATE_LIMIT_EXCEEDED (the plan's per-minute limit), RATE_LIMIT_EXCEEDED (the per-IP backstop) or TENANT_CAPACITY_EXCEEDED (too many concurrent requests). Wait for Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"InternalError":{"description":"INTERNAL_ERROR: something failed on our side. Retry with the same idempotency key; quote correlationId to support if it persists.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"ServiceUnavailable":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}},"paths":{"/api/v1/health":{"get":{"tags":["health"],"description":"Liveness probe","security":[],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"status":{"type":"string","enum":["ok","degraded"]},"timestamp":{"type":"string","format":"date-time"},"version":{"type":"string"},"commit":{"type":"string","nullable":true,"description":"Git commit the running build was deployed from; null outside Railway"}},"required":["status","timestamp","version","commit"]}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"}},"operationId":"getHealth","summary":"Liveness probe"}},"/api/v1/health/ready":{"get":{"tags":["health"],"description":"Readiness probe checking database, Redis, and S3. Deliberately excludes the model API; see the model component of /api/v1/platform/health.","security":[],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"status":{"type":"string","enum":["ok","degraded","unavailable"]},"timestamp":{"type":"string","format":"date-time"},"version":{"type":"string"},"commit":{"type":"string","nullable":true,"description":"Git commit the running build was deployed from; null outside Railway"},"checks":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string"},"status":{"type":"string","enum":["ok","error"]},"critical":{"type":"boolean"},"latencyMs":{"type":"number"},"message":{"type":"string"}},"required":["name","status","critical","latencyMs"]}}},"required":["status","timestamp","version","commit","checks"]}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"type":"object","properties":{"status":{"type":"string"},"timestamp":{"type":"string"},"version":{"type":"string"},"commit":{"type":"string","nullable":true},"checks":{"type":"array"}}}}}}},"operationId":"getHealthReady","summary":"Readiness probe checking database, Redis, and S3"}},"/api/v1/health/status":{"get":{"tags":["health"],"description":"Public status summary: overall status (ok, degraded, unavailable) and the customer-level components order-processing and deliveries (ok, degraded, outage). With a platform operator token (x-provisioning-token) the response is the detailed form (dependency checks, worker liveness, dead-letter count) instead. 503 when a critical dependency is down. A dead-lettered message degrades the status only while the dead-letter count has grown within the last HEALTH_DEAD_LETTER_WINDOW_MINUTES (default 60).","security":[],"responses":{"200":{"description":"OK. The result is in the body."},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"}},"operationId":"getHealthStatus","summary":"Get health status"}},"/api/v1/platform/value":{"get":{"tags":["platform"],"description":"Privacy-safe standardized verified work returned. Requires tenant authentication.","responses":{"200":{"description":"OK. The result is in the body."},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getPlatformValue","summary":"Privacy-safe standardized verified work returned"}},"/api/v1/tenants/{tenantId}":{"get":{"tags":["tenants"],"description":"Get tenant details","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"name":{"type":"string"},"slug":{"type":"string"},"status":{"type":"string","enum":["onboarding","active","suspended","offboarding","offboarded"]},"sandboxMode":{"type":"boolean","description":"Approved orders go to file export only, automatic approvals are not billed, acknowledgements are marked [SANDBOX]."},"settings":{"type":"object","additionalProperties":true},"channels":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"channelType":{"type":"string"},"status":{"type":"string"},"config":{"type":"object","additionalProperties":true}}}},"createdAt":{"type":"string","format":"date-time"},"updatedAt":{"type":"string","format":"date-time"}},"required":["id","name","slug","status","sandboxMode","settings","channels","createdAt","updatedAt"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getTenant","summary":"Get tenant details"},"patch":{"tags":["tenants"],"description":"Update tenant profile (currently: display name). The slug and intake address never change.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"properties":{"name":{"type":"string","minLength":2,"maxLength":100}},"required":["name"]}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"updateTenant","summary":"Update the tenant profile"}},"/api/v1/tenants/{tenantId}/channels":{"get":{"tags":["tenants"],"description":"List tenant channels","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"channels":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"tenantId":{"type":"string","format":"uuid"},"channelType":{"type":"string","enum":["email","sftp","api","upload","gmail","microsoft365","manual"]},"config":{"type":"object","additionalProperties":true},"status":{"type":"string","enum":["active","inactive","error"]},"createdAt":{"type":"string","format":"date-time"},"intakeAddress":{"type":"string","nullable":true,"description":"The forwarding address. Present on one email channel only: the one forwarded mail lands on (the shared forwarding channel when there is one, else the oldest mailbox)."}},"required":["id","tenantId","channelType","config","status","createdAt"]}}},"required":["channels"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"listChannels","summary":"List intake channels"},"post":{"tags":["tenants"],"description":"Create a new intake channel. `config` carries channel-type-specific settings; `config.referenceCustomerId` optionally binds every document arriving on the channel to one reference customer (the trading-partner identity used before extraction). It must be a UUID of an active reference customer of this tenant. On an IMAP mailbox, `config.trustedAuthservIds` (at most 5 lower-case authserv-ids, e.g. [\"mx.google.com\"]) names the receiving servers whose Authentication-Results header this mailbox believes; it asserts whose header to trust, never who a sender is, and omitting it leaves sender verification unchanged. `config.documentTypeDefault` ('order' or 'invoice', default 'order') sets what documents arriving on the channel are read as; email (IMAP, Gmail, Microsoft 365), SFTP and upload channels all honour it, and any other value is ignored. An `email` channel created here is a dedicated IMAP mailbox: `config.imapHost`, `imapPort`, `imapUser` and `imapPassword` are required (400 VALIDATION_ERROR with a `details` entry per missing field, such as `body.config.imapHost`). The shared forwarding address needs no channel of its own (it is created on the first forwarded message) and can coexist with a mailbox; `config.via` is reserved for it and refused here. Before a mailbox is stored, Poppelo signs in to it once: a refused sign-in answers 400 CONNECTION_VERIFICATION_FAILED with the server's reason (`details.errorKind` authentication_failed, connection or host_rejected; `details.field` the field to fix) and nothing is stored. 409 CHANNEL_EXISTS when an active channel of the same kind already exists.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"channelType":{"type":"string","enum":["email","sftp","api","upload"]},"config":{"type":"object","additionalProperties":true,"default":{}}},"required":["channelType"]}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"201":{"description":"Created. The new resource is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"tenantId":{"type":"string","format":"uuid"},"channelType":{"type":"string","enum":["email","sftp","api","upload","gmail","microsoft365","manual"]},"config":{"type":"object","additionalProperties":true,"description":"Channel settings, secrets redacted. `referenceCustomerId` (UUID, optional) is the trading partner every document on this channel belongs to."},"status":{"type":"string","enum":["active","inactive","error"]},"createdAt":{"type":"string","format":"date-time"}},"required":["id","tenantId","channelType","config","status","createdAt"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postChannels","summary":"Create a new intake channel"}},"/api/v1/tenants/{tenantId}/channels/health":{"get":{"tags":["tenants"],"description":"Per-channel liveness: when each intake channel last received a document, and whether that silence is normal for this tenant. The rhythm is read at day level over the last 90 days, so a burst of documents on one day counts once: `medianGapMinutes` is the median gap between consecutive distinct arrival days (UTC) in those 90 days, and `gapSampleSize` is how many such gaps there are. `envelopeCount30d` is the number of documents in the last 30 days. `band` compares the current silence with that median: beyond 3x is 'slow', beyond 6x is 'stale', and never 'slow' under 1 day of silence or 'stale' under 2 days. 'unknown' means there is not enough history to call the silence abnormal (fewer than 10 documents or fewer than 5 distinct arrival days in the last 90 days, or no document at all), and is always the band of a channel a person drives by hand (web upload, manual entry), which has no arrival rhythm. 'inactive' is a channel that is not active.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"computedAt":{"type":"string","format":"date-time"},"channels":{"type":"array","items":{"type":"object","properties":{"channelId":{"type":"string","format":"uuid"},"channelType":{"type":"string"},"status":{"type":"string"},"lastReceivedAt":{"type":"string","format":"date-time","nullable":true},"minutesSinceLast":{"type":"number","nullable":true},"medianGapMinutes":{"type":"number","nullable":true},"gapSampleSize":{"type":"integer"},"envelopeCount30d":{"type":"integer"},"band":{"type":"string","enum":["ok","slow","stale","inactive","unknown"]}},"required":["channelId","channelType","status","lastReceivedAt","gapSampleSize","envelopeCount30d","band"]}}},"required":["computedAt","channels"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getChannelsHealth","summary":"Get channels health"}},"/api/v1/tenants/{tenantId}/channels/{channelId}":{"patch":{"tags":["tenants"],"description":"Update a channel config or status. A config PATCH replaces the whole config object; `config.referenceCustomerId` (UUID of an active reference customer of this tenant) binds the channel to one trading partner, and an explicit null clears the binding. `config.trustedAuthservIds` (at most 5 lower-case authserv-ids) names the receiving servers whose Authentication-Results header an IMAP mailbox believes; omitting it on a PATCH clears it, restoring the unverified default.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"config":{"type":"object","additionalProperties":true},"status":{"type":"string","enum":["active","inactive","error"]}}}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"channelId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"patchChannelsByChannelId","summary":"Update a channel config or status"},"delete":{"tags":["tenants"],"description":"Archive a channel: it stops receiving and is hidden from listings; order history is kept","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"channelId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"deleteChannelsByChannelId","summary":"Archive a channel: it stops receiving and is hidden from listings; order history is kept"}},"/api/v1/tenants/{tenantId}/channels/{channelId}/test-connection":{"post":{"tags":["tenants"],"description":"Test connectivity for an SFTP channel (connects and lists the remote inbox)","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"channelId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"ok":{"type":"boolean"},"fileCount":{"type":"integer"},"hostKeyFingerprint":{"type":"string"},"error":{"type":"string"}},"required":["ok"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postChannelsByChannelIdTestConnection","summary":"Test connectivity for an SFTP channel (connects and lists the remote inbox)"}},"/api/v1/tenants/{tenantId}/rate-limit":{"get":{"tags":["tenants"],"description":"Current per-tenant API rate limit (from the subscription plan) and this minute's usage","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"limitPerMinute":{"type":"integer"},"source":{"type":"string","enum":["plan","default"]},"planSlug":{"type":"string","nullable":true},"currentMinuteUsage":{"type":"integer"},"remaining":{"type":"integer"}},"required":["limitPerMinute","source","currentMinuteUsage","remaining"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getRateLimit","summary":"Current per-tenant API rate limit (from the subscription plan) and this minute's usage"}},"/api/v1/tenants/{tenantId}/settings":{"patch":{"tags":["tenants"],"description":"Update tenant settings (partial merge)","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"confidenceThresholds":{"type":"object","properties":{"autoApprove":{"type":"number","minimum":0,"maximum":1},"reviewQueue":{"type":"number","minimum":0,"maximum":1},"reject":{"type":"number","minimum":0,"maximum":1}},"required":["autoApprove","reviewQueue","reject"]},"autoApprovalEnabled":{"type":"boolean"},"autoApprovalShadowMode":{"type":"boolean"},"sandboxMode":{"type":"boolean"},"naicsCode":{"type":"string","pattern":"^\\d{2,6}$"},"notificationEmail":{"type":"string","format":"email"},"minLineRouting":{"type":"boolean"},"orderValueCeiling":{"type":"number","exclusiveMinimum":0},"orderMinimum":{"type":"number","exclusiveMinimum":0},"approvalPolicies":{"type":"object","properties":{"requireReviewForNewMappings":{"type":"boolean"},"requireReviewForNewCustomers":{"type":"boolean"}}},"priceTolerancePercent":{"type":"number","minimum":0,"maximum":100},"listCurrency":{"type":"string","minLength":3,"maxLength":3},"listCountry":{"type":"string","minLength":2,"maxLength":2},"rampUpOverride":{"type":"boolean"},"queueSlaMinutes":{"type":"integer","exclusiveMinimum":0,"maximum":10080},"ackEmailEnabled":{"type":"boolean"},"intakeSenderHourlyCap":{"type":"integer","exclusiveMinimum":0,"maximum":10000},"retentionMonths":{"type":"integer","minimum":1,"maximum":84},"autoReconciliationEnabled":{"type":"boolean"},"erpWriteBackEnabled":{"type":"boolean"},"omsType":{"type":"string","enum":["netsuite","quickbooks","shopify","custom_rest"]},"defaultConnectorId":{"type":"string","format":"uuid"},"defaultDestinations":{"type":"object","properties":{"commerce":{"type":"string","format":"uuid","nullable":true},"accounting":{"type":"string","format":"uuid","nullable":true}}},"destinationPolicy":{"type":"string","enum":["commerce","accounting","both"]},"quickbooks":{"type":"object","properties":{"orderEntity":{"type":"string","enum":["estimate","invoice"]}}},"autonomy":{"type":"object","properties":{"proposeAfterCleanOrders":{"type":"integer","minimum":1,"maximum":1000}}},"exportConfig":{"type":"object","properties":{"format":{"type":"string","enum":["csv","xlsx","edi850"],"default":"csv"},"columns":{"type":"array","items":{"type":"object","properties":{"field":{"type":"string","minLength":1},"header":{"type":"string","minLength":1}},"required":["field","header"]}},"delivery":{"type":"object","properties":{"method":{"type":"string","enum":["download","email","sftp"]},"email":{"type":"string","format":"email"},"sftp":{"type":"object","properties":{"host":{"type":"string","minLength":1},"port":{"type":"integer","exclusiveMinimum":0,"default":22},"username":{"type":"string","minLength":1},"password":{"type":"string"},"privateKey":{"type":"string"},"hostKeyFingerprint":{"type":"string"},"remotePath":{"type":"string","minLength":1}},"required":["host","username","remotePath"]}},"required":["method"],"default":{"method":"download"}},"edi":{"type":"object","properties":{"senderQualifier":{"type":"string","minLength":1,"maxLength":2,"default":"ZZ"},"senderId":{"type":"string","minLength":1,"maxLength":15},"receiverQualifier":{"type":"string","minLength":1,"maxLength":2,"default":"ZZ"},"receiverId":{"type":"string","minLength":1,"maxLength":15},"usageIndicator":{"type":"string","enum":["P","T"],"default":"T"}},"required":["senderId","receiverId"]}}},"trustBaseline":{"type":"object","properties":{"minutesPerOrder":{"type":"number","exclusiveMinimum":0,"maximum":120},"laborRatePerHour":{"type":"number","exclusiveMinimum":0,"maximum":1000},"reviewMinutesPerOrder":{"type":"number","minimum":0,"maximum":120}},"required":["minutesPerOrder","laborRatePerHour"]},"pricing":{"type":"object","properties":{"perOrderRateCents":{"type":"integer","minimum":0},"platformFeeCents":{"type":"integer","minimum":0},"dailyInferenceBudgetUsd":{"type":"number","exclusiveMinimum":0,"maximum":10000,"nullable":true,"description":"Daily model-spend cap in USD for this tenant: greater than 0, at most 10000, at most two decimal places. null removes it. Once reached, each further document that day fails with DAILY_BUDGET_EXCEEDED. A tenant cap always wins over the platform cap."}}},"approveLinks":{"type":"object","properties":{"enabled":{"type":"boolean"},"expiryHours":{"type":"integer"}}},"documentTypes":{"type":"array","items":{"type":"string","enum":["purchase_order","supplier_invoice"]},"minItems":1},"formatLibrary":{"type":"object","properties":{"contribute":{"type":"boolean"},"consume":{"type":"boolean"}}},"goldenExamples":{"type":"object","properties":{"enabled":{"type":"boolean"}},"required":["enabled"]}}}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"patchSettings","summary":"Update tenant settings (partial merge)"}},"/api/v1/tenants/{tenantId}/deactivate":{"post":{"tags":["tenants"],"description":"Temporarily suspend the tenant. All intake stops: pollers skip the tenant, API keys are refused with 403 TENANT_SUSPENDED on every route except GET routes and POST /reactivate, and order, invoice and upload submissions by a signed-in user are refused with 403 TENANT_SUSPENDED. Data is kept and sign-in stays open for every role so an owner can see state, export and reactivate. Reversible via /reactivate.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postDeactivate","summary":"Temporarily suspend the tenant"}},"/api/v1/tenants/{tenantId}/reactivate":{"post":{"tags":["tenants"],"description":"Reactivate a suspended tenant; order intake resumes.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postReactivate","summary":"Reactivate a suspended tenant; order intake resumes"}},"/api/v1/tenants/{tenantId}/channels/{provider}/connect":{"post":{"tags":["channels"],"description":"Begin the OAuth flow to connect a Gmail or Microsoft 365 mailbox as an intake channel","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":["object","null"],"properties":{"returnTo":{"type":"string","enum":["channels","onboarding","integrations"]}},"additionalProperties":false}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","enum":["gmail","microsoft365"]},"in":"path","name":"provider","required":true}],"responses":{"200":{"description":"A signed-in browser session gets `authorizeUrl` and a short-lived nonce cookie. An API key gets a one-time `connectUrl` instead: a signed-in owner or admin of this tenant must open it in their browser, and only that browser session can finish the connect.","content":{"application/json":{"schema":{"type":"object","description":"A signed-in browser session gets `authorizeUrl` and a short-lived nonce cookie. An API key gets a one-time `connectUrl` instead: a signed-in owner or admin of this tenant must open it in their browser, and only that browser session can finish the connect.","properties":{"authorizeUrl":{"type":"string","description":"Provider consent URL. Session callers only; must be finished in the same browser."},"connectUrl":{"type":"string","description":"One-time link for a signed-in owner or admin of the tenant (API-key callers). Single use."},"expiresAt":{"type":"string","format":"date-time","description":"When the one-time link stops working."},"requiresSignedInAdmin":{"type":"boolean","description":"True when a signed-in owner or admin must open connectUrl."}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postChannelsByProviderConnect","summary":"Begin the OAuth flow to connect a Gmail or Microsoft 365 mailbox as an intake channel"}},"/api/v1/tenants/{tenantId}/channels/microsoft365/admin-consent":{"post":{"tags":["channels"],"description":"Get a Microsoft admin-consent link for connecting a Microsoft 365 mailbox when the organization requires an admin to approve apps. The link asks for exactly the connect scopes (offline_access, Mail.Read, User.Read). Errors: 400 VALIDATION_ERROR (directory), 503 PROVIDER_NOT_CONFIGURED.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":["object","null"],"properties":{"returnTo":{"type":"string","enum":["channels","onboarding","integrations"]},"directory":{"type":"string","maxLength":253,"pattern":"^(?:[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}|(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,63}|organizations)$","description":"Optional. The organization's Microsoft tenant id or one of its domains (contoso.com). Defaults to `organizations`, which lets the admin sign in to their own directory."}},"additionalProperties":false}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"A signed-in browser session gets `adminConsentUrl` (and the connect nonce cookie). Open it as a Microsoft admin, or copy it to one: they approve Poppelo for the organization once, then a user connects the mailbox with the normal connect. An API key gets a one-time `connectUrl` instead, which a signed-in owner or admin of this tenant must open; it starts the admin consent in their browser.","content":{"application/json":{"schema":{"type":"object","description":"A signed-in browser session gets `adminConsentUrl` (and the connect nonce cookie). Open it as a Microsoft admin, or copy it to one: they approve Poppelo for the organization once, then a user connects the mailbox with the normal connect. An API key gets a one-time `connectUrl` instead, which a signed-in owner or admin of this tenant must open; it starts the admin consent in their browser.","properties":{"adminConsentUrl":{"type":"string","description":"Microsoft admin-consent URL. Session callers only."},"connectUrl":{"type":"string","description":"One-time link for a signed-in owner or admin of the tenant (API-key callers). Single use."},"expiresAt":{"type":"string","format":"date-time","description":"When the one-time link stops working (API-key callers)."},"requiresSignedInAdmin":{"type":"boolean","description":"True when a signed-in owner or admin must open connectUrl."},"directory":{"type":"string","description":"The Microsoft directory the admin signs in to: `organizations`, a tenant id or a domain."},"scopes":{"type":"array","items":{"type":"string"},"description":"The Microsoft permissions the admin approves: exactly what the mailbox connect requests."}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postChannelsMicrosoft365AdminConsent","summary":"Create channel microsoft365 admin consent"}},"/api/v1/oauth/{provider}/callback":{"get":{"tags":["channels"],"description":"OAuth provider redirect target completing a mailbox channel connection","parameters":[{"schema":{"type":"string","enum":["gmail","microsoft365"]},"in":"path","name":"provider","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getOauthByProviderCallback","summary":"OAuth provider redirect target completing a mailbox channel connection"}},"/api/v1/tenants/{tenantId}/oauth/quickbooks/connect":{"get":{"tags":["integrations"],"description":"Begin the OAuth flow to connect QuickBooks Online as the ERP write-back target. Pass connectorId to reconnect a company already connected (for example one whose connection expires soon): reconnecting it does not count against the plan limit. Only US QuickBooks Online companies can be connected; a company set up in another country is refused at the end of the flow.","parameters":[{"schema":{"type":"string","enum":["channels","onboarding","integrations"]},"in":"query","name":"returnTo","required":false},{"schema":{"type":"string","format":"uuid"},"in":"query","name":"connectorId","required":false,"description":"The QuickBooks company being reconnected, when it is one already connected."},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"A signed-in browser session gets `authorizeUrl` and a short-lived nonce cookie. An API key gets a one-time `connectUrl` instead: a signed-in owner or admin of this tenant must open it in their browser, and only that browser session can finish the connect.","content":{"application/json":{"schema":{"type":"object","description":"A signed-in browser session gets `authorizeUrl` and a short-lived nonce cookie. An API key gets a one-time `connectUrl` instead: a signed-in owner or admin of this tenant must open it in their browser, and only that browser session can finish the connect.","properties":{"authorizeUrl":{"type":"string","description":"Provider consent URL. Session callers only; must be finished in the same browser."},"connectUrl":{"type":"string","description":"One-time link for a signed-in owner or admin of the tenant (API-key callers). Single use."},"expiresAt":{"type":"string","format":"date-time","description":"When the one-time link stops working."},"requiresSignedInAdmin":{"type":"boolean","description":"True when a signed-in owner or admin must open connectUrl."}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getOauthQuickbooksConnect","summary":"Begin the OAuth flow to connect QuickBooks Online as the ERP write-back target"}},"/api/v1/tenants/{tenantId}/oauth/shopify/connect":{"get":{"tags":["integrations"],"description":"Begin the OAuth flow to connect a Shopify store as the draft-order write-back target. `shop` may be the store name (acme-supply), its myshopify.com domain, or a Shopify admin link.","parameters":[{"schema":{"type":"string","maxLength":255},"in":"query","name":"shop","required":true},{"schema":{"type":"string","enum":["channels","onboarding","integrations"]},"in":"query","name":"returnTo","required":false},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"A signed-in browser session gets `authorizeUrl` and a short-lived nonce cookie. An API key gets a one-time `connectUrl` instead: a signed-in owner or admin of this tenant must open it in their browser, and only that browser session can finish the connect.","content":{"application/json":{"schema":{"type":"object","description":"A signed-in browser session gets `authorizeUrl` and a short-lived nonce cookie. An API key gets a one-time `connectUrl` instead: a signed-in owner or admin of this tenant must open it in their browser, and only that browser session can finish the connect.","properties":{"authorizeUrl":{"type":"string","description":"Provider consent URL. Session callers only; must be finished in the same browser."},"connectUrl":{"type":"string","description":"One-time link for a signed-in owner or admin of the tenant (API-key callers). Single use."},"expiresAt":{"type":"string","format":"date-time","description":"When the one-time link stops working."},"requiresSignedInAdmin":{"type":"boolean","description":"True when a signed-in owner or admin must open connectUrl."}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getOauthShopifyConnect","summary":"Begin the OAuth flow to connect a Shopify store as the draft-order write-back target"}},"/api/v1/oauth/quickbooks/callback":{"get":{"tags":["integrations"],"description":"Intuit OAuth redirect target completing a QuickBooks connection","security":[],"responses":{"200":{"description":"OK. The result is in the body."},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"}},"operationId":"getOauthQuickbooksCallback","summary":"Intuit OAuth redirect target completing a QuickBooks connection"}},"/api/v1/oauth/shopify/callback":{"get":{"tags":["integrations"],"description":"Shopify OAuth redirect target completing a store connection","security":[],"responses":{"200":{"description":"OK. The result is in the body."},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"}},"operationId":"getOauthShopifyCallback","summary":"Shopify OAuth redirect target completing a store connection"}},"/api/v1/oauth/shopify/install":{"get":{"tags":["integrations"],"description":"Shopify App URL: opened by Shopify, signed with the app secret, when a merchant installs or opens the app. Starts the store connect for the signed-in admin, or sends the browser to sign in first. Redirects; never returns JSON on success.","parameters":[{"schema":{"type":"string","maxLength":255},"in":"query","name":"shop","required":false},{"schema":{"type":"string","maxLength":128},"in":"query","name":"hmac","required":false},{"schema":{"type":"string","maxLength":20},"in":"query","name":"timestamp","required":false},{"schema":{"type":"string","maxLength":512},"in":"query","name":"host","required":false}],"security":[],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"}},"operationId":"getOauthShopifyInstall","summary":"Get oauth shopify install"}},"/api/v1/oauth/connect-link":{"get":{"tags":["integrations"],"description":"One-time QuickBooks, Shopify, Gmail or Microsoft 365 connect link returned to an API-key caller. Must be opened in a browser by a signed-in owner or admin of the tenant; redirects to the provider.","parameters":[{"schema":{"type":"string","maxLength":4096},"in":"query","name":"token","required":false}],"security":[],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"}},"operationId":"getOauthConnectLink","summary":"Get oauth connect link"}},"/api/v1/tenants/{tenantId}/connectors/custom_rest":{"put":{"tags":["integrations"],"description":"Configure the custom REST connector: approved orders POST the canonical order JSON to this endpoint (HMAC-signed when a signing secret is set)","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"endpointUrl":{"type":"string"},"authToken":{"type":"string","nullable":true},"signingSecret":{"type":"string","nullable":true}},"required":["endpointUrl"]}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"connectorType":{"type":"string"},"endpointUrl":{"type":"string"},"hasAuthToken":{"type":"boolean"},"hasSigningSecret":{"type":"boolean"}},"required":["connectorType","endpointUrl","hasAuthToken","hasSigningSecret"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"402":{"description":"PLAN_LIMIT_EXCEEDED: the plan has no room for another active destination. When the connect itself found no room, the credentials are stored and the connector is plan-suspended; upgrade, then reactivate it.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"$ref":"#/components/responses/Forbidden"},"409":{"description":"INVALID_STATE: the connector changed while it was being saved; details.currentStatus is its status now, details.next is \"retry\".","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"putConnectorsCustomRest","summary":"Replace connectors custom rest"},"get":{"tags":["integrations"],"description":"Read the custom REST connector configuration (secrets redacted to presence flags)","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getConnectorsCustomRest","summary":"Read the custom REST connector configuration (secrets redacted to presence flags)"},"delete":{"tags":["integrations"],"description":"Remove the custom REST connector; write-back falls back to file export","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"deleteConnectorsCustomRest","summary":"Remove the custom REST connector; write-back falls back to file export"}},"/api/v1/tenants/{tenantId}/connectors/custom_rest/test":{"post":{"tags":["integrations"],"description":"Send a synthetic test order (type \"test\") to the configured custom REST endpoint. Receivers must not fulfill test payloads.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"ok":{"type":"boolean"},"externalId":{"type":"string","nullable":true},"error":{"type":"string","nullable":true,"description":"The connector's own error text. Prefer `summary`, `status` and `bodyExcerpt`."},"status":{"type":"integer","nullable":true,"description":"HTTP status the endpoint answered with; null when it could not be reached."},"statusText":{"type":"string","nullable":true,"description":"Standard reason phrase for `status`, e.g. \"Method Not Allowed\"."},"bodyExcerpt":{"type":"string","nullable":true,"maxLength":200,"description":"At most 200 characters of the response body on a failed test."},"summary":{"type":"string","description":"One plain sentence describing the result, e.g. \"Your endpoint answered 405 Method Not Allowed. …\"."}},"required":["ok","status","statusText","bodyExcerpt","summary"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postConnectorsCustomRestTest","summary":"Send a synthetic test order (type \"test\") to the configured custom REST endpoint"}},"/api/v1/tenants/{tenantId}/connectors/netsuite":{"put":{"tags":["integrations"],"description":"Configure NetSuite write-back with Token-Based Authentication credentials. Credentials are verified with a live read-only probe before being stored.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"accountId":{"type":"string"},"consumerKey":{"type":"string"},"consumerSecret":{"type":"string"},"tokenId":{"type":"string"},"tokenSecret":{"type":"string"}},"required":["accountId","consumerKey","consumerSecret","tokenId","tokenSecret"]}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"connectorType":{"type":"string"},"accountId":{"type":"string"},"verified":{"type":"boolean"}},"required":["connectorType","accountId","verified"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"402":{"description":"PLAN_LIMIT_EXCEEDED: the plan has no room for another active destination. When the connect itself found no room, the credentials are stored and the connector is plan-suspended; upgrade, then reactivate it.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"$ref":"#/components/responses/Forbidden"},"409":{"description":"INVALID_STATE: the connector changed while it was being saved; details.currentStatus is its status now, details.next is \"retry\".","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"putConnectorsNetsuite","summary":"Configure NetSuite write-back with Token-Based Authentication credentials"},"get":{"tags":["integrations"],"description":"Read the NetSuite connector status (credentials never returned)","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getConnectorsNetsuite","summary":"Read the NetSuite connector status (credentials never returned)"},"delete":{"tags":["integrations"],"description":"Remove the NetSuite connector; write-back falls back to file export","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"deleteConnectorsNetsuite","summary":"Remove the NetSuite connector; write-back falls back to file export"}},"/api/v1/tenants/{tenantId}/connectors/netsuite/test":{"post":{"tags":["integrations"],"description":"Test the stored NetSuite connection with a read-only probe","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"ok":{"type":"boolean"},"error":{"type":"string","nullable":true}},"required":["ok"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postConnectorsNetsuiteTest","summary":"Test the stored NetSuite connection with a read-only probe"}},"/api/v1/tenants/{tenantId}/connectors/quickbooks":{"delete":{"tags":["integrations"],"description":"Disconnect QuickBooks: revoke the grant, delete stored credentials, and fall back to file export if it was the destination","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"deleteConnectorsQuickbooks","summary":"Delete connectors quickbooks"}},"/api/v1/tenants/{tenantId}/connectors/shopify":{"delete":{"tags":["integrations"],"description":"Disconnect Shopify: revoke the grant, delete stored credentials, and fall back to file export if it was the destination","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"deleteConnectorsShopify","summary":"Delete connectors shopify"}},"/api/v1/tenants/{tenantId}/connectors/instances/{connectorId}":{"patch":{"tags":["integrations"],"description":"Update non-secret settings on a connected account: its display name, and for QuickBooks/NetSuite the default expense account that supplier invoices post against (required before invoices can be written back as bills; null clears it).","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"displayName":{"type":"string","minLength":1,"maxLength":120},"defaultExpenseAccountId":{"type":["string","null"],"maxLength":100},"posting":{"type":"object","description":"Per-account posting settings; each field is optional and null clears it. QuickBooks companies: orderEntity, classId, departmentId, defaultTermsId, freightItemId, servicesItemId, otherChargesItemId, documentNumber — reference ids are checked against the live company (400 INVALID_QUICKBOOKS_REFERENCE names the field). Shopify stores: allowCustomLineItems, customLineItemsTaxable.","properties":{"allowCustomLineItems":{"type":["boolean","null"],"description":"Shopify only. Post a line this store does not sell (a placeholder part number such as \"NA\", or a SKU with no variant) as a custom line item — title = the PO description, price = the approved unit price, requiresShipping false — once its mapping is confirmed with PUT.../posting-decisions lineMappings ('services'; 'freight' becomes the draft's shipping line). Off by default: such an order is held for the store (POSTING_DECISION_REQUIRED). null resets to off."},"customLineItemsTaxable":{"type":["boolean","null"],"description":"Shopify only. Whether those custom line items are taxable. Default true; null resets it."},"orderEntity":{"type":["string","null"],"enum":["estimate","invoice",null],"description":"What an approved order becomes in this company. null falls back to the tenant-wide settings.quickbooks.orderEntity (default estimate)."},"classId":{"type":["string","null"],"minLength":1,"maxLength":64,"description":"Class applied to every document (requires class tracking per transaction)."},"departmentId":{"type":["string","null"],"minLength":1,"maxLength":64,"description":"Department / Location applied to every document (requires location tracking)."},"defaultTermsId":{"type":["string","null"],"minLength":1,"maxLength":64,"description":"Term used when the customer has no terms of its own."},"freightItemId":{"type":["string","null"],"minLength":1,"maxLength":64,"description":"Service/NonInventory item that freight and shipping charges post against."},"servicesItemId":{"type":["string","null"],"minLength":1,"maxLength":64,"description":"Service/NonInventory item that description-only lines (\"NA\", services) post against."},"otherChargesItemId":{"type":["string","null"],"minLength":1,"maxLength":64,"description":"Service/NonInventory item that handling and other charges post against."},"documentNumber":{"type":["string","null"],"enum":["po","blank",null],"description":"Applies only when the company has custom transaction numbers on (otherwise QuickBooks numbers documents itself). 'po' (default): number the document by the buyer's PO, checked for duplicates first, -R2 on another customer's clash. 'blank': send no number, for the bookkeeper to fill in. null resets to 'po'."}},"additionalProperties":false}},"additionalProperties":false}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"connectorId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"connectorId":{"type":"string","format":"uuid"},"connectorType":{"type":"string"},"displayName":{"type":["null","string"]},"defaultExpenseAccountId":{"type":["null","string"]},"posting":{"type":["null","object"],"properties":{"orderEntity":{"type":"string","enum":["estimate","invoice"]},"orderEntitySource":{"type":"string","enum":["instance","tenant_default"]},"classId":{"type":["null","string"]},"departmentId":{"type":["null","string"]},"defaultTermsId":{"type":["null","string"]},"freightItemId":{"type":["null","string"]},"servicesItemId":{"type":["null","string"]},"otherChargesItemId":{"type":["null","string"]},"documentNumber":{"type":"string","enum":["po","blank"]},"allowCustomLineItems":{"type":"boolean","description":"Shopify stores only."},"customLineItemsTaxable":{"type":"boolean","description":"Shopify stores only."}},"description":"The posting settings now in effect: a QuickBooks company's (orderEntity … documentNumber) or a Shopify store's (allowCustomLineItems, customLineItemsTaxable); null for other connectors."}}}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"object","properties":{"code":{"type":"string"},"message":{"type":"string"},"details":{"type":"object","additionalProperties":true},"correlationId":{"type":"string"}}}}}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"502":{"description":"An upstream provider (an accounting system, store or mailbox) answered with an error; details says which.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"object","properties":{"code":{"type":"string"},"message":{"type":"string"},"details":{"type":"object","additionalProperties":true},"correlationId":{"type":"string"}}}}}}}},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"patchConnectorsInstancesByConnectorId","summary":"Update connector instance"},"delete":{"tags":["integrations"],"description":"Disconnect one connector instance: revoke the grant where supported, delete its credentials, and fall back to file export if it was the active destination","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"connectorId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"deleteConnectorsInstancesByConnectorId","summary":"Delete connector instance"}},"/api/v1/tenants/{tenantId}/connectors/instances/{connectorId}/quickbooks/options":{"get":{"tags":["integrations"],"description":"Live pickers for one QuickBooks company's posting settings: active classes, departments (Locations), terms, Service/NonInventory items (for freight, services and other charges), and the active Expense, Other Expense and Cost of Goods Sold accounts supplier bills can post against (`expenseAccounts`; send one `id` as `defaultExpenseAccountId` on PATCH.../connectors/instances/:connectorId), with the account chosen now (`defaultExpenseAccountId`), plus the company profile (home currency, multicurrency, sales tax mode, custom transaction numbers, class/location tracking, the P.O. Number sales-form field the PO is written to) and the posting settings in effect. Refreshes the cached company profile; read it after changing the company's sales form custom fields.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"connectorId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"connectorId":{"type":"string","format":"uuid"},"companyProfile":{"type":"object","properties":{"homeCurrency":{"type":["null","string"]},"multiCurrencyEnabled":{"type":"boolean"},"taxMode":{"type":"string","enum":["automated","manual","none"]},"customTxnNumbers":{"type":"boolean"},"allowDiscount":{"type":"boolean"},"classTracking":{"type":"boolean"},"departmentTracking":{"type":"boolean"},"companyDefaultTermsId":{"type":["null","string"]},"poCustomField":{"type":["null","object"],"description":"The custom field named like a PO number (\"P.O. Number\", \"PO #\", \"Purchase Order\", \"Customer PO\") that the buyer's PO is written to. source legacy_preferences: a legacy sales-form field from Preferences (definitionId 1-3). source enhanced_transactions: an enhanced custom field (QuickBooks' current Custom fields page), found on the company's recent invoices and estimates; it becomes visible once one document carries a value. null when none was found, so the PO goes on the memo only (looked for again after a day); absent when it could not be read.","properties":{"definitionId":{"type":"string"},"name":{"type":"string"},"source":{"type":"string","enum":["legacy_preferences","enhanced_transactions"]}}},"fetchedAt":{"type":"string"}}},"posting":{"type":"object","properties":{"orderEntity":{"type":"string","enum":["estimate","invoice"]},"orderEntitySource":{"type":"string","enum":["instance","tenant_default"]},"classId":{"type":["null","string"]},"departmentId":{"type":["null","string"]},"defaultTermsId":{"type":["null","string"]},"freightItemId":{"type":["null","string"]},"servicesItemId":{"type":["null","string"]},"otherChargesItemId":{"type":["null","string"]},"documentNumber":{"type":"string","enum":["po","blank"]},"allowCustomLineItems":{"type":"boolean","description":"Shopify stores only."},"customLineItemsTaxable":{"type":"boolean","description":"Shopify stores only."}}},"classes":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"}}}},"departments":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"}}}},"terms":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"dueDays":{"type":["null","integer"]}}}},"items":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"type":{"type":"string"}}}},"expenseAccounts":{"type":["null","array"],"description":"Active accounts a supplier bill can post against (Expense, Other Expense, Cost of Goods Sold), sorted by full name. Send one id as defaultExpenseAccountId on PATCH; the PATCH still checks it against the company. Null when the account list could not be read (see expenseAccountsUnavailable); the other pickers are still returned.","items":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string","description":"Full account name (Parent:Child for a sub-account)."},"accountType":{"type":"string","enum":["Expense","Other Expense","Cost of Goods Sold"]}},"required":["id","name","accountType"]}},"defaultExpenseAccountId":{"type":["null","string"],"description":"The account supplier bills post against now; null when none is set (bills then export as files)."},"expenseAccountsUnavailable":{"type":["null","object"],"description":"Why expenseAccounts is null (the account list could not be read from QuickBooks); null when the list was read. Retry the read; the saved defaultExpenseAccountId is unaffected.","properties":{"code":{"type":"string","enum":["QUICKBOOKS_ACCOUNTS_UNAVAILABLE"]},"message":{"type":"string"}},"required":["code","message"]}}}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"object","properties":{"code":{"type":"string"},"message":{"type":"string"},"details":{"type":"object","additionalProperties":true},"correlationId":{"type":"string"}}}}}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"object","properties":{"code":{"type":"string"},"message":{"type":"string"},"details":{"type":"object","additionalProperties":true},"correlationId":{"type":"string"}}}}}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"502":{"description":"An upstream provider (an accounting system, store or mailbox) answered with an error; details says which.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"object","properties":{"code":{"type":"string"},"message":{"type":"string"},"details":{"type":"object","additionalProperties":true},"correlationId":{"type":"string"}}}}}}}},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getConnectorsInstancesByConnectorIdQuickbooksOptions","summary":"List connectors instances quickbooks options"}},"/api/v1/tenants/{tenantId}/connectors/instances/{connectorId}/reactivate":{"post":{"tags":["integrations"],"description":"Reactivate a connector instance suspended by a plan downgrade (suspended_at set). A suspended instance becomes active when the plan has room (402 otherwise); one that is also in error or disconnected loses the suspension, keeps its status and answers next \"reconnect\". An instance the plan did not suspend answers 409 INVALID_STATE unless it is already active (reactivated false).","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"connectorId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"connectorId":{"type":"string","format":"uuid"},"status":{"type":"string","description":"The connector status after the call: active, or error / disconnected when only the suspension was lifted."},"reactivated":{"type":"boolean","description":"False when the connector was already active and nothing changed."},"next":{"type":"string","enum":["reconnect"],"description":"Present when the suspension was lifted but the credentials still need a reconnect."}},"required":["connectorId","status","reactivated"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"402":{"description":"PLAN_LIMIT_EXCEEDED: the plan has no room for this connector to be active.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND: no such connector for this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"INVALID_STATE: the connector is not plan-suspended (details.next \"reconnect\"), or it changed during the call (details.next \"retry\"); details.currentStatus is its status now.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postConnectorsInstancesByConnectorIdReactivate","summary":"Reactivate a connector instance suspended by a plan downgrade (suspended_at set)"}},"/api/v1/tenants/{tenantId}/connectors/instances/{connectorId}/test":{"post":{"tags":["integrations"],"description":"Test one connected account with a read-only request against its stored credentials: Shopify reads the shop name and granted access scopes; QuickBooks reads CompanyInfo (refreshing the access token once if it expired); NetSuite reads one customer. Returns ok, the account name, required permissions the installation lacks, and latency. A revoked or missing credential sets the instance status to \"error\" (it stops receiving orders until reconnected); a successful test restores \"active\". Transient failures and plan-suspended instances leave the status unchanged. Always 200 when the instance exists — read ok and error.code.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"connectorId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"ok":{"type":"boolean"},"connectorId":{"type":"string","format":"uuid"},"connectorType":{"type":"string"},"checkedAt":{"type":"string","format":"date-time"},"account":{"type":"object","properties":{"name":{"type":"string","nullable":true}},"required":["name"]},"permissions":{"type":"object","properties":{"missing":{"type":"array","items":{"type":"string"},"description":"Required provider scopes this installation was not granted (Shopify), e.g. read_companies."}},"required":["missing"]},"latencyMs":{"type":"number"},"status":{"type":"string","description":"The instance status after the test: active | error | suspended | pending."},"error":{"type":"object","properties":{"code":{"type":"string","enum":["SHOPIFY_AUTH","SHOPIFY_STORE_NOT_FOUND","SHOPIFY_STORE_UNAVAILABLE","SHOPIFY_RATE_LIMITED","SHOPIFY_UNREACHABLE","QBO_AUTH_EXPIRED","QBO_UNREACHABLE","QBO_ERROR","NETSUITE_AUTH","NETSUITE_ERROR","CREDENTIALS_MISSING","UNSUPPORTED_CONNECTOR_TYPE"]},"message":{"type":"string"},"nextStep":{"type":"string"}},"required":["code","message","nextStep"]}},"required":["ok","connectorId","connectorType","checkedAt","account","permissions","latencyMs","status"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postConnectorsInstancesByConnectorIdTest","summary":"Test connector instance"}},"/api/v1/tenants/{tenantId}/order-acknowledgements/settings":{"get":{"tags":["order-acknowledgements"],"description":"Whether buyers get an acknowledgement for each order once it is in the store or the books.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"enabled":{"type":"boolean","description":"Acknowledge each order to its buyer once it is written to the store or the books."},"enabledAt":{"type":"string","format":"date-time","nullable":true,"description":"Orders written before this are never acknowledged automatically."},"receiptAckEnabled":{"type":"boolean","description":"The earlier \"we received your order email\" reply sent at intake (settings.ackEmailEnabled)."},"includePrices":{"type":"boolean","description":"Include unit prices and the order total in the acknowledgement. Default true."}},"required":["enabled","enabledAt","receiptAckEnabled","includePrices"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getOrderAcknowledgementsSettings","summary":"Whether buyers get an acknowledgement for each order once it is in the store or the books"},"put":{"tags":["order-acknowledgements"],"description":"Turn buyer order acknowledgements on or off. Turning them on only acknowledges orders written from now on — it never emails a backlog.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"enabled":{"type":"boolean"},"receiptAckEnabled":{"type":"boolean"},"includePrices":{"type":"boolean"}},"additionalProperties":false,"minProperties":1}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"enabled":{"type":"boolean","description":"Acknowledge each order to its buyer once it is written to the store or the books."},"enabledAt":{"type":"string","format":"date-time","nullable":true,"description":"Orders written before this are never acknowledged automatically."},"receiptAckEnabled":{"type":"boolean","description":"The earlier \"we received your order email\" reply sent at intake (settings.ackEmailEnabled)."},"includePrices":{"type":"boolean","description":"Include unit prices and the order total in the acknowledgement. Default true."}},"required":["enabled","enabledAt","receiptAckEnabled","includePrices"]}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"putOrderAcknowledgementsSettings","summary":"Turn buyer order acknowledgements on or off"}},"/api/v1/tenants/{tenantId}/order-acknowledgements/customers":{"get":{"tags":["order-acknowledgements"],"description":"Customers whose acknowledgement setting differs from the account default.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"customers":{"type":"array","items":{"type":"object","properties":{"referenceCustomerId":{"type":"string","format":"uuid"},"name":{"type":"string"},"mode":{"type":"string","enum":["always","never"]}},"required":["referenceCustomerId","name","mode"]}}},"required":["customers"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getOrderAcknowledgementsCustomers","summary":"Customers whose acknowledgement setting differs from the account default"}},"/api/v1/tenants/{tenantId}/order-acknowledgements/customers/{referenceCustomerId}":{"put":{"tags":["order-acknowledgements"],"description":"Override acknowledgements for one customer: 'always', 'never', or 'default' to follow the account setting.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"mode":{"type":"string","enum":["always","never","default"]}},"required":["mode"],"additionalProperties":false}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"referenceCustomerId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"referenceCustomerId":{"type":"string","format":"uuid"},"name":{"type":"string"},"mode":{"type":"string","enum":["always","never","default"]}},"required":["referenceCustomerId","name","mode"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"putOrderAcknowledgementsCustomersByReferenceCustomerId","summary":"Replace order acknowledgement customer"}},"/api/v1/tenants/{tenantId}/orders/{orderId}/acknowledgements":{"get":{"tags":["order-acknowledgements"],"description":"Acknowledgements sent to the buyer for this order, newest first.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"orderId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"acknowledgements":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"orderId":{"type":"string","format":"uuid"},"envelopeId":{"type":"string","format":"uuid"},"trigger":{"type":"string","enum":["automatic","manual"]},"status":{"type":"string","enum":["sending","sent","failed"]},"recipient":{"type":"string"},"subject":{"type":"string"},"sentAt":{"type":"string","format":"date-time","nullable":true},"createdAt":{"type":"string","format":"date-time"},"lastError":{"type":"string","nullable":true},"requestedBy":{"type":"string","nullable":true}},"required":["id","orderId","envelopeId","trigger","status","recipient","subject","sentAt","createdAt"]}}},"required":["acknowledgements"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getOrdersByOrderIdAcknowledgements","summary":"Acknowledgements sent to the buyer for this order, newest first"}},"/api/v1/tenants/{tenantId}/orders/{orderId}/acknowledge":{"post":{"tags":["order-acknowledgements"],"description":"Send the buyer an acknowledgement for this order now, or send it again. Records an audit row and fires order.acknowledged. Refused (409 ORDER_NOT_WRITTEN) until the order is in the store or the books.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"orderId","required":true}],"responses":{"201":{"description":"Created. The new resource is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"orderId":{"type":"string","format":"uuid"},"envelopeId":{"type":"string","format":"uuid"},"trigger":{"type":"string","enum":["automatic","manual"]},"status":{"type":"string","enum":["sending","sent","failed"]},"recipient":{"type":"string"},"subject":{"type":"string"},"sentAt":{"type":"string","format":"date-time","nullable":true},"createdAt":{"type":"string","format":"date-time"},"lastError":{"type":"string","nullable":true},"requestedBy":{"type":"string","nullable":true}},"required":["id","orderId","envelopeId","trigger","status","recipient","subject","sentAt","createdAt"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"422":{"description":"The request is well formed but its values cannot be used, for example INVALID_PERMISSIONS on an API key.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"502":{"description":"An upstream provider (an accounting system, store or mailbox) answered with an error; details says which.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"postOrdersByOrderIdAcknowledge","summary":"Send the buyer an acknowledgement for this order now, or send it again"}},"/api/v1/tenants/{tenantId}/format-library/partners":{"get":{"tags":["format-library"],"description":"The tenant's own active trading partners for whom the cross-tenant format library has at least one published convention, and which kinds are already active, proposed, suspended, or available to offer. Never lists a domain the tenant does not already have on file.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"partners":{"type":"array","items":{"type":"object","properties":{"referenceCustomerId":{"type":"string","format":"uuid"},"name":{"type":"string"},"buyerDomain":{"type":"string"},"kinds":{"type":"array","items":{"type":"object","properties":{"kind":{"type":"string"},"status":{"type":"string","enum":["active","proposed","suspended","available"]}},"required":["kind","status"]}}},"required":["referenceCustomerId","name","buyerDomain","kinds"]}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getFormatLibraryPartners","summary":"List format library partners"}},"/api/v1/tenants/{tenantId}/double-post-findings":{"get":{"tags":["double-post-findings"],"description":"Possible double posts found in QuickBooks for a write-both account (destinationPolicy both): another app's Invoice or SalesReceipt that looks like an order Poppelo already posted. Newest first. Poppelo never changes the books.","parameters":[{"schema":{"type":"string","enum":["open","dismissed"]},"in":"query","name":"status","required":false},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"findings":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"tenantId":{"type":"string","format":"uuid"},"orderId":{"type":"string","format":"uuid"},"envelopeId":{"type":"string","format":"uuid"},"destinationId":{"type":"string","format":"uuid","nullable":true},"connectorId":{"type":"string","format":"uuid","nullable":true},"realmId":{"type":"string","description":"The QuickBooks company file both documents are in."},"companyName":{"type":"string","nullable":true},"customerName":{"type":"string","nullable":true},"status":{"type":"string","enum":["open","dismissed"]},"matchReason":{"type":"string","enum":["po_reference","total_and_lines"],"description":"po_reference: the PO appears in the other document's DocNumber, PrivateNote, CustomerMemo or a custom field. total_and_lines: same customer, total within $0.01, dated within 2 days, line items overlapping at least 80%."},"matchDetail":{"type":"object","additionalProperties":true},"poppeloDocument":{"type":"object","properties":{"entity":{"type":"string","description":"Estimate, Invoice or SalesReceipt."},"id":{"type":"string","description":"QuickBooks' transaction id in this company."},"docNumber":{"type":"string","nullable":true},"total":{"type":"number","nullable":true},"txnDate":{"type":"string","nullable":true},"createdAt":{"type":"string","nullable":true,"description":"When QuickBooks recorded the document (MetaData.CreateTime)."},"url":{"type":"string","nullable":true,"description":"Opens in the QuickBooks company the browser is signed in to; see linkNote."}},"required":["entity","id","docNumber","total","url"]},"otherDocument":{"type":"object","properties":{"entity":{"type":"string","description":"Estimate, Invoice or SalesReceipt."},"id":{"type":"string","description":"QuickBooks' transaction id in this company."},"docNumber":{"type":"string","nullable":true},"total":{"type":"number","nullable":true},"txnDate":{"type":"string","nullable":true},"createdAt":{"type":"string","nullable":true,"description":"When QuickBooks recorded the document (MetaData.CreateTime)."},"url":{"type":"string","nullable":true,"description":"Opens in the QuickBooks company the browser is signed in to; see linkNote."}},"required":["entity","id","docNumber","total","url"]},"syncApp":{"type":"string","nullable":true,"description":"synder | a2x | webgility | intuit_connector | shopify_sync, when the other document names the app; null otherwise."},"message":{"type":"string","description":"QuickBooks may contain this order twice: Estimate 1043 (Poppelo) and Invoice 2217 (created by another app on 14 Sep)."},"reason":{"type":"string"},"linkNote":{"type":"string"},"excludeInstructions":{"type":"string","nullable":true,"description":"How to make the sync app skip Poppelo's orders; on the tenant's first finding."},"detectedAt":{"type":"string","format":"date-time"},"dismissedAt":{"type":"string","format":"date-time","nullable":true},"dismissedBy":{"type":"string","nullable":true}},"required":["id","orderId","envelopeId","realmId","status","matchReason","poppeloDocument","otherDocument","message","detectedAt"]}}},"required":["findings"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getDoublePostFindings","summary":"List double post findings"}},"/api/v1/tenants/{tenantId}/orders/{orderId}/double-post-findings":{"get":{"tags":["double-post-findings"],"description":"Possible double posts of this order in QuickBooks, open and dismissed, newest first.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"orderId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"findings":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"tenantId":{"type":"string","format":"uuid"},"orderId":{"type":"string","format":"uuid"},"envelopeId":{"type":"string","format":"uuid"},"destinationId":{"type":"string","format":"uuid","nullable":true},"connectorId":{"type":"string","format":"uuid","nullable":true},"realmId":{"type":"string","description":"The QuickBooks company file both documents are in."},"companyName":{"type":"string","nullable":true},"customerName":{"type":"string","nullable":true},"status":{"type":"string","enum":["open","dismissed"]},"matchReason":{"type":"string","enum":["po_reference","total_and_lines"],"description":"po_reference: the PO appears in the other document's DocNumber, PrivateNote, CustomerMemo or a custom field. total_and_lines: same customer, total within $0.01, dated within 2 days, line items overlapping at least 80%."},"matchDetail":{"type":"object","additionalProperties":true},"poppeloDocument":{"type":"object","properties":{"entity":{"type":"string","description":"Estimate, Invoice or SalesReceipt."},"id":{"type":"string","description":"QuickBooks' transaction id in this company."},"docNumber":{"type":"string","nullable":true},"total":{"type":"number","nullable":true},"txnDate":{"type":"string","nullable":true},"createdAt":{"type":"string","nullable":true,"description":"When QuickBooks recorded the document (MetaData.CreateTime)."},"url":{"type":"string","nullable":true,"description":"Opens in the QuickBooks company the browser is signed in to; see linkNote."}},"required":["entity","id","docNumber","total","url"]},"otherDocument":{"type":"object","properties":{"entity":{"type":"string","description":"Estimate, Invoice or SalesReceipt."},"id":{"type":"string","description":"QuickBooks' transaction id in this company."},"docNumber":{"type":"string","nullable":true},"total":{"type":"number","nullable":true},"txnDate":{"type":"string","nullable":true},"createdAt":{"type":"string","nullable":true,"description":"When QuickBooks recorded the document (MetaData.CreateTime)."},"url":{"type":"string","nullable":true,"description":"Opens in the QuickBooks company the browser is signed in to; see linkNote."}},"required":["entity","id","docNumber","total","url"]},"syncApp":{"type":"string","nullable":true,"description":"synder | a2x | webgility | intuit_connector | shopify_sync, when the other document names the app; null otherwise."},"message":{"type":"string","description":"QuickBooks may contain this order twice: Estimate 1043 (Poppelo) and Invoice 2217 (created by another app on 14 Sep)."},"reason":{"type":"string"},"linkNote":{"type":"string"},"excludeInstructions":{"type":"string","nullable":true,"description":"How to make the sync app skip Poppelo's orders; on the tenant's first finding."},"detectedAt":{"type":"string","format":"date-time"},"dismissedAt":{"type":"string","format":"date-time","nullable":true},"dismissedBy":{"type":"string","nullable":true}},"required":["id","orderId","envelopeId","realmId","status","matchReason","poppeloDocument","otherDocument","message","detectedAt"]}}},"required":["findings"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"object","properties":{"code":{"type":"string"},"message":{"type":"string"},"details":{"type":"object","additionalProperties":true}},"required":["code","message"]}}}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getOrdersByOrderIdDoublePostFindings","summary":"Possible double posts of this order in QuickBooks, open and dismissed, newest first"}},"/api/v1/tenants/{tenantId}/orders/{orderId}/double-post-findings/{findingId}/dismiss":{"post":{"tags":["double-post-findings"],"description":"\"Not a duplicate\": dismiss a possible double post. The same pair of documents is never raised again, and the other document no longer matches this account's orders on amount and items alone (a PO match still raises). Changes nothing in QuickBooks. Idempotent: dismissing again returns the finding with alreadyDismissed true.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"orderId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"findingId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"finding":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"tenantId":{"type":"string","format":"uuid"},"orderId":{"type":"string","format":"uuid"},"envelopeId":{"type":"string","format":"uuid"},"destinationId":{"type":"string","format":"uuid","nullable":true},"connectorId":{"type":"string","format":"uuid","nullable":true},"realmId":{"type":"string","description":"The QuickBooks company file both documents are in."},"companyName":{"type":"string","nullable":true},"customerName":{"type":"string","nullable":true},"status":{"type":"string","enum":["open","dismissed"]},"matchReason":{"type":"string","enum":["po_reference","total_and_lines"],"description":"po_reference: the PO appears in the other document's DocNumber, PrivateNote, CustomerMemo or a custom field. total_and_lines: same customer, total within $0.01, dated within 2 days, line items overlapping at least 80%."},"matchDetail":{"type":"object","additionalProperties":true},"poppeloDocument":{"type":"object","properties":{"entity":{"type":"string","description":"Estimate, Invoice or SalesReceipt."},"id":{"type":"string","description":"QuickBooks' transaction id in this company."},"docNumber":{"type":"string","nullable":true},"total":{"type":"number","nullable":true},"txnDate":{"type":"string","nullable":true},"createdAt":{"type":"string","nullable":true,"description":"When QuickBooks recorded the document (MetaData.CreateTime)."},"url":{"type":"string","nullable":true,"description":"Opens in the QuickBooks company the browser is signed in to; see linkNote."}},"required":["entity","id","docNumber","total","url"]},"otherDocument":{"type":"object","properties":{"entity":{"type":"string","description":"Estimate, Invoice or SalesReceipt."},"id":{"type":"string","description":"QuickBooks' transaction id in this company."},"docNumber":{"type":"string","nullable":true},"total":{"type":"number","nullable":true},"txnDate":{"type":"string","nullable":true},"createdAt":{"type":"string","nullable":true,"description":"When QuickBooks recorded the document (MetaData.CreateTime)."},"url":{"type":"string","nullable":true,"description":"Opens in the QuickBooks company the browser is signed in to; see linkNote."}},"required":["entity","id","docNumber","total","url"]},"syncApp":{"type":"string","nullable":true,"description":"synder | a2x | webgility | intuit_connector | shopify_sync, when the other document names the app; null otherwise."},"message":{"type":"string","description":"QuickBooks may contain this order twice: Estimate 1043 (Poppelo) and Invoice 2217 (created by another app on 14 Sep)."},"reason":{"type":"string"},"linkNote":{"type":"string"},"excludeInstructions":{"type":"string","nullable":true,"description":"How to make the sync app skip Poppelo's orders; on the tenant's first finding."},"detectedAt":{"type":"string","format":"date-time"},"dismissedAt":{"type":"string","format":"date-time","nullable":true},"dismissedBy":{"type":"string","nullable":true}},"required":["id","orderId","envelopeId","realmId","status","matchReason","poppeloDocument","otherDocument","message","detectedAt"]},"alreadyDismissed":{"type":"boolean"}},"required":["finding","alreadyDismissed"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"object","properties":{"code":{"type":"string"},"message":{"type":"string"},"details":{"type":"object","additionalProperties":true}},"required":["code","message"]}}}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postOrdersByOrderIdDoublePostFindingsByFindingIdDismiss","summary":"\"Not a duplicate\": dismiss a possible double post"}},"/api/v1/tenants/{tenantId}/summary":{"get":{"tags":["summary"],"description":"The owner's morning summary for a local date: what posted, what needs a person, what couldn't post, what was learned, and time saved. Returns what was emailed that morning when a summary was sent; otherwise computes the 24 hours up to 07:00 that day. Defaults to today in the account's time zone.","parameters":[{"schema":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$"},"in":"query","name":"date","required":false},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"summary":{"type":"object","properties":{"tenantId":{"type":"string","format":"uuid"},"tenantName":{"type":"string"},"date":{"type":"string","format":"date"},"timezone":{"type":"string"},"window":{"type":"object","properties":{"start":{"type":"string","format":"date-time"},"end":{"type":"string","format":"date-time"}},"required":["start","end"]},"weekly":{"type":"boolean"},"quiet":{"type":"boolean"},"posted":{"type":"object","properties":{"count":{"type":"integer"},"value":{"type":"number"},"byDestination":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string"},"count":{"type":"integer"}},"required":["name","count"]}},"link":{"type":"string","description":"The page that shows these orders."}},"required":["count","value","byDestination","link"]},"needsYou":{"type":"object","properties":{"count":{"type":"integer"},"byReason":{"type":"array","items":{"type":"object","properties":{"reason":{"type":"string","enum":["in_review","partly_posted","manual_check"]},"label":{"type":"string"},"count":{"type":"integer"}},"required":["reason","label","count"]}},"link":{"type":"string","description":"The page that shows these orders."}},"required":["count","byReason","link"]},"couldNotPost":{"type":"object","properties":{"count":{"type":"integer"},"needsReconnect":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string"},"connectorType":{"type":"string"}},"required":["name","connectorType"]}},"link":{"type":"string","description":"The page that shows these orders."}},"required":["count","needsReconnect","link"]},"learned":{"type":"object","properties":{"proposed":{"type":"integer"},"activated":{"type":"integer"},"examples":{"type":"array","items":{"type":"string"}},"link":{"type":"string","description":"The page that shows these orders."}},"required":["proposed","activated","examples","link"]},"waitingRules":{"type":"object","description":"Every rule still waiting for a person to turn it on, oldest first, with the first three listed. Each link opens the rules page focused on that rule; turn it on there or with POST /rules/{ruleId}/approve. Absent on summaries stored before this field existed.","properties":{"count":{"type":"integer"},"items":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"ruleType":{"type":"string"},"text":{"type":"string","description":"What turning it on would do, in plain words."},"customerName":{"type":"string","nullable":true},"proposedAt":{"type":"string"},"link":{"type":"string","description":"The page that shows these orders."}},"required":["id","ruleType","text","customerName","proposedAt","link"]}},"link":{"type":"string","description":"The page that shows these orders."}},"required":["count","items","link"]},"timeSaved":{"type":"object","nullable":true,"description":"An estimate from the tenant's own order-entry baseline over the past 7 days, counting touchless and reviewed posted orders; null under 5 orders or when the baseline was never set (timeSavedUnavailable says which). No default baseline is assumed.","properties":{"hours":{"type":"number"},"orders":{"type":"integer"},"minutesPerOrder":{"type":"number","description":"settings.trustBaseline.minutesPerOrder, set at onboarding."},"estimate":{"type":"boolean"},"touchlessOrders":{"type":"integer","description":"Posted with no person; credited the full keying minutes."},"reviewedOrders":{"type":"integer","description":"Posted after review; credited the keying minutes less reviewMinutesPerOrder."},"reviewMinutesPerOrder":{"type":"number","nullable":true,"description":"The median of reviews timed in the app (open to approve, at least 5 in 90 days), else settings.trustBaseline.reviewMinutesPerOrder; null when neither exists, and reviewed orders are then not credited."},"reviewMinutesSource":{"type":"string","enum":["measured","configured","not_measured"]},"reviewSamples":{"type":"integer","description":"Timed reviews the median was taken from."}},"required":["hours","orders","minutesPerOrder","estimate"]},"timeSavedUnavailable":{"type":"string","nullable":true,"enum":["baseline_not_set","too_few_orders",null]}},"required":["tenantId","tenantName","date","timezone","window","weekly","quiet","posted","needsYou","couldNotPost","learned","timeSaved"]},"status":{"type":"string","nullable":true,"enum":["sent","quiet","sending",null]},"sentAt":{"type":"string","format":"date-time","nullable":true}},"required":["summary","status","sentAt"]}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getMorningSummary","summary":"Get the morning summary"}},"/api/v1/tenants/{tenantId}/summary/settings":{"get":{"tags":["summary"],"description":"Whether the morning summary is sent, and the time zone its 07:00 is measured in.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"enabled":{"type":"boolean"},"timezone":{"type":"string","description":"IANA time zone the 07:00 send time is measured in."}},"required":["enabled","timezone"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getSummarySettings","summary":"Whether the morning summary is sent, and the time zone its 07:00 is measured in"},"put":{"tags":["summary"],"description":"Turn the morning summary on or off for the account, or set the IANA time zone (e.g. America/Los_Angeles) it is sent at 07:00 in.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"enabled":{"type":"boolean"},"timezone":{"type":"string","maxLength":64}},"additionalProperties":false,"minProperties":1}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"enabled":{"type":"boolean"},"timezone":{"type":"string","description":"IANA time zone the 07:00 send time is measured in."}},"required":["enabled","timezone"]}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"putSummarySettings","summary":"Replace summary settings"}},"/api/v1/tenants/{tenantId}/orders/manual":{"post":{"tags":["orders"],"description":"Submit an order as structured data, skipping document extraction. The order still runs through validation, confidence routing, and the tenant’s approval policies. To declare a PO revision — the same poNumber resent with changed lines — set revisionNumber (and optionally revisionLabel): a higher number than any prior order sharing that poNumber supersedes it and updates the same posted document at approval instead of creating a second one; omitted/null never supersedes anything; an older revision arriving after a newer one is held for review as po_revision_stale. Set orderCancelled: true to declare the whole order cancelled or void, which gets the same revisionAction: \"cancel\" confirmation at approve as an extracted cancellation.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"customerName":{"type":"string","minLength":1,"maxLength":255},"customerId":{"type":"string","maxLength":100},"poNumber":{"type":"string","maxLength":100},"orderDate":{"type":"string","format":"date-time"},"deliveryDate":{"type":"string","format":"date-time"},"requestedShipDate":{"type":"string","format":"date-time"},"shippingMethod":{"type":"string","maxLength":100},"customerAccountNumber":{"type":"string","maxLength":100},"currency":{"type":"string","minLength":3,"maxLength":3},"specialInstructions":{"type":"string","maxLength":5000},"shippingAddress":{"type":"object","additionalProperties":true},"billingAddress":{"type":"object","additionalProperties":true},"lineItems":{"type":"array","minItems":1,"maxItems":500,"items":{"type":"object","properties":{"sku":{"type":"string","minLength":1,"maxLength":100},"description":{"type":"string","maxLength":2000},"quantity":{"type":"number","exclusiveMinimum":0},"unitPrice":{"type":"number","minimum":0},"uom":{"type":"string","maxLength":20}},"required":["sku","quantity"]}},"revisionNumber":{"type":"integer","minimum":0,"description":"PO revision, stored and compared exactly like an extracted order's revisionNumber: a higher number supersedes an earlier one sharing the same poNumber; omitted/null never supersedes anything (treated as before revision 1); an older revision arriving after a newer one is held for review as po_revision_stale rather than allowed to roll the order back."},"revisionLabel":{"type":"string","maxLength":50,"description":"The revision exactly as the caller states it (\"Rev B\", \"Amendment 2\"), shown to the reviewer alongside revisionNumber."},"idempotencyKey":{"type":"string","maxLength":200},"metadata":{"type":"object","additionalProperties":true,"description":"A top-level \"export\" key is reserved for Poppelo's own export record and is dropped from what is stored."},"entityId":{"type":"string","description":"The business this order belongs to, from list-business-entities. Approval writes it to that business's store and books regardless of the default business; routing rules do not override it. An id that is not one of this tenant's businesses is 400 ENTITY_NOT_FOUND."},"orderCancelled":{"type":"boolean","description":"The whole order is cancelled or void, stated explicitly by the caller. Stored the same way an extracted order's completeness.orderCancelled is, so a revision that cancels a previously posted order gets the same revisionAction: \"cancel\" confirmation at approve as an extracted cancellation."}},"required":["customerName","lineItems"]}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","maxLength":200},"in":"header","name":"idempotency-key","required":false,"description":"Client-chosen key making the submission idempotent: a retry with the same key and the same body returns the original envelope (202) instead of creating a duplicate; the same key with a different body is refused with 409 IDEMPOTENCY_KEY_REUSED. The body field idempotencyKey is equivalent and wins when both are sent."}],"responses":{"202":{"description":"Accepted. Processing continues in the background; follow it with the id in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"envelopeId":{"type":"string","format":"uuid"},"orderId":{"type":"string","format":"uuid"},"status":{"type":"string"},"message":{"type":"string"},"channelId":{"type":"string","format":"uuid"},"createdAt":{"type":"string","format":"date-time"}},"required":["envelopeId","orderId","status","message","channelId","createdAt"]}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"402":{"description":"The plan does not allow this: SUBSCRIPTION_REQUIRED (no active subscription) or PLAN_LIMIT_EXCEEDED (details.resource names the limit).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"submitManualOrder","summary":"Submit an order as structured lines"}},"/api/v1/tenants/{tenantId}/orders/envelopes/{envelopeId}/reconciliation":{"get":{"tags":["orders"],"description":"The destinations of an envelope that a person may need to reconcile or retry, in snake_case. Read-only. certainly_not_written marks a row the worker held before sending anything; the web panel lists it as \"Not sent\" instead of asking whether it arrived. confirmed_not_created_evidence says whether POST.../retry-reconciled has the evidence it requires for the row's current attempt (the same lookup); the web panel offers its Retry only then.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"envelopeId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","required":["envelope","destinations"],"properties":{"envelope":{"type":"object","additionalProperties":true,"properties":{"id":{"type":"string","format":"uuid"},"status":{"type":"string"},"error_message":{"type":"string","nullable":true,"description":"The envelope's last plain-language message. A supplier invoice held for a missing default expense account reads \"This bill is on hold:...\" here, never \"was not sent\": this message carries no proof about earlier deliveries."}}},"destinations":{"type":"array","items":{"type":"object","additionalProperties":true,"properties":{"id":{"type":"string","format":"uuid"},"role":{"type":"string"},"connector_id":{"type":"string","nullable":true},"connector_type":{"type":"string"},"status":{"type":"string"},"external_ref":{"type":"string","nullable":true},"attempt_count":{"type":"integer"},"updated_at":{"type":"string","format":"date-time","description":"Send back unchanged as expectedUpdatedAt."},"last_error":{"type":"string","nullable":true,"description":"Plain-language sentence; never raw provider output. A supplier-invoice row held for a missing default expense account says \"This bill was not sent:...\" only when nothing was sent for it (the invoice detail's certainlyNotWritten rule: that hold on its only delivery, no external_ref), and \"This bill is on hold:...\" otherwise."},"last_error_code":{"type":"string","nullable":true},"technical_detail":{"type":"string","nullable":true},"connector_external_id":{"type":"string","nullable":true,"description":"Shop domain, realmId or accountId. Not a secret."},"connector_display_name":{"type":"string","nullable":true},"certainly_not_written":{"type":"boolean","description":"Display only: true when this destination is parked in manual_handling with a stored ECONOMIC_SAFETY_REFUSED or REVISION_REQUIRES_MANUAL code and attempt_count 0, so nothing was sent to the provider for it (the same rule as certainlyNotWritten on the order detail). False for every other row. Known limit: with DESTINATIONS_V2_CLAIMS off the attempt count can be short, so the flag can be true on a row that may have written. No API decision reads it: POST.../reconcile and POST.../retry-reconciled accept and refuse exactly as before."},"late_success":{"type":"object","nullable":true,"additionalProperties":true,"description":"The provider answered this destination's write with a document after the row was parked (externalRef, at, statusWhenLanded,...). Null when none. While present, POST.../reconcile refuses confirmed_not_created with 409 INVALID_STATE; confirm it delivered with this externalRef.","properties":{"externalRef":{"type":"string","nullable":true},"at":{"type":"string"},"statusWhenLanded":{"type":"string"}}},"confirmed_not_created_evidence":{"type":"boolean","description":"True when a person has recorded confirmed_not_created (POST.../reconcile) for this destination at its current attempt_count. POST.../retry-reconciled runs the same lookup and refuses a row without it (409 \"This attempt has no confirmed-not-created reconciliation evidence.\"). A failed row with no external_ref and this flag false was failed by the worker, not released by a person: retry it with POST /orders/{orderId}/destinations/{destinationId}/retry instead. True is necessary for retry-reconciled, not sufficient: the envelope must also be pending_export with no uncertain sibling and the historical connector active."}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getOrdersEnvelopesByEnvelopeIdReconciliation","summary":"Get reconciliation of order envelope"}},"/api/v1/tenants/{tenantId}/orders/envelopes/{envelopeId}/destinations/{destinationId}/retry-reconciled":{"post":{"tags":["orders"],"description":"Explicitly retry a confirmed-not-created order or invoice at its original destination. Refused with 409 CONFLICT \"Resolve all uncertain outcomes before retrying.\" while the envelope is not pending_export; when another destination still holds it, the message and error.details.holdingDestinations (id, role, connectorType, status, lastErrorCode) name it: retry or reconcile that destination first.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["expectedUpdatedAt","expectedAttemptCount"],"properties":{"expectedUpdatedAt":{"type":"string","format":"date-time"},"expectedAttemptCount":{"type":"integer","minimum":0}}}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"envelopeId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"destinationId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postOrdersEnvelopesByEnvelopeIdDestinationsByDestinationIdRetryReconciled","summary":"Explicitly retry a confirmed-not-created order or invoice at its original destination"}},"/api/v1/tenants/{tenantId}/orders/envelopes/{envelopeId}/destinations/{destinationId}/reconcile":{"post":{"tags":["orders"],"description":"Reconcile an uncertain order or invoice destination using documented human verification. Does not retry a write and makes no provider call. For a QuickBooks or Shopify order destination confirmed delivered, externalRef should name the remote document: the QuickBooks estimate or invoice ID (the txnId in its web address; a document number is also resolved), or the Shopify draft order ID, its admin URL or its #D name. A Shopify draft ID or admin URL is stored as the draft's GID. When the order's other destination is written next, Poppelo reads that document back from this destination's own company or store and compares its pre-tax money first; a document it cannot read or identify holds that write (POSTED_MONEY_MISMATCH) until it is retried or acknowledged. While the destination holds a late provider success (late_success on GET.../reconciliation, its externalRef null when the provider named no document), confirmed_not_created is refused with 409 INVALID_STATE (details.lateSuccess: externalRef, at); confirm it delivered instead. A confirmed_delivered whose externalRef differs from the late success's still succeeds (200) and returns warnings: [\"confirmed_ref_differs_from_provider_response\"], with both references in the audit row.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["outcome","expectedUpdatedAt","expectedAttemptCount","evidenceReference","note","priorAttemptsStopped","providerLookupComplete"],"properties":{"outcome":{"type":"string","enum":["confirmed_delivered","confirmed_not_created"]},"expectedAttemptCount":{"type":"integer","minimum":0},"expectedUpdatedAt":{"type":"string","format":"date-time"},"evidenceReference":{"type":"string","minLength":3,"maxLength":500,"pattern":"\\S"},"note":{"type":"string","minLength":10,"maxLength":4000,"pattern":"\\S"},"externalRef":{"type":"string","minLength":1,"maxLength":255,"pattern":"\\S"},"priorAttemptsStopped":{"type":"boolean","enum":[true]},"providerLookupComplete":{"type":"boolean","enum":[true]}},"allOf":[{"if":{"properties":{"outcome":{"enum":["confirmed_delivered"]}}},"then":{"required":["externalRef"]}}]}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"envelopeId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"destinationId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postOrdersEnvelopesByEnvelopeIdDestinationsByDestinationIdReconcile","summary":"Reconcile an uncertain order or invoice destination using documented human verification"}},"/api/v1/tenants/{tenantId}/orders/":{"post":{"tags":["orders"],"description":"Submit an order for processing","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","description":"An unknown top-level property (for example idempotency_key) is refused with 400 VALIDATION_ERROR.","properties":{"channelId":{"type":"string","format":"uuid"},"document":{"type":"string","description":"Base64-encoded document content, at most 14680064 base64 characters (10.5 MB of binary). Supported formats: PDF, CSV, XLSX, DOCX, HTML, TXT, EML, or images (PNG, JPG, GIF, WEBP). The format is read from the file's bytes and, failing that, from the extension of metadata.filename (default PDF). TIFF images, legacy binary Office files (.xls,.doc) and Outlook.msg files are not supported: convert them to PDF, XLSX, DOCX, CSV, PNG or JPEG first. A file in an unsupported format is refused with 415 UNSUPPORTED_MEDIA_TYPE, and so is one read as a PDF (by its name, or by the PDF default) whose bytes have no PDF header. A value that is not a non-empty base64 string (a number, an empty string, text outside the base64 alphabet) is refused with 400 VALIDATION_ERROR and creates nothing. Larger files (up to 25 MB by default) go through the multipart upload endpoint."},"documentUrl":{"type":"string","format":"uri","description":"URL to fetch the document from, at most 10 MB; same supported formats as `document` (PDF, CSV, XLSX, DOCX, HTML, TXT, EML, or images (PNG, JPG, GIF, WEBP)). An unsupported format is refused with 415 UNSUPPORTED_MEDIA_TYPE."},"idempotencyKey":{"type":"string","maxLength":200,"description":"Client-chosen key making the submission idempotent: a retry with the same key and the same body returns the original envelope instead of creating a duplicate; the same key with a different body is refused with 409 IDEMPOTENCY_KEY_REUSED. Also accepted as an Idempotency-Key header."},"metadata":{"type":"object","additionalProperties":true,"description":"A top-level \"export\" key is reserved for Poppelo's own export record and is dropped from what is stored."}},"anyOf":[{"required":["document"]},{"required":["documentUrl"]}]},"example":{"document":"JVBERi0xLjcKJcfsj6IKNSAwIG9iago8PC9MZW5ndGggNiAwIFI+PgpzdHJlYW0K…","idempotencyKey":"erp-po-88213","metadata":{"filename":"po-88213.pdf","source":"erp-sync"}}}},"description":"An unknown top-level property (for example idempotency_key) is refused with 400 VALIDATION_ERROR."},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","maxLength":200},"in":"header","name":"idempotency-key","required":false,"description":"Client-chosen key making the submission idempotent: a retry with the same key and the same body returns the original envelope (202) instead of creating a duplicate; the same key with a different body is refused with 409 IDEMPOTENCY_KEY_REUSED. The body field idempotencyKey is equivalent and wins when both are sent."}],"responses":{"202":{"description":"Accepted. Processing continues in the background; follow it with the id in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"envelopeId":{"type":"string","format":"uuid"},"status":{"type":"string","enum":["received","extracting","extracted","validating","validated","in_review","auto_approved","approved","exporting","pending_export","exported","rejected","manual_handling","failed"]},"message":{"type":"string"},"channelId":{"type":"string","format":"uuid"},"createdAt":{"type":"string","format":"date-time"},"metadata":{"type":"object","additionalProperties":true,"nullable":true},"statusUrl":{"type":"string","description":"Path to follow this submission: GET it for the envelope status, and the order or invoice id once the document has been read."}},"required":["envelopeId","status","message","channelId","createdAt","statusUrl"]},"example":{"envelopeId":"e5b0f1c2-3d4a-4b6c-8e9f-1a2b3c4d5e6f","status":"received","message":"Order submitted for processing","channelId":"a9d8c7b6-5e4f-4a3b-9c2d-1e0f9a8b7c6d","createdAt":"2026-11-21T14:03:12.481Z","metadata":{"filename":"po-88213.pdf","source":"erp-sync"}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"submitOrder","summary":"Submit a purchase-order document"},"get":{"tags":["orders"],"description":"List orders with pagination","parameters":[{"schema":{"type":"integer","minimum":1,"default":1},"in":"query","name":"page","required":false,"description":"Page number (1-based)"},{"schema":{"type":"integer","minimum":1,"maximum":200},"in":"query","name":"pageSize","required":false,"description":"Items per page (default 20, max 200)"},{"schema":{"type":"integer","minimum":1},"in":"query","name":"limit","required":false,"description":"Deprecated alias of pageSize, clamped to 200. Accepted for one release."},{"schema":{"type":"integer","minimum":0},"in":"query","name":"offset","required":false,"description":"Deprecated: rows to skip. Takes precedence over page when both are sent. Accepted for one release."},{"schema":{"type":"string","enum":["createdAt","confidenceScore","customerName","status","deliveryDate"],"default":"createdAt"},"in":"query","name":"sortBy","required":false},{"schema":{"type":"string","enum":["asc","desc"],"default":"desc"},"in":"query","name":"sortOrder","required":false},{"schema":{"type":"string"},"in":"query","name":"status","required":false,"description":"Filter by envelope status; several statuses comma-separated (e.g. in_review,pending_export,manual_handling). One of: received, extracting, extracted, validating, validated, in_review, auto_approved, approved, exporting, pending_export, exported, rejected, manual_handling, failed. An unknown value is refused with 400 VALIDATION_ERROR. This list holds orders that were read: a document that failed before an order was extracted (status failed with no order) is not listed here, so status=failed shows only orders that failed later (for example on delivery). Follow such a document with GET /envelopes/{envelopeId} (the statusUrl from POST /orders)."},{"schema":{"type":"string","format":"uuid"},"in":"query","name":"envelopeId","required":false,"description":"Only the order extracted from this envelope (the envelopeId POST /orders returned)."},{"schema":{"type":"string"},"in":"query","name":"customer","required":false,"description":"Filter by customer name (substring match), across the whole result set, not just the current page"},{"schema":{"type":"string","format":"date-time"},"in":"query","name":"postedFrom","required":false,"description":"Only orders written to a destination at or after this instant (the morning summary's \"posted\" window)."},{"schema":{"type":"string","format":"date-time"},"in":"query","name":"postedTo","required":false,"description":"Only orders written to a destination before this instant."},{"schema":{"type":"string","format":"date-time"},"in":"query","name":"problemFrom","required":false,"description":"Only orders with a destination that failed or went to manual handling at or after this instant (the summary's \"couldn't post\" window)."},{"schema":{"type":"string","format":"date-time"},"in":"query","name":"problemTo","required":false,"description":"Only orders with a destination that failed or went to manual handling before this instant."},{"schema":{"type":"string","maxLength":100},"in":"query","name":"poNumber","required":false,"description":"Only orders whose PO number contains this text, ignoring case (\"8821\" finds PO-88213)."},{"schema":{"type":"string","maxLength":200},"in":"query","name":"q","required":false,"description":"Search box. Orders whose PO number or customer name contains this text, ignoring case."},{"schema":{"type":"string","format":"date-time"},"in":"query","name":"createdBefore","required":false,"description":"Keyset paging. Only orders created strictly before this instant; pass the last row's createdAt to page further back than page x pageSize = 10,000 allows (with sortBy=createdAt)."},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"envelopeId":{"type":"string","format":"uuid"},"customerName":{"type":"string"},"poNumber":{"type":"string","nullable":true},"confidenceScore":{"type":"number"},"status":{"type":"string","enum":["received","extracting","extracted","validating","validated","in_review","auto_approved","approved","exporting","pending_export","exported","rejected","manual_handling","failed"]},"channelType":{"type":"string"},"lineItemCount":{"type":"integer"},"createdAt":{"type":"string","format":"date-time"},"exportMethod":{"type":"string","enum":["email","download","sftp"],"nullable":true,"description":"How the order went out as a file: email, download or sftp, from its export record. Null when the order has not been exported as a file (for example it posted through a connector, or has not posted yet)."},"exportFormat":{"type":"string","nullable":true,"description":"The exported file's format (csv, xlsx or edi850), from its export record. Null when not exported as a file."},"exportDeliveredTo":{"type":"string","nullable":true,"description":"The address an emailed export went to. Null for any other delivery."},"destinations":{"type":"array","items":{"type":"string"},"description":"Connector types the order is written to (quickbooks, shopify,...), from its destination rows or the legacy single destination. Empty when none."},"matchScore":{"type":"number","description":"The match score the order was routed on (after validation adjustments), 0 to 1 at four decimal places. The same number the needs-review email, the review queue and the order page show. Falls back to confidenceScore for an order not routed yet. confidenceScore keeps its meaning: the extraction score before validation adjusted it."},"matchScorePercent":{"type":"integer","description":"matchScore as the whole percent people see, cut down and never rounded up (0.949 is 94)."},"statusLabel":{"type":"string","description":"The words the orders page shows for the status, as the CSV statusLabel column has them. An approved order held at its destination (status in_review with a manual-downstream hold) reads \"Held — not sent\"; an order whose send failed after it was read (status failed at the integration stage) reads \"Couldn’t send — <destination> refused it\"."},"heldReason":{"type":"string","nullable":true,"description":"Why an approved order was held at its destination and not sent. Null for any other order."},"deliveryState":{"type":"string","nullable":true,"enum":["held","send_failed",null],"description":"Held — approved, then held at its destination on its own data and not sent (status in_review, not in the review queue); send_failed — read and approved, then its send failed (status failed at the integration stage: retry the destination, never re-read it). Null otherwise."}}}},"pagination":{"type":"object","properties":{"page":{"type":"integer"},"pageSize":{"type":"integer"},"total":{"type":"integer"},"totalPages":{"type":"integer"},"estimated":{"type":"boolean","description":"True when total is the planner's estimate (sets past 10,000 rows)."}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"listOrders","summary":"List orders"}},"/api/v1/tenants/{tenantId}/orders/bulk":{"post":{"tags":["orders"],"description":"Submit multiple orders for processing (max 100 per request)","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"orders":{"type":"array","minItems":1,"maxItems":100,"items":{"type":"object","properties":{"channelId":{"type":"string","format":"uuid"},"document":{"type":"string","description":"Base64-encoded document content, at most 14680064 base64 characters (10.5 MB of binary). Supported formats: PDF, CSV, XLSX, DOCX, HTML, TXT, EML, or images (PNG, JPG, GIF, WEBP). The format is read from the file's bytes and, failing that, from the extension of metadata.filename (default PDF). TIFF images, legacy binary Office files (.xls,.doc) and Outlook.msg files are not supported: convert them to PDF, XLSX, DOCX, CSV, PNG or JPEG first. A file in an unsupported format is refused with 415 UNSUPPORTED_MEDIA_TYPE, and so is one read as a PDF (by its name, or by the PDF default) whose bytes have no PDF header. A value that is not a non-empty base64 string (a number, an empty string, text outside the base64 alphabet) is refused with 400 VALIDATION_ERROR and creates nothing. Larger files (up to 25 MB by default) go through the multipart upload endpoint."},"documentUrl":{"type":"string","format":"uri","description":"URL to fetch the document from, at most 10 MB; same supported formats as `document` (PDF, CSV, XLSX, DOCX, HTML, TXT, EML, or images (PNG, JPG, GIF, WEBP)). An unsupported format is refused with 415 UNSUPPORTED_MEDIA_TYPE."},"idempotencyKey":{"type":"string","maxLength":200,"description":"per-item idempotency key. A retried batch returns the original envelope for each item whose key matched (status \"duplicate\") instead of creating it again; the same key with a different item is reported as that item's failure with code IDEMPOTENCY_KEY_REUSED."},"metadata":{"type":"object","additionalProperties":true,"description":"A top-level \"export\" key is reserved for Poppelo's own export record and is dropped from what is stored."}},"anyOf":[{"required":["document"]},{"required":["documentUrl"]}]}}},"required":["orders"]}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"results":{"type":"array","items":{"type":"object","properties":{"envelopeId":{"type":"string","format":"uuid","nullable":true},"status":{"type":"string","enum":["received","duplicate","failed"],"description":"duplicate: the item's idempotencyKey matched an earlier submission and envelopeId is that envelope."},"code":{"type":"string","description":"Machine-readable failure code (e.g. MALWARE_DETECTED, MALWARE_SCAN_UNAVAILABLE). Present only when status is \"failed\"."},"message":{"type":"string"}},"required":["status","message"]}},"succeeded":{"type":"integer"},"failed":{"type":"integer"}},"required":["results","succeeded","failed"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postOrdersBulk","summary":"Submit multiple orders for processing (max 100 per request)"}},"/api/v1/tenants/{tenantId}/orders/{orderId}":{"get":{"tags":["orders"],"description":"Get order detail with line items and validation results","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"orderId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string"},"envelopeId":{"type":"string"},"tenantId":{"type":"string"},"customerName":{"type":"string"},"customerId":{"type":"string","nullable":true},"poNumber":{"type":"string","nullable":true},"shippingAddress":{"type":"object","nullable":true,"additionalProperties":true},"billingAddress":{"type":"object","nullable":true,"additionalProperties":true},"deliveryDate":{"type":"string","nullable":true,"format":"date-time"},"orderDate":{"type":"string","nullable":true,"format":"date-time"},"requestedShipDate":{"type":"string","nullable":true,"format":"date-time"},"shippingMethod":{"type":"string","nullable":true},"customerAccountNumber":{"type":"string","nullable":true},"specialInstructions":{"type":"string","nullable":true},"currency":{"type":"string","nullable":true},"confidenceScore":{"type":"number"},"matchScore":{"type":"number","description":"The match score the order was routed on (after validation adjustments), 0 to 1 at four decimal places. The same number the needs-review email, the review queue and the order page show. Falls back to confidenceScore for an order not routed yet. confidenceScore keeps its meaning: the extraction score before validation adjusted it."},"matchScorePercent":{"type":"integer","description":"matchScore as the whole percent people see, cut down and never rounded up (0.949 is 94)."},"customerNumber":{"type":"string","nullable":true,"description":"The matched customer's number in your own system (the reference customer's source id, e.g. \"C-100\"). Null when the order is not matched to a customer. customerId is the number as printed on the PO."},"exportMethod":{"type":"string","nullable":true,"enum":["email","download","sftp",null],"description":"How the order went out as a file, from its export record, as GET /orders reports it. Null when it was not exported as a file."},"exportFormat":{"type":"string","nullable":true,"description":"The exported file's format (csv, xlsx, edi850). Null when not exported as a file."},"exportDeliveredTo":{"type":"string","nullable":true,"description":"The address an emailed export went to. Null for any other delivery."},"orderValue":{"type":"number","nullable":true,"description":"The order value the review queue, the webhooks and the value ceiling read: quantity × unit price summed over the lines. Null when any line has no unit price."},"linesTotal":{"type":"number","nullable":true,"description":"The lines summed as lineTotal is, to the cent, with line discounts taken off. Null when any line has no unit price."},"charges":{"type":"array","description":"order-level charges read off the document (freight, discount, tax, handling, other), each a positive amount; a discount reduces the total. A discount the lines already carry is not repeated here. Empty when the document prints none or the order was read before charges were extracted.","items":{"type":"object","properties":{"type":{"type":"string","enum":["freight","discount","tax","handling","other"]},"amount":{"type":"number"},"description":{"type":"string","nullable":true}},"required":["type","amount"]}},"chargesTotal":{"type":"number","description":"Charges summed, signed: discounts negative. 0 when there are none."},"orderTotal":{"type":"number","nullable":true,"description":"linesTotal plus chargesTotal, to the cent. The total the exported file states. Null when any line has no unit price."},"statedTotal":{"type":"number","nullable":true,"description":"The grand total printed on the document, when it prints one."},"status":{"type":"string","enum":["received","extracting","extracted","validating","validated","in_review","auto_approved","approved","exporting","pending_export","exported","rejected","manual_handling","failed"]},"channelType":{"type":"string"},"createdAt":{"type":"string","format":"date-time"},"externalOrderId":{"type":"string","nullable":true},"externalConnectorType":{"type":"string","nullable":true},"externalUrl":{"type":"string","nullable":true},"integratedAt":{"type":"string","nullable":true,"format":"date-time"},"statusChangedAt":{"type":"string","format":"date-time","description":"When the status last changed. For an approved or rejected order this is when the decision was made: POST /review/:envelopeId/undo works within the grace period (default 5 minutes) after it."},"statusLabel":{"type":"string","description":"The status in the words GET /orders and the CSV export use (\"Held — not sent\" for an approved order held at its destination; \"Couldn’t send — <destination> refused it\" for one whose send failed after it was read)."},"heldReason":{"type":"string","nullable":true,"description":"Why an approved order was held at its destination and not sent. Null for any other order."},"deliveryState":{"type":"string","nullable":true,"enum":["held","send_failed",null],"description":"As GET /orders reports it."},"businessEntity":{"type":"object","nullable":true,"description":"The business the order was routed to, and how: manual, reviewer, rule, remembered or default.","properties":{"id":{"type":"string"},"name":{"type":"string"},"source":{"type":"string","nullable":true}}},"routingSummary":{"type":"string","nullable":true,"description":"For display: \"Summit Farm & Ranch Inc → Farm store + Farm books\", or \"Store override: Farm store · Books: Pet books\" when a rule split the order."},"destinations":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"role":{"type":"string"},"connectorType":{"type":"string"},"connectorId":{"type":"string","nullable":true,"description":"The connector instance (tenant_connectors.id) this write goes to; match it against GET.../integrations/status instances[] to see whether that connection needs reconnecting."},"connectorLabel":{"type":"string","nullable":true,"description":"The store's or company's current name, refreshed from the provider by the reference sync and the connection test."},"realmId":{"type":"string","nullable":true,"description":"QuickBooks only: the realm (company file) id the document was posted to. Null for other destinations."},"externalUrlNote":{"type":"string","nullable":true,"description":"QuickBooks only: QuickBooks opens externalUrl in the company the browser is signed in to, whatever company holds the document; this names the company to switch to first."},"status":{"type":"string"},"externalRef":{"type":"string","nullable":true},"externalUrl":{"type":"string","nullable":true,"description":"Link to the document in the destination system (the store admin, or QuickBooks)."},"documentLabel":{"type":"string","nullable":true,"description":"The document by the name its system shows: \"Draft #D24\" (Shopify), \"Estimate 1043\" / \"Invoice 1043\" (QuickBooks). Null until a document exists."},"docNumber":{"type":"string","nullable":true,"description":"QuickBooks only: the document's number as QuickBooks returned it — the company's own sequence, or the PO when the company has custom transaction numbers on and numbers by PO. Null when not recorded."},"poNumber":{"type":"string","nullable":true,"description":"QuickBooks only: the buyer's PO recorded on the posted document (memo first line, and the company's P.O. Number field when it has one). Shown with docNumber as \"Invoice 1043 · PO 85347\". Null when not recorded."},"posting":{"type":"object","nullable":true,"description":"What the destination posted, read back at write time. differsFromApproved compares the pre-tax totals. Null when nothing was recorded.","properties":{"postedTotal":{"type":"number","nullable":true},"postedSubtotal":{"type":"number","nullable":true},"postedTax":{"type":"number","nullable":true},"currency":{"type":"string","nullable":true},"approvedSubtotal":{"type":"number","nullable":true},"differsFromApproved":{"type":"boolean"}}},"lastError":{"type":"string","nullable":true,"description":"Plain-language sentence describing the last failure; never raw provider output."},"errorCode":{"type":"string","nullable":true,"enum":["QBO_AUTH_EXPIRED","QBO_ACCESS_DENIED","QBO_DUPLICATE_DOC_NUMBER","QBO_ITEM_NOT_FOUND","QBO_CUSTOMER_INACTIVE","QBO_VALIDATION","QBO_THROTTLED","SHOPIFY_AUTH","SHOPIFY_ACCESS_DENIED","SHOPIFY_SHOP_NOT_FOUND","SHOPIFY_SHOP_FROZEN","SHOPIFY_SHOP_LOCKED","SHOPIFY_VARIANT_NOT_FOUND","SHOPIFY_USER_ERROR","SHOPIFY_THROTTLED","ECONOMIC_SAFETY_REFUSED","REVISION_REQUIRES_MANUAL","CONNECTOR_NEEDS_RECONNECT","DUPLICATE_PO_HELD","POSTING_DECISION_REQUIRED","POSTED_MONEY_MISMATCH","ROUTED_TO_FILE_EXPORT","PROVIDER_REJECTED","PROVIDER_UNAVAILABLE","UNKNOWN_OUTCOME",null],"description":"Stable error code an agent can branch on."},"nextStep":{"type":"object","nullable":true,"properties":{"label":{"type":"string"},"url":{"type":"string","nullable":true}},"required":["label","url"],"description":"The one next action, with a deep link into the web app."},"retryable":{"type":"boolean","nullable":true,"description":"Whether retrying without changing anything can succeed."},"technicalDetail":{"type":"string","nullable":true,"description":"Raw provider response, for support. Show only behind a \"Technical details\" disclosure."},"warnings":{"type":"array","description":"Delivered, but with something to act on. code customer_not_attached: the draft was created without a customer; reasonCode says why (e.g. SHOPIFY_ACCESS_DENIED). posted_total_mismatch, tax_on_exempt_customer or currency_not_applied: the document exists but its money differs from the approved order (read back from the provider); correct it there. reasonCode is null for these.","items":{"type":"object","properties":{"code":{"type":"string","enum":["customer_not_attached","posted_total_mismatch","tax_on_exempt_customer","currency_not_applied"]},"reasonCode":{"type":"string","nullable":true},"message":{"type":"string"},"nextStep":{"type":"object","nullable":true,"properties":{"label":{"type":"string"},"url":{"type":"string","nullable":true}},"required":["label","url"],"description":"The one next action, with a deep link into the web app."},"technicalDetail":{"type":"string","nullable":true}},"required":["code","message"]}},"doublePostFindings":{"type":"array","description":"Open possible double posts of this QuickBooks write: another app's Invoice or SalesReceipt in the same company that looks like this order. Dismiss with POST /orders/:orderId/double-post-findings/:findingId/dismiss. Empty when none.","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"tenantId":{"type":"string","format":"uuid"},"orderId":{"type":"string","format":"uuid"},"envelopeId":{"type":"string","format":"uuid"},"destinationId":{"type":"string","format":"uuid","nullable":true},"connectorId":{"type":"string","format":"uuid","nullable":true},"realmId":{"type":"string","description":"The QuickBooks company file both documents are in."},"companyName":{"type":"string","nullable":true},"customerName":{"type":"string","nullable":true},"status":{"type":"string","enum":["open","dismissed"]},"matchReason":{"type":"string","enum":["po_reference","total_and_lines"],"description":"po_reference: the PO appears in the other document's DocNumber, PrivateNote, CustomerMemo or a custom field. total_and_lines: same customer, total within $0.01, dated within 2 days, line items overlapping at least 80%."},"matchDetail":{"type":"object","additionalProperties":true},"poppeloDocument":{"type":"object","properties":{"entity":{"type":"string","description":"Estimate, Invoice or SalesReceipt."},"id":{"type":"string","description":"QuickBooks' transaction id in this company."},"docNumber":{"type":"string","nullable":true},"total":{"type":"number","nullable":true},"txnDate":{"type":"string","nullable":true},"createdAt":{"type":"string","nullable":true,"description":"When QuickBooks recorded the document (MetaData.CreateTime)."},"url":{"type":"string","nullable":true,"description":"Opens in the QuickBooks company the browser is signed in to; see linkNote."}},"required":["entity","id","docNumber","total","url"]},"otherDocument":{"type":"object","properties":{"entity":{"type":"string","description":"Estimate, Invoice or SalesReceipt."},"id":{"type":"string","description":"QuickBooks' transaction id in this company."},"docNumber":{"type":"string","nullable":true},"total":{"type":"number","nullable":true},"txnDate":{"type":"string","nullable":true},"createdAt":{"type":"string","nullable":true,"description":"When QuickBooks recorded the document (MetaData.CreateTime)."},"url":{"type":"string","nullable":true,"description":"Opens in the QuickBooks company the browser is signed in to; see linkNote."}},"required":["entity","id","docNumber","total","url"]},"syncApp":{"type":"string","nullable":true,"description":"synder | a2x | webgility | intuit_connector | shopify_sync, when the other document names the app; null otherwise."},"message":{"type":"string","description":"QuickBooks may contain this order twice: Estimate 1043 (Poppelo) and Invoice 2217 (created by another app on 14 Sep)."},"reason":{"type":"string"},"linkNote":{"type":"string"},"excludeInstructions":{"type":"string","nullable":true,"description":"How to make the sync app skip Poppelo's orders; on the tenant's first finding."},"detectedAt":{"type":"string","format":"date-time"},"dismissedAt":{"type":"string","format":"date-time","nullable":true},"dismissedBy":{"type":"string","nullable":true}},"required":["id","orderId","envelopeId","realmId","status","matchReason","poppeloDocument","otherDocument","message","detectedAt"]}},"matchedRuleName":{"type":"string","nullable":true},"entityId":{"type":"string","nullable":true,"description":"The business this write belongs to."},"entityName":{"type":"string","nullable":true},"override":{"type":"boolean","description":"This write went outside the order's business because a rule said so."},"attemptCount":{"type":"number","description":"Provider write attempts for this destination; 1 for a write that landed first time."},"certainlyNotWritten":{"type":"boolean","description":"Display only: true when this destination is parked in manual_handling with errorCode ECONOMIC_SAFETY_REFUSED or REVISION_REQUIRES_MANUAL and attemptCount is 0, so nothing was sent to the provider for it; the order page labels it \"Held — not posted\". False for every other row, including a held code after an earlier attempt (that attempt may have written). Known limit: with DESTINATIONS_V2_CLAIMS off the attempt count can be short (a failed shadow write, or a row created after a write already went out), so the flag can be true on a row that may have written. No API decision reads it: posting, retry and reconciliation still treat these codes as a possible write."},"integratedAt":{"type":"string","nullable":true},"pricing":{"type":"object","nullable":true,"properties":{"currencyCode":{"type":"string"},"priceOverrides":{"type":"array","description":"Lines whose approved unit price was sent as a price override and differs from the store catalog price.","items":{"type":"object","properties":{"lineNumber":{"type":"number"},"sku":{"type":"string"},"catalogPrice":{"type":"number","nullable":true},"approvedPrice":{"type":"number"},"currencyCode":{"type":"string"}}}},"storePriceLines":{"type":"array","description":"Lines with no approved unit price, priced by the store catalog.","items":{"type":"object","properties":{"lineNumber":{"type":"number"},"sku":{"type":"string"},"catalogPrice":{"type":"number","nullable":true},"currencyCode":{"type":"string"}}}}}},"details":{"type":"object","additionalProperties":true,"description":"Provider read-back of the write, keyed by kind. details.quickbooks: entity, docNumber, docNumberSource (company_sequence | po_number | left_blank), requestedDocNumber, docNumberNote, poNumber, poCustomField{definitionId, name, value}, postedTotal, postedTax, postedSubtotal, approvedSubtotal, taxCalculatedBy, taxTreatment, currency, exchangeRate, findings[{code, severity, message}], revision{action, outcome, documentId, previousSyncToken, syncToken, revision, previousRevision} — or, for a held write, existingDocumentId/existingDocumentUrl, candidates, blockers, revision{action: held, reason}. details.shopify carries the same revision block (draftId). details.pricing: Shopify price overrides."},"revision":{"type":"object","nullable":true,"description":"This destination's write was a PO revision's. action updated (the earlier revision's document changed in place), cancelled (detail: closed, voided or deleted) or held (detail: converted_to_invoice, estimate_closed, estimate_rejected, invoice_paid, invoice_voided, draft_completed, document_missing). summary is the sentence the order page shows. Null for an ordinary write.","properties":{"action":{"type":"string","enum":["updated","cancelled","held"]},"detail":{"type":"string","nullable":true},"summary":{"type":"string"},"revision":{"type":"string","nullable":true}}}}}},"revision":{"type":"object","nullable":true,"description":"Where this order sits in its PO's revision chain. supersedes is the revision it replaced (with lineDiff against it), supersededBy the later revision that replaced it. Null when the PO has no revisions.","properties":{"revisionLabel":{"type":"string"},"supersedes":{"type":"object","nullable":true,"properties":{"orderId":{"type":"string"},"revisionLabel":{"type":"string"}}},"supersededBy":{"type":"object","nullable":true,"properties":{"orderId":{"type":"string"},"revisionLabel":{"type":"string"}}},"lineDiff":{"type":"array","description":"Each line against the superseded revision, matched by SKU: change is added, removed, changed or unchanged; before and after carry quantity and unitPrice.","items":{"type":"object","properties":{"change":{"type":"string","enum":["added","removed","changed","unchanged"]},"sku":{"type":"string"},"description":{"type":"string","nullable":true},"lineNumber":{"type":"number","nullable":true},"before":{"type":"object","nullable":true,"properties":{"quantity":{"type":"number"},"unitPrice":{"type":"number","nullable":true}}},"after":{"type":"object","nullable":true,"properties":{"quantity":{"type":"number"},"unitPrice":{"type":"number","nullable":true}}}}}}}},"lineItems":{"type":"array"},"validationResults":{"type":"array"},"documentUrl":{"type":"string","nullable":true},"returnToReview":{"type":"object","nullable":true,"description":"Display only: for an order in manual_handling, whether POST /review/:envelopeId/return-to-review would accept it right now (eligible), the code it would refuse with otherwise (refusalCode: NOT_AN_ORDER, MANUAL_HANDLING_SYSTEM_HOLD or DESTINATION_ALREADY_ATTEMPTED), and the connected destinations the confirmation warns about (destinationNames). Null for every other status. The route checks again under the envelope lock before it acts.","properties":{"eligible":{"type":"boolean"},"refusalCode":{"type":"string","nullable":true},"destinationNames":{"type":"array","items":{"type":"string"}}},"required":["eligible","refusalCode","destinationNames"]},"split":{"type":"object","nullable":true,"description":"This order is one of several purchase orders split from one email. index is its 1-based place among them in document order, of how many there are, and siblings every one of them (this order included) with its envelope, order and current PO number; orderId is null only if an order is missing. Null when the order was not split.","properties":{"index":{"type":"integer"},"of":{"type":"integer"},"siblings":{"type":"array","items":{"type":"object","properties":{"envelopeId":{"type":"string","format":"uuid"},"orderId":{"type":"string","format":"uuid","nullable":true},"poNumber":{"type":"string","nullable":true}},"required":["envelopeId","orderId","poNumber"]}}},"required":["index","of","siblings"]}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getOrder","summary":"Get an order"}},"/api/v1/tenants/{tenantId}/orders/{orderId}/timeline":{"get":{"tags":["orders"],"description":"Get order processing timeline from audit log","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"orderId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"events":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string"},"status":{"type":"string"},"label":{"type":"string"},"timestamp":{"type":"string"},"detail":{"type":"string","nullable":true},"action":{"type":"string","description":"The audit action the event was rendered from, e.g. integration.failed or status_transition."},"connectorType":{"type":"string","nullable":true,"description":"Destination connector type (quickbooks, shopify,...) for a destination event; null otherwise."},"role":{"type":"string","nullable":true,"description":"Destination role (commerce, accounting) for a destination event; null otherwise."},"errorCode":{"type":"string","nullable":true,"description":"Stored error code for a failed event, e.g. QBO_VALIDATION. A short code only, never provider text."},"actorType":{"type":"string","nullable":true,"enum":["user","system","agent","api_key","approve_link","session","oauth_app",null],"description":"What kind of actor made this move, from the audit row: user (a person, by session or API key, e.g. \"Handle myself\"), system (a worker or the platform), agent (document understanding), api_key, approve_link or session. Null when the stored type is none of these. Never the actor's id; actorName carries a person's name."},"actorName":{"type":"string","nullable":true,"description":"Who made this move, when it was a person who is a user of this tenant: their name, else their email (\"Approved by Dana Ortiz\"). Null for the system, an API key, and anyone not (or no longer) a user of this tenant."}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getOrdersByOrderIdTimeline","summary":"Get order processing timeline from audit log"}},"/api/v1/tenants/{tenantId}/orders/{orderId}/routing-explanation":{"get":{"tags":["orders"],"description":"Explain why an order was routed the way it was: one step per stage the routing pipeline ran, validation findings, applied reading hints, and the autonomy trace.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"orderId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"orderId":{"type":"string"},"envelopeId":{"type":"string"},"final":{"type":"string"},"headline":{"type":"string"},"steps":{"type":"array","items":{"type":"object","properties":{"stage":{"type":"string"},"outcome":{"type":"string"},"sentence":{"type":"string"},"details":{"type":"object","additionalProperties":true}}}},"validation":{"type":"array","items":{"type":"object","properties":{"validator":{"type":"string"},"status":{"type":"string"},"message":{"type":"string"}}}},"hintsApplied":{"type":"array","items":{"type":"object","properties":{"ruleId":{"type":"string"},"kind":{"type":"string"},"sentence":{"type":"string"}}}},"autonomy":{"type":["null","object"],"properties":{"state":{"type":["null","string"]},"anomalies":{"type":"array","items":{"type":"object","properties":{"code":{"type":"string"},"sentence":{"type":"string"}}}}}},"evaluatedAt":{"type":"string"}},"required":["orderId","envelopeId","final","headline","steps","validation","hintsApplied","evaluatedAt"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getOrdersByOrderIdRoutingExplanation","summary":"Get routing explanation of order"}},"/api/v1/tenants/{tenantId}/orders/{orderId}/export-file":{"get":{"tags":["orders"],"description":"Get a signed download URL for the exported order file. Available once the order has exported (or export is pending retry).","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"orderId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"url":{"type":"string"},"filename":{"type":"string"},"format":{"type":"string"},"deliveredVia":{"type":"string"},"exportedAt":{"type":"string"}},"required":["url","filename","format"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getOrdersByOrderIdExportFile","summary":"Get a signed download URL for the exported order file"}},"/api/v1/tenants/{tenantId}/orders/{envelopeId}/reprocess":{"post":{"tags":["orders"],"description":"Retry a failed envelope: revalidate existing output (mode revalidate_existing) or extract when no output exists (mode reextract). Also takes a document that was filed as \"not an order\" (status rejected with classification non_order, not dismissed): it is read again on the same envelope, with the extraction told a person confirmed it is an order (mode read_as_order). If that read still finds no order the envelope fails with errorCode NO_CONTENT. A document whose stored content was deleted (mail filed as not an order loses its email and attachments 30 days after it was filed, and every document is deleted at the end of the retention window) cannot be read again and responds 409 INVALID_STATE, changing nothing. Any other status is refused with 409 INVALID_STATE.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"envelopeId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postOrdersByEnvelopeIdReprocess","summary":"Reprocess order"}},"/api/v1/tenants/{tenantId}/orders/{envelopeId}/dismiss":{"post":{"tags":["orders"],"description":"Put a document away from the attention page once a person has dealt with it. Takes a document that could not be processed (status failed: it moves to manual_handling, free, and fires envelope.manual_handling), one filed as not an order or not an invoice (status rejected, classification non_order or non_invoice: it stays rejected), or one parked for a person (status manual_handling). Records dismissedAt and who did it, plus an envelope.dismissed audit row; /attention stops listing it. Dismissing twice answers 200 with the first dismissal. Any other status is refused with 409 INVALID_STATE. Dismissing does not undo or check anything in your other systems: for a document parked because a write may have landed, check that system first.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"reason":{"type":"string","maxLength":500,"description":"Optional note on why it was put away"}}}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"envelopeId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"envelopeId":{"type":"string"},"status":{"type":"string"},"dismissedAt":{"type":"string"},"message":{"type":"string"}},"required":["envelopeId","status","dismissedAt","message"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"postOrdersByEnvelopeIdDismiss","summary":"Put a document away from the attention page once a person has dealt with it"}},"/api/v1/tenants/{tenantId}/orders/{orderId}/retry-export":{"post":{"tags":["orders"],"description":"Finish delivering an order stuck in pending_export. Retries every destination that can still be retried (the usual case after a partial fan-out, e.g. the storefront wrote and the ledger did not); falls back to a file export only when the order has no retryable destination. Also takes an approved or auto_approved order that has not moved for 30 minutes and has no delivery still waiting to be sent (its queue message was lost or refused), which otherwise stays approved forever. Any other status is refused with 409 CONFLICT.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"orderId","required":true}],"responses":{"202":{"description":"Accepted. Processing continues in the background; follow it with the id in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"envelopeId":{"type":"string"},"retriedDestinations":{"type":"integer"},"message":{"type":"string"}},"required":["envelopeId","retriedDestinations","message"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postOrdersByOrderIdRetryExport","summary":"Finish delivering an order stuck in pending_export"}},"/api/v1/tenants/{tenantId}/orders/{orderId}/destinations":{"get":{"tags":["orders"],"description":"Per-destination write status for an order","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"orderId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getOrdersByOrderIdDestinations","summary":"Per-destination write status for an order"}},"/api/v1/tenants/{tenantId}/orders/{orderId}/destinations/{destinationId}/retry":{"post":{"tags":["orders"],"description":"Retry a single destination for an order. Allowed for a failed, queued or rescheduled destination while the order is approved or partly delivered; for a destination held for a posting decision once the preview says it can post; and for a destination that failed at the integration stage on an order whose envelope settled failed, which reopens the order for export. Refused with 409 while any destination of the order has an uncertain outcome. A destination parked with POSTED_MONEY_MISMATCH wrote nothing, and can be retried: the write is compared again and posts only if the money now matches. lastErrorDetail.details.diff says which hold it is: another destination of the order already posted different pre-tax money (the difference is in the diff); that destination's own write did not finish, so what it posted is unknown (diff.siblingOutcome \"unknown\", siblingMoney null); or a person confirmed that destination delivered and its document could not be read back to compare (diff.siblingOutcome \"unreadable\" with diff.readBack.reason, including \"not_read\" for a document not read yet). Send ?acknowledgeMoneyDifference=true to post it as it stands even though the money differs from what the other destination posted; this is audited with the difference and applies only to that exact difference. When the other destination was confirmed delivered by a person and its document could not be read back (lastErrorDetail.details.diff.siblingOutcome \"unreadable\" with a readBack.reason other than \"not_read\"), a plain retry reads it again; the flag posts without comparing, bound to that destination and this planned money. A hold with readBack.reason \"not_read\" (the document was never read) cannot be acknowledged (409): retry it without the flag, which reads it. A hold behind a write that did not finish (siblingOutcome \"unknown\") cannot be acknowledged (409): reconcile that destination first. The flag is refused with 400 VALIDATION_ERROR on a destination not parked with POSTED_MONEY_MISMATCH.","parameters":[{"schema":{"type":"boolean"},"in":"query","name":"acknowledgeMoneyDifference","required":false,"description":"Post a destination parked with POSTED_MONEY_MISMATCH even though its pre-tax money differs from what another destination of the order already posted (the difference is in the destination's lastErrorDetail.details.diff), or the document of a destination a person confirmed delivered could not be read back to compare (diff.readBack.reason other than \"not_read\"; a \"not_read\" hold is refused with 409). A hold behind another destination's unfinished write (diff.siblingOutcome \"unknown\") records no difference and is refused with 409: reconcile that destination first. Audited. Refused with 400 on any other destination."},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"orderId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"destinationId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postOrdersByOrderIdDestinationsByDestinationIdRetry","summary":"Retry a single destination for an order"}},"/api/v1/tenants/{tenantId}/orders/{orderId}/report-problem":{"post":{"tags":["orders"],"description":"Log a problem discovered after approval/export. Feeds the accuracy SLA measurement and the learning loop.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"lineItemId":{"type":"string","format":"uuid","description":"The affected line (omit for order-header fields)"},"field":{"type":"string","minLength":1,"description":"Field that was wrong (e.g. sku, quantity, customerName)"},"correctedValue":{"description":"The correct value"},"discoveredBy":{"type":"string","enum":["reviewer","customer","erp_reject"]},"rootCause":{"type":"string"}},"required":["field","correctedValue","discoveredBy"]}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"orderId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"orderId":{"type":"string"},"correctionRecorded":{"type":"boolean"},"accuracyIncidentRecorded":{"type":"boolean"},"autonomyDemoted":{"type":"boolean"},"message":{"type":"string"}},"required":["orderId","correctionRecorded","message"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postOrdersByOrderIdReportProblem","summary":"Log a problem discovered after approval/export"}},"/api/v1/tenants/{tenantId}/orders/export":{"get":{"tags":["orders"],"description":"Export orders as CSV, streamed row by row. At most 50,000 rows per call: narrow the set with the list filters or createdFrom/createdTo, or use the asynchronous full tenant export (POST /api/v1/tenants/:tenantId/export) for everything. A larger set is refused with 400 EXPORT_TOO_LARGE before any row is sent. Columns: envelopeId, status (the code), customerName, orderDate (YYYY-MM-DD: the date printed on the PO, else the day it was received; orderDateSource says which, po or received), totalAmount (the order total to the cent: each line round(quantity x unit price) less its discount, plus the PO's charges such as freight, tax and order discounts, the figure the order page and the exported file state; empty when a line has no price. Until 2026-11-21 it was quantity x unit price summed over the lines), confidence (the extraction score before validation adjusted it; kept for scripts that read it, it is not the match score people see), createdAt (when it was received), then poNumber, statusLabel (the words the orders page shows) and matchScorePercent (the whole-percent match score the app, the review queue and the emails show: read this one, not confidence). The last four columns were appended on 2026-11-21, when orderDate also changed from the received time to the PO date.","parameters":[{"schema":{"type":"string"},"in":"query","name":"status","required":false,"description":"Filter by envelope status; several statuses comma-separated (e.g. in_review,pending_export,manual_handling). One of: received, extracting, extracted, validating, validated, in_review, auto_approved, approved, exporting, pending_export, exported, rejected, manual_handling, failed. An unknown value is refused with 400 VALIDATION_ERROR. This list holds orders that were read: a document that failed before an order was extracted (status failed with no order) is not listed here, so status=failed shows only orders that failed later (for example on delivery). Follow such a document with GET /envelopes/{envelopeId} (the statusUrl from POST /orders)."},{"schema":{"type":"string","format":"uuid"},"in":"query","name":"envelopeId","required":false,"description":"Only the order extracted from this envelope (the envelopeId POST /orders returned)."},{"schema":{"type":"string"},"in":"query","name":"customer","required":false,"description":"Filter by customer name (substring match), across the whole result set, not just the current page"},{"schema":{"type":"string","format":"date-time"},"in":"query","name":"postedFrom","required":false,"description":"Only orders written to a destination at or after this instant (the morning summary's \"posted\" window)."},{"schema":{"type":"string","format":"date-time"},"in":"query","name":"postedTo","required":false,"description":"Only orders written to a destination before this instant."},{"schema":{"type":"string","format":"date-time"},"in":"query","name":"problemFrom","required":false,"description":"Only orders with a destination that failed or went to manual handling at or after this instant (the summary's \"couldn't post\" window)."},{"schema":{"type":"string","format":"date-time"},"in":"query","name":"problemTo","required":false,"description":"Only orders with a destination that failed or went to manual handling before this instant."},{"schema":{"type":"string","maxLength":100},"in":"query","name":"poNumber","required":false,"description":"Only orders whose PO number contains this text, ignoring case (\"8821\" finds PO-88213)."},{"schema":{"type":"string","maxLength":200},"in":"query","name":"q","required":false,"description":"Search box. Orders whose PO number or customer name contains this text, ignoring case."},{"schema":{"type":"string","format":"date-time"},"in":"query","name":"createdFrom","required":false,"description":"Only orders created at or after this instant."},{"schema":{"type":"string","format":"date-time"},"in":"query","name":"createdTo","required":false,"description":"Only orders created before this instant."},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getOrdersExport","summary":"Export orders as CSV, streamed row by row"}},"/api/v1/tenants/{tenantId}/orders/{orderId}/posting-decisions":{"put":{"tags":["orders"],"description":"Replace the posting decisions for one order: tax exemption, order-level charges (freight, discount, tax, handling, other) and description-only line mappings. Omit charges to let charges read off the PO apply when they reconcile with its stated total; send charges (even []) to override them. Refused with 409 ORDER_ALREADY_POSTED once the write has started: the order is exporting or exported, or one of its destinations is still marked as being written, which under the envelope lock means a previous write did not finish and that destination needs reconciling (details.inFlightDestinations). A destination that may have written (integrated, or held in manual_handling with any error code except POSTING_DECISION_REQUIRED and POSTED_MONEY_MISMATCH) freezes fields; so does a legacy order with no destination records that carries an external reference, or that the integration path parked with an uncertain outcome (not a posting hold, not one a person filed for manual handling, not one superseded on upload). Any such destination freezes charges (type, amount and description of each as it would post, in any order) and the effective lineMappings — stored mappings plus active line_posting rules (changing or removing one is refused; adding one is allowed only on a line with a placeholder part number such as NA; a real SKU that QuickBooks cannot resolve is fixed by adding the item in QuickBooks and retrying). A QuickBooks destination also freezes taxExempt and taxExemptionReasonId, which only QuickBooks reads. A change to a frozen field is refused with 409 ORDER_ALREADY_POSTED, details.refusedFields and details.writtenDestinations (the destinations that froze them). So after only Shopify has written, a QuickBooks destination parked with POSTING_DECISION_REQUIRED can still be given its tax exemption or the mapping for a placeholder line and retried; send the stored charges and mappings unchanged. 409 CONFLICT while a worker or retry holds the order. Read the effect with GET.../posting-preview.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"taxExempt":{"type":"boolean","description":"The buyer is tax exempt: QuickBooks lines post NON, and a customer created for this order is created not taxable."},"taxExemptionReasonId":{"type":"string","pattern":"^(?:[1-9]|1[0-5])$","description":"QuickBooks TaxExemptionReasonId: 1 federal gov, 2 state gov, 3 local gov, 4 tribal gov, 5 charitable org, 6 religious org, 7 educational org, 8 hospital, 9 resale, 10 direct pay permit, 11 multiple points of use, 12 direct mail, 13 agricultural production, 14 industrial production/manufacturing, 15 foreign diplomat."},"charges":{"type":"array","maxItems":20,"description":"Order-level charges so that lines + charges reconcile with the PO stated total. Amounts are positive; a discount reduces the total.","items":{"type":"object","properties":{"type":{"type":"string","enum":["freight","discount","tax","handling","other"]},"amount":{"type":"number","minimum":0},"description":{"type":"string","minLength":1,"maxLength":200}},"required":["type","amount"],"additionalProperties":false}},"lineMappings":{"type":"object","description":"order_line_items.id -> 'services' | 'freight': post a description-only line against the company's configured item.","additionalProperties":{"type":"string","enum":["services","freight"]}}},"additionalProperties":false}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"orderId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"orderId":{"type":"string","format":"uuid"},"decisions":{"type":"object","properties":{"taxExempt":{"type":"boolean","description":"The buyer is tax exempt: QuickBooks lines post NON, and a customer created for this order is created not taxable."},"taxExemptionReasonId":{"type":"string","pattern":"^(?:[1-9]|1[0-5])$","description":"QuickBooks TaxExemptionReasonId: 1 federal gov, 2 state gov, 3 local gov, 4 tribal gov, 5 charitable org, 6 religious org, 7 educational org, 8 hospital, 9 resale, 10 direct pay permit, 11 multiple points of use, 12 direct mail, 13 agricultural production, 14 industrial production/manufacturing, 15 foreign diplomat."},"charges":{"type":"array","maxItems":20,"description":"Order-level charges so that lines + charges reconcile with the PO stated total. Amounts are positive; a discount reduces the total.","items":{"type":"object","properties":{"type":{"type":"string","enum":["freight","discount","tax","handling","other"]},"amount":{"type":"number","minimum":0},"description":{"type":"string","minLength":1,"maxLength":200}},"required":["type","amount"],"additionalProperties":false}},"lineMappings":{"type":"object","description":"order_line_items.id -> 'services' | 'freight': post a description-only line against the company's configured item.","additionalProperties":{"type":"string","enum":["services","freight"]}}},"additionalProperties":false},"learned":{"type":"object","description":"Rules proposed because this customer's lines with the same description pattern have now been confirmed to the same item on two orders. A proposed rule does nothing until a person approves it (POST /rules/:ruleId/approve).","properties":{"proposedRules":{"type":"array","items":{"type":"object","properties":{"ruleId":{"type":"string","format":"uuid"},"referenceCustomerId":{"type":"string","format":"uuid"},"customerName":{"type":["null","string"]},"pattern":{"type":"string","description":"The keyword (\"installation\", \"freight\") or normalized description the rule matches."},"target":{"type":"string","enum":["services","freight"]},"occurrences":{"type":"integer"},"description":{"type":"string"}}}}}}}}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"object","properties":{"code":{"type":"string"},"message":{"type":"string"},"details":{"type":"object","additionalProperties":true},"correlationId":{"type":"string"}}}}}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"object","properties":{"code":{"type":"string"},"message":{"type":"string"},"details":{"type":"object","additionalProperties":true},"correlationId":{"type":"string"}}}}}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"object","properties":{"code":{"type":"string"},"message":{"type":"string"},"details":{"type":"object","additionalProperties":true},"correlationId":{"type":"string"}}}}}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"putOrdersByOrderIdPostingDecisions","summary":"Replace orders posting decisions"}},"/api/v1/tenants/{tenantId}/orders/{orderId}/posting-preview":{"get":{"tags":["orders"],"description":"Preview, per destination, the document this order would post if approved now: lines, freight/discount/other charge lines, the pre-tax total compared with the PO stated total, the QuickBooks customer used or created, the Estimate/Invoice choice per company, tax handling, where the PO appears and who numbers the document (poReference), and blockers with the setting that resolves each. Built from the same plan the QuickBooks connector posts. Charges printed on the PO (freight, discount, tax, handling, other) are used when no charges were set and they reconcile with the stated total; chargesSource and extractedCharges say so. A Shopify store previews the draft order: item lines with their own discounts, the order discount, one shipping line for freight, custom lines for handling/other charges, the pre-tax total against the PO, the shop currency (currency) and blockers (an unexplained difference, or an order in a currency the store does not sell in). Each line is checked against the store's synced products; a placeholder part number (\"NA\") or a SKU the store does not sell is a blocker (line_not_in_store, setting allowCustomLineItems) with suggestions, and once the store allows custom line items (posting.allowCustomLineItems) and the line is mapped (lineMappings) it previews as a custom line item at the approved price ('freight' as the shipping line).","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"orderId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"orderId":{"type":"string","format":"uuid"},"learnedLineMappings":{"type":"object","description":"order_line_items.id -> { target, ruleId } for description-only lines an ACTIVE line_posting rule maps for this customer. The preview and the write use them; `decisions` stays what a person stored, and a person's own lineMappings entry always wins.","additionalProperties":{"type":"object","properties":{"target":{"type":"string","enum":["services","freight"]},"ruleId":{"type":"string","format":"uuid"}}}},"decisions":{"type":"object","properties":{"taxExempt":{"type":"boolean","description":"The buyer is tax exempt: QuickBooks lines post NON, and a customer created for this order is created not taxable."},"taxExemptionReasonId":{"type":"string","pattern":"^(?:[1-9]|1[0-5])$","description":"QuickBooks TaxExemptionReasonId: 1 federal gov, 2 state gov, 3 local gov, 4 tribal gov, 5 charitable org, 6 religious org, 7 educational org, 8 hospital, 9 resale, 10 direct pay permit, 11 multiple points of use, 12 direct mail, 13 agricultural production, 14 industrial production/manufacturing, 15 foreign diplomat."},"charges":{"type":"array","maxItems":20,"description":"Order-level charges so that lines + charges reconcile with the PO stated total. Amounts are positive; a discount reduces the total.","items":{"type":"object","properties":{"type":{"type":"string","enum":["freight","discount","tax","handling","other"]},"amount":{"type":"number","minimum":0},"description":{"type":"string","minLength":1,"maxLength":200}},"required":["type","amount"],"additionalProperties":false}},"lineMappings":{"type":"object","description":"order_line_items.id -> 'services' | 'freight': post a description-only line against the company's configured item.","additionalProperties":{"type":"string","enum":["services","freight"]}}},"additionalProperties":false,"description":"The decisions the preview posts with. When no charges were stored, charges printed on the PO (extractedCharges) fill in, but only when lines + those charges equal the stated total within $0.01; chargesSource says which."},"chargesSource":{"type":"string","enum":["reviewer","extracted","none"],"description":"reviewer: charges were set with PUT.../posting-decisions (an empty array included, which overrides the PO). extracted: none were set and the charges read off the PO reconcile with its stated total, so they post as if classified. none: neither."},"extractedCharges":{"type":["null","object"],"description":"The charges extraction read off the PO and whether they reconcile. null for an order read before charges were extracted.","properties":{"charges":{"type":"array","items":{"type":"object","properties":{"type":{"type":"string","enum":["freight","discount","tax","handling","other"]},"amount":{"type":"number","minimum":0},"description":{"type":["null","string"]},"lineLevel":{"type":"boolean","description":"Read as already inside the line figures (a summary of line discounts). Honoured only when the lines' discounts sum to it within $0.01; otherwise counted as order-level (reconciliation.lineLevelReadAsOrderLevel)."}}}},"reconciliation":{"type":"object","properties":{"status":{"type":"string","enum":["reconciled","differs","no_stated_total","unpriced_lines"]},"linesTotal":{"type":["null","number"]},"chargesTotal":{"type":"number","description":"Signed: discounts negative."},"expectedTotal":{"type":["null","number"]},"statedTotal":{"type":["null","number"]},"difference":{"type":["null","number"]},"lineLevelReadAsOrderLevel":{"type":"number","description":"Amount of charges marked lineLevel that the line discounts do not add up to, and were therefore counted as order-level. 0 when every lineLevel mark held."}}}}},"approveSummary":{"type":["null","string"],"description":"e.g. \"Estimate in Summit Pet Supply LLC · Invoice in Summit Farm & Ranch Inc\""},"canPost":{"type":"boolean","description":"True when no destination has a blocker."},"destinations":{"type":"array","items":{"type":"object","additionalProperties":true,"properties":{"role":{"type":"string","enum":["commerce","accounting"]},"connectorType":{"type":"string"},"connectorId":{"type":["null","string"]},"supported":{"type":"boolean","description":"False for destinations without a document plan (their message is the destination-blind economic verdict)."},"canPost":{"type":"boolean"},"companyName":{"type":["null","string"]},"storeName":{"type":["null","string"],"description":"Shopify: the store the draft order is created in."},"currency":{"type":["null","string"],"description":"Shopify: the shop's currencyCode, when known."},"entity":{"type":"string","enum":["estimate","invoice"]},"summary":{"type":"string"},"message":{"type":["null","string"]},"customer":{"type":"object","additionalProperties":true,"description":"{ action: 'use_existing', quickbooksCustomerId, name } or { action: 'create_unless_found', summary, fields }"},"lines":{"type":"array","items":{"type":"object","additionalProperties":true,"properties":{"kind":{"type":"string","enum":["item","freight","other_charge","discount"]},"mappedTo":{"type":"string","enum":["services","freight"]},"lineItemId":{"type":"string"},"lineNumber":{"type":"integer"},"sku":{"type":"string"},"description":{"type":"string"},"itemId":{"type":["null","string"]},"quantity":{"type":"number"},"unitPrice":{"type":"number"},"amount":{"type":"number"}}}},"totals":{"type":"object","additionalProperties":true,"description":"merchandise, freight, otherCharges, discount, preTax, statedSubtotal, statedTotal, statedTax"},"poCheck":{"type":"object","additionalProperties":true,"description":"status: matches | differs | no_stated_total; stated, expected, difference, message, matchesPo"},"tax":{"type":"object","additionalProperties":true,"description":"calculatedBy, treatment, note"},"poReference":{"type":"object","description":"QuickBooks: where the buyer's PO appears and who numbers the document. The PO is always the memo's (PrivateNote) first line; placement custom_field also writes it to the company's P.O. Number sales-form field (at most 31 characters).","properties":{"poNumber":{"type":["null","string"]},"placement":{"type":"string","enum":["custom_field","memo","none","unknown"]},"customField":{"type":["null","object"],"properties":{"definitionId":{"type":"string"},"name":{"type":"string"},"value":{"type":"string"},"truncated":{"type":"boolean"}}},"documentNumber":{"type":"string","enum":["company_sequence","po_number","left_blank","unknown"],"description":"company_sequence: QuickBooks numbers it. po_number: the PO (custom transaction numbers on, posting.documentNumber 'po'). left_blank: custom numbers on and posting.documentNumber 'blank' (or no PO)."},"message":{"type":"string"}}},"blockers":{"type":"array","items":{"type":"object","additionalProperties":true,"properties":{"code":{"type":"string"},"message":{"type":"string"},"lineNumber":{"type":"integer"},"setting":{"type":"string"}}}},"suggestions":{"type":"array","description":"Description-only lines (\"NA\", services, freight) and where they should post; confirm with PUT.../posting-decisions lineMappings.","items":{"type":"object","properties":{"lineItemId":{"type":"string"},"lineNumber":{"type":"integer"},"suggested":{"type":"string","enum":["services","freight"]},"reason":{"type":"string"}}}},"notes":{"type":"array","items":{"type":"string"}}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"object","properties":{"code":{"type":"string"},"message":{"type":"string"},"details":{"type":"object","additionalProperties":true},"correlationId":{"type":"string"}}}}}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getOrdersByOrderIdPostingPreview","summary":"Get posting preview of order"}},"/api/v1/tenants/{tenantId}/orders/{orderId}/destinations/{destinationId}/existing-customer":{"post":{"tags":["orders"],"description":"Confirm an existing QuickBooks customer for a destination held with possible_existing_customer (details.quickbooks.candidates on GET /orders/:id). Only a proposed candidate is accepted (400 NOT_A_PROPOSED_CUSTOMER otherwise); a destination that is not held for this reason returns 409 NO_CUSTOMER_PROPOSAL. Links the company's customer as the order's accounting customer and records the order's printed name as its alias. Nothing is written to QuickBooks: send it with POST.../destinations/:destinationId/retry.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"quickbooksCustomerId":{"type":"string","minLength":1,"maxLength":64,"description":"The candidate id from details.quickbooks.candidates[].id."}},"required":["quickbooksCustomerId"],"additionalProperties":false}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"orderId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"destinationId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"orderId":{"type":"string","format":"uuid"},"destinationId":{"type":"string","format":"uuid"},"connectorId":{"type":"string","format":"uuid"},"quickbooksCustomerId":{"type":"string"},"customerName":{"type":"string","description":"The company's name for the customer the order now posts to."},"referenceCustomerId":{"type":"string","format":"uuid"},"aliasRecorded":{"type":["null","string"],"description":"The order's printed customer name, recorded as an alias; null when it already matched."},"nextStep":{"type":"string"}}}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"object","properties":{"code":{"type":"string"},"message":{"type":"string"},"details":{"type":"object","additionalProperties":true},"correlationId":{"type":"string"}}}}}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"object","properties":{"code":{"type":"string"},"message":{"type":"string"},"details":{"type":"object","additionalProperties":true},"correlationId":{"type":"string"}}}}}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"object","properties":{"code":{"type":"string"},"message":{"type":"string"},"details":{"type":"object","additionalProperties":true},"correlationId":{"type":"string"}}}}}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postOrdersByOrderIdDestinationsByDestinationIdExistingCustomer","summary":"Existing customer order destination"}},"/api/v1/tenants/{tenantId}/invoices/":{"post":{"tags":["invoices"],"description":"Submit a new invoice document for processing","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"channelId":{"type":"string","format":"uuid"},"document":{"type":"string","description":"Base64-encoded document content, at most 14680064 base64 characters (10.5 MB of binary). Supported formats: PDF, CSV, XLSX, DOCX, HTML, TXT, EML, or images (PNG, JPG, GIF, WEBP). The format is read from the file's bytes and, failing that, from the extension of metadata.filename (default PDF). TIFF images, legacy binary Office files (.xls,.doc) and Outlook.msg files are not supported: convert them to PDF, XLSX, DOCX, CSV, PNG or JPEG first. A file in an unsupported format is refused with 415 UNSUPPORTED_MEDIA_TYPE, and so is one read as a PDF (by its name, or by the PDF default) whose bytes have no PDF header. A value that is not a non-empty base64 string (a number, an empty string, text outside the base64 alphabet) is refused with 400 VALIDATION_ERROR and creates nothing. Larger files (up to 25 MB by default) go through the multipart upload endpoint."},"documentUrl":{"type":"string","format":"uri","description":"URL to fetch the document from, at most 10 MB; same supported formats as `document` (PDF, CSV, XLSX, DOCX, HTML, TXT, EML, or images (PNG, JPG, GIF, WEBP)). An unsupported format is refused with 415 UNSUPPORTED_MEDIA_TYPE."},"idempotencyKey":{"type":"string","maxLength":200,"description":"Client-chosen key making the submission idempotent: a retry with the same key and the same body returns the original envelope instead of creating a duplicate; the same key with a different body is refused with 409 IDEMPOTENCY_KEY_REUSED. Also accepted as an Idempotency-Key header."},"metadata":{"type":"object","additionalProperties":true,"description":"A top-level \"export\" key is reserved for Poppelo's own export record and is dropped from what is stored."}},"anyOf":[{"required":["document"]},{"required":["documentUrl"]}]}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","maxLength":200},"in":"header","name":"idempotency-key","required":false,"description":"Client-chosen key making the submission idempotent: a retry with the same key and the same body returns the original envelope (202) instead of creating a duplicate; the same key with a different body is refused with 409 IDEMPOTENCY_KEY_REUSED. The body field idempotencyKey is equivalent and wins when both are sent."}],"responses":{"202":{"description":"Accepted. Processing continues in the background; follow it with the id in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"envelopeId":{"type":"string","format":"uuid"},"status":{"type":"string","enum":["received","extracting","extracted","validating","validated","in_review","auto_approved","approved","exporting","pending_export","exported","rejected","manual_handling","failed"]},"message":{"type":"string"},"channelId":{"type":"string","format":"uuid"},"statusUrl":{"type":"string","description":"Path to follow this submission: GET it for the envelope status, and the order or invoice id once the document has been read."}}}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"413":{"description":"PAYLOAD_TOO_LARGE: the body or file is over the size limit.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"415":{"description":"UNSUPPORTED_MEDIA_TYPE: the document is not in a supported format. Convert it to PDF, XLSX, DOCX, CSV, PNG or JPEG.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"422":{"description":"The request is well formed but its values cannot be used, for example INVALID_PERMISSIONS on an API key.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"submitInvoice","summary":"Submit a supplier-invoice document"},"get":{"tags":["invoices"],"description":"List invoices with pagination. Header and line fields are corrected on approve (POST /:envelopeId/approve); a correction applies to this invoice only and nothing is learned from it, unlike order review. Invoices are always reviewed by a person: auto-approval applies to purchase orders only. page x pageSize may not exceed 10,000 (400 PAGE_TOO_DEEP); pass createdBefore to page further back. pagination.estimated is true when total is the planner's estimate.","parameters":[{"schema":{"type":"integer","minimum":1,"default":1},"in":"query","name":"page","required":false,"description":"Page number (1-based)"},{"schema":{"type":"integer","minimum":1,"maximum":200},"in":"query","name":"pageSize","required":false,"description":"Items per page (default 20, max 200)"},{"schema":{"type":"integer","minimum":1},"in":"query","name":"limit","required":false,"description":"Deprecated alias of pageSize, clamped to 200. Accepted for one release."},{"schema":{"type":"integer","minimum":0},"in":"query","name":"offset","required":false,"description":"Deprecated: rows to skip. Takes precedence over page when both are sent. Accepted for one release."},{"schema":{"type":"string","enum":["createdAt","confidenceScore","vendorName","totalAmount"],"default":"createdAt"},"in":"query","name":"sortBy","required":false},{"schema":{"type":"string","enum":["asc","desc"],"default":"desc"},"in":"query","name":"sortOrder","required":false},{"schema":{"type":"string","enum":["received","extracting","extracted","validating","validated","in_review","auto_approved","approved","exporting","pending_export","exported","rejected","manual_handling","failed"]},"in":"query","name":"status","required":false,"description":"Filter by envelope status. An unknown value is refused with 400 VALIDATION_ERROR."},{"schema":{"type":"string","format":"date-time"},"in":"query","name":"createdBefore","required":false,"description":"Keyset paging. Only invoices created strictly before this instant (with sortBy=createdAt)."},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"envelopeId":{"type":"string","format":"uuid"},"vendorName":{"type":"string"},"invoiceNumber":{"type":"string","nullable":true},"totalAmount":{"type":"number","nullable":true},"confidenceScore":{"type":"number"},"matchScore":{"type":"number","description":"The match score the order was routed on (after validation adjustments), 0 to 1 at four decimal places. The same number the needs-review email, the review queue and the order page show. Falls back to confidenceScore for an order not routed yet. confidenceScore keeps its meaning: the extraction score before validation adjusted it."},"matchScorePercent":{"type":"integer","description":"matchScore as the whole percent people see, cut down and never rounded up (0.949 is 94)."},"status":{"type":"string","enum":["received","extracting","extracted","validating","validated","in_review","auto_approved","approved","exporting","pending_export","exported","rejected","manual_handling","failed"]},"channelType":{"type":"string"},"lineItemCount":{"type":"integer"},"createdAt":{"type":"string","format":"date-time"}}}},"pagination":{"type":"object","properties":{"page":{"type":"integer"},"pageSize":{"type":"integer"},"total":{"type":"integer"},"totalPages":{"type":"integer"},"estimated":{"type":"boolean","description":"True when total is the planner's estimate (sets past 10,000 rows)."}}}},"required":["data","pagination"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"listInvoices","summary":"List supplier invoices"}},"/api/v1/tenants/{tenantId}/invoices/{invoiceId}":{"get":{"tags":["invoices"],"description":"Get invoice detail with line items and validation results. Header and line fields can be corrected on approve (see POST /:envelopeId/approve); a correction applies to this invoice only and is not learned from, unlike order review: no mapping rule, customer profile or golden data is written (see correctionsSupported in the response).","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"invoiceId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"envelopeId":{"type":"string","format":"uuid"},"tenantId":{"type":"string","format":"uuid"},"vendorName":{"type":"string"},"vendorId":{"type":"string","nullable":true},"invoiceNumber":{"type":"string","nullable":true},"remitToAddress":{"type":"object","nullable":true,"additionalProperties":true},"invoiceDate":{"type":"string","nullable":true,"format":"date-time"},"dueDate":{"type":"string","nullable":true,"format":"date-time"},"poNumberReference":{"type":"string","nullable":true},"subtotal":{"type":"number","nullable":true},"taxAmount":{"type":"number","nullable":true},"totalAmount":{"type":"number","nullable":true},"paymentTerms":{"type":"string","nullable":true},"confidenceScore":{"type":"number"},"matchScore":{"type":"number","description":"The match score the order was routed on (after validation adjustments), 0 to 1 at four decimal places. The same number the needs-review email, the review queue and the order page show. Falls back to confidenceScore for an order not routed yet. confidenceScore keeps its meaning: the extraction score before validation adjusted it."},"matchScorePercent":{"type":"integer","description":"matchScore as the whole percent people see, cut down and never rounded up (0.949 is 94)."},"status":{"type":"string","enum":["received","extracting","extracted","validating","validated","in_review","auto_approved","approved","exporting","pending_export","exported","rejected","manual_handling","failed"]},"channelType":{"type":"string","nullable":true},"createdAt":{"type":"string","format":"date-time"},"lineItems":{"type":"array","items":{"type":"object","additionalProperties":true}},"validationResults":{"type":"array","items":{"type":"object","additionalProperties":true}},"documentUrl":{"type":"string","nullable":true},"correctionsSupported":{"type":"boolean"},"destinationChoices":{"type":"array","description":"The accounting companies this invoice is held for when several could take it and nothing names one; empty otherwise. Each instance carries writeBack (post or export) and writeBackReason, the decision approve would make for that company: export means the invoice would be exported as a file, e.g. because the company has no default expense account.","items":{"type":"object","additionalProperties":true,"properties":{"role":{"type":"string","enum":["commerce","accounting"]},"message":{"type":"string"},"instances":{"type":"array","items":{"type":"object","additionalProperties":true,"properties":{"id":{"type":"string"},"connectorType":{"type":"string"},"displayName":{"type":"string","nullable":true},"externalId":{"type":"string","nullable":true},"needsReconnect":{"type":"boolean"},"writeBack":{"type":"string","enum":["post","export"],"description":"What approving this invoice for this company would do, by the same rule approve applies: post (written there as a bill) or export (exported as a file instead)."},"writeBackReason":{"type":"string","enum":["ok","no_accounting_destination","unsupported_connector","expense_account_missing"],"description":"Why: ok for post; expense_account_missing when the company has no default expense account (set one with PATCH.../connectors/:connectorId defaultExpenseAccountId); unsupported_connector when it cannot take bills."}},"required":["id","connectorType","displayName","externalId","writeBack","writeBackReason"]}}},"required":["role","message","instances"]}},"destinations":{"type":"array","description":"Where this invoice was sent to be written as a bill, one row per destination (an invoice has at most one, the accounting role), with its status and, when it did not land, a plain reason. status is pending | exporting | integrated | failed | retry_scheduled | manual_handling | skipped. Empty when the invoice was never queued to a connected system: write-back off, or exported as a file (see invoiceWriteBack).","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"role":{"type":"string","nullable":true},"connectorType":{"type":"string"},"connectorId":{"type":"string","format":"uuid","nullable":true},"connectorLabel":{"type":"string","nullable":true,"description":"The company's name as the tenant connected it."},"status":{"type":"string"},"externalRef":{"type":"string","nullable":true,"description":"The bill id in the destination system, once written."},"attemptCount":{"type":"integer","description":"Write attempts for this destination."},"certainlyNotWritten":{"type":"boolean","description":"Display only: true when this destination is parked in manual_handling with errorCode POSTING_DECISION_REQUIRED for a reason decided before any bill was sent (no default expense account, or the invoice's lines, tax and total do not make a bill that adds up: bill_no_lines, bill_invalid_amount, bill_total_missing, bill_total_mismatch), with no externalRef and attemptCount at most 1; the invoice page then labels it \"Held — not posted\". False for every other row, including a vendor, currency or company-country hold, which can follow an earlier attempt's write, and a held row after an earlier delivery (that delivery may have written). Known limit: with DESTINATIONS_V2_CLAIMS off the attempt count can be short, so the flag can be true on a row that may have written. No API decision reads it: posting, retry and reconciliation are unchanged."},"lastError":{"type":"string","nullable":true,"description":"Plain-language sentence describing the last failure; never raw provider output."},"errorCode":{"type":"string","nullable":true,"enum":["QBO_AUTH_EXPIRED","QBO_ACCESS_DENIED","QBO_DUPLICATE_DOC_NUMBER","QBO_ITEM_NOT_FOUND","QBO_CUSTOMER_INACTIVE","QBO_VALIDATION","QBO_THROTTLED","SHOPIFY_AUTH","SHOPIFY_ACCESS_DENIED","SHOPIFY_SHOP_NOT_FOUND","SHOPIFY_SHOP_FROZEN","SHOPIFY_SHOP_LOCKED","SHOPIFY_VARIANT_NOT_FOUND","SHOPIFY_USER_ERROR","SHOPIFY_THROTTLED","ECONOMIC_SAFETY_REFUSED","REVISION_REQUIRES_MANUAL","CONNECTOR_NEEDS_RECONNECT","DUPLICATE_PO_HELD","POSTING_DECISION_REQUIRED","POSTED_MONEY_MISMATCH","ROUTED_TO_FILE_EXPORT","PROVIDER_REJECTED","PROVIDER_UNAVAILABLE","UNKNOWN_OUTCOME",null],"description":"Stable error code an agent can branch on."},"nextStep":{"type":"object","nullable":true,"properties":{"label":{"type":"string"},"url":{"type":"string","nullable":true}},"required":["label","url"],"description":"The one next action, with a deep link into the web app."},"retryable":{"type":"boolean","nullable":true,"description":"Whether retrying without changing anything can succeed."},"technicalDetail":{"type":"string","nullable":true,"description":"Raw provider response, for support. Show only behind a \"Technical details\" disclosure."},"integratedAt":{"type":"string","nullable":true,"format":"date-time"},"updatedAt":{"type":"string","nullable":true,"format":"date-time"}},"required":["id","role","connectorType","connectorId","connectorLabel","status","externalRef","attemptCount","lastError","errorCode","nextStep"]}},"invoiceWriteBack":{"type":"object","nullable":true,"description":"Set when the tenant has write-back on and this invoice was exported as a file instead of written as a bill, with why: expense_account_missing (the accounting connector has no default expense account; set one with PATCH.../connectors/:connectorId defaultExpenseAccountId), unsupported_connector (the accounting destination cannot take bills) or no_accounting_destination. Null otherwise, including when destinations[] is not empty (a later approval sent it to a connected system).","properties":{"routedTo":{"type":"string","enum":["export"]},"reason":{"type":"string","enum":["no_accounting_destination","unsupported_connector","expense_account_missing"]},"connectorType":{"type":"string","nullable":true},"connectorId":{"type":"string","nullable":true},"message":{"type":"string","description":"The plain sentence the invoice page shows."}},"required":["routedTo","reason","connectorType","connectorId","message"]},"exportFile":{"type":"object","nullable":true,"description":"The CSV file this invoice was exported to, once the export has written it; null otherwise (not exported, or written to a connected system). Fetch a short-lived download URL with GET /:invoiceId/export-file.","properties":{"filename":{"type":"string"},"format":{"type":"string"},"deliveredVia":{"type":"string","nullable":true},"exportedAt":{"type":"string","nullable":true}},"required":["filename","format","deliveredVia","exportedAt"]},"approveDestination":{"type":"object","nullable":true,"description":"Where Approve would send this invoice now, read the way approve decides it and recording nothing. kind post: the bill is written to connectorType/connectorId (connectorLabel is its name). kind file: the invoice is exported as a CSV and delivered by fileExportMethod (download: stored for the invoice page; email: sent to the configured address; sftp: uploaded). kind choice: a company must be chosen first (destinationChoices); each company says whether it posts or exports, and an export goes by fileExportMethod. Null when the invoice is no longer in review, or when it cannot be said (a connection needs reconnecting, or the read failed).","properties":{"kind":{"type":"string","enum":["post","file","choice"]},"connectorType":{"type":"string","nullable":true},"connectorId":{"type":"string","nullable":true},"connectorLabel":{"type":"string","nullable":true},"fileExportMethod":{"type":"string","enum":["download","email","sftp"]}},"required":["kind","connectorType","connectorId","connectorLabel","fileExportMethod"]},"duplicateInvoice":{"type":"object","nullable":true,"description":"The earlier invoice from the same supplier with the same invoice number, when the duplicate_invoice check failed (the most recent result). While it is set, POST /:envelopeId/approve answers 409 APPROVAL_NEEDS_ACKNOWLEDGEMENT until acknowledge.duplicateInvoice is true. matchedStatus is the earlier invoice's status (exported means it was already sent). Null when there is no repeat.","properties":{"invoiceNumber":{"type":"string","nullable":true},"matchedEnvelopeId":{"type":"string","nullable":true},"matchedInvoiceId":{"type":"string","nullable":true},"matchedInvoiceUrl":{"type":"string","nullable":true},"matchedStatus":{"type":"string","nullable":true},"matchedReceivedAt":{"type":"string","nullable":true},"matchedVendorName":{"type":"string","nullable":true},"matchedTotalAmount":{"type":"string","nullable":true},"matchedCurrency":{"type":"string","nullable":true}},"required":["invoiceNumber","matchedEnvelopeId","matchedInvoiceId","matchedInvoiceUrl","matchedStatus","matchedReceivedAt","matchedVendorName","matchedTotalAmount","matchedCurrency"]}},"required":["id","envelopeId","vendorName","confidenceScore","status","lineItems","validationResults","correctionsSupported","destinationChoices","destinations","invoiceWriteBack","exportFile"],"additionalProperties":true}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"getInvoicesByInvoiceId","summary":"Get invoice detail with line items and validation results"}},"/api/v1/tenants/{tenantId}/invoices/{invoiceId}/export-file":{"get":{"tags":["invoices"],"description":"Get a short-lived (15 minute) signed download URL for the CSV file an invoice was exported to. Available once the export has written the file (get-invoice shows it as exportFile). An invoice that has not been exported as a file, or is not this tenant's, answers 404 NOT_FOUND.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"invoiceId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"url":{"type":"string","description":"Signed URL, valid for 15 minutes; it downloads the file under its filename."},"filename":{"type":"string"},"format":{"type":"string","description":"csv"},"deliveredVia":{"type":"string","description":"download"},"exportedAt":{"type":"string"}},"required":["url","filename","format"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"getInvoicesByInvoiceIdExportFile","summary":"Get export file of invoice"}},"/api/v1/tenants/{tenantId}/invoices/{envelopeId}/approve":{"post":{"tags":["invoices"],"description":"Approve an invoice in review, optionally correcting header fields (vendorName, vendorId, invoiceNumber, invoiceDate, dueDate, poNumberReference, subtotal, taxAmount, totalAmount, currency, paymentTerms, remitToAddress.<line1|line2|city|state|zip|country>) via `corrections`, and line fields (description, quantity, unitPrice, amount) via `lineCorrections` (lineItemId + field + correctedValue). After applying corrections the invoice total re-reconciles in the same transaction: a correction that breaks reconciliation (or does not fix an existing break) is refused with 409 INVOICE_TOTAL_MISMATCH (error.details has the arithmetic) and writes nothing. Correcting invoiceNumber or vendorId to a value that already exists for this vendor is refused with 409 DUPLICATE_INVOICE. An unknown field name is refused with 400 INVALID_CORRECTION_FIELD. With write-back on, an invoice is written to the accounting role and follows the same destination rules as a purchase order. If several accounting instances could take it and no rule or default names one (e.g. two QuickBooks companies), nothing is written or exported and the invoice stays in review: responds 409 DESTINATION_CHOICE_REQUIRED with error.details.roles[] (role, message, instances[]); resend with destinationChoices.accounting set to one of those instance ids. Each instance carries writeBack: post (the bill is written to that company) or export (approving for it exports the invoice as a file; writeBackReason says why, e.g. expense_account_missing). The 409 is sent only when at least one company would post: when every candidate company would export, there is nothing to choose and approve exports the invoice as a file with no company chosen (no destination row; GET invoice detail invoiceWriteBack says why). If the accounting destination is a connection that needs reconnecting, responds 409 CONNECTOR_NEEDS_RECONNECT with error.details.destinations[] (role, connectorId, connectorType, displayName, message, nextStep); reconnect it, then approve again. When the same supplier already billed this invoice number (the duplicate_invoice check failed; GET invoice detail duplicateInvoice describes the earlier invoice), approve is refused with 409 APPROVAL_NEEDS_ACKNOWLEDGEMENT, the order route's code, with error.details.duplicateInvoice (invoiceNumber, matchedInvoiceId, matchedInvoiceUrl, matchedStatus, matchedReceivedAt, matchedVendorName, matchedTotalAmount, matchedCurrency) and error.details.required.duplicateInvoice true, and nothing is written; resend with acknowledge.duplicateInvoice set to true to approve it anyway (recorded on the approval). A correction to invoiceNumber or vendorId re-runs the duplicate check instead (409 DUPLICATE_INVOICE when it still matches), so an invoice whose number was corrected to a new one needs no acknowledgement. Corrections apply to this invoice only; nothing is learned from them (no mapping rule, customer profile or golden data), unlike order review. The response reports how many were applied in correctionsApplied. This is the invoice review path: an envelope with no extracted invoice (e.g. a purchase order) is refused with 409 NOT_AN_INVOICE (error.details.documentType); use POST /review/:envelopeId/approve instead.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"notes":{"type":"string"},"destinationChoices":{"type":"object","description":"Per-role pick of the connected instance this order is written to, for a role that several instances could fill and no rule or default names. Required after a 409 DESTINATION_CHOICE_REQUIRED (its error.details.roles[].instances[].id are the valid values); ignored for a role a rule or default already fills.","properties":{"commerce":{"type":"string","format":"uuid"},"accounting":{"type":"string","format":"uuid"}},"additionalProperties":false},"acknowledge":{"type":"object","description":"Acknowledgements for approval gates. duplicateInvoice: true approves an invoice whose supplier and invoice number were already received (answers 409 APPROVAL_NEEDS_ACKNOWLEDGEMENT with details.required.duplicateInvoice).","properties":{"duplicateInvoice":{"type":"boolean"}}},"corrections":{"type":"array","items":{"type":"object","properties":{"field":{"type":"string"},"originalValue":{},"correctedValue":{}},"required":["field","originalValue","correctedValue"]}},"lineCorrections":{"type":"array","items":{"type":"object","properties":{"lineItemId":{"type":"string","format":"uuid"},"field":{"type":"string"},"correctedValue":{}},"required":["lineItemId","field","correctedValue"]}}}}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"envelopeId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"envelopeId":{"type":"string"},"invoiceId":{"type":"string","nullable":true},"status":{"type":"string","enum":["approved"]},"correctionsApplied":{"type":"integer","description":"How many header and line corrections were applied to this invoice before approval."},"routedTo":{"type":"string","enum":["integration","export"],"nullable":true,"description":"Where the approved invoice was sent: integration (queued to be written as a bill) or export (exported as a file). Null for an envelope with no invoice row."},"message":{"type":"string"}},"required":["envelopeId","invoiceId","status","correctionsApplied","message"]}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"approveInvoice","summary":"Approve a supplier invoice in review"}},"/api/v1/tenants/{tenantId}/invoices/{envelopeId}/reject":{"post":{"tags":["invoices"],"description":"Reject an invoice in review. reasonCode (optional) is the machine-readable cause: duplicate, multi_po, unreadable, wrong_customer, pricing, not_an_order or other; it is recorded on the audit row.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"reason":{"type":"string","pattern":"\\S"},"reasonCode":{"type":"string","enum":["duplicate","multi_po","unreadable","wrong_customer","pricing","not_an_order","other"]},"notes":{"type":"string"}}}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"envelopeId","required":true}],"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"rejectInvoice","summary":"Reject a supplier invoice in review"}},"/api/v1/tenants/{tenantId}/envelopes/{envelopeId}":{"get":{"tags":["orders"],"description":"The envelope status poll: where a submitted document is, and the order or invoice it became. Poll until `resting` is true (status one of exported, manual_handling, rejected, failed) or `awaitingHuman` is true (status one of in_review, pending_export, manual_handling): nothing further happens without a person. orderId or invoiceId is set once extraction has produced one; use it with GET /orders/:orderId, /routing-explanation and /report-problem. errorCode carries the last recorded failure code (extraction, or the failed destination). decision is the routing outcome once validation ran. contentPurge is set when the stored email and attachments were deleted while the envelope record was kept: reason non_order_30d is mail filed as not an order, deleted 30 days after it was filed (at is when). Needs orders:read only, unlike GET /review/:envelopeId.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"envelopeId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"envelopeId":{"type":"string","format":"uuid"},"documentType":{"type":"string","enum":["order","invoice"]},"status":{"type":"string","enum":["received","extracting","extracted","validating","validated","in_review","auto_approved","approved","exporting","pending_export","exported","rejected","manual_handling","failed"]},"terminal":{"type":"boolean","description":"The state machine has no transition out of this status."},"resting":{"type":"boolean","description":"One of exported, manual_handling, rejected, failed: stop polling."},"awaitingHuman":{"type":"boolean","description":"One of in_review, pending_export, manual_handling: a person must act."},"orderId":{"type":"string","format":"uuid","nullable":true},"invoiceId":{"type":"string","format":"uuid","nullable":true},"errorCode":{"type":"string","nullable":true},"errorMessage":{"type":"string","nullable":true},"decision":{"type":"object","nullable":true,"properties":{"action":{"type":"string","enum":["auto_approve","review","reject"]},"adjustedScore":{"type":"number","nullable":true},"wouldAutoApprove":{"type":"boolean","nullable":true}},"required":["action"]},"contentPurge":{"type":"object","nullable":true,"description":"Set when the stored content was deleted and the record kept.","properties":{"at":{"type":"string","format":"date-time"},"reason":{"type":"string","nullable":true,"description":"non_order_30d: mail filed as not an order, deleted after the short window."},"windowDays":{"type":"integer","nullable":true}},"required":["at","reason","windowDays"]},"createdAt":{"type":"string","format":"date-time"},"updatedAt":{"type":"string","format":"date-time"}},"required":["envelopeId","documentType","status","terminal","resting","awaitingHuman","orderId","invoiceId","errorCode","errorMessage","decision","createdAt","updatedAt"]},"example":{"envelopeId":"e5b0f1c2-3d4a-4b6c-8e9f-1a2b3c4d5e6f","documentType":"order","status":"in_review","terminal":false,"resting":false,"awaitingHuman":true,"orderId":"0f1e2d3c-4b5a-4968-8776-655443322110","invoiceId":null,"errorCode":null,"errorMessage":null,"decision":{"action":"review","adjustedScore":0.87,"wouldAutoApprove":false},"contentPurge":null,"createdAt":"2026-11-21T14:03:12.481Z","updatedAt":"2026-11-21T14:03:41.090Z"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"getEnvelope","summary":"Get the processing status of a submission"}},"/api/v1/tenants/{tenantId}/review/":{"get":{"tags":["review"],"description":"List review queue items. Default sort: ship-by date, then order value, then age (PRD v3 §3.4.2). An approved order its destination held before sending (status in_review with a manual-downstream hold, ECONOMIC_SAFETY_REFUSED or REVISION_REQUIRES_MANUAL) is not listed or counted here: GET /attention lists it under held, and it is approved again from GET /review/:envelopeId.","parameters":[{"schema":{"type":"integer","minimum":1,"default":1},"in":"query","name":"page","required":false,"description":"Page number (1-based)"},{"schema":{"type":"integer","minimum":1,"maximum":200},"in":"query","name":"pageSize","required":false,"description":"Items per page (default 20, max 200)"},{"schema":{"type":"integer","minimum":1},"in":"query","name":"limit","required":false,"description":"Deprecated alias of pageSize, clamped to 200. Accepted for one release."},{"schema":{"type":"integer","minimum":0},"in":"query","name":"offset","required":false,"description":"Deprecated: rows to skip. Takes precedence over page when both are sent. Accepted for one release."},{"schema":{"type":"string","enum":["queue","confidenceScore","createdAt","customerName","shipBy","orderValue","deliveryDate"],"default":"queue"},"in":"query","name":"sortBy","required":false},{"schema":{"type":"string","enum":["asc","desc"],"default":"asc"},"in":"query","name":"sortOrder","required":false},{"schema":{"type":"string"},"in":"query","name":"customer","required":false,"description":"Filter by customer name (substring match)"},{"schema":{"type":"string","maxLength":100},"in":"query","name":"poNumber","required":false,"description":"Only orders whose PO number contains this text, ignoring case."},{"schema":{"type":"string","maxLength":200},"in":"query","name":"q","required":false,"description":"Orders whose PO number or customer name contains this text, ignoring case."},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"type":"object","properties":{"envelopeId":{"type":"string"},"customerName":{"type":"string"},"poNumber":{"type":"string","nullable":true},"channelType":{"type":"string"},"confidenceScore":{"type":"number"},"matchScore":{"type":"number","description":"The match score the order was routed on (after validation adjustments), 0 to 1 at four decimal places. The same number the needs-review email, the review queue and the order page show. Falls back to confidenceScore for an order not routed yet. confidenceScore keeps its meaning: the extraction score before validation adjusted it."},"matchScorePercent":{"type":"integer","description":"matchScore as the whole percent people see, cut down and never rounded up (0.949 is 94)."},"status":{"type":"string"},"shipBy":{"type":"string","nullable":true},"shipByKind":{"type":"string","nullable":true,"enum":["ship","delivery",null],"description":"What shipBy is. ship: the PO printed a ship date. delivery: it printed only a requested delivery date, which shipBy fell back to (read it as \"deliver by\"). Null when shipBy is null."},"orderValue":{"type":"number","nullable":true,"description":"The order total: each line round(quantity x unit price) less its discount, plus the PO's charges (freight, tax, order discounts), the figure the order page and the exported file state. Null when a line has no price. sortBy=orderValue still orders by the line value recorded at extraction."},"currency":{"type":"string","nullable":true},"minLineConfidence":{"type":"number","nullable":true},"documentType":{"type":"string","nullable":true},"createdAt":{"type":"string"},"ageMinutes":{"type":"number"},"slaBreached":{"type":"boolean"},"lockedBy":{"type":"string","nullable":true},"lockedAt":{"type":"string","nullable":true},"unmatchedLineCount":{"type":"number"},"unknownCustomer":{"type":"boolean"},"possibleDuplicate":{"type":"boolean"},"heldReason":{"type":"string","nullable":true,"description":"Why an approved order came back to review, in plain language — e.g. \"Held: PO 56633 is already in Summit Pet store from the order received 12 Sep.\" Null when it was never approved."},"repeatOfPoNumber":{"type":"string","nullable":true,"description":"The PO number this order repeats: the duplicate check found an earlier order with the same PO number (or the same revision sent twice), or the export/integration PO claim blocked it because another order already sent that PO (reviewHold.code DUPLICATE_PO_HELD). Null otherwise; a match on content alone is reported by possibleDuplicate only."},"multiPoMerged":{"type":"boolean","description":"True when the document held several purchase orders with distinct PO numbers that were merged into this one order. Such an order is never approvable (approve responds 409 MULTI_PO_MERGED): reject it and have the sender resubmit each PO separately."},"mergedPoCount":{"type":"integer","nullable":true,"description":"How many distinct PO numbers were merged into this order. Null when multiPoMerged is false, or when the merged PO numbers were not recorded."}}}},"pagination":{"type":"object","properties":{"page":{"type":"number"},"pageSize":{"type":"number"},"total":{"type":"number"},"totalPages":{"type":"number"}},"required":["page","pageSize","total","totalPages"]},"autoApprovedToday":{"type":"number"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"listReviewQueue","summary":"List the review queue"}},"/api/v1/tenants/{tenantId}/review/{envelopeId}/claim":{"post":{"tags":["review"],"description":"Claim a review item for exclusive editing. Renews a claim you already hold. 409 CONFLICT while another reviewer holds a live claim (one renewed in the last 10 minutes); error.details says who (lockedBy, lockedByName: name, else email, null when not readable), since when (lockedSince) and when it lapses (lockedUntil), all ISO 8601. 409 NOT_REVIEWABLE when the envelope exists but has left review (any status other than validated or in_review, for example already approved by a teammate); error.details.status is its current status. 404 when the envelope is not this tenant's.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"envelopeId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"envelopeId":{"type":"string"},"lockedBy":{"type":"string"},"lockedUntil":{"type":"string"}},"required":["envelopeId","lockedBy","lockedUntil"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"object","properties":{"code":{"type":"string","enum":["CONFLICT","NOT_REVIEWABLE"],"description":"CONFLICT while another reviewer holds a live claim; NOT_REVIEWABLE when the envelope is not in review (not validated or in_review)."},"message":{"type":"string"},"details":{"type":"object","description":"CONFLICT: who holds the claim and when it frees, all null when no live claim is held (none, or older than 10 minutes). NOT_REVIEWABLE: only status.","properties":{"status":{"type":"string","description":"NOT_REVIEWABLE only: the envelope status it is in now (for example approved, rejected, manual_handling, exporting, exported)."},"lockedBy":{"type":"string","nullable":true,"description":"User id of the reviewer holding a live claim."},"lockedByName":{"type":"string","nullable":true,"description":"The holder's name, else their email; null when the holder is not a user of this tenant or cannot be read."},"lockedSince":{"type":"string","format":"date-time","nullable":true,"description":"When the holder opened the order (ISO 8601)."},"lockedUntil":{"type":"string","format":"date-time","nullable":true,"description":"When the claim lapses (10 minutes after the holder's last renewal) unless they renew or release it first (ISO 8601)."}}},"correlationId":{"type":"string"}},"required":["code","message"]}},"required":["error"]}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postReviewByEnvelopeIdClaim","summary":"Claim a review item for exclusive editing"}},"/api/v1/tenants/{tenantId}/review/{envelopeId}/release":{"post":{"tags":["review"],"description":"Release a claimed review item","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"envelopeId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"envelopeId":{"type":"string"},"message":{"type":"string"}},"required":["envelopeId","message"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postReviewByEnvelopeIdRelease","summary":"Release a claimed review item"}},"/api/v1/tenants/{tenantId}/review/{envelopeId}":{"get":{"tags":["review"],"description":"Get review detail for an envelope: the envelope, the extracted order with lines, the reference-data flags, where Approve will send it (destinationPreview), any PO revision, and the validation results. Needs review:read; for a light status poll use GET /envelopes/:envelopeId (orders:read).","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"envelopeId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"envelope":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"channelType":{"type":"string"},"status":{"type":"string","enum":["received","extracting","extracted","validating","validated","in_review","auto_approved","approved","exporting","pending_export","exported","rejected","manual_handling","failed"]},"rawStoragePath":{"type":"string"},"metadata":{"type":"object","additionalProperties":true},"createdAt":{"type":"string"}},"additionalProperties":true},"documentUrl":{"type":"string","nullable":true},"sender":{"type":"object","nullable":true,"description":"Who sent an emailed order (email, gmail, microsoft365 channels), from the envelope metadata the mailbox pollers stamp. Null for upload, API, SFTP and manual orders. auth is the provider-checked verdict: pass, fail, none (not verified; a generic IMAP mailbox is always none), or null when the envelope predates sender verification. Display evidence only: it changes no routing or approval.","properties":{"address":{"type":"string","nullable":true},"domain":{"type":"string","nullable":true},"auth":{"type":"string","nullable":true,"enum":["pass","fail","none",null]},"channel":{"type":"string"}},"additionalProperties":false},"order":{"type":"object","nullable":true,"additionalProperties":true},"referenceData":{"type":"object","properties":{"hasProducts":{"type":"boolean"},"hasCustomers":{"type":"boolean"},"changedSinceExtraction":{"type":"boolean","description":"The envelope is in review and reference data (a successful sync, or a product or customer row) changed after the order was matched or last re-checked. POST /review/:envelopeId/rematch re-checks it."}},"additionalProperties":true},"destinationPreview":{"type":"object","nullable":true,"additionalProperties":true},"revision":{"type":"object","nullable":true,"additionalProperties":true},"customerResolution":{"type":"object","nullable":true,"description":"Why the order is not matched to a customer, when customerResolutionMethod is unresolved and the tenant has reference customers. outcome ambiguous: a resolver rung found two or more distinct customers and, by design, did not pick one; candidates are the tied rows (capped is true when there were 10 or more). outcome no_match: no customer matched. Derived when read with the order's own reference scope and sender; never changes the stored resolution. Null otherwise, including when reference data changed and the order would now match (see referenceData.changedSinceExtraction and POST /review/:envelopeId/rematch).","properties":{"outcome":{"type":"string","enum":["ambiguous","no_match"]},"rung":{"type":"string","enum":["source_id","exact_name","normalized_name","alias"],"description":"The resolver rung that tied (ambiguous only)"},"capped":{"type":"boolean"},"candidates":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid","description":"reference_customers.id; send it to POST /review/:envelopeId/customer to match the order"},"name":{"type":"string"},"connectorId":{"type":"string","nullable":true},"connectorType":{"type":"string","nullable":true,"description":"Type of the connection the row was synced from; null for an uploaded list"},"connectorName":{"type":"string","nullable":true,"description":"Display name of that connection"},"sourceSystem":{"type":"string"},"email":{"type":"string","nullable":true},"senderDomains":{"type":"array","items":{"type":"string"}}},"required":["id","name","connectorId","connectorType","connectorName","sourceSystem","email","senderDomains"],"additionalProperties":false}}},"required":["outcome"],"additionalProperties":false},"validationResults":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string"},"validatorName":{"type":"string"},"status":{"type":"string"},"message":{"type":"string","nullable":true},"confidenceAdjustment":{"type":"number","nullable":true},"details":{"type":"object","nullable":true,"additionalProperties":true}},"additionalProperties":true}}},"required":["envelope","documentUrl","order","referenceData","destinationPreview","revision","validationResults"],"additionalProperties":true}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"getReviewItem","summary":"Get an order in review"}},"/api/v1/tenants/{tenantId}/review/{envelopeId}/document-text":{"get":{"tags":["review"],"description":"Get the extracted text content of the source document for an envelope. Returns raw text for text-based documents and OCR/preprocessed text for PDFs.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"envelopeId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"envelopeId":{"type":"string"},"text":{"type":"string"},"contentType":{"type":"string"},"extractedFrom":{"type":"string","enum":["raw","ocr"]}},"required":["envelopeId","text","contentType","extractedFrom"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getReviewByEnvelopeIdDocumentText","summary":"Get the extracted text content of the source document for an envelope"}},"/api/v1/tenants/{tenantId}/review/{envelopeId}/approve":{"post":{"tags":["review"],"description":"Approve an order with optional corrections. If the envelope held several purchase orders with distinct PO numbers that were merged into one order (metadata.multiPoMerged), it can never be approved: responds 409 MULTI_PO_MERGED with error.details.poNumbers[]; reject it (reason \"Several purchase orders in one email\") and have the sender resubmit each PO separately. Checked before every other gate; no acknowledgement lifts it. If the order has lines with no catalog product, a customer not in the customer list, or a PO number already received (a failing duplicate check; revisions are exempt), responds 409 APPROVAL_NEEDS_ACKNOWLEDGEMENT with the facts to acknowledge in error.details (details.required says which acknowledge flags to send; details.duplicate names the earlier order). A 200 lists destinations[]: a destination with willHold true will not be written because another order already holds this PO there — reason says why. If write-back is on and a role the order is written to has several connected instances with no rule or default naming one (e.g. two QuickBooks companies), nothing is written and the order stays in review: responds 409 DESTINATION_CHOICE_REQUIRED with error.details.roles[] (role, message, instances[]); resend with destinationChoices.<role> set to one of those instance ids. If write-back is on and a destination the order belongs to is a connection that needs reconnecting (status error), nothing is written, nothing is routed elsewhere and the order stays in review: responds 409 CONNECTOR_NEEDS_RECONNECT with error.details.destinations[] (role, connectorId, connectorType, displayName, message, nextStep); reconnect it, then approve again. If the tenant has businesses and the order's customer (names compared ignoring case, punctuation and legal suffixes, \"&\" = \"and\") is known in two or more of them with no rule deciding, nothing is routed by the default business: responds 409 BUSINESS_CHOICE_REQUIRED with error.details.candidates[] (id, name); resend with businessEntityId set to one of them. The printed spelling becomes an alias on that business's customer, and the order's customer is resolved inside it. If the order is routed to a Shopify store and a line quantity is not a whole number, responds 409 WHOLE_UNITS_REQUIRED (error.details.lines); convert the unit or correct the quantity and approve again. If the customer is a Shopify B2B company with several locations and the ship-to matches none, responds 409 SHOPIFY_LOCATION_REQUIRED with error.details.locations; correct shipToCode to one location's code and approve again. If write-back is on and the order data itself cannot post to a destination it is about to be sent to (a printed line total that is not quantity x price less discount, or a line with no valid quantity or price: blocker codes extension_mismatch and economic_safety in GET /orders/:orderId/posting-preview), nothing is approved, enqueued or billed and the order stays in review: responds 409 POSTING_BLOCKED with error.details.blockers[] (destination, role, connectorType, connectorId, code, message, lineNumber?, setting?). The check runs after the corrections in this request are applied, so correcting the line in the same approve clears it. Setup and posting-decision blockers (a missing freight or services item, a currency the books are not kept in, an unlisted line, an unexplained difference) do not refuse: the order is approved, the other destinations post, and that destination is held for a decision (POST.../destinations/:destinationId/retry once decided). If the preview cannot be built just now, the approval is not blocked and postingCheck is \"unavailable\". This is the order review path: an envelope with no extracted order (e.g. a supplier invoice) is refused with 409 NOT_AN_ORDER (error.details.documentType); use POST /invoices/:envelopeId/approve instead.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"corrections":{"type":"array","description":"Field edits applied before approval. `field` is one of: a header field (customerName, poNumber, specialInstructions, deliveryDate, orderDate, requestedShipDate, shippingMethod, customerAccountNumber, shipToCode); `shippingAddress.<line1|line2|city|state|zip|country>`; or `lineItems[<key>].<sku|description|quantity|unitPrice|uom|discount>`, where <key> is the line id (a UUID from GET /orders/{orderId}) or a zero-based position in line-number order. Example: [{\"field\":\"lineItems[0].quantity\",\"originalValue\":10,\"correctedValue\":12},{\"field\":\"poNumber\",\"originalValue\":\"PO-1\",\"correctedValue\":\"PO-1001\"}]. Any other field is refused with 400 INVALID_CORRECTION_FIELD (error.details.field) and nothing is changed.","items":{"type":"object","properties":{"field":{"type":"string"},"originalValue":{},"correctedValue":{}},"required":["field","originalValue","correctedValue"],"allOf":[{"if":{"properties":{"field":{"type":"string","pattern":"\\.quantity$"}}},"then":{"properties":{"correctedValue":{"anyOf":[{"type":"number","exclusiveMinimum":0},{"type":"string","pattern":"^\\s*(?=[0-9.]*[1-9])[0-9]*\\.?[0-9]+\\s*$"}]}}}},{"if":{"properties":{"field":{"type":"string","pattern":"\\.(unitPrice|discount)$"}}},"then":{"properties":{"correctedValue":{"anyOf":[{"type":["number","null"],"minimum":0},{"type":"string","pattern":"^\\s*([0-9]*\\.?[0-9]+)?\\s*$"}]}}}}]}},"addedLines":{"type":"array","maxItems":100,"description":"Lines the reviewer typed in because extraction missed them; inserted onto the order before it is exported.","items":{"type":"object","properties":{"sku":{"type":"string","minLength":1,"maxLength":100},"description":{"type":"string","nullable":true},"quantity":{"type":"number","exclusiveMinimum":0},"unitPrice":{"type":"number","minimum":0,"nullable":true},"uom":{"type":"string","maxLength":20,"nullable":true}},"required":["sku","quantity"]}},"removedLineIds":{"type":"array","maxItems":500,"description":"IDs of extracted lines the reviewer removed; deleted from the order before it is exported.","items":{"type":"string","format":"uuid"}},"notes":{"type":"string"},"acknowledge":{"type":"object","description":"Required when the order has lines with no catalog product, a customer not in the customer list, or a PO number already received; without the matching flag the approve is refused with 409 APPROVAL_NEEDS_ACKNOWLEDGEMENT whose details list exactly what must be acknowledged.","properties":{"unmatchedLines":{"type":"boolean","description":"Approve lines with no catalog product, lines whose product is archived or draft in the destination store or inactive in the destination books (those entries carry reason \"inactive_product\", status and message), and lines a destination Shopify store does not sell and cannot yet take as a custom line item (reason \"not_in_store\" and message — the store's draft is held as POSTING_DECISION_REQUIRED until the store allows custom line items and the line's mapping is confirmed, or the line is matched). Replacing the SKU or removing the line lifts the hold instead."},"unknownCustomer":{"type":"boolean","description":"Approve a customer not in the customer list. error.details.unknownCustomer.destinations names where the order is written, and the message says what happens there: a Shopify draft has no customer unless Shopify finds exactly one customer by the verified sender’s email or by that name; QuickBooks uses its customer with that exact name if it has one, holds the order for you if it has a likely match, and otherwise adds a new customer; NetSuite uses the customer ID printed on the order or a customer with that exact name, and otherwise creates a new customer; a custom REST destination receives the name as printed; a file export carries the name as printed."},"duplicatePo":{"type":"boolean","description":"Approve even though this PO number was already received. The audit row records it with the matched order."}},"additionalProperties":false},"destinationChoices":{"type":"object","description":"Per-role pick of the connected instance this order is written to, for a role that several instances could fill and no rule or default names. Required after a 409 DESTINATION_CHOICE_REQUIRED (its error.details.roles[].instances[].id are the valid values); ignored for a role a rule or default already fills.","properties":{"commerce":{"type":"string","format":"uuid"},"accounting":{"type":"string","format":"uuid"}},"additionalProperties":false},"revisionAction":{"type":"string","enum":["cancel","update"],"description":"What a revision of a PO that was already posted does to the earlier documents. \"cancel\" confirms it cancels the PO: the Shopify draft is deleted, a QuickBooks estimate closed and an invoice voided, each with an audit row. Without it, a revision that says the order is cancelled, has no line with a quantity (zero-quantity rows are dropped at extraction) or has every line at quantity zero is refused with 409 REVISION_CANCELLATION_CONFIRMATION_REQUIRED (error.details.reason: document_cancelled, no_lines or zero_quantities; error.details.documents). \"update\" updates the documents with the revision's lines despite a cancellation statement; refused with 400 REVISION_UPDATE_HAS_NO_LINES when no line has a quantity. 400 REVISION_NOTHING_TO_CANCEL when nothing earlier was posted."},"businessEntityId":{"type":"string","format":"uuid","description":"The business this order belongs to, when the reviewer changes it: the store and books of that business are written, whatever rules or the default would pick. Recorded as a correction; re-routing one customer to the same business twice proposes a routing rule. An id that is not one of this tenant's businesses is 400 ENTITY_NOT_FOUND."}}},"example":{"corrections":[{"field":"lineItems[0].quantity","originalValue":"12","correctedValue":"24"}],"notes":"Quantity confirmed with the buyer by phone."}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"envelopeId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"envelopeId":{"type":"string"},"status":{"type":"string"},"message":{"type":"string"},"apiKeyName":{"type":"string","nullable":true,"description":"Name of the API key that performed this action (present when auth is via API key)"},"savedAsFileInstead":{"type":"boolean","description":"True when write-back is on but no connection could take this order (none connected for its type, or none resolvable), so it was exported as a file instead of written to the system. The message says so."},"postingCheck":{"type":"string","enum":["passed","unavailable","not_applicable"],"description":"Whether the posting preview was checked before sending. passed: no destination has an order-data problem (a destination can still be held afterwards for a setup or posting decision). unavailable: the preview could not be built just now, so the approval was not blocked and each destination checks the order again when it posts. not_applicable: no write-back destination (file export) or a confirmed cancellation."},"destinations":{"type":"array","description":"What approval will write, per destination. Empty when the order goes to file export. willHold true means another order already holds this PO number at that destination, so nothing will be written there; reason says so in plain language.","items":{"type":"object","properties":{"role":{"type":"string"},"connectorId":{"type":"string","nullable":true},"connectorType":{"type":"string"},"destinationName":{"type":"string"},"willHold":{"type":"boolean"},"reason":{"type":"string","nullable":true},"heldByEnvelopeId":{"type":"string","nullable":true},"heldByOrderUrl":{"type":"string","nullable":true},"action":{"type":"string","enum":["create","update","cancel"],"description":"Create a new document, update the one an earlier revision of this PO posted (documentLabel), or cancel it (revisionAction \"cancel\")."},"documentLabel":{"type":"string","nullable":true,"description":"For update/cancel: the existing document, e.g. \"Estimate 1043\" or \"Draft #D24\"."},"documentUrl":{"type":"string","nullable":true}},"required":["role","connectorType","destinationName","willHold"]}},"businessEntity":{"type":"object","nullable":true,"description":"The business the order was routed to and how: manual, reviewer, rule, remembered or default.","properties":{"id":{"type":"string"},"name":{"type":"string"},"source":{"type":"string"}}},"proposedRules":{"type":"array","description":"Mapping rules proposed because this correction was the second occurrence of a pattern (PRD v3 §3.5.1)","items":{"type":"object","properties":{"ruleId":{"type":"string"},"ruleType":{"type":"string"},"alias":{"type":"string"},"targetSku":{"type":"string"},"partnerName":{"type":"string","nullable":true},"occurrences":{"type":"number"}}}},"proposedRoutingRules":{"type":"array","description":"Routing rules proposed because people have now approved this customer into this business twice against what rules or the default would pick. Proposed only: they route nothing until activated (POST /destination-rules/:ruleId/activate).","items":{"type":"object","properties":{"ruleId":{"type":"string"},"name":{"type":"string"},"entityId":{"type":"string"},"entityName":{"type":"string"},"referenceCustomerId":{"type":"string"},"occurrences":{"type":"number"}}}},"proposedCustomerRules":{"type":"array","description":"customer_alias rules proposed because a corrected customer name was the second occurrence of a pattern","items":{"type":"object","properties":{"ruleId":{"type":"string"},"name":{"type":"string"},"targetCustomerId":{"type":"string"},"targetCustomerName":{"type":"string"},"occurrences":{"type":"number"}}}},"proposedUomRules":{"type":"array","description":"uom_conversion rules proposed because a corrected UOM label was the second occurrence of a pattern for this SKU","items":{"type":"object","properties":{"ruleId":{"type":"string"},"sku":{"type":"string"},"label":{"type":"string"},"expectedUom":{"type":"string"},"partnerName":{"type":"string","nullable":true},"occurrences":{"type":"number"}}}},"learning":{"type":"object","description":"What this approval taught the system, per corrected field. `learned` is what actually changed; `nothingLearned` names every corrected field that changed nothing and why — the common and truthful case for a corrected quantity, price, date or address. Every rule named here is proposed only: it does nothing until a person activates it at /rules.","properties":{"recorded":{"type":"number","description":"Corrections written to the append-only ledger by this approval."},"status":{"type":"string","enum":["ok","failed"],"description":"Whether the post-commit learning write-backs (rule proposals, customer profile, golden-data) completed. 'failed' means the approval itself still succeeded but at least one write-back threw — see `failures`. Omitted when no correction/line edit was present to learn from."},"failures":{"type":"array","description":"Present when status is 'failed'. One entry per write-back stage that threw.","items":{"type":"object","properties":{"stage":{"type":"string","enum":["customer_alias","profile","golden_data"]},"error":{"type":"string"}},"required":["stage","error"]}},"learned":{"type":"array","items":{"type":"object","properties":{"kind":{"type":"string","enum":["customer_alias_learned","rule_proposed","hint_proposed","hint_suspended","rule_suspended"]},"ruleId":{"type":"string","description":"Present on every kind except customer_alias_learned."},"ruleType":{"type":"string","description":"rule_proposed and rule_suspended."},"summary":{"type":"string","description":"rule_proposed: the mapping in one line."},"hintKind":{"type":"string","description":"hint_proposed and hint_suspended.","enum":["sku_column_placeholder","part_number_source","ship_to_label","default_uom","date_order","price_basis"]},"sentence":{"type":"string","description":"hint_proposed and hint_suspended: the exact sentence the hint puts in front of the extraction model."},"occurrences":{"type":"number","description":"rule_proposed and hint_proposed."},"evidence":{"type":"string","description":"hint_proposed, where the detector can name one: the verbatim thing on the document the hint was derived from — for date_order, the quoted date token the direction was read off."},"variant":{"type":"string","description":"customer_alias_learned: the spelling the document used."},"canonical":{"type":"string","description":"customer_alias_learned: the trading partner it now resolves to."}},"required":["kind"]}},"nothingLearned":{"type":"array","items":{"type":"object","properties":{"field":{"type":"string","description":"The corrected field, as the reviewer addressed it."},"reason":{"type":"string","enum":["not_learnable","first_occurrence","already_pending","no_partner","unverified_transport","conflicting_reference_data"],"description":"Why the field taught nothing. `conflicting_reference_data` is the one that names a fixable problem: the correction disagrees with the tenant's own reference data (today, a ship-to code the deterministic matcher resolves to a different location on file), so nothing is learned until a person corrects that data."},"occurrences":{"type":"number","description":"first_occurrence: how many times this pattern has been seen."},"threshold":{"type":"number","description":"first_occurrence: occurrences needed before a rule is proposed."}},"required":["field","reason"]}}},"required":["recorded","learned","nothingLearned"]}},"required":["envelopeId","status","message"]}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"approveOrder","summary":"Approve an order in review"}},"/api/v1/tenants/{tenantId}/review/{envelopeId}/reject":{"post":{"tags":["review"],"description":"Reject an order with a reason. reasonCode (optional) is the machine-readable cause: duplicate, multi_po, unreadable, wrong_customer, pricing, not_an_order or other; it is stored on the review record and the audit row so rejections can be aggregated.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"reason":{"type":"string","minLength":1,"pattern":"\\S"},"reasonCode":{"type":"string","enum":["duplicate","multi_po","unreadable","wrong_customer","pricing","not_an_order","other"]},"notes":{"type":"string"}},"required":["reason"]},"example":{"reason":"Duplicate of PO 88213 received yesterday."}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"envelopeId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"envelopeId":{"type":"string"},"status":{"type":"string"},"message":{"type":"string"},"apiKeyName":{"type":"string","nullable":true,"description":"Name of the API key that performed this action (present when auth is via API key)"}},"required":["envelopeId","status","message"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"rejectOrder","summary":"Reject an order in review"}},"/api/v1/tenants/{tenantId}/review/{envelopeId}/skip":{"post":{"tags":["review"],"description":"Skip a review item: it stays in review and its claim lock is released. Refused with 409 LOCKED while another reviewer holds a live claim (one taken in the last 10 minutes).","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"notes":{"type":"string"}}}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"envelopeId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"envelopeId":{"type":"string"},"status":{"type":"string"},"message":{"type":"string"},"apiKeyName":{"type":"string","nullable":true,"description":"Name of the API key that performed this action (present when auth is via API key)"}},"required":["envelopeId","status","message"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postReviewByEnvelopeIdSkip","summary":"Skip a review item: it stays in review and its claim lock is released"}},"/api/v1/tenants/{tenantId}/review/{envelopeId}/undo":{"post":{"tags":["review"],"description":"Undo a recent approval or rejection. Only works within the grace period (default 5 minutes) and before the order has been sent to integration; past the grace period responds 410 GRACE_PERIOD_EXPIRED, and an envelope that is not approved or rejected responds 409. A document filed as not an order when it was read (status rejected, classification non_order) is not a review decision and responds 409 NOT_AN_ORDER_USE_REPROCESS: read it again as an order with POST /orders/:envelopeId/reprocess. One filed as not an invoice (classification non_invoice) responds 409 NOT_AN_INVOICE_RESUBMIT: submit it again with POST /invoices. Neither refusal changes anything or fires a webhook. Only the reviewer who made the decision, or an owner or admin, can undo it; anyone else gets 403 FORBIDDEN. Fires envelope.in_review with previousStatus set to the undone status (approved or rejected) and undone: true. Reopens the envelope for review but does not revert corrections or restore deleted line items already applied by the decision being undone — it returns the order to the queue with those edits kept, not to its original extracted state.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"reason":{"type":"string","description":"Optional reason for undoing the review decision"}}}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"envelopeId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"envelopeId":{"type":"string"},"previousStatus":{"type":"string"},"status":{"type":"string"},"message":{"type":"string"},"undoneReviewId":{"type":"string","nullable":true}},"required":["envelopeId","previousStatus","status","message"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"description":"The credential is valid but may not do this: FORBIDDEN or ACCESS_DENIED (the key lacks the permission scope, or the role is too low, or the tenant in the path is not the key's tenant), TENANT_SUSPENDED for writes on a suspended account, MFA_REQUIRED for a session that owes a passkey.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"404":{"$ref":"#/components/responses/NotFound"},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"object","properties":{"code":{"type":"string"},"message":{"type":"string"},"details":{"type":"object","description":"Present on NOT_AN_ORDER_USE_REPROCESS and NOT_AN_INVOICE_RESUBMIT.","properties":{"classification":{"type":"string","enum":["non_order","non_invoice"]}}},"correlationId":{"type":"string"}}}}}}}},"410":{"description":"Gone: the resource existed but has expired or been used.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"object","properties":{"code":{"type":"string"},"message":{"type":"string"},"correlationId":{"type":"string"},"elapsedMinutes":{"type":"number"},"gracePeriodMinutes":{"type":"number"}}}}}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postReviewByEnvelopeIdUndo","summary":"Undo a recent approval or rejection"}},"/api/v1/tenants/{tenantId}/review/{envelopeId}/manual":{"post":{"tags":["review"],"description":"Mark an envelope for manual handling. The document is removed from the review queue and excluded from billing.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"reason":{"type":"string","description":"Why the document needs manual handling (e.g. unreadable)"}}}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"envelopeId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"envelopeId":{"type":"string"},"status":{"type":"string"},"message":{"type":"string"}},"required":["envelopeId","status","message"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"postReviewByEnvelopeIdManual","summary":"Mark an envelope for manual handling"}},"/api/v1/tenants/{tenantId}/review/{envelopeId}/return-to-review":{"post":{"tags":["review"],"description":"Move an order marked for manual handling (\"Handle myself\") back to the review queue. Allowed only when all of these hold, checked under the envelope lock: the envelope is in manual_handling (else 409 NOT_IN_MANUAL_HANDLING); it is a purchase order (else 409 NOT_AN_ORDER); a person put it there from review, through POST /review/:envelopeId/manual on an in_review order (a hold Poppelo made itself, for example after a failed or uncertain delivery, is refused with 409 MANUAL_HANDLING_SYSTEM_HOLD); and nothing was ever sent to a destination: no destination attempt, external reference, delivered export/integration dispatch or duplicate-PO claim held by this order (else 409 DESTINATION_ALREADY_ATTEMPTED). It is also refused with 409 DESTINATION_ALREADY_ATTEMPTED and details.exportStarted true when the order's audit trail shows it ever moved into exporting, even if that export later failed and the order came back to review: it may already be in your system, so enter it by hand instead. If the order was already entered in a destination by hand, do not move it back: approving it would enter it twice. On success the envelope is in_review, its review lock and attention-page dismissal are cleared, the order is re-validated (so a PO another order took in the meantime shows as a duplicate and must be acknowledged on approval), and envelope.in_review fires with previousStatus manual_handling and reason returned_to_review. Billing: moving back writes no usage event and changes none; the order stays free until a person resolves it again, and an approval then counts like any other approval on the plan.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","nullable":true,"additionalProperties":false,"properties":{"reason":{"type":"string","maxLength":1000,"description":"Optional note on why it goes back (recorded on the audit trail and the webhook)"}}}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"envelopeId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"envelopeId":{"type":"string","format":"uuid"},"orderId":{"type":"string","format":"uuid"},"previousStatus":{"type":"string","enum":["manual_handling"]},"status":{"type":"string","enum":["in_review"]},"message":{"type":"string"}},"required":["envelopeId","orderId","previousStatus","status","message"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"postReviewByEnvelopeIdReturnToReview","summary":"Move an order marked for manual handling (\"Handle myself\") back to the review queue"}},"/api/v1/tenants/{tenantId}/review/{envelopeId}/resolve-line":{"post":{"tags":["review"],"description":"Resolve a flagged line item (e.g. select a candidate SKU). Re-runs validation and returns the updated confidence. Refused with 409 LOCKED while another reviewer holds a live claim (one taken in the last 10 minutes).","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"lineItemId":{"type":"string","format":"uuid"},"sku":{"type":"string","minLength":1},"description":{"type":"string","nullable":true},"quantity":{"type":"number","exclusiveMinimum":0},"unitPrice":{"type":"number","nullable":true,"minimum":0},"uom":{"type":"string","nullable":true}},"required":["lineItemId","sku"]}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"envelopeId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"lineItemId":{"type":"string"},"sku":{"type":"string"},"resolutionMethod":{"type":"string"},"lineConfidence":{"type":"number"},"adjustedScore":{"type":"number"},"minLineConfidence":{"type":"number","nullable":true},"validationResults":{"type":"array","items":{"type":"object","properties":{"validatorName":{"type":"string"},"status":{"type":"string"},"message":{"type":"string","nullable":true},"confidenceAdjustment":{"type":"number","nullable":true},"details":{"type":"object","nullable":true,"additionalProperties":true}}}}},"required":["lineItemId","sku","resolutionMethod","lineConfidence","adjustedScore"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postReviewByEnvelopeIdResolveLine","summary":"Resolve line review"}},"/api/v1/tenants/{tenantId}/review/{envelopeId}/customer":{"post":{"tags":["review"],"description":"Match the order to an existing reference customer; sets the canonical customer name and re-validates. Refused with 409 LOCKED while another reviewer holds a live claim (one taken in the last 10 minutes).","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"referenceCustomerId":{"type":"string","format":"uuid"}},"required":["referenceCustomerId"]}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"envelopeId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"orderId":{"type":"string"},"customerName":{"type":"string"},"resolvedCustomerId":{"type":"string"},"customerResolutionMethod":{"type":"string"},"adjustedScore":{"type":"number"},"validationResults":{"type":"array","items":{"type":"object","properties":{"validatorName":{"type":"string"},"status":{"type":"string"},"message":{"type":"string","nullable":true},"confidenceAdjustment":{"type":"number","nullable":true},"details":{"type":"object","nullable":true,"additionalProperties":true}}}},"proposedCustomerRule":{"type":"object","nullable":true,"description":"A customer_alias rule proposed because this match was the second occurrence of a pattern","properties":{"ruleId":{"type":"string"},"name":{"type":"string"},"targetCustomerId":{"type":"string"},"targetCustomerName":{"type":"string"},"occurrences":{"type":"number"}}}},"required":["orderId","customerName","resolvedCustomerId","customerResolutionMethod","adjustedScore"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"chooseReviewCustomer","summary":"Choose the customer of an order in review"}},"/api/v1/tenants/{tenantId}/review/{envelopeId}/rematch":{"post":{"tags":["review"],"description":"Re-check an order in review against the current catalog and customer list (after a reference-data sync or upload). Re-runs part matching on lines that are still unmatched or only have candidates, and customer matching when the customer is unresolved; a line or customer a person matched is never changed. Then re-validates. Never approves, routes or changes the envelope status: the order stays in review. 409 INVALID_STATE when the envelope is not in_review, 409 NOT_AN_ORDER for an invoice, 409 LOCKED while another reviewer holds a live claim (one taken in the last 10 minutes), 404 for an envelope that is not this tenant's. GET /review/:envelopeId reports referenceData.changedSinceExtraction when a re-check would see newer reference data.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"envelopeId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"envelopeId":{"type":"string"},"orderId":{"type":"string"},"status":{"type":"string","description":"Always in_review: a re-check never moves the envelope"},"linesChecked":{"type":"integer","description":"Lines re-run through part matching (unmatched or candidates-only lines)"},"linesChanged":{"type":"array","items":{"type":"object","properties":{"lineItemId":{"type":"string"},"lineNumber":{"type":"integer"},"before":{"type":"object","properties":{"sku":{"type":"string"},"resolutionMethod":{"type":"string","nullable":true}}},"after":{"type":"object","properties":{"sku":{"type":"string"},"resolutionMethod":{"type":"string"},"candidateCount":{"type":"integer"}}}}}},"customer":{"type":"object","properties":{"checked":{"type":"boolean","description":"False when the customer was already decided (matched by a rung or by a person) and was left alone"},"changed":{"type":"boolean"},"before":{"type":"object","properties":{"resolvedCustomerId":{"type":"string","nullable":true},"customerResolutionMethod":{"type":"string","nullable":true}}},"after":{"type":"object","properties":{"resolvedCustomerId":{"type":"string","nullable":true},"customerResolutionMethod":{"type":"string","nullable":true}}}}},"adjustedScore":{"type":"number"},"minLineConfidence":{"type":"number"},"validationResults":{"type":"array","items":{"type":"object","properties":{"validatorName":{"type":"string"},"status":{"type":"string"},"message":{"type":"string","nullable":true},"confidenceAdjustment":{"type":"number","nullable":true},"details":{"type":"object","nullable":true,"additionalProperties":true}}}}},"required":["envelopeId","orderId","status","linesChecked","linesChanged","customer","adjustedScore"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"rematchReviewItem","summary":"Match an order in review against the catalog again"}},"/api/v1/tenants/{tenantId}/review/sku-search":{"get":{"tags":["review"],"description":"Search reference products by SKU or description for review form autocomplete","parameters":[{"schema":{"type":"string","minLength":1},"in":"query","name":"search","required":false},{"schema":{"type":"integer","minimum":1,"maximum":20,"default":10},"in":"query","name":"limit","required":false},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"type":"object","properties":{"sku":{"type":"string"},"description":{"type":"string","nullable":true},"unitPrice":{"type":"string","nullable":true},"uom":{"type":"string","nullable":true}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getReviewSkuSearch","summary":"Search reference products by SKU or description for review form autocomplete"}},"/api/v1/tenants/{tenantId}/review/customer-search":{"get":{"tags":["review"],"description":"Search reference customers by name, source id, email or sender domain for form autocomplete. Each match says which system and connection it came from, so two customers with one name can be told apart.","parameters":[{"schema":{"type":"string","minLength":1},"in":"query","name":"search","required":false},{"schema":{"type":"integer","minimum":1,"maximum":20,"default":10},"in":"query","name":"limit","required":false},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"sourceId":{"type":"string","nullable":true},"sourceSystem":{"type":"string","description":"The system the customer was read from: quickbooks, shopify, netsuite or csv_upload"},"connectorType":{"type":"string","nullable":true,"description":"Type of the connection the row was synced from; null for an uploaded list"},"connectorName":{"type":"string","nullable":true,"description":"Display name of that connection, when it has one"},"sourceLabel":{"type":"string","description":"Human label for the source, for example \"Shopify\" or \"Farm store (Shopify)\""},"email":{"type":"string","nullable":true,"description":"The customer email the source system holds"},"senderDomains":{"type":"array","items":{"type":"string"},"description":"Email domains this customer sends orders from"}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"searchReviewCustomers","summary":"Search reference customers for the review form"}},"/api/v1/tenants/{tenantId}/profiles/":{"get":{"tags":["profiles"],"description":"List customer profiles for a tenant","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"tenantId":{"type":"string","format":"uuid"},"customerId":{"type":"string","nullable":true},"customerName":{"type":"string"},"referenceCustomerId":{"type":"string","format":"uuid","nullable":true},"profileVersion":{"type":"integer"},"skuMappings":{"type":"object","additionalProperties":true},"orderCount":{"type":"integer"},"accuracyStats":{"type":"object","additionalProperties":true},"createdAt":{"type":"string"},"updatedAt":{"type":"string"}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getProfiles","summary":"List customer profiles for a tenant"}},"/api/v1/tenants/{tenantId}/profiles/{profileId}":{"delete":{"tags":["profiles"],"description":"Delete a customer profile","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"profileId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"deleteProfilesByProfileId","summary":"Delete a customer profile"}},"/api/v1/tenants/{tenantId}/profiles/{profileId}/mappings/{mappingKey}":{"delete":{"tags":["profiles"],"description":"Delete one learned SKU mapping from a customer profile","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"profileId","required":true},{"schema":{"type":"string"},"in":"path","name":"mappingKey","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"deleteProfilesByProfileIdMappingsByMappingKey","summary":"Delete one learned SKU mapping from a customer profile"}},"/api/v1/tenants/{tenantId}/metrics/":{"get":{"tags":["metrics"],"description":"Get tenant processing metrics. Defaults to the last 30 days. `window` bounds accuracy, volume totals, processing-time and confidence aggregates. Use window=all explicitly for historical reports. Every figure counts purchase orders only; supplier invoices are reviewed by a person and never counted as auto-approved. Pending review counts include every currently queued order. Dashboard aggregates are cached for up to 30 seconds.","parameters":[{"schema":{"type":"string","enum":["30d","90d","all"],"default":"30d"},"in":"query","name":"window","required":false},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"computedAt":{"type":"string","format":"date-time"},"window":{"type":"string","enum":["30d","90d","all"]},"accuracy":{"type":"object","properties":{"autoApprovalRate":{"type":"number"},"humanCorrectionRate":{"type":"number"},"rejectionRate":{"type":"number"},"resolvedOrders":{"type":"integer","description":"Purchase orders decided in the window (exported, approved, auto-approved or rejected): the denominator of the three rates. When 0 the rates are unmeasured, not zero. Supplier invoices are not counted."},"autoApprovedOrders":{"type":"integer","description":"Purchase orders handled automatically (no person decided them) among the orders decided in the window: the numerator of autoApprovalRate."},"approvedUnchangedRate":{"type":"number","description":"Decided orders a person approved without correcting anything. autoApprovalRate + approvedUnchangedRate + humanCorrectionRate + rejectionRate = 1 whenever resolvedOrders > 0 (each counted once: a person's approval with a correction is humanCorrectionRate, one without is this)."},"approvedUnchangedOrders":{"type":"integer","description":"The numerator of approvedUnchangedRate."},"correctedOrders":{"type":"integer","description":"The numerator of humanCorrectionRate: decided orders a person approved with at least one correction."},"rejectedOrders":{"type":"integer","description":"The numerator of rejectionRate."}}},"volume":{"type":"object","properties":{"totalOrders":{"type":"integer"},"last24h":{"type":"integer"},"last7d":{"type":"integer"},"last30d":{"type":"integer"},"dollarValueTotal":{"type":"number"},"dollarValue30d":{"type":"number"},"sent30d":{"type":"integer","description":"Purchase orders sent on to their destination (status exported) in the last 30 days, counted by the moment they were sent (exported_at), whenever they arrived. An order sent again (a PO revision) counts once, on its latest send. Supplier invoices are not counted."},"linesRead30d":{"type":"integer","description":"Order lines Poppelo read on the purchase orders received in the last 30 days (the same orders as volume.last30d), which no one had to type. Supplier invoices are not counted."},"failedDocuments":{"type":"integer","description":"purchase-order documents received in the window that could not be read (status failed). totalOrders, last24h, last7d and last30d leave them out, as the orders list and the timeseries do."}}},"processing":{"type":"object","properties":{"avgProcessingTimeMs":{"type":"number","description":"Average time to read, in milliseconds: from the moment the document arrived to the moment its read finished and it was routed (auto-approved, sent to review, or rejected). Time spent waiting for a person, delivering to a destination or later changes are not included. Orders with no recorded routing decision are left out, including documents rejected at extraction as not an order or not an invoice, which are never routed; every metrics figure (summary, per customer, per channel, export) treats them the same way."},"avgEndToEndMs":{"type":"number","nullable":true,"description":"Average start to finish, in milliseconds: from the moment a purchase order arrived to the moment it was sent on (exported), over orders whose status is exported and that arrived in the window. Includes reading, review wait and delivery. Null when no order in the window has been sent on. Supplier invoices are not included."},"medianEndToEndMs":{"type":"number","nullable":true,"description":"Median start to finish, in milliseconds: from the moment a purchase order arrived to the moment it was sent on (exported), over the same orders as avgEndToEndMs (exported, arrived in the window). Null when no order in the window has been sent on."},"avgReviewTimeMs":{"type":"number"},"pendingReview":{"type":"integer"}}},"confidence":{"type":"object","properties":{"avgScore":{"type":"number"},"distribution":{"type":"object","properties":{"high":{"type":"integer"},"medium":{"type":"integer"},"low":{"type":"integer"}}}}},"recentActivity":{"type":"array","description":"The 5 most recently received purchase orders that are approved, sent, waiting for review or failed, newest first. Orders still being read, rejected or handled by hand are left out. state is one of sent, approved, needs_review or failed; destinations lists the connector types the order is written to (envelope_destinations, else the legacy single destination), empty when none is recorded. Not windowed.","items":{"type":"object","required":["envelopeId","orderId","poNumber","customerName","status","state","destinations","receivedAt"],"properties":{"envelopeId":{"type":"string","format":"uuid"},"orderId":{"type":"string","format":"uuid","nullable":true,"description":"The extracted order, for GET /orders/:orderId. Null for a document that was never read (state failed)."},"poNumber":{"type":"string","nullable":true},"customerName":{"type":"string","nullable":true},"status":{"type":"string","enum":["exported","approved","auto_approved","pending_export","exporting","in_review","failed"]},"state":{"type":"string","enum":["sent","approved","needs_review","failed"]},"destinations":{"type":"array","items":{"type":"string"}},"receivedAt":{"type":"string","format":"date-time"},"exportMethod":{"type":"string","nullable":true,"enum":["email","download","sftp",null],"description":"How the order went out as a file, from its export record. Null when it was not exported as a file."},"exportFormat":{"type":"string","nullable":true,"enum":["csv","xlsx","edi850",null],"description":"The exported file's format."},"exportDeliveredTo":{"type":"string","nullable":true,"description":"The address an emailed export went to."}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getMetrics","summary":"Get tenant processing metrics"}},"/api/v1/tenants/{tenantId}/metrics/timeseries":{"get":{"tags":["metrics"],"description":"Get daily time-series metrics for the last 30 days. `orders` counts purchase orders received that day, leaving out documents that could not be read (status failed); `sent` counts purchase orders sent on to their destination that day (status exported, by exported_at), whenever they arrived. A day appears when it has either. Supplier invoices are not counted.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"computedAt":{"type":"string","format":"date-time"},"daily":{"type":"array","items":{"type":"object","properties":{"date":{"type":"string"},"orders":{"type":"integer"},"autoApproved":{"type":"integer"},"reviewed":{"type":"integer"},"rejected":{"type":"integer"},"sent":{"type":"integer","description":"Purchase orders sent on to their destination this day (exported_at), whenever they arrived. Summed over the series it equals GET /metrics volume.sent30d, up to the day boundary."},"avgConfidence":{"type":"number"}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getMetricsTimeseries","summary":"Get daily time-series metrics for the last 30 days"}},"/api/v1/tenants/{tenantId}/metrics/customers":{"get":{"tags":["metrics"],"description":"Get per-customer processing metrics with pagination. Defaults to the last 30 days; use window=all explicitly for all-time figures. Cached for up to 30 seconds per tenant, window and page.","parameters":[{"schema":{"type":"integer","minimum":1,"default":1},"in":"query","name":"page","required":false,"description":"Page number (1-based)"},{"schema":{"type":"integer","minimum":1,"maximum":200},"in":"query","name":"pageSize","required":false,"description":"Items per page (default 50, max 200)"},{"schema":{"type":"integer","minimum":1},"in":"query","name":"limit","required":false,"description":"Deprecated alias of pageSize, clamped to 200. Accepted for one release."},{"schema":{"type":"integer","minimum":0},"in":"query","name":"offset","required":false,"description":"Deprecated: rows to skip. Takes precedence over page when both are sent. Accepted for one release."},{"schema":{"type":"string","enum":["30d","90d","all"],"default":"30d"},"in":"query","name":"window","required":false},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"computedAt":{"type":"string","format":"date-time"},"window":{"type":"string","enum":["30d","90d","all"]},"data":{"type":"array","items":{"type":"object","properties":{"customerName":{"type":"string"},"orderCount":{"type":"integer"},"avgConfidence":{"type":"number"},"autoApprovedCount":{"type":"integer"},"reviewedCount":{"type":"integer"},"rejectedCount":{"type":"integer"},"avgProcessingTimeMs":{"type":"number","description":"Average time to read, in milliseconds: from the moment the document arrived to the moment its read finished and it was routed (auto-approved, sent to review, or rejected). Time spent waiting for a person, delivering to a destination or later changes are not included. Orders with no recorded routing decision are left out, including documents rejected at extraction as not an order or not an invoice, which are never routed; every metrics figure (summary, per customer, per channel, export) treats them the same way."},"lastOrderAt":{"type":"string"}}}},"pagination":{"type":"object","properties":{"page":{"type":"integer"},"pageSize":{"type":"integer"},"total":{"type":"integer"},"totalPages":{"type":"integer"}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getMetricsCustomers","summary":"Get per-customer processing metrics with pagination"}},"/api/v1/tenants/{tenantId}/metrics/queue-health":{"get":{"tags":["metrics"],"description":"Get queue depth and worker health metrics: envelope counts by status, queue depths per processing stage, and average end-to-end processing time for the last 24 hours","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"computedAt":{"type":"string","format":"date-time"},"queueDepths":{"type":"object","properties":{"documentUnderstanding":{"type":"integer"},"validation":{"type":"integer"},"integration":{"type":"integer"},"notification":{"type":"integer"}}},"statusCounts":{"type":"object","properties":{"received":{"type":"integer"},"processing":{"type":"integer"},"awaitingReview":{"type":"integer"},"approved":{"type":"integer"},"rejected":{"type":"integer"},"integrated":{"type":"integer"},"failed":{"type":"integer"}}},"avgProcessingTimeLast24hMs":{"type":"number","nullable":true}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getMetricsQueueHealth","summary":"Get metrics queue health"}},"/api/v1/tenants/{tenantId}/metrics/roi":{"get":{"tags":["metrics"],"description":"Compute ROI, cost savings, and efficiency metrics. Query params override default assumptions.","parameters":[{"schema":{"type":"string"},"in":"query","name":"minutesPerManualOrder","required":false,"description":"Average minutes to process one order manually (default 8)"},{"schema":{"type":"string"},"in":"query","name":"hourlyRate","required":false,"description":"Hourly cost of manual processing staff (default 25)"},{"schema":{"type":"string"},"in":"query","name":"manualCostPerOrder","required":false,"description":"Override manual cost per order instead of deriving from minutesPerManualOrder * hourlyRate (default: derived)"},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"computedAt":{"type":"string","format":"date-time"},"totalOrdersProcessed":{"type":"integer"},"autoApprovedOrders":{"type":"integer"},"estimatedTimeSavedMinutes":{"type":"number"},"estimatedCostSavedDollars":{"type":"number"},"costPerOrder":{"type":"number","nullable":true},"manualCostPerOrder":{"type":"number"},"savingsPercentage":{"type":"number","nullable":true},"monthOverMonthGrowth":{"type":"number","nullable":true},"currentMonthOrders":{"type":"integer"},"previousMonthOrders":{"type":"integer"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getMetricsRoi","summary":"Compute ROI, cost savings, and efficiency metrics"}},"/api/v1/tenants/{tenantId}/metrics/channels":{"get":{"tags":["metrics"],"description":"Get per-channel processing metrics","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"computedAt":{"type":"string","format":"date-time"},"data":{"type":"array","items":{"type":"object","properties":{"channelId":{"type":"string","format":"uuid"},"channelType":{"type":"string"},"orderCount":{"type":"integer"},"avgConfidence":{"type":"number"},"autoApprovalRate":{"type":"number"},"avgProcessingTimeMs":{"type":"number","description":"Average time to read, in milliseconds: from the moment the document arrived to the moment its read finished and it was routed (auto-approved, sent to review, or rejected). Time spent waiting for a person, delivering to a destination or later changes are not included. Orders with no recorded routing decision are left out, including documents rejected at extraction as not an order or not an invoice, which are never routed; every metrics figure (summary, per customer, per channel, export) treats them the same way."}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getMetricsChannels","summary":"Get per-channel processing metrics"}},"/api/v1/tenants/{tenantId}/metrics/my-performance":{"get":{"tags":["metrics"],"description":"Get the authenticated user's personal review performance metrics including review counts by time period, average review time, and accuracy rate","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"computedAt":{"type":"string","format":"date-time"},"reviewerId":{"type":"string"},"authMethod":{"type":"string","enum":["session","api_key","oauth"]},"reviews":{"type":"object","properties":{"total":{"type":"integer"},"approved":{"type":"integer"},"rejected":{"type":"integer"},"skipped":{"type":"integer"}}},"reviewsByPeriod":{"type":"object","properties":{"today":{"type":"integer"},"thisWeek":{"type":"integer"},"thisMonth":{"type":"integer"}}},"avgReviewTimeMs":{"type":"number","nullable":true},"accuracyRate":{"type":"number","nullable":true,"description":"Fraction of approved reviews where no subsequent correction was needed (null if no data)"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"No valid credential: UNAUTHORIZED. Send X-API-Key (or a web session); a revoked or expired key is refused the same way.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getMetricsMyPerformance","summary":"Get metrics my performance"}},"/api/v1/tenants/{tenantId}/metrics/export":{"get":{"tags":["metrics"],"description":"Export metrics summary as CSV, or the ROI statement CSV with ?report=roi-statement. The avgProcessingTimeMs row is the average time to read: from arrival to the moment the read finished and the order was routed, excluding review wait and delivery. In the ROI statement CSV, estimatedOverageCents is the overage GET /billing/usage estimates (billable orders beyond the plan's included orders, times its overage price; 0 within the allowance or with no plan), the same figure as GET /metrics/roi/statement.","parameters":[{"schema":{"type":"string"},"in":"query","name":"report","required":false},{"schema":{"type":"string"},"in":"query","name":"period","required":false},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getMetricsExport","summary":"Export metrics summary as CSV, or the ROI statement CSV with ?report=roi-statement"}},"/api/v1/tenants/{tenantId}/metrics/trust":{"get":{"tags":["metrics"],"description":"Trust dashboard metrics: weekly auto-approval rate alongside the counterfactual rate (what would have run unattended on the tenant's own settings, which is the only series that says anything before autonomy is switched on), measured line accuracy vs the 99.5% guarantee, savings with visible arithmetic, and this calendar month (`currentPeriod`). `currentPeriod.estimatedOverageCents` is the same estimated overage as GET /metrics/roi/statement for this calendar month and the same arithmetic as GET /billing/usage. `currentPeriod.invoiceEstimateCents`, `perOrderRateCents` and `rateSource` are deprecated: they do not subtract the plan allowance; use `estimatedOverageCents`.","parameters":[{"schema":{"type":"string","enum":["30d","90d","all"],"default":"30d"},"in":"query","name":"window","required":false},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","additionalProperties":true,"properties":{"currentPeriod":{"type":"object","additionalProperties":true,"description":"This calendar month, counted from usage_events.","properties":{"billableOrders":{"type":"integer","description":"Orders counted toward the plan this calendar month."},"billableAutoApproved":{"type":"integer"},"billableReviewed":{"type":"integer"},"reviewedFree":{"type":"integer"},"manualHandlingFree":{"type":"integer"},"autoApprovedOrders":{"type":"integer","description":"Purchase orders handled automatically this calendar month. Supplier invoices are never counted."},"approvedByPersonOrders":{"type":"integer","description":"Purchase orders a person approved this calendar month (an undone approval is not counted). A rejection is not counted here; see rejectedOrders. billableReviewed and reviewedFree keep counting every person's decision for billing, invoices and rejections included."},"rejectedOrders":{"type":"integer","description":"Purchase orders a person rejected this calendar month."},"manualHandlingOrders":{"type":"integer","description":"Purchase orders moved to manual handling this calendar month."},"estimatedOverageCents":{"type":"integer","nullable":true,"description":"Estimated overage, this calendar month: orders counted toward the plan beyond its included orders, times the plan's overage price. The same figure as GET /metrics/roi/statement for this month (`money.estimatedOverageCents`) and the same arithmetic as GET /billing/usage. 0 within the allowance, on an unlimited plan, or when the plan bills no overage (no overage price, Stripe overage price or Stripe subscription); null with no subscription. The bill counts per billing period, so it can differ."},"invoiceEstimateCents":{"type":"number","nullable":true,"deprecated":true,"description":"Deprecated: does not subtract the plan allowance; use estimatedOverageCents. Platform fee plus every billable order times perOrderRateCents."},"perOrderRateCents":{"type":"number","nullable":true,"deprecated":true,"description":"Deprecated: does not subtract the plan allowance; use estimatedOverageCents. The rate behind invoiceEstimateCents."},"rateSource":{"type":"string","nullable":true,"deprecated":true,"description":"Deprecated: does not subtract the plan allowance; use estimatedOverageCents. Where perOrderRateCents came from: `settings`, `overage` (the overage price) or `plan` (the plan price divided by its included documents), else null."},"planName":{"type":"string","nullable":true},"dollarValueProcessedCents":{"type":"integer"},"straightThroughRatePct":{"type":"number","nullable":true}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getMetricsTrust","summary":"Get metrics trust"}},"/api/v1/tenants/{tenantId}/metrics/roi/statement":{"get":{"tags":["metrics"],"description":"ROI statement for one period: volume, time, money, and accuracy. `period=current` (the default) is the tenant's subscription period when one exists, else the calendar month; an explicit `YYYY-MM` is always a calendar month (UTC). `period.source` says which. `period.end` is exclusive. `money.estimatedOverageCents` is the same overage GET /billing/usage estimates: billable orders in the period beyond the plan's included orders, times the plan's overage price; 0 within the allowance, on an unlimited plan, or when the plan bills no overage (no overage price, Stripe overage price or Stripe subscription); null with no subscription. It no longer multiplies every billable order by a per-order rate. `money.rateSource` is `overage` when the plan bills overage, else null. On a calendar-month statement the allowance is applied to that month, while the bill counts per billing period, so the two can differ; a disclaimer says so.","parameters":[{"schema":{"type":"string"},"in":"query","name":"period","required":false},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getMetricsRoiStatement","summary":"ROI statement for one period: volume, time, money, and accuracy"}},"/api/v1/tenants/{tenantId}/metrics/value/orders":{"get":{"tags":["metrics"],"description":"Paginated orders behind tenant work returned, including withdrawn earned snapshots.","parameters":[{"schema":{"type":"integer","minimum":1,"default":1},"in":"query","name":"page","required":false,"description":"Page number (1-based)"},{"schema":{"type":"integer","minimum":1,"maximum":200},"in":"query","name":"pageSize","required":false,"description":"Items per page (default 50, max 200)"},{"schema":{"type":"integer","minimum":1},"in":"query","name":"limit","required":false,"description":"Deprecated alias of pageSize, clamped to 200. Accepted for one release."},{"schema":{"type":"integer","minimum":0},"in":"query","name":"offset","required":false,"description":"Deprecated: rows to skip. Takes precedence over page when both are sent. Accepted for one release."},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","required":["computedAt","data","pagination"],"properties":{"computedAt":{"type":"string","format":"date-time"},"data":{"type":"array","items":{"type":"object","required":["envelopeId","orderId","poNumber","customerName","deliveredAt","state","tenantReturnedMs","reviewTimeMs","reviewTimeSource","withdrawalReason"],"properties":{"envelopeId":{"type":"string","format":"uuid"},"orderId":{"type":"string","format":"uuid"},"poNumber":{"type":["null","string"]},"customerName":{"type":"string"},"deliveredAt":{"type":"string","format":"date-time"},"state":{"type":"string","enum":["pending","verified","withdrawn"]},"tenantReturnedMs":{"type":"integer","minimum":0},"reviewTimeMs":{"type":"integer","minimum":0},"reviewTimeSource":{"type":"string","enum":["measured","fallback","none"]},"withdrawalReason":{"type":["null","string"]}}}},"pagination":{"type":"object","required":["page","pageSize","total","totalPages"],"properties":{"page":{"type":"integer"},"pageSize":{"type":"integer"},"total":{"type":"integer"},"totalPages":{"type":"integer"}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getMetricsValueOrders","summary":"Paginated orders behind tenant work returned, including withdrawn earned snapshots"}},"/api/v1/tenants/{tenantId}/metrics/sla/run":{"post":{"tags":["metrics"],"description":"Run the monthly accuracy SLA check (defaults to the previous calendar month).","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"month":{"type":"string","pattern":"^\\d{4}-\\d{2}$","description":"Calendar month YYYY-MM (default: previous month)"}}}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postMetricsSlaRun","summary":"Run the monthly accuracy SLA check (defaults to the previous calendar month)"}},"/api/v1/tenants/{tenantId}/metrics/threshold-impact":{"get":{"tags":["metrics"],"description":"Preview how many of the tenant's last 30 days of orders would have cleared a candidate auto-approve threshold.","parameters":[{"schema":{"type":"string"},"in":"query","name":"threshold","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"threshold":{"type":"number"},"wouldAutoApprove":{"type":"integer"},"total":{"type":"integer"},"windowDays":{"type":"integer"}},"required":["threshold","wouldAutoApprove","total","windowDays"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getMetricsThresholdImpact","summary":"Get metrics threshold impact"}},"/api/v1/tenants/{tenantId}/metrics/pilot":{"get":{"tags":["metrics"],"description":"Shadow-mode pilot measurement from the tenant's own routed orders. exceptionReasons counts why each order needed a person (unknown customer, unmapped SKU, unit mismatch, price variance, credit, duplicate, multi-PO, unverified sender and more; one order can carry several reasons). rampImpact counts orders that would have run unattended without and with the new-customer ramp-up, per customer. anomalyImpact shows the same would-have count with and without the per-customer anomaly rules, which the worker evaluates in shadow on every order because live routing applies them only once a customer is autonomous. falseApprovals compares every would-have-auto-approved order a person decided with what that person finally posted, field by field for customer, SKU, quantity, unit and price, plus lines added or removed; a rejection counts as a false approval. Only measured orders count toward the bar: orders routed after this measurement shipped, whose document-level gates were evaluated and whose would-have-posted order was snapshotted. Orders judged from the reviewer's correction record instead (routed earlier, or no snapshot) are reported under fallback and never counted, because that record misses resolve-line edits and so can only make the system look safer. The bar is tenant-level: meetsBar needs at least minOrders measured orders (default 200) with at most maxFalseApprovals wrong (default 0). Each customer then needs customerMinOrders measured orders (default 10) with the same limit to be eligible. Agree the numbers with the customer before the pilot. A would-have-auto-approve here also requires that no document-level gate (multi-PO, sender check, value ceiling, credit hold and other force-review flags) would have held the order; orders routed before that was recorded are counted and reported as unverifiedCounterfactuals. Read-only.","parameters":[{"schema":{"type":"string","enum":["14d","30d","90d","all"],"default":"30d"},"in":"query","name":"window","required":false},{"schema":{"type":"integer","minimum":1,"maximum":100000,"default":200},"in":"query","name":"minOrders","required":false},{"schema":{"type":"integer","minimum":0,"maximum":100000,"default":0},"in":"query","name":"maxFalseApprovals","required":false},{"schema":{"type":"integer","minimum":1,"maximum":100000,"default":10},"in":"query","name":"customerMinOrders","required":false},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"window":{"type":"string"},"since":{"type":"string","nullable":true},"computedAt":{"type":"string"},"truncated":{"type":"boolean","description":"More routed orders exist than the 5,000 read; narrow the window."},"exceptionReasons":{"type":"object","properties":{"routed":{"type":"integer"},"held":{"type":"integer"},"heldRate":{"type":"number","nullable":true},"byCategory":{"type":"array","items":{"type":"object","properties":{"category":{"type":"string"},"orders":{"type":"integer"},"shareOfHeld":{"type":"number"}},"required":["category","orders","shareOfHeld"]}},"byReason":{"type":"array","items":{"type":"object","properties":{"reason":{"type":"string"},"category":{"type":"string"},"orders":{"type":"integer"}},"required":["reason","category","orders"]}}},"required":["routed","held","heldRate","byCategory","byReason"]},"rampImpact":{"type":"object","properties":{"routed":{"type":"integer"},"withoutRamp":{"type":"integer","description":"Would have run unattended on the tenant's own bar."},"withRamp":{"type":"integer","description":"Would have run unattended with the new-customer ramp-up applied."},"heldOnlyByRamp":{"type":"integer"},"missingRampData":{"type":"integer","description":"Would-haves routed before the ramp bar was recorded; in neither withRamp nor heldOnlyByRamp."},"withoutRampRate":{"type":"number","nullable":true},"withRampRate":{"type":"number","nullable":true},"unverifiedCounterfactuals":{"type":"integer"},"byCustomer":{"type":"array","items":{"type":"object","properties":{"routed":{"type":"integer"},"withoutRamp":{"type":"integer","description":"Would have run unattended on the tenant's own bar."},"withRamp":{"type":"integer","description":"Would have run unattended with the new-customer ramp-up applied."},"heldOnlyByRamp":{"type":"integer"},"missingRampData":{"type":"integer","description":"Would-haves routed before the ramp bar was recorded; in neither withRamp nor heldOnlyByRamp."},"withoutRampRate":{"type":"number","nullable":true},"withRampRate":{"type":"number","nullable":true},"customerId":{"type":"string","nullable":true,"description":"Resolved trading partner; null groups every unresolved order."},"customerName":{"type":"string","nullable":true},"cleanApprovals":{"type":"integer","nullable":true}}}}}},"anomalyImpact":{"type":"object","description":"Would-have-auto-approved orders with and without the per-customer anomaly rules (unfamiliar sender, unmapped SKU, unknown ship-to, value outlier, unresolved customer). The rules apply only once a customer is granted autonomy, so live routing never runs them while auto-approval is off; the worker evaluates them in shadow on every would-have order. withRampAndAnomalyRules is the projection a customer will see after go-live with per-customer autonomy enforced. notEvaluated: would-haves routed before the rules were recorded, never counted in withAnomalyRules.","properties":{"routed":{"type":"integer"},"withoutAnomalyRules":{"type":"integer","description":"Would have run unattended before the anomaly rules."},"withAnomalyRules":{"type":"integer","description":"Of those, the orders no anomaly rule would hold."},"heldByAnomalyRules":{"type":"integer"},"notEvaluated":{"type":"integer"},"withRampAndAnomalyRules":{"type":"integer","description":"Clears the ramp bar too and no anomaly rule holds it."},"withoutAnomalyRulesRate":{"type":"number","nullable":true},"withAnomalyRulesRate":{"type":"number","nullable":true},"withRampAndAnomalyRulesRate":{"type":"number","nullable":true},"byAnomaly":{"type":"array","items":{"type":"object","properties":{"anomaly":{"type":"string"},"orders":{"type":"integer"}}}},"byCustomer":{"type":"array","items":{"type":"object","properties":{"routed":{"type":"integer"},"withoutAnomalyRules":{"type":"integer","description":"Would have run unattended before the anomaly rules."},"withAnomalyRules":{"type":"integer","description":"Of those, the orders no anomaly rule would hold."},"heldByAnomalyRules":{"type":"integer"},"notEvaluated":{"type":"integer"},"withRampAndAnomalyRules":{"type":"integer","description":"Clears the ramp bar too and no anomaly rule holds it."},"withoutAnomalyRulesRate":{"type":"number","nullable":true},"withAnomalyRulesRate":{"type":"number","nullable":true},"withRampAndAnomalyRulesRate":{"type":"number","nullable":true},"customerId":{"type":"string","nullable":true,"description":"Resolved trading partner; null groups every unresolved order."},"customerName":{"type":"string","nullable":true}}}}}},"falseApprovals":{"type":"object","properties":{"bar":{"type":"object","properties":{"minOrders":{"type":"integer"},"maxFalseApprovals":{"type":"integer"},"customerMinOrders":{"type":"integer"}},"required":["minOrders","maxFalseApprovals","customerMinOrders"]},"meetsBar":{"type":"boolean","description":"Tenant-level: measured orders only."},"measured":{"type":"object","properties":{"compared":{"type":"integer","description":"Would-have-auto-approved orders a person has approved or rejected."},"falseApprovals":{"type":"integer"},"falseApprovalRate":{"type":"number","nullable":true},"pending":{"type":"integer","description":"Would-haves still waiting for a person; not in compared."},"byReason":{"type":"object","additionalProperties":{"type":"integer"},"description":"customer, sku, quantity, uom, price, lines (a line added or removed) and rejected. One order can count under several."},"basis":{"type":"object","properties":{"snapshot":{"type":"integer","description":"Compared field by field against the order as routed."},"reviewRecord":{"type":"integer","description":"No snapshot: judged from the reviewer's correction record, which misses resolve-line edits. Always in fallback."},"rejected":{"type":"integer"}},"required":["snapshot","reviewRecord","rejected"]}},"required":["compared","falseApprovals","falseApprovalRate","pending","byReason","basis"],"description":"Orders routed after this measurement shipped. The only counts the bar reads."},"fallback":{"type":"object","description":"Orders judged on weaker evidence (routed earlier, or no snapshot). Reported, never counted toward the bar.","properties":{"compared":{"type":"integer","description":"Would-have-auto-approved orders a person has approved or rejected."},"falseApprovals":{"type":"integer"},"falseApprovalRate":{"type":"number","nullable":true},"pending":{"type":"integer","description":"Would-haves still waiting for a person; not in compared."},"byReason":{"type":"object","additionalProperties":{"type":"integer"},"description":"customer, sku, quantity, uom, price, lines (a line added or removed) and rejected. One order can count under several."},"basis":{"type":"object","properties":{"snapshot":{"type":"integer","description":"Compared field by field against the order as routed."},"reviewRecord":{"type":"integer","description":"No snapshot: judged from the reviewer's correction record, which misses resolve-line edits. Always in fallback."},"rejected":{"type":"integer"}},"required":["snapshot","reviewRecord","rejected"]},"unverifiedCounterfactuals":{"type":"integer","description":"Would-haves whose document-level gates were never evaluated."}},"required":["compared","falseApprovals","falseApprovalRate","pending","byReason","basis","unverifiedCounterfactuals"]},"byCustomer":{"type":"array","items":{"type":"object","properties":{"customerId":{"type":"string","nullable":true,"description":"Resolved trading partner; null groups every unresolved order."},"customerName":{"type":"string","nullable":true},"measured":{"type":"object","properties":{"compared":{"type":"integer","description":"Would-have-auto-approved orders a person has approved or rejected."},"falseApprovals":{"type":"integer"},"falseApprovalRate":{"type":"number","nullable":true},"pending":{"type":"integer","description":"Would-haves still waiting for a person; not in compared."},"byReason":{"type":"object","additionalProperties":{"type":"integer"},"description":"customer, sku, quantity, uom, price, lines (a line added or removed) and rejected. One order can count under several."},"basis":{"type":"object","properties":{"snapshot":{"type":"integer","description":"Compared field by field against the order as routed."},"reviewRecord":{"type":"integer","description":"No snapshot: judged from the reviewer's correction record, which misses resolve-line edits. Always in fallback."},"rejected":{"type":"integer"}},"required":["snapshot","reviewRecord","rejected"]}},"required":["compared","falseApprovals","falseApprovalRate","pending","byReason","basis"]},"fallback":{"type":"object","properties":{"compared":{"type":"integer","description":"Would-have-auto-approved orders a person has approved or rejected."},"falseApprovals":{"type":"integer"},"falseApprovalRate":{"type":"number","nullable":true},"pending":{"type":"integer","description":"Would-haves still waiting for a person; not in compared."},"byReason":{"type":"object","additionalProperties":{"type":"integer"},"description":"customer, sku, quantity, uom, price, lines (a line added or removed) and rejected. One order can count under several."},"basis":{"type":"object","properties":{"snapshot":{"type":"integer","description":"Compared field by field against the order as routed."},"reviewRecord":{"type":"integer","description":"No snapshot: judged from the reviewer's correction record, which misses resolve-line edits. Always in fallback."},"rejected":{"type":"integer"}},"required":["snapshot","reviewRecord","rejected"]}},"required":["compared","falseApprovals","falseApprovalRate","pending","byReason","basis"]},"meetsCustomerMinimum":{"type":"boolean","description":"At least customerMinOrders measured, at most maxFalseApprovals wrong."},"eligible":{"type":"boolean","description":"The tenant meets the bar and this customer meets its minimum."}},"required":["customerId","customerName","measured","fallback","meetsCustomerMinimum","eligible"]}},"examples":{"type":"array","items":{"type":"object","properties":{"envelopeId":{"type":"string","format":"uuid"},"customerName":{"type":"string","nullable":true},"reasons":{"type":"array","items":{"type":"string"}},"basis":{"type":"string","nullable":true},"measured":{"type":"boolean"}}}}},"required":["bar","meetsBar","measured","fallback","byCustomer","examples"]}},"required":["window","since","computedAt","truncated","exceptionReasons","rampImpact","anomalyImpact","falseApprovals"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"getMetricsPilot","summary":"Shadow-mode pilot measurement from the tenant's own routed orders"}},"/api/v1/tenants/{tenantId}/metrics/trial-report":{"get":{"tags":["metrics"],"description":"The trial report, from the tenant's own orders. The trial proves the review queue: timeSavedOnReviewed is reviewed orders × (the tenant's keying minutes − the median review minutes measured in the app, open to approve), null with timeSavedUnavailable when the desk baseline was never set (baseline_not_set) or fewer than minimumTimedReviews reviews were timed (review_time_not_measured); no default is assumed. errorsCaught counts orders a reviewer corrected before posting. goLive is progress toward the auto-approval bar, all time: measuredOrders and falseApprovals against bar (200 measured, 0 false by default), ordersToGo, estimatedBarDate at the trial's pace, and projectedTouchlessRate after the ramp and the anomaly rules. The bar is expected in the first paid month, not inside the trial: shadow measurement runs on every routed order whatever the plan. autoApprovalOnBeforeBar warns that orders running unattended are no longer compared with a reviewer. Read-only.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","additionalProperties":true,"properties":{"tenantName":{"type":"string"},"generatedAt":{"type":"string"},"trial":{"type":"object","additionalProperties":true},"orders":{"type":"object","additionalProperties":true},"reviewTime":{"type":"object","additionalProperties":true},"baseline":{"type":"object","additionalProperties":true},"timeSavedOnReviewed":{"type":"object","nullable":true,"additionalProperties":true},"timeSavedUnavailable":{"type":"string","nullable":true,"enum":["baseline_not_set","review_time_not_measured",null]},"errorsCaught":{"type":"object","additionalProperties":true},"goLive":{"type":"object","additionalProperties":true},"lines":{"type":"array","items":{"type":"string"},"description":"The same report as plain sentences, as the email shows it."}},"required":["trial","orders","reviewTime","baseline","timeSavedOnReviewed","timeSavedUnavailable","errorsCaught","goLive","lines"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"getMetricsTrialReport","summary":"The trial report, from the tenant's own orders"}},"/api/v1/tenants/{tenantId}/metrics/accuracy":{"get":{"tags":["metrics"],"description":"Daily accuracy series and window totals from the tenant's own measured corrections — never a benchmark. Rates are null below the volume floor (20 orders in the window).","parameters":[{"schema":{"type":"string","enum":["30d","90d","12w"]},"in":"query","name":"window","required":false},{"schema":{"type":"string","format":"uuid"},"in":"query","name":"partnerId","required":false},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"window":{"type":"string"},"floor":{"type":"integer"},"series":{"type":"array","items":{"type":"object","properties":{"day":{"type":"string"},"orders":{"type":"integer"},"autoApproved":{"type":"integer"},"reviewed":{"type":"integer"},"rejected":{"type":"integer"},"wouldAutoApprove":{"type":"integer"},"reviewCorrectionRate":{"type":"number","nullable":true},"postApprovalCorrectionRate":{"type":"number","nullable":true},"avgConfidence":{"type":"number","nullable":true}}}},"totals":{"type":"object","properties":{"orders":{"type":"integer"},"autoApproved":{"type":"integer"},"reviewed":{"type":"integer"},"rejected":{"type":"integer"},"wouldAutoApprove":{"type":"integer"},"reviewCorrectionRate":{"type":"number","nullable":true},"postApprovalCorrectionRate":{"type":"number","nullable":true}}},"byField":{"type":"array","items":{"type":"object","properties":{"field":{"type":"string"},"reviewTime":{"type":"integer"},"postApproval":{"type":"integer"}}}},"insufficientVolume":{"type":"boolean"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getMetricsAccuracy","summary":"Get metrics accuracy"}},"/api/v1/tenants/{tenantId}/metrics/accuracy/partners":{"get":{"tags":["metrics"],"description":"One row per trading partner: the tenant's own measured correction rates, order volume, and autonomy state.","parameters":[{"schema":{"type":"string","enum":["30d","90d","12w"]},"in":"query","name":"window","required":false},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"window":{"type":"string"},"floor":{"type":"integer"},"partners":{"type":"array","items":{"type":"object","properties":{"referenceCustomerId":{"type":"string","format":"uuid"},"name":{"type":"string"},"orders":{"type":"integer"},"reviewCorrectionRate":{"type":"number","nullable":true},"postApprovalCorrectionRate":{"type":"number","nullable":true},"autonomyState":{"type":"string"},"insufficientVolume":{"type":"boolean"}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getMetricsAccuracyPartners","summary":"List metrics accuracy partners"}},"/api/v1/tenants/{tenantId}/metrics/accuracy/recompute":{"post":{"tags":["metrics"],"description":"Recompute this tenant's accuracy snapshots for the trailing 35 days. Runs in the background; returns immediately. For support use — the nightly sweep already keeps this current.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"202":{"description":"Accepted. Processing continues in the background; follow it with the id in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"status":{"type":"string"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postMetricsAccuracyRecompute","summary":"Recompute this tenant's accuracy snapshots for the trailing 35 days"}},"/api/v1/tenants/{tenantId}/metrics/quality-alerts":{"get":{"tags":["metrics"],"description":"This tenant's quality regression alerts: a trading partner's, or the whole tenant's, own measured rate moved outside its own baseline — never a cross-tenant benchmark. state=open (default) excludes both acknowledged and resolved rows; acknowledged excludes resolved; resolved lists closed alerts.","parameters":[{"schema":{"type":"string","enum":["open","acknowledged","resolved"]},"in":"query","name":"state","required":false},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"alerts":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"referenceCustomerId":{"type":"string","format":"uuid","nullable":true},"referenceCustomerName":{"type":"string","nullable":true,"description":"null = the whole-tenant row, not one trading partner."},"metric":{"type":"string","enum":["post_approval_correction_rate","review_correction_rate","would_auto_approve_share"]},"windowDays":{"type":"integer"},"currentValue":{"type":"number"},"baselineValue":{"type":"number"},"currentOrders":{"type":"integer"},"firstSeenAt":{"type":"string"},"lastAlertedAt":{"type":"string"},"acknowledgedAt":{"type":"string","nullable":true},"acknowledgedBy":{"type":"string","nullable":true},"resolvedAt":{"type":"string","nullable":true}},"required":["id","referenceCustomerId","metric","windowDays","currentValue","baselineValue","currentOrders","firstSeenAt","lastAlertedAt"]}}},"required":["alerts"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getMetricsQualityAlerts","summary":"List metrics quality alerts"}},"/api/v1/tenants/{tenantId}/metrics/quality-alerts/{id}/acknowledge":{"post":{"tags":["metrics"],"description":"Acknowledge an open quality alert: records who and when, and moves it out of state=open (it stops rendering on the Trust page). Does not resolve it — the row stays until the sweep sees the condition clear for 3 consecutive days. Idempotent: acknowledging again returns the alert with alreadyAcknowledged true and does not overwrite who acknowledged it first.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"id","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"alert":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"referenceCustomerId":{"type":"string","format":"uuid","nullable":true},"referenceCustomerName":{"type":"string","nullable":true,"description":"null = the whole-tenant row, not one trading partner."},"metric":{"type":"string","enum":["post_approval_correction_rate","review_correction_rate","would_auto_approve_share"]},"windowDays":{"type":"integer"},"currentValue":{"type":"number"},"baselineValue":{"type":"number"},"currentOrders":{"type":"integer"},"firstSeenAt":{"type":"string"},"lastAlertedAt":{"type":"string"},"acknowledgedAt":{"type":"string","nullable":true},"acknowledgedBy":{"type":"string","nullable":true},"resolvedAt":{"type":"string","nullable":true}},"required":["id","referenceCustomerId","metric","windowDays","currentValue","baselineValue","currentOrders","firstSeenAt","lastAlertedAt"]},"alreadyAcknowledged":{"type":"boolean"}},"required":["alert","alreadyAcknowledged"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postMetricsQualityAlertsByIdAcknowledge","summary":"Acknowledge metrics quality alert"}},"/api/v1/tenants/{tenantId}/dashboard/":{"get":{"tags":["metrics"],"description":"Everything the status board shows, in one request: connector health (integrations), items needing attention, channel liveness, plan usage, the review queue (first 100), the metrics summary, the 10 most recent orders, onboarding status, pipeline queue health and the daily outcome timeseries. Each section is the corresponding endpoint's own response, read with the caller's credential, reported as ok / forbidden / unavailable. Holds at most requestBudget.maxConcurrentTenantRequests of the tenant's in-flight request slots, and retries a section refused for capacity after its Retry-After.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","required":["computedAt","requestBudget","sections"],"properties":{"computedAt":{"type":"string","format":"date-time"},"requestBudget":{"type":"object","required":["maxConcurrentTenantRequests"],"properties":{"maxConcurrentTenantRequests":{"type":"integer"}}},"sections":{"type":"object","required":["integrations","attention","channelHealth","usage","reviewQueue","metrics","recentOrders","onboarding","queueHealth","timeseries"],"properties":{"integrations":{"type":"object","required":["state","status"],"properties":{"state":{"type":"string","enum":["ok","forbidden","unavailable"],"description":"ok: `data` is the section route's own 200 body. forbidden: this caller may not read the section (render nothing). unavailable: it could not be read — treat as unknown, never as \"nothing to report\"."},"status":{"type":"integer","description":"HTTP status the section route answered with (after retries)."},"data":{"type":"object","additionalProperties":true},"error":{"type":"object","properties":{"code":{"type":"string"},"message":{"type":"string"}},"required":["code","message"]}}},"attention":{"type":"object","required":["state","status"],"properties":{"state":{"type":"string","enum":["ok","forbidden","unavailable"],"description":"ok: `data` is the section route's own 200 body. forbidden: this caller may not read the section (render nothing). unavailable: it could not be read — treat as unknown, never as \"nothing to report\"."},"status":{"type":"integer","description":"HTTP status the section route answered with (after retries)."},"data":{"type":"object","additionalProperties":true},"error":{"type":"object","properties":{"code":{"type":"string"},"message":{"type":"string"}},"required":["code","message"]}}},"channelHealth":{"type":"object","required":["state","status"],"properties":{"state":{"type":"string","enum":["ok","forbidden","unavailable"],"description":"ok: `data` is the section route's own 200 body. forbidden: this caller may not read the section (render nothing). unavailable: it could not be read — treat as unknown, never as \"nothing to report\"."},"status":{"type":"integer","description":"HTTP status the section route answered with (after retries)."},"data":{"type":"object","additionalProperties":true},"error":{"type":"object","properties":{"code":{"type":"string"},"message":{"type":"string"}},"required":["code","message"]}}},"usage":{"type":"object","required":["state","status"],"properties":{"state":{"type":"string","enum":["ok","forbidden","unavailable"],"description":"ok: `data` is the section route's own 200 body. forbidden: this caller may not read the section (render nothing). unavailable: it could not be read — treat as unknown, never as \"nothing to report\"."},"status":{"type":"integer","description":"HTTP status the section route answered with (after retries)."},"data":{"type":"object","additionalProperties":true},"error":{"type":"object","properties":{"code":{"type":"string"},"message":{"type":"string"}},"required":["code","message"]}}},"reviewQueue":{"type":"object","required":["state","status"],"properties":{"state":{"type":"string","enum":["ok","forbidden","unavailable"],"description":"ok: `data` is the section route's own 200 body. forbidden: this caller may not read the section (render nothing). unavailable: it could not be read — treat as unknown, never as \"nothing to report\"."},"status":{"type":"integer","description":"HTTP status the section route answered with (after retries)."},"data":{"type":"object","additionalProperties":true},"error":{"type":"object","properties":{"code":{"type":"string"},"message":{"type":"string"}},"required":["code","message"]}}},"metrics":{"type":"object","required":["state","status"],"properties":{"state":{"type":"string","enum":["ok","forbidden","unavailable"],"description":"ok: `data` is the section route's own 200 body. forbidden: this caller may not read the section (render nothing). unavailable: it could not be read — treat as unknown, never as \"nothing to report\"."},"status":{"type":"integer","description":"HTTP status the section route answered with (after retries)."},"data":{"type":"object","additionalProperties":true},"error":{"type":"object","properties":{"code":{"type":"string"},"message":{"type":"string"}},"required":["code","message"]}}},"recentOrders":{"type":"object","required":["state","status"],"properties":{"state":{"type":"string","enum":["ok","forbidden","unavailable"],"description":"ok: `data` is the section route's own 200 body. forbidden: this caller may not read the section (render nothing). unavailable: it could not be read — treat as unknown, never as \"nothing to report\"."},"status":{"type":"integer","description":"HTTP status the section route answered with (after retries)."},"data":{"type":"object","additionalProperties":true},"error":{"type":"object","properties":{"code":{"type":"string"},"message":{"type":"string"}},"required":["code","message"]}}},"onboarding":{"type":"object","required":["state","status"],"properties":{"state":{"type":"string","enum":["ok","forbidden","unavailable"],"description":"ok: `data` is the section route's own 200 body. forbidden: this caller may not read the section (render nothing). unavailable: it could not be read — treat as unknown, never as \"nothing to report\"."},"status":{"type":"integer","description":"HTTP status the section route answered with (after retries)."},"data":{"type":"object","additionalProperties":true},"error":{"type":"object","properties":{"code":{"type":"string"},"message":{"type":"string"}},"required":["code","message"]}}},"queueHealth":{"type":"object","required":["state","status"],"properties":{"state":{"type":"string","enum":["ok","forbidden","unavailable"],"description":"ok: `data` is the section route's own 200 body. forbidden: this caller may not read the section (render nothing). unavailable: it could not be read — treat as unknown, never as \"nothing to report\"."},"status":{"type":"integer","description":"HTTP status the section route answered with (after retries)."},"data":{"type":"object","additionalProperties":true},"error":{"type":"object","properties":{"code":{"type":"string"},"message":{"type":"string"}},"required":["code","message"]}}},"timeseries":{"type":"object","required":["state","status"],"properties":{"state":{"type":"string","enum":["ok","forbidden","unavailable"],"description":"ok: `data` is the section route's own 200 body. forbidden: this caller may not read the section (render nothing). unavailable: it could not be read — treat as unknown, never as \"nothing to report\"."},"status":{"type":"integer","description":"HTTP status the section route answered with (after retries)."},"data":{"type":"object","additionalProperties":true},"error":{"type":"object","properties":{"code":{"type":"string"},"message":{"type":"string"}},"required":["code","message"]}}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getDashboard","summary":"Get the dashboard"}},"/api/v1/tenants/{tenantId}/golden-data/stats":{"get":{"tags":["golden-data"],"description":"Get golden data statistics for a tenant","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"count":{"type":"integer"},"latestAddedAt":{"type":"string","nullable":true}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getGoldenDataStats","summary":"Get golden data statistics for a tenant"}},"/api/v1/tenants/{tenantId}/golden-data/":{"get":{"tags":["golden-data"],"description":"List golden data entries for a tenant, newest first, one page at a time. Pass the returned nextCursor back as cursor for the next page; nextCursor is null on the last page.","parameters":[{"schema":{"type":"integer","minimum":1,"maximum":200,"default":50},"in":"query","name":"limit","required":false},{"schema":{"type":"string","maxLength":200},"in":"query","name":"cursor","required":false},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"type":"object","properties":{"envelopeId":{"type":"string"},"orderId":{"type":"string","description":"The approved order, for GET /orders/:orderId."},"poNumber":{"type":"string","nullable":true,"description":"The PO number as approved, when the order has one."},"addedAt":{"type":"string"},"hadCorrections":{"type":"boolean"},"customerName":{"type":"string"},"referenceCustomerId":{"type":"string","nullable":true,"description":"The order's customer on the customer list; null when approved without one. Partner checks read only orders of a listed customer."},"lineItemCount":{"type":"integer"}}}},"nextCursor":{"type":"string","nullable":true}},"required":["data","nextCursor"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getGoldenData","summary":"List golden data entries for a tenant, newest first, one page at a time"}},"/api/v1/tenants/{tenantId}/golden-data/partners":{"get":{"tags":["golden-data"],"description":"The trading partners a partner check (POST /golden-data/evaluations) can be started for: active reference customers with at least one approved order that a check could read again, once each, with that count (verifiedOrders), sorted by name.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"name":{"type":"string"},"verifiedOrders":{"type":"integer"}},"required":["id","name","verifiedOrders"]}}},"required":["data"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getGoldenDataPartners","summary":"List golden data partners"}},"/api/v1/tenants/{tenantId}/golden-data/{envelopeId}":{"get":{"tags":["golden-data"],"description":"Get one golden data entry: the verified order saved when the order was approved.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"envelopeId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"envelopeId":{"type":"string"},"addedAt":{"type":"string"},"hadCorrections":{"type":"boolean"},"document":{"type":"string"},"documentStoragePath":{"type":"string"},"verifiedOrder":{"type":"object","additionalProperties":true},"schemaVersion":{"type":"integer","description":"2 for entries written from 2026-10-07, which name their trading partner. Absent on older entries."},"referenceCustomerId":{"type":"string","nullable":true},"senderDomain":{"type":"string","nullable":true}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getGoldenDataByEnvelopeId","summary":"Get one golden data entry: the verified order saved when the order was approved"}},"/api/v1/tenants/{tenantId}/golden-data/evaluations":{"post":{"tags":["golden-data"],"description":"Start a partner check: re-read up to 25 of one trading partner's approved orders through today's extraction and grade each read against what a person approved, field by field, by the release gate's rules. Runs in the background; answers 202 with the queued run. Poll GET /golden-data/evaluations/:runId or subscribe to golden_evaluation.completed. Each re-read is a model call counted against the daily inference budget; the run stops as budget_exhausted when the budget is reached. withExamples: true re-reads with up to two of the partner's own earlier approved documents in the prompt, each strictly older than the document being read. One run per tenant at a time (409 GOLDEN_EVAL_ALREADY_RUNNING). 422 GOLDEN_EVAL_NO_EXAMPLES when the partner has no approved order that can be re-read. A result is evidence for a person; it never changes routing or autonomy.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"properties":{"referenceCustomerId":{"type":"string","format":"uuid","description":"The trading partner to check."},"sampleSize":{"type":"integer","minimum":1,"maximum":25,"default":10},"withExamples":{"type":"boolean","default":false}},"required":["referenceCustomerId"]}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"202":{"description":"Accepted. Processing continues in the background; follow it with the id in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"referenceCustomerId":{"type":"string","format":"uuid"},"withExamples":{"type":"boolean"},"sampleSize":{"type":"integer"},"status":{"type":"string","enum":["queued","running","completed","failed","budget_exhausted"]},"requestedBy":{"type":"string"},"summary":{"type":"object","nullable":true,"properties":{"sampled":{"type":"integer"},"replayed":{"type":"integer"},"passed":{"type":"integer"},"failed":{"type":"integer"},"skipped":{"type":"integer"},"blockingMissCounts":{"type":"object","additionalProperties":{"type":"integer"}},"reviewableMisses":{"type":"integer"}}},"spendUsd":{"type":"number"},"errorMessage":{"type":"string","nullable":true},"createdAt":{"type":"string"},"startedAt":{"type":"string","nullable":true},"finishedAt":{"type":"string","nullable":true}},"required":["id","referenceCustomerId","withExamples","sampleSize","status","createdAt"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"object","properties":{"code":{"type":"string"},"message":{"type":"string"},"details":{"type":"object","additionalProperties":true}},"required":["code","message"]}}}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"object","properties":{"code":{"type":"string"},"message":{"type":"string"},"details":{"type":"object","additionalProperties":true}},"required":["code","message"]}}}}}},"422":{"description":"The request is well formed but its values cannot be used, for example INVALID_PERMISSIONS on an API key.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"object","properties":{"code":{"type":"string"},"message":{"type":"string"},"details":{"type":"object","additionalProperties":true}},"required":["code","message"]}}}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postGoldenDataEvaluations","summary":"Create golden data evaluation"},"get":{"tags":["golden-data"],"description":"List partner checks, newest first, optionally for one trading partner.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"query","name":"referenceCustomerId","required":false},{"schema":{"type":"integer","minimum":1,"maximum":100,"default":20},"in":"query","name":"limit","required":false},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"referenceCustomerId":{"type":"string","format":"uuid"},"withExamples":{"type":"boolean"},"sampleSize":{"type":"integer"},"status":{"type":"string","enum":["queued","running","completed","failed","budget_exhausted"]},"requestedBy":{"type":"string"},"summary":{"type":"object","nullable":true,"properties":{"sampled":{"type":"integer"},"replayed":{"type":"integer"},"passed":{"type":"integer"},"failed":{"type":"integer"},"skipped":{"type":"integer"},"blockingMissCounts":{"type":"object","additionalProperties":{"type":"integer"}},"reviewableMisses":{"type":"integer"}}},"spendUsd":{"type":"number"},"errorMessage":{"type":"string","nullable":true},"createdAt":{"type":"string"},"startedAt":{"type":"string","nullable":true},"finishedAt":{"type":"string","nullable":true}},"required":["id","referenceCustomerId","withExamples","sampleSize","status","createdAt"]}}},"required":["data"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getGoldenDataEvaluations","summary":"List partner checks, newest first, optionally for one trading partner"}},"/api/v1/tenants/{tenantId}/golden-data/evaluations/{runId}":{"get":{"tags":["golden-data"],"description":"Get one partner check with a result per re-read document: passed, failed (with the fields that differed from what was approved) or skipped (with the reason).","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"runId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"run":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"referenceCustomerId":{"type":"string","format":"uuid"},"withExamples":{"type":"boolean"},"sampleSize":{"type":"integer"},"status":{"type":"string","enum":["queued","running","completed","failed","budget_exhausted"]},"requestedBy":{"type":"string"},"summary":{"type":"object","nullable":true,"properties":{"sampled":{"type":"integer"},"replayed":{"type":"integer"},"passed":{"type":"integer"},"failed":{"type":"integer"},"skipped":{"type":"integer"},"blockingMissCounts":{"type":"object","additionalProperties":{"type":"integer"}},"reviewableMisses":{"type":"integer"}}},"spendUsd":{"type":"number"},"errorMessage":{"type":"string","nullable":true},"createdAt":{"type":"string"},"startedAt":{"type":"string","nullable":true},"finishedAt":{"type":"string","nullable":true}},"required":["id","referenceCustomerId","withExamples","sampleSize","status","createdAt"]},"results":{"type":"array","items":{"type":"object","properties":{"envelopeId":{"type":"string","format":"uuid"},"outcome":{"type":"string","enum":["passed","failed","skipped"]},"blockingMisses":{"type":"array","items":{"type":"string"}},"reviewableMisses":{"type":"array","items":{"type":"string"}},"cosmeticMisses":{"type":"array","items":{"type":"string"}},"exampleEnvelopeIds":{"type":"array","items":{"type":"string"}},"skipReason":{"type":"string","nullable":true}},"required":["envelopeId","outcome"]}}},"required":["run","results"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"object","properties":{"code":{"type":"string"},"message":{"type":"string"},"details":{"type":"object","additionalProperties":true}},"required":["code","message"]}}}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getGoldenDataEvaluationsByRunId","summary":"Get golden data evaluation"}},"/api/v1/tenants/{tenantId}/upload/":{"post":{"tags":["upload"],"description":"Upload a document for extraction. It is read as a purchase order or a supplier invoice: an explicit `documentType` ('order' or 'invoice', as a form field or a query parameter) wins; otherwise the upload channel's `documentTypeDefault` applies, which a tenant that chose supplier invoices at onboarding has set to 'invoice'; otherwise 'order'. Any other value is ignored. Email (IMAP, Gmail, Microsoft 365) and SFTP channels read their own `documentTypeDefault` the same way. Supported formats: PDF, CSV, XLSX, DOCX, HTML, TXT, EML, or images (PNG, JPG, GIF, WEBP). TIFF images, legacy binary Office files (.xls,.doc) and Outlook.msg files are not supported: convert them to PDF, XLSX, DOCX, CSV, PNG or JPEG first. A file in an unsupported format is refused with 415 UNSUPPORTED_MEDIA_TYPE, as is a file named.pdf whose bytes have no PDF header. Maximum file size 25 MB (INTAKE_MAX_ATTACHMENT_MB; 413 PAYLOAD_TOO_LARGE above it).","parameters":[{"schema":{"type":"string"},"in":"query","name":"documentType","required":false,"description":"'order' or 'invoice'. Overrides the upload channel's default for this document; the same value may be sent as a `documentType` multipart form field. Other values are ignored."},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"202":{"description":"Accepted. Processing continues in the background; follow it with the id in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"envelopeId":{"type":"string","format":"uuid"},"status":{"type":"string","enum":["received","extracting","extracted","validating","validated","in_review","auto_approved","approved","exporting","pending_export","exported","rejected","manual_handling","failed"]},"statusUrl":{"type":"string","description":"Path to follow this submission: GET it for the envelope status, and the order or invoice id once the document has been read."}},"required":["envelopeId","status","statusUrl"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"413":{"description":"PAYLOAD_TOO_LARGE: the body or file is over the size limit.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"415":{"$ref":"#/components/responses/UnsupportedMediaType"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"uploadDocument","summary":"Upload a document (multipart)","requestBody":{"required":true,"content":{"multipart/form-data":{"schema":{"type":"object","required":["file"],"properties":{"file":{"type":"string","format":"binary","description":"The document. PDF, CSV, XLSX, DOCX, HTML, TXT, EML or an image (PNG, JPG, GIF, WEBP); the format is read from the file's bytes, then its name. Up to 25 MB by default; a larger file is refused with 413 PAYLOAD_TOO_LARGE."},"documentType":{"type":"string","enum":["order","invoice"],"description":"Read the file as a purchase order or a supplier invoice. Omit it to use the upload channel's default (order unless the account chose invoices). The same value may be sent as the documentType query parameter."},"customerName":{"type":"string","description":"Optional hint: the customer the order is from."},"poNumber":{"type":"string","description":"Optional hint: the PO number."},"specialInstructions":{"type":"string","description":"Optional notes kept with the order."}}},"encoding":{"file":{"contentType":"application/octet-stream"}}}}}}},"/api/v1/tenants/{tenantId}/upload/{envelopeId}/status":{"get":{"tags":["upload"],"description":"Get processing status for an uploaded document","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"envelopeId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"envelopeId":{"type":"string","format":"uuid"},"status":{"type":"string","enum":["received","extracting","extracted","validating","validated","in_review","auto_approved","approved","exporting","pending_export","exported","rejected","manual_handling","failed"]},"confidence":{"type":"number","nullable":true},"customerName":{"type":"string","nullable":true},"errorMessage":{"type":"string","nullable":true},"classification":{"type":"string","nullable":true,"description":"non_order when the document was read and judged not an order (status rejected). It can be read again as an order with POST /orders/:envelopeId/reprocess."},"createdAt":{"type":"string","format":"date-time"},"updatedAt":{"type":"string","format":"date-time"}},"required":["envelopeId","status","createdAt","updatedAt"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getUploadStatus","summary":"Get the status of an upload"}},"/api/v1/tenants/{tenantId}/upload/{envelopeId}/reprocess":{"post":{"tags":["upload"],"description":"Re-process a previously uploaded document as a NEW envelope, optionally replacing the file. Only a document that could not be processed (failed), was rejected or filed as not an order, or was put aside for a person (manual_handling) can be replaced; anything else is refused with 409 INVALID_STATE (an order on its way or already sent would be sent twice). The original is marked superseded: a failed one moves to manual_handling (metadata.supersededBy names the new envelope) and every original is dismissed from the attention page. When the stored document of the original was deleted (mail filed as not an order after 30 days, or the retention window), only a replacement file is accepted; without one the request responds 409 INVALID_STATE and changes nothing. To retry the SAME envelope without a new file, use POST /orders/:envelopeId/reprocess instead.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"envelopeId","required":true}],"responses":{"202":{"description":"Accepted. Processing continues in the background; follow it with the id in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"envelopeId":{"type":"string","format":"uuid"},"status":{"type":"string","enum":["received","extracting","extracted","validating","validated","in_review","auto_approved","approved","exporting","pending_export","exported","rejected","manual_handling","failed"]},"reprocessedFrom":{"type":"string","format":"uuid"},"statusUrl":{"type":"string","description":"Path to follow this submission: GET it for the envelope status, and the order or invoice id once the document has been read."}},"required":["envelopeId","status","reprocessedFrom","statusUrl"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postUploadByEnvelopeIdReprocess","summary":"Re-process a previously uploaded document as a NEW envelope, optionally replacing the file"}},"/api/v1/tenants/{tenantId}/attention/":{"get":{"tags":["orders"],"description":"List items needing human attention: envelopes that failed processing (failed; with notAnInvoice true, a document an invoice inbox found no invoice in), approved orders whose export could not be delivered, envelopes stuck mid-pipeline with no status change in over 30 minutes, documents filed as not an order (notAnOrder: re-read one with POST /orders/:envelopeId/reprocess, or put it away with POST /orders/:envelopeId/dismiss), and documents the system parked for a person (needsPerson: status manual_handling; uncertainWrite true means a write may have landed and the destination must be checked first). approved orders whose send failed after they were read (deliveryFailed: the destination refused the order or the connector errored; retry the destination with POST /orders/:orderId/destinations/:destinationId/retry when retryable is true, else open the order to reconcile it; never re-read them, the read was fine), and approved orders held at the destination, not sent (held: the order's own data stopped the posting; correct it and approve it again from the review page). Delivery failures are not in the failed list. Dismissed documents are not listed. Each list is capped at 50 rows; pass the returned nextCursor back as the matching *Before querystring param to page further back.","parameters":[{"schema":{"type":"string","format":"date-time"},"in":"query","name":"failedBefore","required":false},{"schema":{"type":"string","format":"date-time"},"in":"query","name":"pendingExportBefore","required":false},{"schema":{"type":"string","format":"date-time"},"in":"query","name":"stuckProcessingBefore","required":false},{"schema":{"type":"string","format":"date-time"},"in":"query","name":"notAnOrderBefore","required":false},{"schema":{"type":"string","format":"date-time"},"in":"query","name":"needsPersonBefore","required":false},{"schema":{"type":"string","format":"date-time"},"in":"query","name":"deliveryFailedBefore","required":false},{"schema":{"type":"string","format":"date-time"},"in":"query","name":"heldBefore","required":false},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"failed":{"type":"array","items":{"type":"object","properties":{"envelopeId":{"type":"string"},"documentType":{"type":"string"},"channelType":{"type":"string"},"errorMessage":{"type":"string","nullable":true},"sourceLabel":{"type":"string","nullable":true,"description":"The stored file name, else the email subject or sender."},"notAnInvoice":{"type":"boolean","description":"True for a document an invoice-reading channel found no invoice in (status rejected, classification non_invoice). It is not retried: send it again as an order if it is one (upload with documentType order), or put it away with POST /orders/:envelopeId/dismiss."},"createdAt":{"type":"string"}},"required":["envelopeId","documentType","channelType","createdAt"]}},"pendingExport":{"type":"array","items":{"type":"object","properties":{"envelopeId":{"type":"string"},"orderId":{"type":"string","nullable":true},"customerName":{"type":"string","nullable":true},"poNumber":{"type":"string","nullable":true},"errorMessage":{"type":"string","nullable":true},"createdAt":{"type":"string"},"approvedAt":{"type":"string","nullable":true,"description":"When the order was last approved (a person or automatically); null when no approval is recorded."}},"required":["envelopeId","createdAt"]}},"stuckProcessing":{"type":"array","items":{"type":"object","properties":{"envelopeId":{"type":"string"},"documentType":{"type":"string"},"channelType":{"type":"string"},"status":{"type":"string"},"orderId":{"type":"string","nullable":true,"description":"Set for an approved order: POST /orders/:orderId/retry-export sends it again."},"updatedAt":{"type":"string"},"createdAt":{"type":"string"}},"required":["envelopeId","documentType","channelType","status","updatedAt","createdAt"]}},"notAnOrder":{"type":"array","items":{"type":"object","properties":{"envelopeId":{"type":"string"},"channelType":{"type":"string"},"sourceLabel":{"type":"string","nullable":true},"createdAt":{"type":"string"},"contentDeletedAt":{"type":"string","nullable":true,"description":"When the stored email and attachments were deleted (mail filed as not an order keeps its content 30 days). Set means it can no longer be read again; it can still be put away."}},"required":["envelopeId","channelType","createdAt"]}},"needsPerson":{"type":"array","items":{"type":"object","properties":{"envelopeId":{"type":"string"},"documentType":{"type":"string"},"orderId":{"type":"string","nullable":true},"customerName":{"type":"string","nullable":true},"poNumber":{"type":"string","nullable":true},"errorMessage":{"type":"string","nullable":true},"uncertainWrite":{"type":"boolean"},"createdAt":{"type":"string"},"updatedAt":{"type":"string"}},"required":["envelopeId","documentType","uncertainWrite","createdAt","updatedAt"]}},"deliveryFailed":{"type":"array","description":"Approved orders whose send failed after they were read. Not in failed.","items":{"type":"object","properties":{"envelopeId":{"type":"string"},"orderId":{"type":"string","nullable":true},"customerName":{"type":"string","nullable":true},"poNumber":{"type":"string","nullable":true},"destinationId":{"type":"string","nullable":true,"description":"The destination row that failed; retry it with POST /orders/:orderId/destinations/:destinationId/retry."},"destinationName":{"type":"string","nullable":true,"description":"The tenant's name for the destination, else the product (QuickBooks, Shopify)."},"errorMessage":{"type":"string","nullable":true,"description":"One plain sentence: what the destination said."},"errorCode":{"type":"string","nullable":true},"retryable":{"type":"boolean","description":"True when the destination wrote nothing and may be sent again; false when the outcome is uncertain and the order must be reconciled first."},"createdAt":{"type":"string"},"approvedAt":{"type":"string","nullable":true,"description":"When the order was last approved (a person or automatically); null when no approval is recorded."},"updatedAt":{"type":"string"}},"required":["envelopeId","retryable","createdAt","updatedAt"]}},"held":{"type":"array","description":"Approved orders held at the destination, not sent (status in_review with a manual-downstream hold). Not in the review queue.","items":{"type":"object","properties":{"envelopeId":{"type":"string"},"orderId":{"type":"string","nullable":true},"customerName":{"type":"string","nullable":true},"poNumber":{"type":"string","nullable":true},"reason":{"type":"string","nullable":true,"description":"Why it was held, in the words the order page shows."},"createdAt":{"type":"string"},"updatedAt":{"type":"string"}},"required":["envelopeId","createdAt","updatedAt"]}},"proposedRules":{"type":"array","items":{"type":"object","properties":{"ruleId":{"type":"string"},"description":{"type":"string"},"createdAt":{"type":"string"}},"required":["ruleId","description","createdAt"]}},"counts":{"type":"object","properties":{"failed":{"type":"integer"},"pendingExport":{"type":"integer"},"stuckProcessing":{"type":"integer"},"notAnOrder":{"type":"integer"},"needsPerson":{"type":"integer"},"deliveryFailed":{"type":"integer"},"held":{"type":"integer"},"proposedRules":{"type":"integer"}},"required":["failed","pendingExport","stuckProcessing","notAnOrder","needsPerson","deliveryFailed","held","proposedRules"]},"nextCursor":{"type":"object","properties":{"failed":{"type":"string","nullable":true},"pendingExport":{"type":"string","nullable":true},"stuckProcessing":{"type":"string","nullable":true},"notAnOrder":{"type":"string","nullable":true},"needsPerson":{"type":"string","nullable":true},"deliveryFailed":{"type":"string","nullable":true},"held":{"type":"string","nullable":true}},"required":["failed","pendingExport","stuckProcessing","notAnOrder","needsPerson","deliveryFailed","held"]}},"required":["failed","pendingExport","stuckProcessing","notAnOrder","needsPerson","deliveryFailed","held","proposedRules","counts","nextCursor"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"listAttention","summary":"List the items that need a person"}},"/api/v1/provision/tenants":{"post":{"tags":["provisioning"],"description":"Provision a new tenant with API key. Requires the x-provisioning-token header (platform-issued credential). The raw API key is returned once and cannot be retrieved again. Atomic: the tenant, key, channels, trial and audit entry are created in one transaction, so a failure (500 PROVISIONING_FAILED) creates nothing and is safe to retry. Send idempotencyKey (or an Idempotency-Key header) so a retry after a lost response returns the same tenant (200) instead of a 409.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string","minLength":2,"maxLength":100},"slug":{"type":"string","minLength":2,"maxLength":100,"pattern":"^[a-z0-9]+(?:-[a-z0-9]+)*$","description":"URL-friendly identifier. Auto-generated from name if omitted."},"contactEmail":{"type":"string","format":"email"},"omsType":{"type":"string","enum":["netsuite","quickbooks","shopify","custom_rest"],"description":"The system orders are written to. Exactly the connector types that exist."},"plan":{"type":"string","enum":["starter-2026","core-2026","growth-2026","scale-2026","core","growth","scale"],"description":"Starts a 14-day trial on this plan (no card), so the returned key can submit orders immediately and plan entitlements apply. Omit it and the response lists SUBSCRIPTION_REQUIRED in nextSteps: orders return 402 until a plan is started via POST /tenants/:id/billing/checkout."},"channels":{"type":"array","maxItems":10,"items":{"type":"object","properties":{"type":{"type":"string","enum":["email","sftp","api","upload"]},"config":{"type":"object","additionalProperties":true}},"required":["type"]}},"settings":{"type":"object","properties":{"confidenceThresholds":{"type":"object","properties":{"autoApprove":{"type":"number","minimum":0,"maximum":1},"reviewQueue":{"type":"number","minimum":0,"maximum":1},"reject":{"type":"number","minimum":0,"maximum":1}}},"autoApprovalEnabled":{"type":"boolean"}}},"idempotencyKey":{"type":"string","minLength":1,"maxLength":255,"description":"Client-chosen key (a UUID is ideal) that makes provisioning safe to retry. Also accepted as an Idempotency-Key header; the body field wins. A retry with the same key and the same body within 24 hours returns 200 with the original tenant instead of creating another: with a new apiKey while the key issued last has never been used (that unused key is revoked), or 409 KEY_ALREADY_ISSUED once it has. The same key with a different body gets 409 IDEMPOTENCY_KEY_REUSED; after 24 hours, 409 IDEMPOTENCY_KEY_EXPIRED. A request that failed created nothing and reserved nothing, so its retry provisions normally."}},"required":["name","contactEmail","omsType"]}}}},"security":[{"provisioningToken":[]}],"responses":{"200":{"description":"Replay of an earlier call with the same idempotency key and body: the original tenant, with a newly issued API key (the unused one from before is revoked).","content":{"application/json":{"schema":{"type":"object","properties":{"tenant":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"name":{"type":"string"},"slug":{"type":"string"},"status":{"type":"string","enum":["onboarding","active","suspended","offboarding","offboarded"]}},"required":["id","name","slug","status"]},"idempotentReplay":{"type":"boolean","description":"True when this response replays an earlier call with the same idempotency key (HTTP 200): the tenant, channels, subscription and nextSteps are as that call returned them, and apiKey is newly issued."},"apiKey":{"type":"string","description":"Raw API key. Store securely — it cannot be retrieved again."},"channels":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"tenantId":{"type":"string","format":"uuid"},"channelType":{"type":"string","enum":["email","sftp","api","upload"]},"config":{"type":"object","additionalProperties":true},"status":{"type":"string","enum":["active","inactive"]},"createdAt":{"type":"string","format":"date-time"}},"required":["id","tenantId","channelType","config","status","createdAt"]}},"subscription":{"type":"object","nullable":true,"description":"The trial started for `plan`, or null when no plan was requested.","properties":{"plan":{"type":"string","enum":["starter-2026","core-2026","growth-2026","scale-2026"]},"status":{"type":"string","enum":["trialing","active"]},"trialEndsAt":{"type":"string","format":"date-time","nullable":true}},"required":["plan","status","trialEndsAt"]},"nextSteps":{"type":"array","description":"What the caller must do before the tenant is fully usable. Empty when nothing blocks orders.","items":{"type":"object","properties":{"code":{"type":"string","enum":["SUBSCRIPTION_REQUIRED","ADD_PAYMENT_METHOD","CONNECT_DESTINATION"]},"message":{"type":"string"},"url":{"type":"string","description":"Page a person can open to do this."},"method":{"type":"string"},"path":{"type":"string","description":"API call an agent can make to do this."},"dueBy":{"type":"string","format":"date-time"}},"required":["code","message"]}},"message":{"type":"string"}},"required":["tenant","apiKey","channels","subscription","nextSteps","message","idempotentReplay"],"description":"Replay of an earlier call with the same idempotency key and body: the original tenant, with a newly issued API key (the unused one from before is revoked)."}}}},"201":{"description":"Tenant provisioned.","content":{"application/json":{"schema":{"type":"object","properties":{"tenant":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"name":{"type":"string"},"slug":{"type":"string"},"status":{"type":"string","enum":["onboarding","active","suspended","offboarding","offboarded"]}},"required":["id","name","slug","status"]},"idempotentReplay":{"type":"boolean","description":"True when this response replays an earlier call with the same idempotency key (HTTP 200): the tenant, channels, subscription and nextSteps are as that call returned them, and apiKey is newly issued."},"apiKey":{"type":"string","description":"Raw API key. Store securely — it cannot be retrieved again."},"channels":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"tenantId":{"type":"string","format":"uuid"},"channelType":{"type":"string","enum":["email","sftp","api","upload"]},"config":{"type":"object","additionalProperties":true},"status":{"type":"string","enum":["active","inactive"]},"createdAt":{"type":"string","format":"date-time"}},"required":["id","tenantId","channelType","config","status","createdAt"]}},"subscription":{"type":"object","nullable":true,"description":"The trial started for `plan`, or null when no plan was requested.","properties":{"plan":{"type":"string","enum":["starter-2026","core-2026","growth-2026","scale-2026"]},"status":{"type":"string","enum":["trialing","active"]},"trialEndsAt":{"type":"string","format":"date-time","nullable":true}},"required":["plan","status","trialEndsAt"]},"nextSteps":{"type":"array","description":"What the caller must do before the tenant is fully usable. Empty when nothing blocks orders.","items":{"type":"object","properties":{"code":{"type":"string","enum":["SUBSCRIPTION_REQUIRED","ADD_PAYMENT_METHOD","CONNECT_DESTINATION"]},"message":{"type":"string"},"url":{"type":"string","description":"Page a person can open to do this."},"method":{"type":"string"},"path":{"type":"string","description":"API call an agent can make to do this."},"dueBy":{"type":"string","format":"date-time"}},"required":["code","message"]}},"message":{"type":"string"}},"required":["tenant","apiKey","channels","subscription","nextSteps","message","idempotentReplay"],"description":"Tenant provisioned."}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"description":"No valid credential: UNAUTHORIZED. Send X-API-Key (or a web session); a revoked or expired key is refused the same way.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"$ref":"#/components/responses/Forbidden"},"409":{"description":"CONFLICT (slug taken), IDEMPOTENCY_KEY_REUSED (same key, different body), IDEMPOTENCY_KEY_EXPIRED, or KEY_ALREADY_ISSUED (details.tenantId names the tenant already provisioned for this key).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"description":"TENANT_RATE_LIMIT_EXCEEDED (the plan's per-minute limit), RATE_LIMIT_EXCEEDED (the per-IP backstop) or TENANT_CAPACITY_EXCEEDED (too many concurrent requests). Wait for Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"500":{"description":"PROVISIONING_FAILED: the transaction was rolled back and nothing was created. Safe to retry.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"postProvisionTenants","summary":"Provision a new tenant with API key"}},"/api/v1/provision/signup":{"post":{"summary":"Public signup — create a tenant and its owner user","tags":["provisioning"],"description":"Creates a tenant in onboarding status and an owner user. This request sends no email: sign in with the same address at next.signInUrl to receive a sign-in link. A plan, a trial and API keys need that signed-in person. The response is the same whether or not the address was already registered. No authentication required; rate-limited per IP.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["name","email","termsAccepted"],"properties":{"name":{"type":"string","minLength":2,"maxLength":100},"email":{"type":"string","format":"email"},"planSlug":{"type":"string","enum":["starter-2026","core-2026","growth-2026","scale-2026"]},"termsAccepted":{"type":"boolean","enum":[true]},"marketingEmails":{"type":"boolean","default":false}}}}}},"security":[],"responses":{"201":{"description":"Created. The new resource is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"message":{"type":"string"},"next":{"type":"object","description":"What to do next. This request sends no email.","properties":{"action":{"type":"string","enum":["sign_in"]},"signInUrl":{"type":["null","string"],"description":"The web sign-in page, where the same address gets a sign-in link."},"message":{"type":"string"}},"required":["action","signInUrl","message"]}},"required":["message","next"]}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"422":{"description":"The request is well formed but its values cannot be used, for example INVALID_PERMISSIONS on an API key.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"description":"TENANT_RATE_LIMIT_EXCEEDED (the plan's per-minute limit), RATE_LIMIT_EXCEEDED (the per-IP backstop) or TENANT_CAPACITY_EXCEEDED (too many concurrent requests). Wait for Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"postProvisionSignup"}},"/api/v1/provision/signup/session":{"post":{"summary":"Create an organization for the signed-in person (OAuth signup)","tags":["provisioning"],"description":"Creates a tenant in onboarding status with the signed-in user as owner. Requires a browser session for a user who belongs to no tenant yet; the owner email is taken from the session. API keys cannot call this.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["name","termsAccepted"],"properties":{"name":{"type":"string","minLength":2,"maxLength":100},"planSlug":{"type":"string","enum":["starter-2026","core-2026","growth-2026","scale-2026"]},"termsAccepted":{"type":"boolean","enum":[true]},"marketingEmails":{"type":"boolean","default":false}}}}}},"security":[],"responses":{"201":{"description":"Created. The new resource is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"message":{"type":"string"}},"required":["message"]}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"description":"No valid credential: UNAUTHORIZED. Send X-API-Key (or a web session); a revoked or expired key is refused the same way.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"description":"The credential is valid but may not do this: FORBIDDEN or ACCESS_DENIED (the key lacks the permission scope, or the role is too low, or the tenant in the path is not the key's tenant), TENANT_SUSPENDED for writes on a suspended account, MFA_REQUIRED for a session that owes a passkey.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"description":"TENANT_RATE_LIMIT_EXCEEDED (the plan's per-minute limit), RATE_LIMIT_EXCEEDED (the per-IP backstop) or TENANT_CAPACITY_EXCEEDED (too many concurrent requests). Wait for Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"postProvisionSignupSession"}},"/api/v1/public/plans":{"get":{"tags":["billing"],"description":"Public list of purchasable subscription plans","security":[],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"type":"object","properties":{"slug":{"type":"string"},"name":{"type":"string"},"monthlyPriceCents":{"type":"integer"},"includedAutoApprovals":{"type":"integer","nullable":true,"description":"Deprecated alias of includedOrders."},"includedOrders":{"type":"integer","nullable":true,"description":"Orders the monthly fee includes, counted in billingUnit. Null = unlimited."},"billingUnit":{"type":"string","enum":["processed","auto_approved"],"description":"processed: every purchase order approved counts, unattended or by a person."},"overagePriceCents":{"type":"integer"},"envelopeLimit":{"type":"integer","nullable":true},"userLimit":{"type":"integer","nullable":true},"features":{"type":"object","additionalProperties":true},"contactSales":{"type":"boolean"}},"required":["slug","name","monthlyPriceCents","contactSales"]}}},"required":["data"]}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"getPublicPlans","summary":"Public list of purchasable subscription plans"}},"/api/v1/events/":{"post":{"tags":["marketing"],"description":"Record one anonymous marketing-funnel event. No cookie is set or read.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"event":{"type":"string","enum":["demo_start"]},"page":{"type":"string","maxLength":255}},"required":["event"],"additionalProperties":false}}}},"security":[],"responses":{"202":{"description":"Accepted. Processing continues in the background; follow it with the id in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"accepted":{"type":"boolean"}},"required":["accepted"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"}},"operationId":"postEvents","summary":"Record one anonymous marketing-funnel event"}},"/api/v1/tenants/{tenantId}/webhooks/":{"post":{"tags":["webhooks"],"description":"Create a webhook subscription","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"url":{"type":"string","description":"HTTPS endpoint URL to receive webhook POST requests"},"events":{"type":"array","items":{"type":"string","enum":["webhook.test","webhook.disabled","envelope.extracted","envelope.in_review","envelope.validating","envelope.auto_approved","envelope.approved","envelope.manual_handling","envelope.rejected","envelope.failed","envelope.completed","envelope.destination.completed","envelope.destination.failed","envelope.destination.skipped","envelope.destination.needs_reconciliation","envelope.partially_delivered","envelope.exported","envelope.export_failed","envelope.duplicate_blocked","envelope.sla_breach","order.acknowledged","order.possible_double_post","autonomy.proposed","autonomy.granted","autonomy.demoted","autonomy.revoked","mapping_rule.proposed","intake.sender_throttled","intake.scanner_unavailable","intake.mailbox_resynced","intake.duplicate_file","channel.imap_connection_failed","channel.sftp_connection_failed","channel.sftp_finalize_failed","channel.oauth_connection_failed","connector.oauth_connection_failed","connector.disconnected","connector.warning","tenant.retention_purge_completed","tenant.export_completed","tenant.export_failed","tenant.offboarding","tenant.offboarded","quality.regression_detected","quality.regression_resolved","format_library.hints_offered","golden_evaluation.completed","*"]},"minItems":1,"description":"Array of event names to subscribe to, e.g. [\"envelope.completed\", \"envelope.failed\"] or [\"*\"] for all events"},"secret":{"type":"string","minLength":16,"maxLength":128,"description":"HMAC secret for payload verification. Auto-generated if omitted."},"description":{"type":"string","maxLength":255,"description":"Optional human-readable label for this subscription"}},"required":["url","events"]}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"201":{"description":"Created. The new resource is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"tenantId":{"type":"string","format":"uuid"},"url":{"type":"string"},"events":{"type":"array","items":{"type":"string"}},"secret":{"type":"string","description":"Full secret, only returned on creation"},"active":{"type":"boolean"},"description":{"type":"string","nullable":true},"createdAt":{"type":"string","format":"date-time"},"updatedAt":{"type":"string","format":"date-time"}},"required":["id","tenantId","url","events","secret","active","createdAt","updatedAt"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"createWebhook","summary":"Create a webhook subscription"},"get":{"tags":["webhooks"],"description":"List webhook subscriptions for a tenant","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"tenantId":{"type":"string","format":"uuid"},"url":{"type":"string"},"events":{"type":"array","items":{"type":"string"}},"secret":{"type":"string","description":"Masked secret (last 4 chars visible)"},"active":{"type":"boolean"},"description":{"type":"string","nullable":true},"consecutiveFailures":{"type":"integer","description":"Deliveries that failed their first attempt in a row; 0 while healthy. Reset by PATCH active: true."},"autoDisabledAt":{"type":"string","format":"date-time","nullable":true,"description":"When the dispatcher switched this subscription off after a sustained failure streak; null when it is active or a person disabled it."},"createdAt":{"type":"string","format":"date-time"},"updatedAt":{"type":"string","format":"date-time"}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"listWebhooks","summary":"List webhook subscriptions"}},"/api/v1/tenants/{tenantId}/webhooks/{webhookId}":{"patch":{"tags":["webhooks"],"description":"Update a webhook subscription","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"url":{"type":"string"},"events":{"type":"array","items":{"type":"string","enum":["webhook.test","webhook.disabled","envelope.extracted","envelope.in_review","envelope.validating","envelope.auto_approved","envelope.approved","envelope.manual_handling","envelope.rejected","envelope.failed","envelope.completed","envelope.destination.completed","envelope.destination.failed","envelope.destination.skipped","envelope.destination.needs_reconciliation","envelope.partially_delivered","envelope.exported","envelope.export_failed","envelope.duplicate_blocked","envelope.sla_breach","order.acknowledged","order.possible_double_post","autonomy.proposed","autonomy.granted","autonomy.demoted","autonomy.revoked","mapping_rule.proposed","intake.sender_throttled","intake.scanner_unavailable","intake.mailbox_resynced","intake.duplicate_file","channel.imap_connection_failed","channel.sftp_connection_failed","channel.sftp_finalize_failed","channel.oauth_connection_failed","connector.oauth_connection_failed","connector.disconnected","connector.warning","tenant.retention_purge_completed","tenant.export_completed","tenant.export_failed","tenant.offboarding","tenant.offboarded","quality.regression_detected","quality.regression_resolved","format_library.hints_offered","golden_evaluation.completed","*"]},"minItems":1},"active":{"type":"boolean"},"description":{"type":"string","maxLength":255,"nullable":true}}}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"webhookId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"tenantId":{"type":"string","format":"uuid"},"url":{"type":"string"},"events":{"type":"array","items":{"type":"string"}},"secret":{"type":"string"},"active":{"type":"boolean"},"description":{"type":"string","nullable":true},"createdAt":{"type":"string","format":"date-time"},"updatedAt":{"type":"string","format":"date-time"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"patchWebhooksByWebhookId","summary":"Update a webhook subscription"},"delete":{"tags":["webhooks"],"description":"Delete a webhook subscription","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"webhookId","required":true}],"responses":{"204":{"description":"Subscription deleted successfully"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"deleteWebhooksByWebhookId","summary":"Delete a webhook subscription"}},"/api/v1/tenants/{tenantId}/webhooks/{webhookId}/deliveries":{"get":{"tags":["webhooks"],"description":"List webhook delivery logs for a specific subscription","parameters":[{"schema":{"type":"integer","minimum":1,"default":1},"in":"query","name":"page","required":false,"description":"Page number (1-based)"},{"schema":{"type":"integer","minimum":1,"maximum":200},"in":"query","name":"pageSize","required":false,"description":"Items per page (default 50, max 200)"},{"schema":{"type":"integer","minimum":1},"in":"query","name":"limit","required":false,"description":"Deprecated alias of pageSize, clamped to 200. Accepted for one release."},{"schema":{"type":"integer","minimum":0},"in":"query","name":"offset","required":false,"description":"Deprecated: rows to skip. Takes precedence over page when both are sent. Accepted for one release."},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"webhookId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"webhookSubscriptionId":{"type":"string","format":"uuid"},"event":{"type":"string"},"statusCode":{"type":"integer","nullable":true},"success":{"type":"boolean"},"durationMs":{"type":"integer","nullable":true},"error":{"type":"string","nullable":true},"createdAt":{"type":"string","format":"date-time"}}}},"pagination":{"type":"object","properties":{"page":{"type":"integer"},"pageSize":{"type":"integer"},"total":{"type":"integer"},"totalPages":{"type":"integer"}},"required":["page","pageSize","total","totalPages"]},"total":{"type":"integer","description":"Deprecated: pagination.total. Kept for one release."},"limit":{"type":"integer","description":"Deprecated: pagination.pageSize. Kept for one release."},"offset":{"type":"integer","description":"Deprecated. Kept for one release."}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getWebhooksByWebhookIdDeliveries","summary":"List webhook delivery logs for a specific subscription"}},"/api/v1/tenants/{tenantId}/webhooks/{webhookId}/pending-deliveries":{"get":{"tags":["webhooks"],"description":"List queued/dead webhook deliveries awaiting or past retry for a subscription","parameters":[{"schema":{"type":"string","enum":["pending","delivered","dead"]},"in":"query","name":"status","required":false},{"schema":{"type":"integer","minimum":1,"default":1},"in":"query","name":"page","required":false,"description":"Page number (1-based)"},{"schema":{"type":"integer","minimum":1,"maximum":200},"in":"query","name":"pageSize","required":false,"description":"Items per page (default 50, max 200)"},{"schema":{"type":"integer","minimum":1},"in":"query","name":"limit","required":false,"description":"Deprecated alias of pageSize, clamped to 200. Accepted for one release."},{"schema":{"type":"integer","minimum":0},"in":"query","name":"offset","required":false,"description":"Deprecated: rows to skip. Takes precedence over page when both are sent. Accepted for one release."},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"webhookId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"event":{"type":"string"},"attempts":{"type":"integer"},"nextAttemptAt":{"type":"string","format":"date-time","nullable":true},"lastError":{"type":"string","nullable":true},"status":{"type":"string"},"createdAt":{"type":"string","format":"date-time"},"updatedAt":{"type":"string","format":"date-time"}}}},"pagination":{"type":"object","properties":{"page":{"type":"integer"},"pageSize":{"type":"integer"},"total":{"type":"integer"},"totalPages":{"type":"integer"}},"required":["page","pageSize","total","totalPages"]},"total":{"type":"integer","description":"Deprecated: pagination.total. Kept for one release."},"limit":{"type":"integer","description":"Deprecated: pagination.pageSize. Kept for one release."},"offset":{"type":"integer","description":"Deprecated. Kept for one release."}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getWebhooksByWebhookIdPendingDeliveries","summary":"List queued/dead webhook deliveries awaiting or past retry for a subscription"}},"/api/v1/tenants/{tenantId}/webhooks/{webhookId}/pending-deliveries/{pendingId}/redeliver":{"post":{"tags":["webhooks"],"description":"Immediately retry a queued or dead webhook delivery","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"webhookId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"pendingId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"delivered":{"type":"boolean"},"statusCode":{"type":"integer","nullable":true},"error":{"type":"string","nullable":true}},"required":["delivered"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postWebhooksByWebhookIdPendingDeliveriesByPendingIdRedeliver","summary":"Immediately retry a queued or dead webhook delivery"}},"/api/v1/tenants/{tenantId}/webhooks/{webhookId}/rotate":{"post":{"tags":["webhooks"],"description":"Rotate a webhook signing secret (returned once)","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"webhookId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string"},"secret":{"type":"string"},"rotatedAt":{"type":"string"}},"required":["id","secret","rotatedAt"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postWebhooksByWebhookIdRotate","summary":"Rotate a webhook signing secret (returned once)"}},"/api/v1/tenants/{tenantId}/webhooks/{webhookId}/test":{"post":{"tags":["webhooks"],"description":"Send a signed webhook.test event to this subscription","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"webhookId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"delivered":{"type":"boolean"},"statusCode":{"type":"integer","nullable":true},"attempts":{"type":"integer"},"durationMs":{"type":"integer"},"error":{"type":"string","nullable":true}},"required":["delivered","attempts"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postWebhooksByWebhookIdTest","summary":"Send a signed webhook.test event to this subscription"}},"/api/v1/tenants/{tenantId}/users/me":{"get":{"tags":["users"],"description":"Get the current session user's profile (session auth only).","parameters":[{"schema":{"type":"string"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string"},"tenantId":{"type":"string"},"name":{"type":"string"},"email":{"type":"string"},"role":{"type":"string"},"status":{"type":"string"},"createdAt":{"type":"string","format":"date-time"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"No valid credential: UNAUTHORIZED. Send X-API-Key (or a web session); a revoked or expired key is refused the same way.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"getUsersMe","summary":"Get the current session user's profile (session auth only)"},"patch":{"tags":["users"],"description":"Update the current session user's own profile. Email is deliberately excluded — it is the login identity. Omitting `name` leaves it unchanged; pass `name: null` to clear it.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":["string","null"],"minLength":1,"maxLength":200}}}}}},"parameters":[{"schema":{"type":"string"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string"},"tenantId":{"type":"string"},"name":{"type":"string","nullable":true},"email":{"type":"string"},"role":{"type":"string"},"status":{"type":"string"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"patchUsersMe","summary":"Update the current session user's own profile"}},"/api/v1/tenants/{tenantId}/users/me/sessions":{"get":{"tags":["users"],"description":"List the current session user's own active sessions.","parameters":[{"schema":{"type":"string"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"sessions":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string"},"createdAt":{"type":"string","format":"date-time"},"expires":{"type":"string","format":"date-time"},"authenticationProvider":{"type":"string"},"ipAddress":{"type":["null","string"]},"userAgent":{"type":["null","string"]},"isCurrent":{"type":"boolean"}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"No valid credential: UNAUTHORIZED. Send X-API-Key (or a web session); a revoked or expired key is refused the same way.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"getUsersMeSessions","summary":"List the current session user's own active sessions"}},"/api/v1/tenants/{tenantId}/users/me/sessions/{sessionId}":{"delete":{"tags":["users"],"description":"Revoke one of the current session user's own sessions.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"sessionId","required":true}],"responses":{"204":{"description":"Session revoked."},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"description":"No valid credential: UNAUTHORIZED. Send X-API-Key (or a web session); a revoked or expired key is refused the same way.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"deleteUsersMeSessionsBySessionId","summary":"Revoke one of the current session user's own sessions"}},"/api/v1/tenants/{tenantId}/users/me/passkeys":{"get":{"tags":["users"],"description":"List the signed-in person's passkeys. Session auth only.","parameters":[{"schema":{"type":"string"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"passkeys":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"name":{"type":"string"},"deviceType":{"type":"string","enum":["singleDevice","multiDevice"]},"backedUp":{"type":"boolean","description":"Synced to the person's cloud account (for example iCloud Keychain or Google Password Manager)."},"createdAt":{"type":"string","format":"date-time"},"lastUsedAt":{"type":"string","format":"date-time","nullable":true}},"required":["id","name","deviceType","backedUp","createdAt"]}}},"required":["passkeys"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"No valid credential: UNAUTHORIZED. Send X-API-Key (or a web session); a revoked or expired key is refused the same way.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"description":"The credential is valid but may not do this: FORBIDDEN or ACCESS_DENIED (the key lacks the permission scope, or the role is too low, or the tenant in the path is not the key's tenant), TENANT_SUSPENDED for writes on a suspended account, MFA_REQUIRED for a session that owes a passkey.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"getUsersMePasskeys","summary":"List the signed-in person's passkeys"}},"/api/v1/tenants/{tenantId}/users/me/passkeys/{passkeyId}":{"patch":{"tags":["users"],"description":"Rename one of the signed-in person's passkeys.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["name"],"properties":{"name":{"type":"string","minLength":1,"maxLength":100}}}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"passkeyId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"name":{"type":"string"},"deviceType":{"type":"string","enum":["singleDevice","multiDevice"]},"backedUp":{"type":"boolean","description":"Synced to the person's cloud account (for example iCloud Keychain or Google Password Manager)."},"createdAt":{"type":"string","format":"date-time"},"lastUsedAt":{"type":"string","format":"date-time","nullable":true}},"required":["id","name","deviceType","backedUp","createdAt"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"No valid credential: UNAUTHORIZED. Send X-API-Key (or a web session); a revoked or expired key is refused the same way.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"description":"The credential is valid but may not do this: FORBIDDEN or ACCESS_DENIED (the key lacks the permission scope, or the role is too low, or the tenant in the path is not the key's tenant), TENANT_SUSPENDED for writes on a suspended account, MFA_REQUIRED for a session that owes a passkey.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"patchUsersMePasskeysByPasskeyId","summary":"Rename one of the signed-in person's passkeys"},"delete":{"tags":["users"],"description":"Remove one of the signed-in person's passkeys. Needs a session that has proven a passkey (a passkey sign-in or a step-up), so a session opened by an email link alone cannot strip someone's passkeys. 403 MFA_REQUIRED otherwise.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"passkeyId","required":true}],"responses":{"204":{"description":"Done. There is no body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"No valid credential: UNAUTHORIZED. Send X-API-Key (or a web session); a revoked or expired key is refused the same way.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"description":"The credential is valid but may not do this: FORBIDDEN or ACCESS_DENIED (the key lacks the permission scope, or the role is too low, or the tenant in the path is not the key's tenant), TENANT_SUSPENDED for writes on a suspended account, MFA_REQUIRED for a session that owes a passkey.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"deleteUsersMePasskeysByPasskeyId","summary":"Remove one of the signed-in person's passkeys"}},"/api/v1/tenants/{tenantId}/users/{userId}/passkeys":{"get":{"tags":["users"],"description":"List a member's passkeys (no key material), to see what a reset would remove.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"userId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"passkeys":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"name":{"type":"string"},"deviceType":{"type":"string","enum":["singleDevice","multiDevice"]},"backedUp":{"type":"boolean","description":"Synced to the person's cloud account (for example iCloud Keychain or Google Password Manager)."},"createdAt":{"type":"string","format":"date-time"},"lastUsedAt":{"type":"string","format":"date-time","nullable":true}},"required":["id","name","deviceType","backedUp","createdAt"]}}},"required":["passkeys"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"No valid credential: UNAUTHORIZED. Send X-API-Key (or a web session); a revoked or expired key is refused the same way.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"description":"The credential is valid but may not do this: FORBIDDEN or ACCESS_DENIED (the key lacks the permission scope, or the role is too low, or the tenant in the path is not the key's tenant), TENANT_SUSPENDED for writes on a suspended account, MFA_REQUIRED for a session that owes a passkey.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"getUsersByUserIdPasskeys","summary":"List a member's passkeys (no key material), to see what a reset would remove"}},"/api/v1/tenants/{tenantId}/users/{userId}/mfa/reset":{"post":{"tags":["users"],"description":"Remove all of a member's passkeys and end their sessions, so they can sign in again and add a new one. Needs an admin browser session that has proven a passkey or signed in with SSO (403 MFA_REQUIRED otherwise); not for yourself. Never for the owner, and another admin's only by the owner (403 FORBIDDEN).","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"userId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"passkeysRemoved":{"type":"integer"},"sessionsEnded":{"type":"integer"}},"required":["passkeysRemoved","sessionsEnded"]}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"description":"No valid credential: UNAUTHORIZED. Send X-API-Key (or a web session); a revoked or expired key is refused the same way.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"description":"The credential is valid but may not do this: FORBIDDEN or ACCESS_DENIED (the key lacks the permission scope, or the role is too low, or the tenant in the path is not the key's tenant), TENANT_SUSPENDED for writes on a suspended account, MFA_REQUIRED for a session that owes a passkey.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"postUsersByUserIdMfaReset","summary":"Create user mfa reset"}},"/api/v1/tenants/{tenantId}/users/":{"get":{"tags":["users"],"description":"List all users in the tenant.","parameters":[{"schema":{"type":"string"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string","nullable":true},"email":{"type":"string"},"role":{"type":"string"},"status":{"type":"string"},"createdAt":{"type":"string","format":"date-time"},"updatedAt":{"type":"string","format":"date-time"}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"getUsers","summary":"List all users in the tenant"}},"/api/v1/tenants/{tenantId}/users/{userId}/role":{"patch":{"tags":["users"],"description":"Change a user's role (owner only). Cannot change your own role or demote the owner — ownership transfer is a separate, explicit action. While the tenant requires single sign-on, making someone admin whose email is not on a verified domain answers 409 SSO_ENFORCED_OFF_DOMAIN: they could never sign in.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"role":{"type":"string","enum":["admin","operator","viewer"]}},"required":["role"]}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"userId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string","nullable":true},"email":{"type":"string"},"role":{"type":"string"},"status":{"type":"string"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"patchUsersByUserIdRole","summary":"Change a user's role (owner only)"}},"/api/v1/tenants/{tenantId}/users/{userId}":{"delete":{"tags":["users"],"description":"Deactivate a user: revokes their sessions and API keys, and blocks sign-in. Cannot deactivate yourself or the owner.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"userId","required":true}],"responses":{"204":{"description":"User deactivated successfully"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"deleteUsersByUserId","summary":"Deactivate a user: revokes their sessions and API keys, and blocks sign-in"}},"/api/v1/tenants/{tenantId}/users/{userId}/reactivate":{"post":{"tags":["users"],"description":"Reverse a deactivation, restoring sign-in access. While the tenant requires single sign-on, reactivating an owner or admin whose email is not on a verified domain answers 409 SSO_ENFORCED_OFF_DOMAIN.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"userId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string","nullable":true},"email":{"type":"string"},"role":{"type":"string"},"status":{"type":"string"}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postUsersByUserIdReactivate","summary":"Reverse a deactivation, restoring sign-in access"}},"/api/v1/tenants/{tenantId}/users/{userId}/transfer-ownership":{"post":{"tags":["users"],"description":"Transfer organization ownership to an active admin. Session-only in effect — an API key can never authenticate as owner. While the tenant requires single sign-on, a new owner whose email is not on a verified domain answers 409 SSO_ENFORCED_OFF_DOMAIN.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"userId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"object","properties":{"previousOwner":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string","nullable":true},"email":{"type":"string"}}},"newOwner":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string","nullable":true},"email":{"type":"string"}}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postUsersByUserIdTransferOwnership","summary":"Transfer organization ownership to an active admin"}},"/api/v1/me":{"get":{"tags":["users"],"description":"Who is calling: the tenant id and the principal (an API key with its name and scopes, a signed-in person with their role, or a connected app acting for a person). Any valid credential may call it; no scope is required. MCP tool: whoami.","responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"tenantId":{"type":"string","format":"uuid"},"principalType":{"type":"string","enum":["api_key","user","oauth_app"],"description":"api_key: an X-API-Key. user: a signed-in person (session). oauth_app: a connected app acting for a person (MCP OAuth)."},"apiKey":{"type":["null","object"],"description":"The key behind the request (principalType api_key), else null.","properties":{"id":{"type":"string","format":"uuid"},"name":{"type":["null","string"]},"permissions":{"type":"array","items":{"type":"string"},"description":"Its scopes; [\"*\"] is full access."}}},"user":{"type":["null","object"],"description":"The person behind the request (principalType user or oauth_app), else null.","properties":{"id":{"type":"string","format":"uuid"},"role":{"type":["null","string"],"description":"Live role: owner, admin, operator or viewer."}}},"connectedApp":{"type":["null","object"],"description":"The connected app (principalType oauth_app), else null.","properties":{"clientId":{"type":["null","string"]},"name":{"type":["null","string"]},"scopes":{"type":"array","items":{"type":"string"}}}}},"required":["tenantId","principalType","apiKey","user","connectedApp"]}}}},"401":{"description":"No valid credential: UNAUTHORIZED. Send X-API-Key (or a web session); a revoked or expired key is refused the same way.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getMe","summary":"Who am I: the tenant and permissions of this credential"}},"/api/v1/tenants/{tenantId}/invitations/":{"post":{"tags":["invitations"],"description":"Invite a user to the tenant by email. Returns an invite link that works regardless of whether the invitation email actually sent. While the tenant requires single sign-on, inviting an admin whose email is not on a verified domain answers 409 SSO_ENFORCED_OFF_DOMAIN: they could never sign in.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"email":{"type":"string","format":"email"},"role":{"type":"string","enum":["admin","operator","viewer"],"default":"viewer"}},"required":["email"]}}}},"parameters":[{"schema":{"type":"string"},"in":"path","name":"tenantId","required":true}],"responses":{"201":{"description":"Created. The new resource is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"invitation":{"type":"object","properties":{"id":{"type":"string"},"email":{"type":"string"},"role":{"type":"string"},"expiresAt":{"type":"string","format":"date-time"},"createdAt":{"type":"string","format":"date-time"}}},"inviteUrl":{"type":"string","description":"The token is hashed at rest — this is the only response that ever carries the plaintext link"},"emailed":{"type":"boolean","description":"Whether the invitation email actually sent"},"message":{"type":"string"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postInvitations","summary":"Invite a user to the tenant by email"},"get":{"tags":["invitations"],"description":"List invitations for the tenant, including pending, expired and accepted ones. The token is hashed at rest, so a working invite link cannot be reconstructed here — POST /:id/resend is the only way to get a fresh one for an existing invitation.","parameters":[{"schema":{"type":"string"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string"},"email":{"type":"string"},"role":{"type":"string"},"expiresAt":{"type":"string","format":"date-time"},"acceptedAt":{"type":"string","format":"date-time","nullable":true},"createdAt":{"type":"string","format":"date-time"},"invitedByName":{"type":"string","nullable":true},"invitedByEmail":{"type":"string","nullable":true},"invitedByApiKeyName":{"type":"string","nullable":true}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"getInvitations","summary":"List invitations for the tenant, including pending, expired and accepted ones"}},"/api/v1/tenants/{tenantId}/invitations/{id}":{"delete":{"tags":["invitations"],"description":"Revoke a pending invitation. Has no effect on an already-accepted invitation.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"id","required":true}],"responses":{"204":{"description":"Invitation revoked successfully"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"deleteInvitationsById","summary":"Revoke a pending invitation"}},"/api/v1/tenants/{tenantId}/invitations/{id}/resend":{"post":{"tags":["invitations"],"description":"Reissue a pending invitation with a fresh token and a new 7-day expiry, and re-send the email. Use for an invitation that expired or is about to.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"id","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"invitation":{"type":"object","properties":{"id":{"type":"string"},"email":{"type":"string"},"role":{"type":"string"},"expiresAt":{"type":"string","format":"date-time"},"createdAt":{"type":"string","format":"date-time"}}},"inviteUrl":{"type":"string","description":"The token is hashed at rest — this is the only response that ever carries the plaintext link"},"emailed":{"type":"boolean","description":"Whether the invitation email actually sent"},"message":{"type":"string"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postInvitationsByIdResend","summary":"Resend invitation"}},"/api/v1/invitations/accept/{token}":{"get":{"tags":["invitations"],"description":"Validate an invitation token (public, no auth). Returns the invited email, role and tenant name for the invite-accept page to render; never returns the raw token. An invitation to a tenant that is being offboarded or has been offboarded is refused with 403 TENANT_OFFBOARDING or TENANT_OFFBOARDED; a suspended tenant still takes new members.","parameters":[{"schema":{"type":"string"},"in":"path","name":"token","required":true}],"security":[],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"email":{"type":"string"},"role":{"type":"string"},"tenantName":{"type":"string"},"sso":{"type":"object","description":"How the invitee signs in to accept. enabled: send them to the inviting tenant's IdP (tenantId). enforced: no magic link is offered. conflict: the email's domain enforces SSO for a different tenant, so this invitation cannot be accepted with that address.","properties":{"enabled":{"type":"boolean"},"enforced":{"type":"boolean"},"tenantId":{"type":["null","string"]},"conflict":{"type":"boolean"}},"required":["enabled","enforced","tenantId","conflict"]}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"}},"operationId":"getInvitationsAcceptByToken","summary":"Validate an invitation token (public, no auth)"}},"/api/v1/approve-links/{token}":{"get":{"tags":["approve-links"],"description":"Public, unauthenticated: the summary of the order an approve link points to (no tenant id — the token is the only proof of authorization). state is ready/expired/consumed/revoked. lines lists the order lines (sku, description, quantity, uom, unitPrice, lineTotal; at most 100, in line order) only while state is ready, so the person approving sees what they approve; it is empty for a link that can no longer approve. total is the order total (lines less their discounts plus the PO's charges), with linesTotal, charges, chargesTotal and orderTotal spelling it out; when a line has no price, orderTotal and linesTotal are null and total is the sum of the priced lines. reasons lists, while state is ready, the checks that did not pass (why the order stopped for a person), and each line says whether it is flagged.","parameters":[{"schema":{"type":"string","minLength":1},"in":"path","name":"token","required":true}],"security":[],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"envelopeId":{"type":"string"},"poNumber":{"type":"string","nullable":true},"customerName":{"type":"string"},"lineCount":{"type":"integer"},"total":{"type":"number","nullable":true},"currency":{"type":"string","nullable":true},"destination":{"type":"string","nullable":true},"expiresAt":{"type":"string"},"state":{"type":"string","enum":["ready","expired","consumed","revoked"]},"lines":{"type":"array","items":{"type":"object","properties":{"lineNumber":{"type":"integer"},"sku":{"type":"string"},"description":{"type":"string","nullable":true},"quantity":{"type":"number"},"uom":{"type":"string","nullable":true},"unitPrice":{"type":"number","nullable":true},"discount":{"type":"number","nullable":true,"description":"The line's printed discount; null when it has none."},"lineTotal":{"type":"number","nullable":true,"description":"round(quantity x unitPrice) less the line's discount, to the cent, as on the order page; null when the line has no price."},"flagged":{"type":"boolean"}},"required":["lineNumber","sku","description","quantity","uom","unitPrice","discount","lineTotal"]}},"linesTotal":{"type":"number","nullable":true},"charges":{"type":"array","items":{"type":"object","properties":{"type":{"type":"string","enum":["freight","discount","tax","handling","other"]},"amount":{"type":"number","description":"Positive magnitude; a discount reduces the total by it."},"description":{"type":"string","nullable":true}},"required":["type","amount","description"]}},"chargesTotal":{"type":"number"},"orderTotal":{"type":"number","nullable":true},"reasons":{"type":"array","items":{"type":"string"},"description":"The messages of the checks that did not pass, as the validators wrote them (for agents and logs)."},"checks":{"type":"array","description":"The checks that did not pass (at most five, failures first): validatorName, status (warn or fail), message and the validator's structured details. The approve page words them as the order page does.","items":{"type":"object","properties":{"validatorName":{"type":"string"},"status":{"type":"string","enum":["warn","fail"]},"message":{"type":"string"},"details":{"type":"object","additionalProperties":true}},"required":["validatorName","status","message","details"]}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"}},"operationId":"getApproveLinksByToken","summary":"Get approve link"},"post":{"tags":["approve-links"],"description":"Public, unauthenticated: redeem a single-use approve link. Approves the order it points to as-is, through the same approveOrder path the review page uses. 410 LINK_EXPIRED, 409 LINK_CONSUMED, 409 LINK_REVOKED, 404 otherwise. The approval can also be refused with the review route's own codes, e.g. 409 MULTI_PO_MERGED for an order that merged several purchase orders (never approvable; the reviewer rejects it). An order with something to acknowledge (lines with no catalog match, a customer not on the list, a PO number already received) is refused with 409 APPROVAL_NEEDS_ACKNOWLEDGEMENT and details.required naming each one; nothing is approved and the link stays usable. Resend with the optional body { acknowledge: { unmatchedLines, unknownCustomer, duplicatePo } } set to true for each, exactly as on POST /review/:envelopeId/approve. A body with any other property is refused with 400 VALIDATION_ERROR.","parameters":[{"schema":{"type":"string","minLength":1},"in":"path","name":"token","required":true}],"security":[],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"}},"operationId":"postApproveLinksByToken","summary":"Public, unauthenticated: redeem a single-use approve link"}},"/api/v1/tenants/{tenantId}/api-keys/":{"get":{"tags":["api-keys"],"description":"List API keys for the tenant. Never returns the full key value.","parameters":[{"schema":{"type":"string"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"prefix":{"type":"string"},"name":{"type":"string"},"status":{"type":"string","enum":["active","rotating","expired","revoked"],"description":"Derived from the stored state: revoked; expired (past expiresAt); rotating (rotated, still usable until its grace ends at expiresAt); active. Four values (earlier releases sent only active and revoked): only active and rotating keys authenticate, so a client looking for working keys keeps both."},"permissions":{"type":"array","items":{"type":"string"}},"expiresAt":{"type":"string","format":"date-time","nullable":true},"createdAt":{"type":"string","format":"date-time"},"lastUsedAt":{"type":"string","format":"date-time","nullable":true},"requestCount":{"type":"integer"},"revokedAt":{"type":"string","format":"date-time","nullable":true},"rotatedAt":{"type":"string","format":"date-time","nullable":true},"replacedByKeyId":{"type":"string","format":"uuid","nullable":true},"createdByUserId":{"type":"string","format":"uuid","nullable":true},"createdByName":{"type":"string","nullable":true},"createdByEmail":{"type":"string","nullable":true}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"listApiKeys","summary":"List API keys"},"post":{"tags":["api-keys"],"description":"Create a new API key. Returns the raw key value exactly once.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string","minLength":1,"maxLength":100},"permissions":{"type":"array","items":{"type":"string","enum":["*","api-keys:read","api-keys:write","audit:read","autonomy:read","autonomy:write","billing:read","billing:write","channels:read","channels:write","golden-data:read","golden-data:write","integrations:read","integrations:write","metrics:read","notifications:read","notifications:write","onboarding:read","onboarding:write","orders:read","orders:write","reference-data:read","reference-data:write","review:read","review:write","settings:read","settings:write","sso:read","sso:write","upload:write","users:read","users:write","webhooks:read","webhooks:write"]},"description":"Permission scopes, each \"resource:read\" or \"resource:write\". Omit for the integration default (submit and follow orders, review, read reference data; nothing on the admin plane). Pass [\"*\"] for full access."},"expiresAt":{"type":"string","format":"date-time","description":"When the key stops working. Must be in the future (a past time is refused with 400 VALIDATION_ERROR). Omit for a key that does not expire."}},"required":["name"]}}}},"parameters":[{"schema":{"type":"string"},"in":"path","name":"tenantId","required":true}],"responses":{"201":{"description":"Created. The new resource is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"apiKey":{"type":"string","description":"Full key value, only returned on creation"},"details":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"tenantId":{"type":"string","format":"uuid"},"prefix":{"type":"string"},"name":{"type":"string"},"status":{"type":"string"},"permissions":{"type":"array","items":{"type":"string"},"description":"The scopes the key was granted (the integration default when none were sent)."},"expiresAt":{"type":"string","format":"date-time","nullable":true},"createdAt":{"type":"string","format":"date-time"}}},"message":{"type":"string"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"createApiKey","summary":"Create an API key"}},"/api/v1/tenants/{tenantId}/api-keys/{keyId}/rotate":{"post":{"tags":["api-keys"],"description":"Rotate an API key: mints a replacement with the same name, permissions and expiry, then revokes the old one (or keeps it usable for an optional grace period, during which it lists as rotating). Returns the new raw key exactly once. A key is rotated at most once: rotating a key that was already rotated, is revoked or is past its expiry answers 409 INVALID_STATE with details.currentStatus and details.reason (already_rotated, revoked or expired), and mints nothing. For already_rotated, rotate the key in replacedByKeyId; for revoked or expired, create a new key. oldKeyStatus active_until_grace_period in the response is the state GET /api-keys lists as rotating.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"gracePeriodHours":{"type":"integer","minimum":0,"maximum":168,"default":0,"description":"Hours to keep the old key active after rotation; 0 revokes it immediately"}}}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"keyId","required":true}],"responses":{"201":{"description":"Created. The new resource is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"apiKey":{"type":"string","description":"Full new key value, only returned once"},"details":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"prefix":{"type":"string"},"name":{"type":"string"},"status":{"type":"string"},"expiresAt":{"type":"string","format":"date-time","nullable":true},"createdAt":{"type":"string","format":"date-time"}}},"oldKeyStatus":{"type":"string","enum":["active_until_grace_period","revoked"]},"message":{"type":"string"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"object","properties":{"code":{"type":"string"},"message":{"type":"string"},"correlationId":{"type":"string"},"details":{"type":"object","properties":{"currentStatus":{"type":"string","enum":["active","rotating","expired","revoked"]},"reason":{"type":"string","enum":["already_rotated","revoked","expired"]}}}}}}}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postApiKeysByKeyIdRotate","summary":"Rotate api key"}},"/api/v1/tenants/{tenantId}/api-keys/{keyId}/usage":{"get":{"tags":["api-keys"],"description":"Usage analytics for an API key: requests per day for the last 7 days, and the top 5 endpoints accessed.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"keyId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"daily":{"type":"array","items":{"type":"object","properties":{"date":{"type":"string","format":"date"},"requests":{"type":"integer"}}}},"topEndpoints":{"type":"array","items":{"type":"object","properties":{"method":{"type":"string"},"endpoint":{"type":"string"},"requests":{"type":"integer"}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getApiKeysByKeyIdUsage","summary":"Get usage of api key"}},"/api/v1/tenants/{tenantId}/api-keys/{keyId}":{"delete":{"tags":["api-keys"],"description":"Revoke an API key. Revoking the tenant's last usable key requires ?confirm=true (409 CONFIRMATION_REQUIRED without it). A key that is already revoked answers 409 INVALID_STATE with details.currentStatus; a key this tenant does not own answers 404. A rotating key can be revoked, which ends its grace period early.","parameters":[{"schema":{"type":"string","enum":["true"]},"in":"query","name":"confirm","required":false,"description":"Pass true to confirm revoking the tenant's last usable API key"},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"keyId","required":true}],"responses":{"204":{"description":"Key revoked successfully"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"object","properties":{"code":{"type":"string"},"message":{"type":"string"},"correlationId":{"type":"string"},"details":{"type":"object","properties":{"currentStatus":{"type":"string","enum":["active","rotating","expired","revoked"]}}}}}}}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"deleteApiKeysByKeyId","summary":"Revoke an API key"}},"/api/v1/tenants/{tenantId}/onboarding/chat":{"post":{"tags":["onboarding"],"description":"Conversational onboarding: send a message, get the assistant's reply and what it configured so far. Omit sessionId to start a session.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"message":{"type":"string","minLength":1,"maxLength":2000},"sessionId":{"type":"string","format":"uuid"}},"required":["message"]}}}},"parameters":[{"schema":{"type":"string"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"sessionId":{"type":"string","format":"uuid"},"response":{"type":"string"},"toolResults":{"type":"array","items":{"type":"object","additionalProperties":true}},"configuredSoFar":{"type":"object","additionalProperties":true},"isComplete":{"type":"boolean"}},"required":["sessionId","response","isComplete"]}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"postOnboardingChat","summary":"Create onboarding chat"}},"/api/v1/tenants/{tenantId}/onboarding/status":{"get":{"tags":["onboarding"],"description":"Onboarding progress: the wizard step, connected mailboxes, the forwarding address and whether mail delivery is configured.","parameters":[{"schema":{"type":"string"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"tenantName":{"type":"string"},"tenantStatus":{"type":"string"},"ownerName":{"type":"string","nullable":true},"ownerEmail":{"type":"string","nullable":true},"onboardingStatus":{"type":"string"},"currentStep":{"type":"string","nullable":true,"description":"Furthest wizard step saved so far."},"resumeStep":{"type":"string","description":"The wizard step to show next when setup is resumed. The wizard order is basics, documents, connect-inbox, destination, verify."},"deliveryChosen":{"type":"boolean","description":"A delivery choice was saved on the destination step (for a live connector, only once it is connected)."},"testFinished":{"type":"boolean","description":"The verify (test) step was left, by finishing or skipping it."},"skippedInbox":{"type":"boolean"},"completedAt":{"type":"string","nullable":true},"intakeAddress":{"type":"string","nullable":true},"forwardingConfirmation":{"type":"object","nullable":true,"additionalProperties":true},"connectedProviders":{"type":"array","items":{"type":"object","properties":{"provider":{"type":"string"},"status":{"type":"string"}}}},"envelopeCount":{"type":"integer","description":"Documents received through any channel, the sample upload included."},"inboxEnvelopeCount":{"type":"integer","description":"Documents received through a mailbox (email, Gmail or Microsoft 365 channel). The wizard says the inbox is connected only when this is above zero."},"latestEnvelopeAt":{"type":"string","nullable":true},"mailDeliveryConfigured":{"type":"boolean"},"onboardingEmails":{"type":"array","description":"The trial onboarding email sequence: one entry per step, in order, with whether it was sent. A step is sent at most once; not_sent covers both not due yet and skipped because the step was already done.","items":{"type":"object","properties":{"step":{"type":"string","enum":["connect_inbox","forward_first_order","review_first_order","connect_destination","offer_help"]},"status":{"type":"string","enum":["not_sent","sending","sent","failed"]},"sentAt":{"type":"string","nullable":true}}}}},"additionalProperties":true}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"getOnboardingStatus","summary":"Get onboarding status"}},"/api/v1/tenants/{tenantId}/onboarding/guided":{"post":{"tags":["onboarding"],"description":"Advance the guided onboarding wizard one step. `step` is one of basics, documents, connect-inbox, destination, verify, done, in the order the wizard shows them: delivery comes before the test, so the first order is read after the catalog is connected. `nextStep` names the one that follows. `done` is accepted once the saved step is destination or verify, or connect-inbox with `skippedInbox`. On `basics`, `data.minutesPerOrder` (minutes to key one order today, up to 120) and `data.laborRatePerHour` (loaded hourly cost of that person, up to 1000) are required unless the tenant already set them (settings.trustBaseline); time saved is measured against them. The API assumes no default; the web wizard shows typical values pre-filled for the person to keep or change. On `verify`, `data.skippedTest` (boolean, optional) records leaving the test step, so a resumed setup does not ask for the test again. On `documents`, `data.documentTypes` is a non-empty array of 'purchase_order' and/or 'supplier_invoice'. When it is ['supplier_invoice'] alone, finishing (`done`) marks every active channel as an invoice channel (`config.documentTypeDefault: 'invoice'`), and channels the system creates afterwards for that tenant (the shared email inbox, the upload channel, a Gmail or Microsoft 365 mailbox connected later) start as invoice channels too. Email (IMAP, Gmail, Microsoft 365), SFTP and upload channels all read invoices this way. A channel carries one document type: with both selected, channels stay 'order' and a channel is switched to invoices with PATCH /tenants/{tenantId}/channels/{channelId} (`config.documentTypeDefault`) or per upload with the upload route's `documentType` field.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"step":{"type":"string","enum":["basics","documents","connect-inbox","destination","verify","done"]},"data":{"type":"object","additionalProperties":true,"default":{}}},"required":["step"]}}}},"parameters":[{"schema":{"type":"string"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"nextStep":{"type":"string","nullable":true},"configuredSoFar":{"type":"object","additionalProperties":true},"isComplete":{"type":"boolean"},"tenantStatus":{"type":"string","nullable":true,"description":"On `done`: the tenant's status afterwards. Finishing moves only an `onboarding` tenant to `active`; any other status is left as it was."},"statusChanged":{"type":"boolean","description":"On `done`: whether finishing moved the tenant from onboarding to active."}},"additionalProperties":true}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"postOnboardingGuided","summary":"Advance the guided onboarding wizard one step"}},"/api/v1/tenants/{tenantId}/audit/":{"get":{"tags":["audit"],"description":"List audit log entries with pagination and optional filters","parameters":[{"schema":{"type":"integer","minimum":1,"default":1},"in":"query","name":"page","required":false,"description":"Page number (1-based)"},{"schema":{"type":"integer","minimum":1,"maximum":200},"in":"query","name":"pageSize","required":false,"description":"Items per page (default 20, max 200)"},{"schema":{"type":"integer","minimum":1},"in":"query","name":"limit","required":false,"description":"Deprecated alias of pageSize, clamped to 200. Accepted for one release."},{"schema":{"type":"integer","minimum":0},"in":"query","name":"offset","required":false,"description":"Deprecated: rows to skip. Takes precedence over page when both are sent. Accepted for one release."},{"schema":{"type":"string"},"in":"query","name":"action","required":false,"description":"Filter by action (e.g. \"order.submitted\", \"api_key.created\")"},{"schema":{"type":"string"},"in":"query","name":"actorType","required":false,"description":"Filter by actor type (e.g. \"api_key\", \"user\", \"system\")"},{"schema":{"type":"string","format":"date-time"},"in":"query","name":"startDate","required":false,"description":"Include entries created at or after this ISO 8601 timestamp"},{"schema":{"type":"string","format":"date-time"},"in":"query","name":"endDate","required":false,"description":"Include entries created at or before this ISO 8601 timestamp"},{"schema":{"type":"string","maxLength":200},"in":"query","name":"search","required":false,"description":"Case-insensitive substring match on action, or an exact envelope id when the value is a UUID. The paged list no longer searches the metadata JSON; GET /:entryId shows an entry's full metadata."},{"schema":{"type":"string","format":"uuid"},"in":"query","name":"envelopeId","required":false,"description":"Only entries for this envelope"},{"schema":{"type":"string","format":"date-time"},"in":"query","name":"createdBefore","required":false,"description":"Keyset paging. Only entries created strictly before this instant; page x pageSize may not exceed 10,000 (400 PAGE_TOO_DEEP)."},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"envelopeId":{"type":"string","format":"uuid","nullable":true},"tenantId":{"type":"string","format":"uuid"},"action":{"type":"string"},"actor":{"type":"string"},"actorType":{"type":"string"},"beforeState":{"type":"object","nullable":true,"additionalProperties":true},"afterState":{"type":"object","nullable":true,"additionalProperties":true},"metadata":{"type":"object","additionalProperties":true},"createdAt":{"type":"string","format":"date-time"},"ipAddress":{"type":"string","nullable":true},"userAgent":{"type":"string","nullable":true}}}},"pagination":{"type":"object","properties":{"page":{"type":"integer"},"pageSize":{"type":"integer"},"total":{"type":"integer"},"totalPages":{"type":"integer"},"estimated":{"type":"boolean","description":"True when total is the planner's estimate (sets past 10,000 rows)."}}}}}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"object","properties":{"code":{"type":"string"},"message":{"type":"string"},"details":{"type":"object","additionalProperties":true}}}}}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"getAudit","summary":"List audit log entries with pagination and optional filters"}},"/api/v1/tenants/{tenantId}/audit/export":{"get":{"tags":["audit"],"description":"Export the audit log as NDJSON (application/x-ndjson), oldest first, one entry per line with the fields of GET /audit/:entryId. X-Next-Cursor carries the id of the last entry when more may follow; send it back as `after`. Absent means the export is complete up to now.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"query","name":"after","required":false,"description":"Cursor: the id of the last entry already read (X-Next-Cursor of the previous call)."},{"schema":{"type":"integer","minimum":1,"maximum":10000,"default":1000},"in":"query","name":"limit","required":false,"description":"Entries per call (max 10000)."},{"schema":{"type":"string","maxLength":100},"in":"query","name":"action","required":false,"description":"Only this action"},{"schema":{"type":"string","format":"date-time"},"in":"query","name":"startDate","required":false,"description":"Entries created at or after this instant"},{"schema":{"type":"string","format":"date-time"},"in":"query","name":"endDate","required":false,"description":"Entries created at or before this instant"},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/x-ndjson":{"schema":{"type":"object","properties":{"error":{"type":"object","properties":{"code":{"type":"string","description":"A machine-readable code from the error-code catalogue (the enum on the Error schema in the published spec)."},"message":{"type":"string","description":"One sentence for a person."},"details":{"description":"Structured facts about the refusal. For VALIDATION_ERROR always an array of { path, message, code }, on every route: path names the request part first, then dots, with an index in brackets (body.config.imapHost, body.lines[0].sku, querystring.status); code is the rule that failed (required, enum, type, format, invalid,...); an entry may carry extra keys of its own. For a 409 gate, what to resend.","anyOf":[{"type":"object","additionalProperties":true},{"type":"array","items":{"type":"object","additionalProperties":true}}]},"correlationId":{"type":"string","description":"The request id (or envelope/order id) to quote to support."}},"required":["code","message"]}},"required":["error"]}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/x-ndjson":{"schema":{"type":"object","properties":{"error":{"type":"object","properties":{"code":{"type":"string","description":"A machine-readable code from the error-code catalogue (the enum on the Error schema in the published spec)."},"message":{"type":"string","description":"One sentence for a person."},"details":{"description":"Structured facts about the refusal. For VALIDATION_ERROR always an array of { path, message, code }, on every route: path names the request part first, then dots, with an index in brackets (body.config.imapHost, body.lines[0].sku, querystring.status); code is the rule that failed (required, enum, type, format, invalid,...); an entry may carry extra keys of its own. For a 409 gate, what to resend.","anyOf":[{"type":"object","additionalProperties":true},{"type":"array","items":{"type":"object","additionalProperties":true}}]},"correlationId":{"type":"string","description":"The request id (or envelope/order id) to quote to support."}},"required":["code","message"]}},"required":["error"]}}}}},"operationId":"getAuditExport","summary":"Get audit export"}},"/api/v1/tenants/{tenantId}/audit/{entryId}":{"get":{"tags":["audit"],"description":"Get a single audit log entry by ID","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"entryId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"envelopeId":{"type":"string","format":"uuid","nullable":true},"tenantId":{"type":"string","format":"uuid"},"action":{"type":"string"},"actor":{"type":"string"},"actorType":{"type":"string"},"beforeState":{"type":"object","nullable":true,"additionalProperties":true},"afterState":{"type":"object","nullable":true,"additionalProperties":true},"metadata":{"type":"object","additionalProperties":true},"createdAt":{"type":"string","format":"date-time"},"ipAddress":{"type":"string","nullable":true},"userAgent":{"type":"string","nullable":true}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getAuditByEntryId","summary":"Get a single audit log entry by ID"}},"/api/v1/tenants/{tenantId}/billing/":{"get":{"tags":["billing"],"description":"The current subscription and its plan; subscription is null before checkout.","parameters":[{"schema":{"type":"string"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"subscription":{"type":"object","nullable":true,"additionalProperties":true,"properties":{"id":{"type":"string"},"status":{"type":"string"},"planName":{"type":"string"},"planSlug":{"type":"string"},"currentPeriodStart":{"type":"string","nullable":true},"currentPeriodEnd":{"type":"string","nullable":true},"trialEnd":{"type":"string","nullable":true},"cancelAtPeriodEnd":{"type":"boolean"},"envelopeLimit":{"type":"integer","nullable":true},"userLimit":{"type":"integer","nullable":true},"monthlyPriceCents":{"type":"integer"},"overagePriceCents":{"type":"integer","nullable":true},"includedAutoApprovals":{"type":"integer","nullable":true,"description":"Deprecated alias of includedOrders, kept for existing clients."},"includedOrders":{"type":"integer","nullable":true,"description":"Orders the monthly fee includes, counted in billingUnit. Null = unlimited."},"billingUnit":{"type":"string","enum":["processed","auto_approved"],"description":"processed: every purchase order approved counts, unattended or by a person. auto_approved: only orders approved without a person count (plans retired)."},"overageBilling":{"type":"boolean"},"planChange":{"type":"string","enum":["in_app","checkout"],"description":"in_app: change plan with POST /billing/change-plan. checkout: start a new subscription with POST /billing/checkout."},"features":{"type":"object","additionalProperties":true}}},"checkoutTrial":{"type":"object","description":"What a checkout started now gives: a full trial, the days left on a card-less trial, or billing from today.","properties":{"trial":{"type":"string","enum":["full","remaining","none"]},"trialDays":{"type":"integer","nullable":true},"trialEnd":{"type":"string","nullable":true}},"required":["trial"]}},"required":["subscription","checkoutTrial"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"getBilling","summary":"The current subscription and its plan; subscription is null before checkout"}},"/api/v1/tenants/{tenantId}/billing/usage":{"get":{"tags":["billing"],"description":"Usage in the current billing period: envelopes against the plan ceiling, order outcomes, and the overage estimate.","parameters":[{"schema":{"type":"string"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"currentPeriod":{"type":"object","properties":{"start":{"type":"string","nullable":true},"end":{"type":"string","nullable":true}},"additionalProperties":true},"envelopes":{"type":"object","additionalProperties":true},"orders":{"type":"object","additionalProperties":true},"overage":{"type":"object","additionalProperties":true}},"additionalProperties":true}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"getBillingUsage","summary":"Get billing usage"}},"/api/v1/tenants/{tenantId}/billing/plans":{"get":{"tags":["billing"],"description":"The active plan catalogue. contactSales plans have no self-serve checkout.","parameters":[{"schema":{"type":"string"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"type":"object","properties":{"slug":{"type":"string"},"name":{"type":"string"},"monthlyPriceCents":{"type":"integer"},"envelopeLimit":{"type":"integer","nullable":true},"userLimit":{"type":"integer","nullable":true},"includedAutoApprovals":{"type":"integer","nullable":true},"includedOrders":{"type":"integer","nullable":true},"billingUnit":{"type":"string","enum":["processed","auto_approved"]},"overagePriceCents":{"type":"integer","nullable":true},"features":{"type":"object","additionalProperties":true},"isActive":{"type":"boolean"},"contactSales":{"type":"boolean"}},"additionalProperties":true}}},"required":["data"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"getBillingPlans","summary":"The active plan catalogue"}},"/api/v1/tenants/{tenantId}/billing/checkout":{"post":{"tags":["billing"],"description":"Create a Stripe Checkout session for a self-serve plan; a person opens the returned url. Same-origin successUrl/cancelUrl only.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"planSlug":{"type":"string","enum":["starter-2026","core-2026","growth-2026","scale-2026"]},"successUrl":{"type":"string","format":"uri"},"cancelUrl":{"type":"string","format":"uri"}},"required":["planSlug"]}}}},"parameters":[{"schema":{"type":"string"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"url":{"type":"string","nullable":true}},"required":["url"]}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"402":{"description":"The plan does not allow this: SUBSCRIPTION_REQUIRED (no active subscription) or PLAN_LIMIT_EXCEEDED (details.resource names the limit).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"postBillingCheckout","summary":"Create a Stripe Checkout session for a self-serve plan; a person opens the returned url"}},"/api/v1/tenants/{tenantId}/billing/checkout/confirm":{"post":{"tags":["billing"],"description":"Confirm a completed Stripe Checkout by its session id (the session_id Stripe appends to the success URL). Records the subscription if the webhook has not yet. confirmed=false means the checkout is not finished; try again shortly.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"sessionId":{"type":"string","pattern":"^cs_[A-Za-z0-9_]+$","maxLength":255}},"required":["sessionId"]}}}},"parameters":[{"schema":{"type":"string"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"confirmed":{"type":"boolean"},"subscriptionStatus":{"type":"string","nullable":true}},"required":["confirmed","subscriptionStatus"]}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"502":{"description":"An upstream provider (an accounting system, store or mailbox) answered with an error; details says which.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"postBillingCheckoutConfirm","summary":"Create billing checkout confirm"}},"/api/v1/tenants/{tenantId}/billing/change-plan":{"post":{"tags":["billing"],"description":"Move the current subscription to another self-serve plan. Applies now; Stripe prorates the monthly fee for the days left in the period (an upgrade adds the difference to the next bill, a downgrade credits it). Answers 409 PLAN_CHANGE_NEEDS_CHECKOUT when there is no paid subscription to change — use POST /billing/checkout.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"planSlug":{"type":"string","enum":["starter-2026","core-2026","growth-2026","scale-2026"]}},"required":["planSlug"]}}}},"parameters":[{"schema":{"type":"string"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"changed":{"type":"boolean","description":"False when the tenant was already on this plan."},"plan":{"type":"object","properties":{"slug":{"type":"string"},"name":{"type":"string"},"monthlyPriceCents":{"type":"integer"},"includedAutoApprovals":{"type":"integer","nullable":true},"overagePriceCents":{"type":"integer","nullable":true}},"required":["slug","name","monthlyPriceCents"]},"effective":{"type":"string","enum":["now"]},"proration":{"type":"string","enum":["create_prorations"]}},"required":["changed","plan","effective","proration"]}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"502":{"description":"An upstream provider (an accounting system, store or mailbox) answered with an error; details says which.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"postBillingChangePlan","summary":"Move the current subscription to another self-serve plan"}},"/api/v1/tenants/{tenantId}/billing/portal":{"post":{"tags":["billing"],"description":"Create a Stripe Customer Portal session; a person opens the returned url.","parameters":[{"schema":{"type":"string"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"url":{"type":"string","nullable":true}},"required":["url"]}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"postBillingPortal","summary":"Create a Stripe Customer Portal session; a person opens the returned url"}},"/api/v1/tenants/{tenantId}/billing/entitlements":{"get":{"tags":["billing"],"description":"Plan entitlements and current usage against each limit","parameters":[{"schema":{"type":"string"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"plan":{"type":"string","nullable":true},"planName":{"type":"string","nullable":true},"entitlements":{"type":"object","properties":{"maxActiveDestinations":{"type":"number","nullable":true},"maxStorefrontsPerType":{"type":"number","nullable":true},"maxRoutingRules":{"type":"number","nullable":true},"fanOut":{"type":"boolean"},"invoiceWriteBack":{"type":"boolean"},"channels":{"type":"array","items":{"type":"string"}},"sso":{"type":"boolean","description":"Whether the plan includes setting up single sign-on (Growth, Scale, Enterprise). Absent permits."}},"additionalProperties":true},"usage":{"type":"object","properties":{"activeDestinations":{"type":"number"},"storefrontsPerType":{"type":"object","additionalProperties":true},"routingRules":{"type":"number"}}},"suspended":{"type":"object","properties":{"connectors":{"type":"array","items":{"type":"object","properties":{"connectorId":{"type":"string"},"connectorType":{"type":"string"},"label":{"type":"string","nullable":true},"suspendedAt":{"type":"string","nullable":true},"reason":{"type":"string","nullable":true}}}},"rules":{"type":"array","items":{"type":"object","properties":{"ruleId":{"type":"string"},"name":{"type":"string"},"suspendedAt":{"type":"string","nullable":true},"reason":{"type":"string","nullable":true}}}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"getBillingEntitlements","summary":"Plan entitlements and current usage against each limit"}},"/api/v1/tenants/{tenantId}/reference-data/sync-config":{"get":{"tags":["reference-data"],"description":"Get reference data sync configuration","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getReferenceDataSyncConfig","summary":"Get reference data sync configuration"},"put":{"tags":["reference-data"],"description":"Create or update reference data sync configuration","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"connectorType":{"type":"string","enum":["netsuite","shopify","quickbooks"]},"config":{"type":"object","additionalProperties":true},"syncScheduleCron":{"type":"string","nullable":true},"syncEnabled":{"type":"boolean"}},"required":["connectorType"]}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"putReferenceDataSyncConfig","summary":"Create or update reference data sync configuration"}},"/api/v1/tenants/{tenantId}/reference-data/sync":{"post":{"tags":["reference-data"],"description":"Queue a manual reference data sync. Answers 202 at once; the reference-sync worker starts the run within about a minute under the same per-connector lock the schedule uses. Poll `statusUrl` (GET /reference-data/sync/status) for lastSyncAt, lastSyncStatus and lastSyncStats. A request made while a run is in progress is kept and answered by a further run once it finishes (`runInProgress: true`).","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postReferenceDataSync","summary":"Queue a manual reference data sync"}},"/api/v1/tenants/{tenantId}/reference-data/sync/status":{"get":{"tags":["reference-data"],"description":"Get each connection's sync status and data freshness, and the active customer and product totals. Freshness is measured from the last successful sync: fresh (< 1 hour), hours_old (< 1 day), stale (a day old, or the latest attempt failed; staleSince says since when) or never. totals.byConnector breaks the totals down per connection; the all-zeros connectorId is CSV-uploaded rows.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getReferenceDataSyncStatus","summary":"Get reference data sync status"}},"/api/v1/tenants/{tenantId}/reference-data/retire-csv":{"post":{"tags":["reference-data"],"description":"Deactivate customers and products that came from CSV uploads, once a connected system supplies them instead. Rows are kept (past orders reference them) but stop matching.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"customersRetired":{"type":"integer"},"productsRetired":{"type":"integer"}},"required":["customersRetired","productsRetired"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postReferenceDataRetireCsv","summary":"Create reference data retire csv"}},"/api/v1/tenants/{tenantId}/reference-data/customers":{"get":{"tags":["reference-data"],"description":"List reference customers (paginated, searchable). Each row names the connection it was synced from (connectorLabel, connectorType); total counts every matching row. Filter to one store or company with connectorId (the all-zeros id is CSV-uploaded rows).","parameters":[{"schema":{"type":"string"},"in":"query","name":"search","required":false},{"schema":{"type":"integer","minimum":1,"default":1},"in":"query","name":"page","required":false,"description":"Page number (1-based)"},{"schema":{"type":"integer","minimum":1,"maximum":200},"in":"query","name":"pageSize","required":false,"description":"Items per page (default 50, max 200)"},{"schema":{"type":"integer","minimum":1},"in":"query","name":"limit","required":false,"description":"Deprecated alias of pageSize, clamped to 200. Accepted for one release."},{"schema":{"type":"integer","minimum":0},"in":"query","name":"offset","required":false,"description":"Deprecated: rows to skip. Takes precedence over page when both are sent. Accepted for one release."},{"schema":{"type":"boolean","default":false},"in":"query","name":"activeOnly","required":false},{"schema":{"type":"string","pattern":"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"},"in":"query","name":"connectorId","required":false},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","description":"Customers, each with the connection it came from.","items":{"type":"object","additionalProperties":true,"properties":{"connectorId":{"type":"string"},"connectorLabel":{"type":"string","nullable":true,"description":"The store or company this row was synced from, by its current name. Null for CSV-uploaded rows."},"connectorType":{"type":"string","nullable":true,"description":"shopify | quickbooks | netsuite; null for CSV-uploaded rows."}}}},"pagination":{"type":"object","properties":{"page":{"type":"integer"},"pageSize":{"type":"integer"},"total":{"type":"integer"},"totalPages":{"type":"integer"}},"required":["page","pageSize","total","totalPages"]},"total":{"type":"integer","description":"Rows matching the filters across every page, not the length of this page. Deprecated: pagination.total; kept for one release."},"limit":{"type":"integer","description":"Deprecated: pagination.pageSize. Kept for one release."},"offset":{"type":"integer","description":"Deprecated. Kept for one release."}},"required":["data","pagination","total","limit","offset"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getReferenceDataCustomers","summary":"List reference customers (paginated, searchable)"},"post":{"tags":["reference-data"],"description":"Add one reference customer by hand, without a file. It is stored as an uploaded customer (the same source a CSV import uses), so a later upload with the same customer number updates it. `name` is required; `sourceId` is your customer number and is generated when left out. Sender domains are checked exactly as on PATCH: a value that is not a domain, or a public email provider such as gmail.com, is refused with 400 VALIDATION_ERROR and nothing is written. An active customer with the same name (ignoring case), or an uploaded customer with the same sourceId, is refused with 409 CONFLICT naming the field, rather than overwritten. A property other than name, sourceId, aliases and senderDomains (a typo such as emailDomains) is refused with 400 VALIDATION_ERROR, details naming each one, and nothing is written; it used to be dropped silently. Writes one reference_data.customer_created audit row.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":true,"required":["name"],"properties":{"name":{"type":"string","minLength":1,"maxLength":500,"description":"The customer's name as it appears on their orders."},"sourceId":{"type":"string","minLength":1,"maxLength":255,"description":"Your customer number or account id for them. Optional."},"aliases":{"type":"array","maxItems":100,"items":{"type":"string","maxLength":500},"description":"Other names the customer uses on documents; trimmed and de-duplicated ignoring case."},"senderDomains":{"type":"array","maxItems":50,"items":{"type":"string","maxLength":320},"description":"Email domains this customer sends orders from, such as acme.com."}}}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"201":{"description":"The customer as stored.","content":{"application/json":{"schema":{"description":"The customer as stored.","type":"object","additionalProperties":true,"properties":{"id":{"type":"string"},"name":{"type":"string"},"sourceId":{"type":"string"},"sourceSystem":{"type":"string"},"connectorId":{"type":"string"},"senderDomains":{"type":"array","items":{"type":"string"}},"aliases":{"type":"array","items":{"type":"string"}},"isActive":{"type":"boolean"}},"required":["id","name","sourceId","senderDomains","aliases"]}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postReferenceDataCustomers","summary":"Add one reference customer by hand, without a file"},"delete":{"tags":["reference-data"],"description":"Clear all reference customers for this tenant, from every source (connected systems and CSV uploads), for a re-sync. Rows from a connected system return on its next sync; CSV-uploaded rows and edits made here do not. Writes one reference_data.cleared audit row with the rows deleted per source, in the same transaction.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"deleteReferenceDataCustomers","summary":"Delete reference data customers"}},"/api/v1/tenants/{tenantId}/reference-data/customers/{customerId}":{"patch":{"tags":["reference-data"],"description":"Edit one reference customer's name, sender domains and aliases in place, whether it was synced from a connection or uploaded. A name is trimmed and must not be empty; a connection that supplies the customer may rename it again on its next sync. Each list given replaces the stored one (send [] to clear it); a list left out is unchanged. Domains are reduced to the bare host (\"https://Acme.com/x\", \"buyer@acme.com\" and \"@acme.com\" all become \"acme.com\"), lower-cased and de-duplicated; a value that is not a domain, or a public email provider such as gmail.com, is refused with 400 VALIDATION_ERROR and nothing is written. A later sync keeps the edited domains when the source sends none, and merges its own aliases with these.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"minProperties":1,"properties":{"name":{"type":"string","minLength":1,"maxLength":500,"description":"The customer's name as you want it shown and matched. Trimmed; inner spaces collapsed."},"senderDomains":{"type":"array","maxItems":50,"items":{"type":"string","maxLength":320},"description":"Email domains this customer sends orders from, such as acme.com. Replaces the stored list."},"aliases":{"type":"array","maxItems":100,"items":{"type":"string","maxLength":500},"description":"Other names the customer uses on documents. Replaces the stored list; trimmed and de-duplicated ignoring case."}}}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"customerId","required":true}],"responses":{"200":{"description":"The customer as stored after the edit.","content":{"application/json":{"schema":{"description":"The customer as stored after the edit.","type":"object","additionalProperties":true,"properties":{"id":{"type":"string"},"name":{"type":"string"},"sourceId":{"type":"string"},"sourceSystem":{"type":"string"},"connectorId":{"type":"string"},"senderDomains":{"type":"array","items":{"type":"string"}},"aliases":{"type":"array","items":{"type":"string"}},"isActive":{"type":"boolean"}},"required":["id","name","senderDomains","aliases"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"patchReferenceDataCustomersByCustomerId","summary":"Update reference data customer"}},"/api/v1/tenants/{tenantId}/reference-data/products":{"get":{"tags":["reference-data"],"description":"List reference products (paginated, searchable). Each row names the connection it was synced from (connectorLabel, connectorType): the same SKU synced from two stores or companies is two rows with their own prices. total counts every matching row. Filter to one store or company with connectorId (the all-zeros id is CSV-uploaded rows).","parameters":[{"schema":{"type":"string"},"in":"query","name":"search","required":false},{"schema":{"type":"integer","minimum":1,"default":1},"in":"query","name":"page","required":false,"description":"Page number (1-based)"},{"schema":{"type":"integer","minimum":1,"maximum":200},"in":"query","name":"pageSize","required":false,"description":"Items per page (default 50, max 200)"},{"schema":{"type":"integer","minimum":1},"in":"query","name":"limit","required":false,"description":"Deprecated alias of pageSize, clamped to 200. Accepted for one release."},{"schema":{"type":"integer","minimum":0},"in":"query","name":"offset","required":false,"description":"Deprecated: rows to skip. Takes precedence over page when both are sent. Accepted for one release."},{"schema":{"type":"boolean","default":true},"in":"query","name":"activeOnly","required":false},{"schema":{"type":"string","pattern":"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"},"in":"query","name":"connectorId","required":false},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","description":"Products, each with the connection it came from.","items":{"type":"object","additionalProperties":true,"properties":{"connectorId":{"type":"string"},"connectorLabel":{"type":"string","nullable":true,"description":"The store or company this row was synced from, by its current name. Null for CSV-uploaded rows."},"connectorType":{"type":"string","nullable":true,"description":"shopify | quickbooks | netsuite; null for CSV-uploaded rows."}}}},"pagination":{"type":"object","properties":{"page":{"type":"integer"},"pageSize":{"type":"integer"},"total":{"type":"integer"},"totalPages":{"type":"integer"}},"required":["page","pageSize","total","totalPages"]},"total":{"type":"integer","description":"Rows matching the filters across every page, not the length of this page. Deprecated: pagination.total; kept for one release."},"limit":{"type":"integer","description":"Deprecated: pagination.pageSize. Kept for one release."},"offset":{"type":"integer","description":"Deprecated. Kept for one release."}},"required":["data","pagination","total","limit","offset"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getReferenceDataProducts","summary":"List reference products (paginated, searchable)"},"delete":{"tags":["reference-data"],"description":"Clear all reference products for this tenant, from every source (connected systems and CSV uploads), for a re-sync. Rows from a connected system return on its next sync; CSV-uploaded rows and edits made here do not. Writes one reference_data.cleared audit row with the rows deleted per source, in the same transaction.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"deleteReferenceDataProducts","summary":"Delete reference data products"}},"/api/v1/tenants/{tenantId}/reference-data/upload/{kind}/preview":{"post":{"tags":["reference-data"],"description":"Preview a reference-data CSV: proposed column mapping, sample rows, duplicate conflicts","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","enum":["products","customers","cross-references"]},"in":"path","name":"kind","required":true}],"responses":{"200":{"description":"The proposed column mapping, sample rows and duplicate-key conflicts.","content":{"application/json":{"schema":{"description":"The proposed column mapping, sample rows and duplicate-key conflicts."}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postReferenceDataUploadByKindPreview","summary":"Preview a reference-data CSV: proposed column mapping, sample rows, duplicate conflicts"}},"/api/v1/tenants/{tenantId}/reference-data/cross-references":{"post":{"tags":["reference-data"],"description":"Import customer part-number cross references (their part number → your SKU) as JSON. Lands as partner-scoped active mapping rules, so the resolver prefers them over tenant-wide ones. Rows naming a customer or SKU the tenant does not have are reported with their position, never created. Returns per-row outcomes.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["records"],"properties":{"records":{"type":"array","minItems":1,"maxItems":5000,"items":{"type":"object","required":["customerRef","customerPartNumber","sku"],"properties":{"customerRef":{"type":"string","description":"The trading partner, matched by account number first and then by name."},"customerPartNumber":{"type":"string","description":"The part number as that customer writes it on their purchase orders."},"sku":{"type":"string","description":"The canonical SKU in your catalog."}}}}}}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postReferenceDataCrossReferences","summary":"Import customer part-number cross references (their part number → your SKU) as JSON"}},"/api/v1/tenants/{tenantId}/reference-data/upload/cross-references":{"post":{"tags":["reference-data"],"description":"Bulk upload customer part-number cross references (their part number → your SKU) as CSV, XLSX or JSON. Lands as partner-scoped active mapping rules. Rows naming an unknown customer or SKU are reported, never invented.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"Per-row import outcomes and the number of rows read.","content":{"application/json":{"schema":{"description":"Per-row import outcomes and the number of rows read."}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postReferenceDataUploadCrossReferences","summary":"Create reference data upload cross reference"}},"/api/v1/tenants/{tenantId}/reference-data/upload/customers":{"post":{"tags":["reference-data"],"description":"Bulk upload reference customers via CSV, Excel (.xlsx) or JSON. Sender domains (a `sender_domains` column, semicolon- or comma-separated, or `senderDomains` in JSON) are stored as bare domains; a value that is not a domain, or is a public email provider, is listed in `domainProblems` on the answer and not stored, and its row is still imported.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"The import counts, and any sender domains that were not stored (`domainProblems`).","content":{"application/json":{"schema":{"description":"The import counts, and any sender domains that were not stored (`domainProblems`)."}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postReferenceDataUploadCustomers","summary":"Bulk upload reference customers via CSV, Excel (.xlsx) or JSON"}},"/api/v1/tenants/{tenantId}/reference-data/upload/products":{"post":{"tags":["reference-data"],"description":"Bulk upload reference products via CSV, Excel (.xlsx) or JSON. A file of up to 5,000 products is imported at once and answered 200 with imported, deduped, orphaned and orphanedSkus. A larger file (more than 5,000 products, or over 1024 KB) is loaded in the background: the answer is 202 with an importId and a statusUrl (GET /reference-data/imports/:importId) to poll for progress and the same counts when it finishes. Either way the whole file lands in one transaction, or none of it does. Form fields: `mapping` (JSON column mapping from the preview), `complete` (\"true\" when the file is the whole product master).","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"imported":{"type":"integer"},"deduped":{"type":"integer"},"orphaned":{"type":"integer"},"orphanedSkus":{"type":"array","items":{"type":"string"}}},"required":["imported","deduped","orphaned","orphanedSkus"]}}}},"202":{"description":"Accepted. Processing continues in the background; follow it with the id in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"importId":{"type":"string","format":"uuid"},"kind":{"type":"string","enum":["products"]},"status":{"type":"string","enum":["queued","running","succeeded","failed"]},"filename":{"type":"string"},"rowsTotal":{"type":"integer","nullable":true,"description":"Products found in the file; null until the worker has read it."},"rowsDone":{"type":"integer","description":"Products saved so far."},"result":{"type":"object","nullable":true,"description":"Set once the upload succeeds: the same counts an inline upload answers with.","properties":{"imported":{"type":"integer"},"deduped":{"type":"integer"},"orphaned":{"type":"integer"},"orphanedSkus":{"type":"array","items":{"type":"string"}}}},"message":{"type":"string","description":"What is happening or what happened, in plain English, ready to show a person."},"statusUrl":{"type":"string"},"createdAt":{"type":"string","format":"date-time"},"startedAt":{"type":"string","format":"date-time","nullable":true},"finishedAt":{"type":"string","format":"date-time","nullable":true}},"required":["importId","kind","status","filename","rowsTotal","rowsDone","result","message","statusUrl","createdAt","startedAt","finishedAt"]}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postReferenceDataUploadProducts","summary":"Bulk upload reference products via CSV, Excel (.xlsx) or JSON"}},"/api/v1/tenants/{tenantId}/reference-data/imports":{"get":{"tags":["reference-data"],"description":"The ten most recent background product uploads, newest first, each with its status and a plain-English message.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"type":"object","properties":{"importId":{"type":"string","format":"uuid"},"kind":{"type":"string","enum":["products"]},"status":{"type":"string","enum":["queued","running","succeeded","failed"]},"filename":{"type":"string"},"rowsTotal":{"type":"integer","nullable":true,"description":"Products found in the file; null until the worker has read it."},"rowsDone":{"type":"integer","description":"Products saved so far."},"result":{"type":"object","nullable":true,"description":"Set once the upload succeeds: the same counts an inline upload answers with.","properties":{"imported":{"type":"integer"},"deduped":{"type":"integer"},"orphaned":{"type":"integer"},"orphanedSkus":{"type":"array","items":{"type":"string"}}}},"message":{"type":"string","description":"What is happening or what happened, in plain English, ready to show a person."},"statusUrl":{"type":"string"},"createdAt":{"type":"string","format":"date-time"},"startedAt":{"type":"string","format":"date-time","nullable":true},"finishedAt":{"type":"string","format":"date-time","nullable":true}},"required":["importId","kind","status","filename","rowsTotal","rowsDone","result","message","statusUrl","createdAt","startedAt","finishedAt"]}}},"required":["data"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getReferenceDataImports","summary":"List reference data imports"}},"/api/v1/tenants/{tenantId}/reference-data/imports/{importId}":{"get":{"tags":["reference-data"],"description":"Progress of a background product upload (the statusUrl a 202 from POST /upload/products returns). status is queued, running, succeeded or failed; rowsDone of rowsTotal while running; result holds imported, deduped, orphaned and orphanedSkus once it succeeds; message says what happened in plain English.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"importId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"importId":{"type":"string","format":"uuid"},"kind":{"type":"string","enum":["products"]},"status":{"type":"string","enum":["queued","running","succeeded","failed"]},"filename":{"type":"string"},"rowsTotal":{"type":"integer","nullable":true,"description":"Products found in the file; null until the worker has read it."},"rowsDone":{"type":"integer","description":"Products saved so far."},"result":{"type":"object","nullable":true,"description":"Set once the upload succeeds: the same counts an inline upload answers with.","properties":{"imported":{"type":"integer"},"deduped":{"type":"integer"},"orphaned":{"type":"integer"},"orphanedSkus":{"type":"array","items":{"type":"string"}}}},"message":{"type":"string","description":"What is happening or what happened, in plain English, ready to show a person."},"statusUrl":{"type":"string"},"createdAt":{"type":"string","format":"date-time"},"startedAt":{"type":"string","format":"date-time","nullable":true},"finishedAt":{"type":"string","format":"date-time","nullable":true}},"required":["importId","kind","status","filename","rowsTotal","rowsDone","result","message","statusUrl","createdAt","startedAt","finishedAt"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getReferenceDataImportsByImportId","summary":"Get reference data import"}},"/api/v1/tenants/{tenantId}/reference-data/customers/import":{"post":{"tags":["reference-data"],"description":"Import reference customers as JSON (the twin of the multipart POST /upload/customers). Rows are upserted by sourceId; a repeated sourceId keeps the last occurrence.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["records"],"additionalProperties":false,"properties":{"records":{"type":"array","minItems":1,"maxItems":5000,"items":{"type":"object","required":["sourceId","name"],"properties":{"sourceId":{"type":"string","minLength":1,"description":"Your stable id for the customer (account number)."},"name":{"type":"string","minLength":1},"aliases":{"type":"array","items":{"type":"string"},"description":"Other spellings the customer uses on documents."},"senderDomains":{"anyOf":[{"type":"string"},{"type":"array","items":{"type":"string"}}],"description":"Email domains this customer sends orders from, as an array or one comma-separated string. Each is stored as its bare domain (\"https://www.Acme.com/\" and \"orders@acme.com\" store \"acme.com\"); a value that is not a domain, or is a public email provider, is listed in domainProblems and not stored."},"isActive":{"type":"boolean","default":true},"externalData":{"type":"object","additionalProperties":true}}}}}}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"imported":{"type":"integer"},"deduped":{"type":"integer"},"domainProblems":{"type":"array","description":"Present only when some sender domains could not be stored. Each entry names the record (row is its 1-based position in the file or records array, header excluded), the value as given, and why: invalid (not a domain name) or public_mailbox (gmail.com and the like name millions of senders). The record itself was still imported with its other domains.","items":{"type":"object","properties":{"row":{"type":"integer"},"sourceId":{"type":"string"},"value":{"type":"string"},"reason":{"type":"string","enum":["invalid","public_mailbox"]},"detail":{"type":"string"}},"required":["row","sourceId","value","reason","detail"]}}},"required":["imported","deduped"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postReferenceDataCustomersImport","summary":"Import reference customers as JSON (the twin of the multipart POST /upload/customers)"}},"/api/v1/tenants/{tenantId}/reference-data/products/import":{"post":{"tags":["reference-data"],"description":"Import reference products as JSON (the twin of the multipart POST /upload/products). Rows are upserted by SKU. With complete: true, uploaded SKUs absent from the records are marked inactive (never deleted); connector-synced rows are untouched.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["records"],"additionalProperties":false,"properties":{"records":{"type":"array","minItems":1,"maxItems":5000,"items":{"type":"object","required":["sku"],"properties":{"sku":{"type":"string","minLength":1},"sourceId":{"type":"string","description":"Defaults to the SKU."},"description":{"type":"string","nullable":true},"aliases":{"type":"array","items":{"type":"string"}},"uom":{"type":"string","nullable":true},"unitPrice":{"type":"number","nullable":true},"isActive":{"type":"boolean","default":true},"externalData":{"type":"object","additionalProperties":true}}}},"complete":{"type":"boolean","default":false,"description":"The records are the complete product master: uploaded (CSV/JSON) SKUs absent from them are marked inactive, never deleted."}}}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"imported":{"type":"integer"},"deduped":{"type":"integer"},"orphaned":{"type":"integer"},"orphanedSkus":{"type":"array","items":{"type":"string"}}},"required":["imported","deduped","orphaned","orphanedSkus"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postReferenceDataProductsImport","summary":"Import reference products as JSON (the twin of the multipart POST /upload/products)"}},"/api/v1/tenants/{tenantId}/reference-data/customers/bulk-delete":{"post":{"tags":["reference-data"],"description":"Delete multiple reference customers by ID","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"ids":{"type":"array","items":{"type":"string","format":"uuid"},"minItems":1,"maxItems":500}},"required":["ids"]}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"deleted":{"type":"integer"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postReferenceDataCustomersBulkDelete","summary":"Delete multiple reference customers by ID"}},"/api/v1/tenants/{tenantId}/reference-data/products/bulk-delete":{"post":{"tags":["reference-data"],"description":"Delete multiple reference products by ID","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"ids":{"type":"array","items":{"type":"string","format":"uuid"},"minItems":1,"maxItems":500}},"required":["ids"]}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"deleted":{"type":"integer"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postReferenceDataProductsBulkDelete","summary":"Delete multiple reference products by ID"}},"/api/v1/tenants/{tenantId}/reference-data/customers/export":{"get":{"tags":["reference-data"],"description":"Export all reference customers as CSV","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getReferenceDataCustomersExport","summary":"Export all reference customers as CSV"}},"/api/v1/tenants/{tenantId}/reference-data/products/export":{"get":{"tags":["reference-data"],"description":"Export all reference products as CSV","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getReferenceDataProductsExport","summary":"Export all reference products as CSV"}},"/api/v1/tenants/{tenantId}/integrations/status":{"get":{"tags":["integrations"],"description":"Get OMS integration status, counts, and recent delivery history","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"connectorType":{"type":"string","nullable":true},"invoiceWriteBack":{"type":"object","description":"Whether supplier invoices are written to the accounting destination as bills, by the same rule invoice routing uses. When supported is false they export as files: no_accounting_destination, unsupported_connector (the destination cannot take bills) or expense_account_missing (set one with PATCH.../connectors/instances/:connectorId defaultExpenseAccountId; for QuickBooks, choose it from GET.../connectors/instances/:connectorId/quickbooks/options expenseAccounts).","properties":{"supported":{"type":"boolean"},"connectorType":{"type":"string","nullable":true},"connectorId":{"type":"string","nullable":true},"reason":{"type":"string","enum":["ok","no_accounting_destination","unsupported_connector","expense_account_missing"]}},"required":["supported","connectorType","connectorId","reason"]},"defaultConnectorId":{"type":"string","nullable":true},"instances":{"type":"array","items":{"type":"object","properties":{"connectorId":{"type":"string","format":"uuid"},"connectorType":{"type":"string"},"externalId":{"type":"string"},"displayName":{"type":"string","nullable":true},"status":{"type":"string"},"refreshTokenExpiresAt":{"type":"string","format":"date-time","nullable":true},"lastRefreshedAt":{"type":"string","format":"date-time","nullable":true},"isDefault":{"type":"boolean"},"role":{"type":"string","enum":["commerce","accounting"]},"environment":{"type":"string","enum":["sandbox","production"],"nullable":true},"lastError":{"type":"string","nullable":true,"description":"Why the connection last stopped working; null when nothing went wrong."},"delivery":{"type":"object","description":"This connector's own delivery record: only orders and invoices sent to it (its envelope_destinations rows) and its latest connection test.","properties":{"state":{"type":"string","enum":["healthy","error","idle","no_activity"]},"reason":{"type":"string"},"sent":{"type":"integer"},"couldNotSend":{"type":"integer","description":"Failed or parked for a person (manual_handling) at this destination."},"waiting":{"type":"integer"},"lastSentAt":{"type":"string","format":"date-time","nullable":true},"lastProblemAt":{"type":"string","format":"date-time","nullable":true},"lastProblem":{"type":"string","nullable":true},"lastTest":{"type":"object","nullable":true,"properties":{"ok":{"type":"boolean"},"at":{"type":"string","format":"date-time"}}},"recent":{"type":"array","items":{"type":"object","properties":{"envelopeId":{"type":"string","format":"uuid"},"documentType":{"type":"string","enum":["order","invoice"]},"reference":{"type":"string","nullable":true},"status":{"type":"string"},"timestamp":{"type":"string","format":"date-time"},"error":{"type":"string","nullable":true}}}}}}},"required":["connectorId","connectorType","externalId","status","isDefault","role"]}},"quickbooksConnected":{"type":"boolean"},"quickbooksOrderEntity":{"type":"string","enum":["estimate","invoice"]},"shopifyConnected":{"type":"boolean"},"shopifyShopDomain":{"type":"string","nullable":true},"netsuiteConnected":{"type":"boolean"},"netsuiteAccountId":{"type":"string","nullable":true},"customRestConnected":{"type":"boolean"},"customRestEndpointUrl":{"type":"string","nullable":true},"erpWriteBackEnabled":{"type":"boolean"},"destinationPolicy":{"type":"string","enum":["commerce","accounting","both"],"nullable":true},"fanOutAllowed":{"type":"boolean"},"skippedDestinationsCount":{"type":"integer"},"skippedDestinationsReason":{"type":"string","enum":["plan","claims_disabled"],"nullable":true},"ambiguousRoles":{"type":"array","description":"Roles with several connected instances (e.g. two QuickBooks companies) and no default or routing rule naming one. Orders into such a role are held for a choice at approval; set settings.defaultDestinations.<role> or add a rule to clear it.","items":{"type":"string","enum":["commerce","accounting"]}},"lastSyncAt":{"type":"string","format":"date-time","nullable":true},"lastErrorAt":{"type":"string","format":"date-time","nullable":true},"lastError":{"type":"string","nullable":true},"totalIntegrated":{"type":"integer"},"totalFailed":{"type":"integer"},"pendingCount":{"type":"integer"},"recentDeliveries":{"type":"array","items":{"type":"object","properties":{"envelopeId":{"type":"string","format":"uuid"},"status":{"type":"string"},"timestamp":{"type":"string","format":"date-time"},"error":{"type":"string","nullable":true}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getIntegrationsStatus","summary":"Get OMS integration status, counts, and recent delivery history"}},"/api/v1/tenants/{tenantId}/rules/":{"get":{"tags":["rules"],"description":"List mapping rules with hit/miss counts and lifecycle status. Filter by partnerId to see everything learned or imported for one trading partner — including tenant-wide rules, which apply to that partner too. Reading-hint rows (rule_type \"reading_hint\") carry the typed hint under `hint` and the exact sentence it puts in front of the extraction model under `hintSentence` — the same renderer the extraction path uses, without the multi-hint preface. A stored row that no longer parses (or cannot be rendered) returns `hint: null`, `hintSentence: null` and `hintError`.","parameters":[{"schema":{"type":"string","enum":["proposed","active","suspended"]},"in":"query","name":"status","required":false},{"schema":{"type":"string","format":"uuid"},"in":"query","name":"partnerId","required":false},{"schema":{"type":"integer","minimum":1,"maximum":1000,"default":500},"in":"query","name":"limit","required":false},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string"},"ruleType":{"type":"string"},"match":{"type":"object","additionalProperties":true},"apply":{"type":"object","additionalProperties":true},"origin":{"type":"string"},"status":{"type":"string"},"hitCount":{"type":"number"},"missCount":{"type":"number"},"partnerId":{"type":"string","nullable":true},"partnerName":{"type":"string","nullable":true},"targetCustomerName":{"type":"string","nullable":true},"approvedBy":{"type":"string","nullable":true},"createdAt":{"type":"string"},"updatedAt":{"type":"string"},"sourceCorrections":{"type":"array","nullable":true,"items":{"type":"object","properties":{"beforeValue":{},"afterValue":{},"correctedAt":{"type":"string"},"agentConfidence":{"type":"number","nullable":true}}}},"library":{"type":"object","nullable":true,"properties":{"buyerDomain":{"type":"string"},"evidence":{"type":"string","enum":["seen once","established","well established"]},"retired":{"type":"boolean"}}},"hint":{"type":"object","additionalProperties":true,"nullable":true},"hintSentence":{"type":"string","nullable":true},"hintError":{"type":"string","nullable":true}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getRules","summary":"List mapping rules with hit/miss counts and lifecycle status"},"post":{"tags":["rules"],"description":"Create a manual mapping rule (active immediately). ruleType \"part_alias\" (the default) maps a customer part number to a canonical SKU and takes { alias, targetSku, partnerId? }. ruleType \"reading_hint\" records how one trading partner lays out its documents and takes { partnerId, hint } — hint is one of the six typed shapes (sku_column_placeholder, part_number_source, ship_to_label, default_uom, date_order, price_basis); hints are always partner-scoped and a partner holds at most one hint per kind.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"ruleType":{"type":"string","enum":["part_alias","reading_hint"],"default":"part_alias","description":"Which rule shape the body carries (default part_alias)"},"alias":{"type":"string","minLength":1,"description":"part_alias: the customer part number to map"},"targetSku":{"type":"string","minLength":1,"description":"part_alias: the canonical SKU it resolves to"},"partnerId":{"type":"string","format":"uuid","description":"Reference customer to scope the rule to. Optional for part_alias, required for reading_hint."},"hint":{"type":"object","additionalProperties":true,"description":"reading_hint: the typed hint, e.g. { \"kind\": \"ship_to_label\", \"label\": \"Deliver To:\" }. Validated against the reading-hint schema; free text is limited to 40 printable characters."}}}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"201":{"description":"Created. The new resource is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string"},"ruleType":{"type":"string"},"match":{"type":"object","additionalProperties":true},"apply":{"type":"object","additionalProperties":true},"origin":{"type":"string"},"status":{"type":"string"},"hitCount":{"type":"number"},"missCount":{"type":"number"},"partnerId":{"type":"string","nullable":true},"partnerName":{"type":"string","nullable":true},"targetCustomerName":{"type":"string","nullable":true},"approvedBy":{"type":"string","nullable":true},"createdAt":{"type":"string"},"updatedAt":{"type":"string"},"sourceCorrections":{"type":"array","nullable":true,"items":{"type":"object","properties":{"beforeValue":{},"afterValue":{},"correctedAt":{"type":"string"},"agentConfidence":{"type":"number","nullable":true}}}},"library":{"type":"object","nullable":true,"properties":{"buyerDomain":{"type":"string"},"evidence":{"type":"string","enum":["seen once","established","well established"]},"retired":{"type":"boolean"}}},"hint":{"type":"object","additionalProperties":true,"nullable":true},"hintSentence":{"type":"string","nullable":true},"hintError":{"type":"string","nullable":true}}}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postRules","summary":"Create a manual mapping rule (active immediately)"}},"/api/v1/tenants/{tenantId}/rules/{ruleId}/approve":{"post":{"tags":["rules"],"description":"Approve a proposed mapping rule — it applies automatically from then on. Only a proposed rule can be approved: an active or suspended one answers 409 CONFLICT (a suspended rule stays suspended), and a rule id this tenant does not have answers 404 NOT_FOUND. Approving a reading hint is refused with HINT_BUDGET_EXCEEDED when it would push the partner past its rendered hint budget.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"ruleId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string"},"ruleType":{"type":"string"},"match":{"type":"object","additionalProperties":true},"apply":{"type":"object","additionalProperties":true},"origin":{"type":"string"},"status":{"type":"string"},"hitCount":{"type":"number"},"missCount":{"type":"number"},"partnerId":{"type":"string","nullable":true},"partnerName":{"type":"string","nullable":true},"targetCustomerName":{"type":"string","nullable":true},"approvedBy":{"type":"string","nullable":true},"createdAt":{"type":"string"},"updatedAt":{"type":"string"},"sourceCorrections":{"type":"array","nullable":true,"items":{"type":"object","properties":{"beforeValue":{},"afterValue":{},"correctedAt":{"type":"string"},"agentConfidence":{"type":"number","nullable":true}}}},"library":{"type":"object","nullable":true,"properties":{"buyerDomain":{"type":"string"},"evidence":{"type":"string","enum":["seen once","established","well established"]},"retired":{"type":"boolean"}}},"hint":{"type":"object","additionalProperties":true,"nullable":true},"hintSentence":{"type":"string","nullable":true},"hintError":{"type":"string","nullable":true}}}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postRulesByRuleIdApprove","summary":"Approve a proposed mapping rule — it applies automatically from then on"}},"/api/v1/tenants/{tenantId}/rules/{ruleId}/suspend":{"post":{"tags":["rules"],"description":"Suspend a mapping rule","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"ruleId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string"},"ruleType":{"type":"string"},"match":{"type":"object","additionalProperties":true},"apply":{"type":"object","additionalProperties":true},"origin":{"type":"string"},"status":{"type":"string"},"hitCount":{"type":"number"},"missCount":{"type":"number"},"partnerId":{"type":"string","nullable":true},"partnerName":{"type":"string","nullable":true},"targetCustomerName":{"type":"string","nullable":true},"approvedBy":{"type":"string","nullable":true},"createdAt":{"type":"string"},"updatedAt":{"type":"string"},"sourceCorrections":{"type":"array","nullable":true,"items":{"type":"object","properties":{"beforeValue":{},"afterValue":{},"correctedAt":{"type":"string"},"agentConfidence":{"type":"number","nullable":true}}}},"library":{"type":"object","nullable":true,"properties":{"buyerDomain":{"type":"string"},"evidence":{"type":"string","enum":["seen once","established","well established"]},"retired":{"type":"boolean"}}},"hint":{"type":"object","additionalProperties":true,"nullable":true},"hintSentence":{"type":"string","nullable":true},"hintError":{"type":"string","nullable":true}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postRulesByRuleIdSuspend","summary":"Suspend a mapping rule"}},"/api/v1/tenants/{tenantId}/destination-rules/":{"get":{"tags":["destination-rules"],"description":"List destination routing rules in evaluation order","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"priority":{"type":"number"},"match":{"type":"object","additionalProperties":true},"connectorId":{"type":"string","nullable":true,"description":"The connector a connector rule targets; null for a business rule."},"connectorType":{"type":"string","nullable":true},"connectorLabel":{"type":"string","nullable":true},"role":{"type":"string","nullable":true},"entityId":{"type":"string","nullable":true,"description":"The business a business rule targets; null for a connector rule."},"entityName":{"type":"string","nullable":true,"description":"The business the rule sends orders to: the target business, or the business holding the target connector."},"roleOverride":{"type":"boolean","description":"A connector rule that claims only its own role even when its connector is part of a business — an explicit split (\"Store override\")."},"enabled":{"type":"boolean"},"suspended":{"type":"boolean"},"suspendedReason":{"type":"string","nullable":true},"catchAll":{"type":"boolean"},"catchAllNeedsConfirmation":{"type":"boolean"},"matchLabels":{"type":"object","additionalProperties":{"type":"string"},"description":"Display names for id conditions, read fresh: customerId → the reference customer's current name, channelId → the inbox address or path."},"status":{"type":"string","enum":["active","proposed","dismissed"],"description":"proposed: learned from re-routed approvals; routes nothing until POST /:ruleId/activate."},"occurrences":{"type":"number","nullable":true,"description":"For a learned rule: the re-routed approvals behind it."},"createdAt":{"type":"string"},"updatedAt":{"type":"string"}}}},"supportedMatchKeys":{"type":"array","items":{"type":"string"}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getDestinationRules","summary":"List destination routing rules in evaluation order"},"post":{"tags":["destination-rules"],"description":"Create a destination routing rule. Target a business with entityId: matching orders go wholly to that business’s store and books. Or target one system with connectorId: if that connector belongs to a business the whole order follows it, unless roleOverride is true, which sends only that role there and leaves the other with the order’s business (an explicit split, labelled \"Store override\"). Send exactly one of entityId and connectorId (400 INVALID_RULE_TARGET); an id that is not this tenant’s is 404 ENTITY_NOT_FOUND / CONNECTOR_NOT_FOUND. Unsupported match keys are refused with 400 UNSUPPORTED_MATCH_KEY and nothing is created; an explicit empty match creates a catch-all (catchAll: true) that matches every order.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string","minLength":1,"maxLength":255},"connectorId":{"type":"string","format":"uuid"},"entityId":{"type":"string","format":"uuid","description":"The business matching orders go to."},"roleOverride":{"type":"boolean","description":"Connector rules only: send just this role to the connector even when it belongs to a business."},"match":{"type":"object","description":"Conditions, ANDed. Supported keys: channelId, channelType, customerId, customerName, senderDomain, shipToState; each value must be a non-empty string (senderDomain a domain, shipToState a state or province — a full name is stored as its code). Any other key is refused with 400 UNSUPPORTED_MATCH_KEY (details.unsupportedMatchKeys, details.supportedMatchKeys). An explicit empty object is a catch-all that matches every order.","properties":{"channelId":{"type":"string","format":"uuid","description":"The inbox (tenant_channels id) the order arrived at."},"channelType":{"type":"string","description":"email, gmail, microsoft365, sftp, api, upload or manual (a phone or typed order)."},"customerId":{"type":"string","description":"A reference customer id (reference_customers.id): matches the order's resolved customer, or — when resolution did not succeed — any name or alias of that customer. A value that is not a reference customer id compares with the document's customer account id."},"customerName":{"type":"string","description":"Case-insensitive; also matches an order resolved to, or printed under a known alias of, the reference customer of that name."},"senderDomain":{"type":"string","description":"The email sender's domain, e.g. north40.example; subdomains match too. Orders without a sender (upload, API, SFTP, typed) never match."},"shipToState":{"type":"string","description":"Two-letter state or province code of the shipping address, e.g. OR."}},"additionalProperties":true},"priority":{"type":"integer","minimum":0,"maximum":100000},"enabled":{"type":"boolean"}},"required":["name"]}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"201":{"description":"Created. The new resource is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"priority":{"type":"number"},"match":{"type":"object","additionalProperties":true},"connectorId":{"type":"string","nullable":true,"description":"The connector a connector rule targets; null for a business rule."},"connectorType":{"type":"string","nullable":true},"connectorLabel":{"type":"string","nullable":true},"role":{"type":"string","nullable":true},"entityId":{"type":"string","nullable":true,"description":"The business a business rule targets; null for a connector rule."},"entityName":{"type":"string","nullable":true,"description":"The business the rule sends orders to: the target business, or the business holding the target connector."},"roleOverride":{"type":"boolean","description":"A connector rule that claims only its own role even when its connector is part of a business — an explicit split (\"Store override\")."},"enabled":{"type":"boolean"},"suspended":{"type":"boolean"},"suspendedReason":{"type":"string","nullable":true},"catchAll":{"type":"boolean"},"catchAllNeedsConfirmation":{"type":"boolean"},"matchLabels":{"type":"object","additionalProperties":{"type":"string"},"description":"Display names for id conditions, read fresh: customerId → the reference customer's current name, channelId → the inbox address or path."},"status":{"type":"string","enum":["active","proposed","dismissed"],"description":"proposed: learned from re-routed approvals; routes nothing until POST /:ruleId/activate."},"occurrences":{"type":"number","nullable":true,"description":"For a learned rule: the re-routed approvals behind it."},"createdAt":{"type":"string"},"updatedAt":{"type":"string"}}}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"402":{"description":"The plan does not allow this: SUBSCRIPTION_REQUIRED (no active subscription) or PLAN_LIMIT_EXCEEDED (details.resource names the limit).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postDestinationRules","summary":"Create a destination routing rule"}},"/api/v1/tenants/{tenantId}/destination-rules/{ruleId}":{"patch":{"tags":["destination-rules"],"description":"Update a destination routing rule. Sending `match: {}` makes (or confirms) a catch-all that matches every order; unsupported match keys are refused with 400 UNSUPPORTED_MATCH_KEY and the rule is left unchanged.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string","minLength":1,"maxLength":255},"connectorId":{"type":"string","format":"uuid","description":"Repoint at one system; clears entityId."},"entityId":{"type":"string","format":"uuid","description":"Repoint at a business; clears connectorId and roleOverride."},"roleOverride":{"type":"boolean","description":"Connector rules only: claim just this role."},"match":{"type":"object","description":"Conditions, ANDed. Supported keys: channelId, channelType, customerId, customerName, senderDomain, shipToState; each value must be a non-empty string (senderDomain a domain, shipToState a state or province — a full name is stored as its code). Any other key is refused with 400 UNSUPPORTED_MATCH_KEY (details.unsupportedMatchKeys, details.supportedMatchKeys). An explicit empty object is a catch-all that matches every order.","properties":{"channelId":{"type":"string","format":"uuid","description":"The inbox (tenant_channels id) the order arrived at."},"channelType":{"type":"string","description":"email, gmail, microsoft365, sftp, api, upload or manual (a phone or typed order)."},"customerId":{"type":"string","description":"A reference customer id (reference_customers.id): matches the order's resolved customer, or — when resolution did not succeed — any name or alias of that customer. A value that is not a reference customer id compares with the document's customer account id."},"customerName":{"type":"string","description":"Case-insensitive; also matches an order resolved to, or printed under a known alias of, the reference customer of that name."},"senderDomain":{"type":"string","description":"The email sender's domain, e.g. north40.example; subdomains match too. Orders without a sender (upload, API, SFTP, typed) never match."},"shipToState":{"type":"string","description":"Two-letter state or province code of the shipping address, e.g. OR."}},"additionalProperties":true},"priority":{"type":"integer","minimum":0,"maximum":100000},"enabled":{"type":"boolean"}},"additionalProperties":false}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"ruleId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"priority":{"type":"number"},"match":{"type":"object","additionalProperties":true},"connectorId":{"type":"string","nullable":true,"description":"The connector a connector rule targets; null for a business rule."},"connectorType":{"type":"string","nullable":true},"connectorLabel":{"type":"string","nullable":true},"role":{"type":"string","nullable":true},"entityId":{"type":"string","nullable":true,"description":"The business a business rule targets; null for a connector rule."},"entityName":{"type":"string","nullable":true,"description":"The business the rule sends orders to: the target business, or the business holding the target connector."},"roleOverride":{"type":"boolean","description":"A connector rule that claims only its own role even when its connector is part of a business — an explicit split (\"Store override\")."},"enabled":{"type":"boolean"},"suspended":{"type":"boolean"},"suspendedReason":{"type":"string","nullable":true},"catchAll":{"type":"boolean"},"catchAllNeedsConfirmation":{"type":"boolean"},"matchLabels":{"type":"object","additionalProperties":{"type":"string"},"description":"Display names for id conditions, read fresh: customerId → the reference customer's current name, channelId → the inbox address or path."},"status":{"type":"string","enum":["active","proposed","dismissed"],"description":"proposed: learned from re-routed approvals; routes nothing until POST /:ruleId/activate."},"occurrences":{"type":"number","nullable":true,"description":"For a learned rule: the re-routed approvals behind it."},"createdAt":{"type":"string"},"updatedAt":{"type":"string"}}}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"402":{"description":"The plan does not allow this: SUBSCRIPTION_REQUIRED (no active subscription) or PLAN_LIMIT_EXCEEDED (details.resource names the limit).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"patchDestinationRulesByRuleId","summary":"Update a destination routing rule"},"delete":{"tags":["destination-rules"],"description":"Delete a destination routing rule","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"ruleId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"deleted":{"type":"boolean"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"deleteDestinationRulesByRuleId","summary":"Delete a destination routing rule"}},"/api/v1/tenants/{tenantId}/destination-rules/options":{"get":{"tags":["destination-rules"],"description":"Choices for building a routing rule without ids: channels[] labelled by address or path, senderDomains[] seen in the last 90 days, recentOrders[] to test with (preview with orderId), businesses[] and customers[] (reference customers whose name or alias contains customerSearch, with aliases, source system and the company they were synced from).","parameters":[{"schema":{"type":"string","maxLength":200},"in":"query","name":"customerSearch","required":false},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"channels":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string"},"channelType":{"type":"string"},"label":{"type":"string"}}}},"senderDomains":{"type":"array","items":{"type":"object","properties":{"domain":{"type":"string"},"orders":{"type":"number"},"lastSeenAt":{"type":"string"}}}},"recentOrders":{"type":"array","items":{"type":"object","properties":{"orderId":{"type":"string"},"customerName":{"type":"string"},"poNumber":{"type":"string","nullable":true},"channelType":{"type":"string"},"receivedAt":{"type":"string"}}}},"businesses":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"isDefault":{"type":"boolean","description":"Orders nothing else routes go to the default business."},"commerceConnectorId":{"type":"string","nullable":true,"description":"The store (tenant_connectors id)."},"accountingConnectorId":{"type":"string","nullable":true,"description":"The company file (tenant_connectors id)."},"commerce":{"type":"object","nullable":true,"properties":{"connectorId":{"type":"string"},"connectorType":{"type":"string"},"label":{"type":"string"},"status":{"type":"string"}}},"accounting":{"type":"object","nullable":true,"properties":{"connectorId":{"type":"string"},"connectorType":{"type":"string"},"label":{"type":"string"},"status":{"type":"string"}}},"summary":{"type":"string","description":"For display: \"Summit Farm & Ranch Inc → Farm store + Farm books\"."},"createdAt":{"type":"string"},"updatedAt":{"type":"string"}}}},"customers":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"aliases":{"type":"array","items":{"type":"string"}},"sourceSystem":{"type":"string"},"companyLabel":{"type":"string","nullable":true}}}},"supportedMatchKeys":{"type":"array","items":{"type":"string"}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getDestinationRulesOptions","summary":"List destination rules options"}},"/api/v1/tenants/{tenantId}/destination-rules/order":{"put":{"tags":["destination-rules"],"description":"Set the evaluation order of routing rules: ruleIds first to last. Priorities become 10, 20, 30… in that order, in one transaction. An id that is not one of this tenant's rules is 404 RULE_NOT_FOUND and nothing changes. Rules not listed keep their priority.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"ruleIds":{"type":"array","minItems":1,"maxItems":500,"items":{"type":"string","format":"uuid"}}},"required":["ruleIds"],"additionalProperties":false}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"priority":{"type":"number"},"match":{"type":"object","additionalProperties":true},"connectorId":{"type":"string","nullable":true,"description":"The connector a connector rule targets; null for a business rule."},"connectorType":{"type":"string","nullable":true},"connectorLabel":{"type":"string","nullable":true},"role":{"type":"string","nullable":true},"entityId":{"type":"string","nullable":true,"description":"The business a business rule targets; null for a connector rule."},"entityName":{"type":"string","nullable":true,"description":"The business the rule sends orders to: the target business, or the business holding the target connector."},"roleOverride":{"type":"boolean","description":"A connector rule that claims only its own role even when its connector is part of a business — an explicit split (\"Store override\")."},"enabled":{"type":"boolean"},"suspended":{"type":"boolean"},"suspendedReason":{"type":"string","nullable":true},"catchAll":{"type":"boolean"},"catchAllNeedsConfirmation":{"type":"boolean"},"matchLabels":{"type":"object","additionalProperties":{"type":"string"},"description":"Display names for id conditions, read fresh: customerId → the reference customer's current name, channelId → the inbox address or path."},"status":{"type":"string","enum":["active","proposed","dismissed"],"description":"proposed: learned from re-routed approvals; routes nothing until POST /:ruleId/activate."},"occurrences":{"type":"number","nullable":true,"description":"For a learned rule: the re-routed approvals behind it."},"createdAt":{"type":"string"},"updatedAt":{"type":"string"}}}}}}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"putDestinationRulesOrder","summary":"Set the evaluation order of routing rules: ruleIds first to last"}},"/api/v1/tenants/{tenantId}/destination-rules/{ruleId}/activate":{"post":{"tags":["destination-rules"],"description":"Activate a proposed routing rule (learned from re-routed approvals): from now on it routes matching orders. Counts against the plan's routing-rule limit (402 PLAN_LIMIT_EXCEEDED). 409 RULE_NOT_PROPOSED for a rule that is not a proposal.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"ruleId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"priority":{"type":"number"},"match":{"type":"object","additionalProperties":true},"connectorId":{"type":"string","nullable":true,"description":"The connector a connector rule targets; null for a business rule."},"connectorType":{"type":"string","nullable":true},"connectorLabel":{"type":"string","nullable":true},"role":{"type":"string","nullable":true},"entityId":{"type":"string","nullable":true,"description":"The business a business rule targets; null for a connector rule."},"entityName":{"type":"string","nullable":true,"description":"The business the rule sends orders to: the target business, or the business holding the target connector."},"roleOverride":{"type":"boolean","description":"A connector rule that claims only its own role even when its connector is part of a business — an explicit split (\"Store override\")."},"enabled":{"type":"boolean"},"suspended":{"type":"boolean"},"suspendedReason":{"type":"string","nullable":true},"catchAll":{"type":"boolean"},"catchAllNeedsConfirmation":{"type":"boolean"},"matchLabels":{"type":"object","additionalProperties":{"type":"string"},"description":"Display names for id conditions, read fresh: customerId → the reference customer's current name, channelId → the inbox address or path."},"status":{"type":"string","enum":["active","proposed","dismissed"],"description":"proposed: learned from re-routed approvals; routes nothing until POST /:ruleId/activate."},"occurrences":{"type":"number","nullable":true,"description":"For a learned rule: the re-routed approvals behind it."},"createdAt":{"type":"string"},"updatedAt":{"type":"string"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"402":{"description":"The plan does not allow this: SUBSCRIPTION_REQUIRED (no active subscription) or PLAN_LIMIT_EXCEEDED (details.resource names the limit).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postDestinationRulesByRuleIdActivate","summary":"Activate destination rule"}},"/api/v1/tenants/{tenantId}/destination-rules/{ruleId}/dismiss":{"post":{"tags":["destination-rules"],"description":"Dismiss a proposed routing rule. It never routes, and the same customer-to-business pattern is not proposed again. 409 RULE_NOT_PROPOSED for a rule that is not a proposal.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"ruleId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"priority":{"type":"number"},"match":{"type":"object","additionalProperties":true},"connectorId":{"type":"string","nullable":true,"description":"The connector a connector rule targets; null for a business rule."},"connectorType":{"type":"string","nullable":true},"connectorLabel":{"type":"string","nullable":true},"role":{"type":"string","nullable":true},"entityId":{"type":"string","nullable":true,"description":"The business a business rule targets; null for a connector rule."},"entityName":{"type":"string","nullable":true,"description":"The business the rule sends orders to: the target business, or the business holding the target connector."},"roleOverride":{"type":"boolean","description":"A connector rule that claims only its own role even when its connector is part of a business — an explicit split (\"Store override\")."},"enabled":{"type":"boolean"},"suspended":{"type":"boolean"},"suspendedReason":{"type":"string","nullable":true},"catchAll":{"type":"boolean"},"catchAllNeedsConfirmation":{"type":"boolean"},"matchLabels":{"type":"object","additionalProperties":{"type":"string"},"description":"Display names for id conditions, read fresh: customerId → the reference customer's current name, channelId → the inbox address or path."},"status":{"type":"string","enum":["active","proposed","dismissed"],"description":"proposed: learned from re-routed approvals; routes nothing until POST /:ruleId/activate."},"occurrences":{"type":"number","nullable":true,"description":"For a learned rule: the re-routed approvals behind it."},"createdAt":{"type":"string"},"updatedAt":{"type":"string"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"402":{"description":"The plan does not allow this: SUBSCRIPTION_REQUIRED (no active subscription) or PLAN_LIMIT_EXCEEDED (details.resource names the limit).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postDestinationRulesByRuleIdDismiss","summary":"Dismiss a proposed routing rule"}},"/api/v1/tenants/{tenantId}/destination-rules/preview":{"post":{"tags":["destination-rules"],"description":"Preview which destinations approving an order with these attributes would write to — after the tenant’s destinationPolicy and the plan’s fan-out gate, exactly as approval decides — and which resolved destinations are left out and why.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","description":"Order attributes to route: channelId, channelType, customerId, customerName, senderDomain, shipToState, resolvedCustomerId (the reference customer the order resolved to), entityId (a business chosen for the order). Or send orderId alone to test an existing order exactly as approval would route it.","properties":{"channelId":{"type":"string","format":"uuid","description":"The inbox (tenant_channels id) the order arrived at."},"channelType":{"type":"string","description":"email, gmail, microsoft365, sftp, api, upload or manual (a phone or typed order)."},"customerId":{"type":"string","description":"A reference customer id (reference_customers.id): matches the order's resolved customer, or — when resolution did not succeed — any name or alias of that customer. A value that is not a reference customer id compares with the document's customer account id."},"customerName":{"type":"string","description":"Case-insensitive; also matches an order resolved to, or printed under a known alias of, the reference customer of that name."},"senderDomain":{"type":"string","description":"The email sender's domain, e.g. north40.example; subdomains match too. Orders without a sender (upload, API, SFTP, typed) never match."},"shipToState":{"type":"string","description":"Two-letter state or province code of the shipping address, e.g. OR."},"resolvedCustomerId":{"type":"string","format":"uuid"},"entityId":{"type":"string","format":"uuid"},"orderId":{"type":"string","format":"uuid","description":"Route this order of the tenant, with everything approval would read."}},"additionalProperties":false}}},"description":"Order attributes to route: channelId, channelType, customerId, customerName, senderDomain, shipToState, resolvedCustomerId (the reference customer the order resolved to), entityId (a business chosen for the order). Or send orderId alone to test an existing order exactly as approval would route it."},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"entity":{"type":"object","nullable":true,"description":"The business approval routes the order to, and why: source is manual, reviewer, rule, remembered or default. Null when the tenant has no business that applies.","properties":{"id":{"type":"string"},"name":{"type":"string"},"source":{"type":"string","enum":["manual","reviewer","rule","remembered","customer","default"],"description":"customer: the order’s customer is known only in this business."},"ruleId":{"type":"string","nullable":true},"ruleName":{"type":"string","nullable":true}}},"routingSummary":{"type":"string","nullable":true,"description":"For display: \"Summit Farm & Ranch Inc → Farm store + Farm books\", or \"Store override: Farm store · Books: Pet books\" when a rule splits the order."},"destinations":{"type":"array","items":{"type":"object","properties":{"role":{"type":"string","enum":["commerce","accounting"]},"connectorId":{"type":"string","nullable":true},"connectorType":{"type":"string"},"connectorLabel":{"type":"string","nullable":true},"externalId":{"type":"string","nullable":true},"matchedRuleId":{"type":"string","nullable":true},"matchedRuleName":{"type":"string","nullable":true},"entityId":{"type":"string","nullable":true,"description":"The business this write belongs to."},"entityName":{"type":"string","nullable":true},"override":{"type":"boolean","description":"True when a rule sent this role outside the order's business — a \"Store override\" split."},"needsReconnect":{"type":"boolean","description":"Present (true) when this destination's connection must be reconnected; a write-back approval is held (409 CONNECTOR_NEEDS_RECONNECT), never routed elsewhere."}}}},"excluded":{"type":"array","items":{"type":"object","properties":{"role":{"type":"string","enum":["commerce","accounting"]},"connectorId":{"type":"string","nullable":true},"connectorType":{"type":"string"},"connectorLabel":{"type":"string","nullable":true},"externalId":{"type":"string","nullable":true},"matchedRuleId":{"type":"string","nullable":true},"matchedRuleName":{"type":"string","nullable":true},"entityId":{"type":"string","nullable":true,"description":"The business this write belongs to."},"entityName":{"type":"string","nullable":true},"override":{"type":"boolean","description":"True when a rule sent this role outside the order's business — a \"Store override\" split."},"needsReconnect":{"type":"boolean","description":"Present (true) when this destination's connection must be reconnected; a write-back approval is held (409 CONNECTOR_NEEDS_RECONNECT), never routed elsewhere."},"reason":{"type":"string","enum":["policy","plan","claims_disabled"],"description":"policy: settings.destinationPolicy sends orders to the other system only; plan: writing to both systems needs a plan with fan-out; claims_disabled: multi-destination writes are not enabled on this deployment."},"message":{"type":"string","description":"Plain-language reason, for display."}}}},"choiceRequired":{"type":"array","items":{"type":"object","properties":{"role":{"type":"string","enum":["commerce","accounting"]},"message":{"type":"string","description":"Plain language, e.g. \"Choose which QuickBooks company this order belongs to.\""},"instances":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid","description":"tenant_connectors.id"},"connectorType":{"type":"string"},"displayName":{"type":"string","nullable":true},"externalId":{"type":"string","nullable":true,"description":"Shop domain, QuickBooks realmId, NetSuite account id."},"needsReconnect":{"type":"boolean","description":"Present (true) when the connection must be reconnected; choosing it holds the approval with 409 CONNECTOR_NEEDS_RECONNECT."}},"required":["id","connectorType"]}}},"required":["role","message","instances"]}},"reconnectRequired":{"type":"array","items":{"type":"object","properties":{"role":{"type":"string","enum":["commerce","accounting"]},"connectorId":{"type":"string","format":"uuid","nullable":true},"connectorType":{"type":"string"},"displayName":{"type":"string","nullable":true},"message":{"type":"string","description":"Plain language, e.g. \"Reconnect Summit Farm store to post this order.\""},"nextStep":{"type":"object","properties":{"label":{"type":"string"},"url":{"type":"string","nullable":true}},"required":["label"]}},"required":["role","connectorType","message","nextStep"]}},"businessChoice":{"type":"object","nullable":true,"properties":{"customerName":{"type":"string","nullable":true},"message":{"type":"string"},"candidates":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"}}}}}},"evaluated":{"type":"array","items":{"type":"object","properties":{"ruleId":{"type":"string"},"name":{"type":"string"},"priority":{"type":"number"},"enabled":{"type":"boolean"},"matched":{"type":"boolean"},"status":{"type":"string"},"conditions":{"type":"array","description":"Each condition of the rule and whether it held, with the reason in words.","items":{"type":"object","properties":{"key":{"type":"string"},"expected":{"type":"string"},"actual":{"type":"string","nullable":true},"matched":{"type":"boolean"},"message":{"type":"string"}}}}}}},"fallsBackToFileExport":{"type":"boolean"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"postDestinationRulesPreview","summary":"Create destination rule preview"}},"/api/v1/tenants/{tenantId}/business-entities/":{"get":{"tags":["business-entities"],"description":"List the tenant’s businesses (legal entities). Each binds at most one store to one company file; routing keeps an order inside one business. A tenant with one store and one company has one, created automatically.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"isDefault":{"type":"boolean","description":"Orders nothing else routes go to the default business."},"commerceConnectorId":{"type":"string","nullable":true,"description":"The store (tenant_connectors id)."},"accountingConnectorId":{"type":"string","nullable":true,"description":"The company file (tenant_connectors id)."},"commerce":{"type":"object","nullable":true,"properties":{"connectorId":{"type":"string"},"connectorType":{"type":"string"},"label":{"type":"string"},"status":{"type":"string"}}},"accounting":{"type":"object","nullable":true,"properties":{"connectorId":{"type":"string"},"connectorType":{"type":"string"},"label":{"type":"string"},"status":{"type":"string"}}},"summary":{"type":"string","description":"For display: \"Summit Farm & Ranch Inc → Farm store + Farm books\"."},"createdAt":{"type":"string"},"updatedAt":{"type":"string"}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getBusinessEntities","summary":"List the tenant’s businesses (legal entities)"},"post":{"tags":["business-entities"],"description":"Create a business: a name, the store it sells through and the company file it keeps its books in. A connector belongs to one business (409 CONNECTOR_ALREADY_ASSIGNED); a store cannot go in the books slot or the reverse (400 CONNECTOR_ROLE_MISMATCH); a connector id that is not this tenant’s is 404 CONNECTOR_NOT_FOUND.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string","minLength":1,"maxLength":255},"commerceConnectorId":{"type":"string","format":"uuid","nullable":true,"description":"The store this business sells through. null clears it."},"accountingConnectorId":{"type":"string","format":"uuid","nullable":true,"description":"The company file this business keeps its books in. null clears it."},"isDefault":{"type":"boolean","description":"Make this the default business; the previous default stops being one."}},"required":["name"],"additionalProperties":false}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"201":{"description":"Created. The new resource is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"isDefault":{"type":"boolean","description":"Orders nothing else routes go to the default business."},"commerceConnectorId":{"type":"string","nullable":true,"description":"The store (tenant_connectors id)."},"accountingConnectorId":{"type":"string","nullable":true,"description":"The company file (tenant_connectors id)."},"commerce":{"type":"object","nullable":true,"properties":{"connectorId":{"type":"string"},"connectorType":{"type":"string"},"label":{"type":"string"},"status":{"type":"string"}}},"accounting":{"type":"object","nullable":true,"properties":{"connectorId":{"type":"string"},"connectorType":{"type":"string"},"label":{"type":"string"},"status":{"type":"string"}}},"summary":{"type":"string","description":"For display: \"Summit Farm & Ranch Inc → Farm store + Farm books\"."},"createdAt":{"type":"string"},"updatedAt":{"type":"string"}}}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postBusinessEntities","summary":"Create business entity"}},"/api/v1/tenants/{tenantId}/business-entities/{entityId}":{"patch":{"tags":["business-entities"],"description":"Rename a business, change its store or company file (null clears a slot), or make it the default. The same refusals as create apply; an entity id that is not this tenant’s is 404 ENTITY_NOT_FOUND.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string","minLength":1,"maxLength":255},"commerceConnectorId":{"type":"string","format":"uuid","nullable":true,"description":"The store this business sells through. null clears it."},"accountingConnectorId":{"type":"string","format":"uuid","nullable":true,"description":"The company file this business keeps its books in. null clears it."},"isDefault":{"type":"boolean","description":"Make this the default business; the previous default stops being one."}},"additionalProperties":false}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"entityId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"isDefault":{"type":"boolean","description":"Orders nothing else routes go to the default business."},"commerceConnectorId":{"type":"string","nullable":true,"description":"The store (tenant_connectors id)."},"accountingConnectorId":{"type":"string","nullable":true,"description":"The company file (tenant_connectors id)."},"commerce":{"type":"object","nullable":true,"properties":{"connectorId":{"type":"string"},"connectorType":{"type":"string"},"label":{"type":"string"},"status":{"type":"string"}}},"accounting":{"type":"object","nullable":true,"properties":{"connectorId":{"type":"string"},"connectorType":{"type":"string"},"label":{"type":"string"},"status":{"type":"string"}}},"summary":{"type":"string","description":"For display: \"Summit Farm & Ranch Inc → Farm store + Farm books\"."},"createdAt":{"type":"string"},"updatedAt":{"type":"string"}}}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"patchBusinessEntitiesByEntityId","summary":"Update business entity"},"delete":{"tags":["business-entities"],"description":"Delete a business. Refused with 409 ENTITY_IN_USE while a routing rule targets it (details.ruleIds) — delete or repoint those rules first. Its store and company file stay connected.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"entityId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"deleted":{"type":"boolean"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"deleteBusinessEntitiesByEntityId","summary":"Delete a business"}},"/api/v1/tenants/{tenantId}/autonomy/customers":{"get":{"tags":["autonomy"],"description":"Every trading partner with at least one resolved order, with its autonomy state and derived clean streak. Filter by state=proposed for the proposal list. Listing is also the proposal trigger: a supervised customer whose streak meets the tenant bar becomes proposed (audit + autonomy.proposed webhook, once).","parameters":[{"schema":{"type":"string","enum":["supervised","proposed","autonomous","demoted"]},"in":"query","name":"state","required":false},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"mode":{"type":"string","enum":["off","shadow","enforce"]},"proposeAfterCleanOrders":{"type":"integer"},"data":{"type":"array","items":{"type":"object","properties":{"referenceCustomerId":{"type":"string","format":"uuid"},"name":{"type":"string"},"state":{"type":"string","enum":["supervised","proposed","autonomous","demoted"]},"cleanStreak":{"type":"integer"},"proposeAfterCleanOrders":{"type":"integer"},"eligible":{"type":"boolean"},"streakOrderIds":{"type":"array","items":{"type":"string","format":"uuid"}},"streakBrokenBy":{"type":["null","object"],"properties":{"orderId":{"type":"string","format":"uuid"},"reason":{"type":"string","enum":["corrected","incident","rejected","acknowledged"]}}},"proposedAt":{"type":["null","string"],"format":"date-time"},"grantedBy":{"type":["null","string"]},"grantedAt":{"type":["null","string"],"format":"date-time"},"demotedAt":{"type":["null","string"],"format":"date-time"},"demotionReason":{"type":["null","string"]},"incidentId":{"type":["null","string"],"format":"uuid"}}}}},"required":["mode","proposeAfterCleanOrders","data"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getAutonomyCustomers","summary":"List autonomy customers"}},"/api/v1/tenants/{tenantId}/autonomy/customers/{referenceCustomerId}":{"get":{"tags":["autonomy"],"description":"One trading partner: autonomy state, derived clean streak with the orders behind it, and its grant/demotion history from the audit log.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"referenceCustomerId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"referenceCustomerId":{"type":"string","format":"uuid"},"name":{"type":"string"},"state":{"type":"string","enum":["supervised","proposed","autonomous","demoted"]},"cleanStreak":{"type":"integer"},"proposeAfterCleanOrders":{"type":"integer"},"eligible":{"type":"boolean"},"streakOrderIds":{"type":"array","items":{"type":"string","format":"uuid"}},"streakBrokenBy":{"type":["null","object"],"properties":{"orderId":{"type":"string","format":"uuid"},"reason":{"type":"string","enum":["corrected","incident","rejected","acknowledged"]}}},"proposedAt":{"type":["null","string"],"format":"date-time"},"grantedBy":{"type":["null","string"]},"grantedAt":{"type":["null","string"],"format":"date-time"},"demotedAt":{"type":["null","string"],"format":"date-time"},"demotionReason":{"type":["null","string"]},"incidentId":{"type":["null","string"],"format":"uuid"},"mode":{"type":"string","enum":["off","shadow","enforce"]},"history":{"type":"array","items":{"type":"object","properties":{"action":{"type":"string"},"actor":{"type":"string"},"actorType":{"type":"string"},"at":{"type":"string","format":"date-time"},"metadata":{"type":"object","additionalProperties":true}}}},"recentRoutingHeadlines":{"type":"array","items":{"type":"object","properties":{"orderId":{"type":"string","format":"uuid"},"headline":{"type":"string"},"evaluatedAt":{"type":"string"}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getAutonomyCustomersByReferenceCustomerId","summary":"Get autonomy customer"}},"/api/v1/tenants/{tenantId}/autonomy/customers/{referenceCustomerId}/grant":{"post":{"tags":["autonomy"],"description":"Let this trading partner run unattended; fires autonomy.granted. Only a person can grant: a signed-in admin, or a connected app acting for one (MCP OAuth). An API key is refused with 403 AUTONOMY_GRANT_REQUIRES_PERSON (it can still revoke). The partner must meet the clean-streak bar (eligible: true, cleanStreak >= proposeAfterCleanOrders); below it the grant is refused with 409 AUTONOMY_NOT_ELIGIBLE (error.details.cleanStreak, error.details.required) unless the body sends override: true with a reason of at least 10 characters (otherwise 422 OVERRIDE_REASON_REQUIRED). An override grant is audited as autonomy.override_granted. grantedBy in the response is the person who granted. Autonomy is an additional gate, never an override of routing: the order still has to clear the confidence threshold and every existing downgrade. The body is optional.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"reason":{"type":"string","maxLength":500,"description":"Why. Required (at least 10 characters) with override: true."},"override":{"type":"boolean","description":"Grant although the partner is below the clean-streak bar. Needs a reason; audited as autonomy.override_granted."}},"additionalProperties":false}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"referenceCustomerId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"referenceCustomerId":{"type":"string","format":"uuid"},"name":{"type":"string"},"state":{"type":"string","enum":["supervised","proposed","autonomous","demoted"]},"cleanStreak":{"type":"integer"},"proposeAfterCleanOrders":{"type":"integer"},"eligible":{"type":"boolean"},"streakOrderIds":{"type":"array","items":{"type":"string","format":"uuid"}},"streakBrokenBy":{"type":["null","object"],"properties":{"orderId":{"type":"string","format":"uuid"},"reason":{"type":"string","enum":["corrected","incident","rejected","acknowledged"]}}},"proposedAt":{"type":["null","string"],"format":"date-time"},"grantedBy":{"type":["null","string"]},"grantedAt":{"type":["null","string"],"format":"date-time"},"demotedAt":{"type":["null","string"],"format":"date-time"},"demotionReason":{"type":["null","string"]},"incidentId":{"type":["null","string"],"format":"uuid"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"description":"The credential is valid but may not do this: FORBIDDEN or ACCESS_DENIED (the key lacks the permission scope, or the role is too low, or the tenant in the path is not the key's tenant), TENANT_SUSPENDED for writes on a suspended account, MFA_REQUIRED for a session that owes a passkey.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"422":{"description":"The request is well formed but its values cannot be used, for example INVALID_PERMISSIONS on an API key.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postAutonomyCustomersByReferenceCustomerIdGrant","summary":"Let this trading partner run unattended; fires autonomy.granted"}},"/api/v1/tenants/{tenantId}/autonomy/customers/{referenceCustomerId}/revoke":{"post":{"tags":["autonomy"],"description":"Take unattended processing away from this trading partner (back to supervised); fires autonomy.revoked. Any admin principal may revoke, API keys included. The body is optional.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"reason":{"type":"string","maxLength":500}},"additionalProperties":false}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"referenceCustomerId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"referenceCustomerId":{"type":"string","format":"uuid"},"name":{"type":"string"},"state":{"type":"string","enum":["supervised","proposed","autonomous","demoted"]},"cleanStreak":{"type":"integer"},"proposeAfterCleanOrders":{"type":"integer"},"eligible":{"type":"boolean"},"streakOrderIds":{"type":"array","items":{"type":"string","format":"uuid"}},"streakBrokenBy":{"type":["null","object"],"properties":{"orderId":{"type":"string","format":"uuid"},"reason":{"type":"string","enum":["corrected","incident","rejected","acknowledged"]}}},"proposedAt":{"type":["null","string"],"format":"date-time"},"grantedBy":{"type":["null","string"]},"grantedAt":{"type":["null","string"],"format":"date-time"},"demotedAt":{"type":["null","string"],"format":"date-time"},"demotionReason":{"type":["null","string"]},"incidentId":{"type":["null","string"],"format":"uuid"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"description":"The credential is valid but may not do this: FORBIDDEN or ACCESS_DENIED (the key lacks the permission scope, or the role is too low, or the tenant in the path is not the key's tenant), TENANT_SUSPENDED for writes on a suspended account, MFA_REQUIRED for a session that owes a passkey.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postAutonomyCustomersByReferenceCustomerIdRevoke","summary":"Revoke autonomy customer"}},"/api/v1/tenants/{tenantId}/diagnostics/":{"post":{"tags":["diagnostics"],"description":"Run the order diagnostic: projected auto-approval rate, exception mix, top recurring patterns with pre-seeded rules, and a purchase recommendation.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"threshold":{"type":"number","minimum":0.5,"maximum":1,"default":0.95,"description":"Auto-approval threshold to project against"}}}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postDiagnostics","summary":"Create diagnostic"},"get":{"tags":["diagnostics"],"description":"List diagnostic runs","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getDiagnostics","summary":"List diagnostic runs"}},"/api/v1/tenants/{tenantId}/diagnostics/{diagnosticId}":{"get":{"tags":["diagnostics"],"description":"Get a diagnostic run with its full report","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"diagnosticId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getDiagnosticsByDiagnosticId","summary":"Get a diagnostic run with its full report"}},"/api/v1/tenants/{tenantId}/notifications/preferences":{"get":{"tags":["notifications"],"description":"List notification preferences for a tenant","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"query","name":"userId","required":false},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"tenantId":{"type":"string","format":"uuid"},"userId":{"type":"string","format":"uuid","nullable":true},"channel":{"type":"string","enum":["email","webhook","in_app"]},"eventType":{"type":"string","enum":["order_failed","review_needed","plan_limit_warning","completed","failed","needs_review","rejected","export_failed","morning_summary","onboarding_emails"]},"enabled":{"type":"boolean"},"config":{"type":"object","additionalProperties":true},"createdAt":{"type":"string","format":"date-time"},"updatedAt":{"type":"string","format":"date-time"}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getNotificationsPreferences","summary":"List notification preferences for a tenant"},"put":{"tags":["notifications"],"description":"Upsert notification preferences for a tenant","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"preferences":{"type":"array","minItems":1,"maxItems":50,"items":{"type":"object","properties":{"channel":{"type":"string","enum":["email","webhook","in_app"]},"eventType":{"type":"string","enum":["order_failed","review_needed","plan_limit_warning","completed","failed","needs_review","rejected","export_failed","morning_summary","onboarding_emails"]},"enabled":{"type":"boolean"},"config":{"type":"object","additionalProperties":true},"userId":{"type":"string","format":"uuid","nullable":true}},"required":["channel","eventType","enabled"]}}},"required":["preferences"]}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"tenantId":{"type":"string","format":"uuid"},"userId":{"type":"string","format":"uuid","nullable":true},"channel":{"type":"string"},"eventType":{"type":"string"},"enabled":{"type":"boolean"},"config":{"type":"object","additionalProperties":true},"createdAt":{"type":"string","format":"date-time"},"updatedAt":{"type":"string","format":"date-time"}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"putNotificationsPreferences","summary":"Upsert notification preferences for a tenant"}},"/api/v1/tenants/{tenantId}/notifications/test":{"post":{"tags":["notifications"],"description":"Send a test notification (logs only in this phase)","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"channel":{"type":"string","enum":["email","webhook","in_app"],"description":"Notification channel to test"},"target":{"type":"string","minLength":1,"maxLength":500,"description":"Target address (email, webhook URL, etc.)"}},"required":["channel","target"]}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"message":{"type":"string"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"501":{"description":"Not implemented for this tenant or destination.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postNotificationsTest","summary":"Send a test notification (logs only in this phase)"}},"/api/v1/tenants/{tenantId}/export":{"post":{"tags":["tenants"],"description":"Queue a full-tenant data export bundle (tenant config, channels, envelopes, orders, line items, reference data, audit trail) as a JSON document in object storage","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"202":{"description":"Accepted. Processing continues in the background; follow it with the id in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"exportId":{"type":"string","format":"uuid"},"status":{"type":"string","enum":["queued"]}},"required":["exportId","status"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postExport","summary":"Create export"}},"/api/v1/tenants/{tenantId}/export/latest":{"get":{"tags":["tenants"],"description":"The tenant's most recent full data export: its status, and signed download URLs once it has completed. `export` is null when no export has been requested yet. Owner or admin only.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"export":{"type":"object","properties":{"exportId":{"type":"string","format":"uuid"},"status":{"type":"string","enum":["queued","running","completed","failed"]},"downloadUrl":{"type":"string","nullable":true,"description":"Signed URL to the bundle index, valid for 900 seconds. Null unless status is completed."},"parts":{"type":"array","description":"The bundle index (downloadUrl) names one NDJSON part per table section; each part is signed here. Empty unless status is completed.","items":{"type":"object","properties":{"section":{"type":"string"},"rows":{"type":"integer"},"bytes":{"type":"integer"},"sha256":{"type":"string"},"downloadUrl":{"type":"string"}},"required":["section","rows","bytes","sha256","downloadUrl"]}},"error":{"type":"string","nullable":true},"createdAt":{"type":"string","format":"date-time"},"completedAt":{"type":"string","format":"date-time","nullable":true}},"required":["exportId","status","createdAt"],"nullable":true}},"required":["export"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getExportLatest","summary":"Get export latest"}},"/api/v1/tenants/{tenantId}/export/{exportId}":{"get":{"tags":["tenants"],"description":"Get tenant export status and a signed download URL when complete","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"exportId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"exportId":{"type":"string","format":"uuid"},"status":{"type":"string","enum":["queued","running","completed","failed"]},"downloadUrl":{"type":"string","nullable":true,"description":"Signed URL to the bundle index, valid for 900 seconds. Null unless status is completed."},"parts":{"type":"array","description":"The bundle index (downloadUrl) names one NDJSON part per table section; each part is signed here. Empty unless status is completed.","items":{"type":"object","properties":{"section":{"type":"string"},"rows":{"type":"integer"},"bytes":{"type":"integer"},"sha256":{"type":"string"},"downloadUrl":{"type":"string"}},"required":["section","rows","bytes","sha256","downloadUrl"]}},"error":{"type":"string","nullable":true},"createdAt":{"type":"string","format":"date-time"},"completedAt":{"type":"string","format":"date-time","nullable":true}},"required":["exportId","status","createdAt"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getExportByExportId","summary":"Get tenant export status and a signed download URL when complete"}},"/api/v1/tenants/{tenantId}/offboard":{"post":{"tags":["tenants"],"description":"Offboard the tenant: revoke access, cancel billing, purge documents from storage (final export bundle retained), and mark the tenant offboarded. DB records (orders, audit, billing) are retained per the 7-year requirement. Two-step: the first call returns a confirmation token, the second call with that token executes. Requires a signed-in owner; API keys are refused.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"confirm":{"type":"string","description":"The tenant's slug, typed as confirmation"},"finalExport":{"type":"boolean","default":true},"confirmationToken":{"type":"string"}},"required":["confirm"]}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postOffboard","summary":"Create offboard"}},"/api/v1/tenants/{tenantId}/offboard/status":{"get":{"tags":["tenants"],"description":"Offboarding progress: tenant status plus lifecycle audit events","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getOffboardStatus","summary":"Offboarding progress: tenant status plus lifecycle audit events"}},"/api/v1/tenants/{tenantId}/privacy-requests":{"get":{"tags":["privacy"],"description":"Shopify privacy compliance requests (customers/data_request, customers/redact, shop/redact) that affected this tenant, newest first, with what was done. A completed data request whose export is still stored has exportAvailable: true; fetch it from /privacy-requests/{requestId}/download. Exports are removed at offboarding and after the tenant retention window, after which exportAvailable is false.","parameters":[{"schema":{"type":"integer","minimum":1,"maximum":200,"default":50},"in":"query","name":"limit","required":false},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"type":"object","properties":{"requestId":{"type":"string","format":"uuid"},"topic":{"type":"string","enum":["customers/data_request","customers/redact","shop/redact"]},"shopDomain":{"type":"string"},"status":{"type":"string","enum":["received","processing","completed","failed"]},"receivedAt":{"type":"string","format":"date-time"},"completedAt":{"type":"string","format":"date-time","nullable":true},"exportAvailable":{"type":"boolean"},"outcome":{"type":"object","additionalProperties":true,"nullable":true}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"getPrivacyRequests","summary":"List privacy requests"}},"/api/v1/tenants/{tenantId}/privacy-requests/{requestId}/download":{"get":{"tags":["privacy"],"description":"Download the export prepared for a Shopify customers/data_request. Redirects to a short-lived signed URL; ?format=json returns it instead. 404 when there is no export or it has been removed under the retention policy.","parameters":[{"schema":{"type":"string","enum":["redirect","json"],"default":"redirect"},"in":"query","name":"format","required":false},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"requestId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"downloadUrl":{"type":"string"},"expiresInSeconds":{"type":"integer"}},"required":["downloadUrl","expiresInSeconds"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"getPrivacyRequestsByRequestIdDownload","summary":"Download the export prepared for a Shopify customers/data_request"}},"/.well-known/oauth-authorization-server":{"get":{"tags":["oauth"],"description":"RFC 8414 authorization server metadata for the hosted MCP endpoint: endpoints, S256 PKCE, public clients (none), CIMD and DCR support, scopes orderflow:read, orderflow:write and offline_access. 404 when MCP OAuth is off.","security":[],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"issuer":{"type":"string"},"authorization_endpoint":{"type":"string"},"token_endpoint":{"type":"string"},"registration_endpoint":{"type":"string"},"revocation_endpoint":{"type":"string"},"response_types_supported":{"type":"array","items":{"type":"string"}},"grant_types_supported":{"type":"array","items":{"type":"string"}},"code_challenge_methods_supported":{"type":"array","items":{"type":"string"}},"token_endpoint_auth_methods_supported":{"type":"array","items":{"type":"string"}},"revocation_endpoint_auth_methods_supported":{"type":"array","items":{"type":"string"}},"scopes_supported":{"type":"array","items":{"type":"string"}},"client_id_metadata_document_supported":{"type":"boolean"},"authorization_response_iss_parameter_supported":{"type":"boolean"}}}}}},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"}},"operationId":"getWellKnownOauthAuthorizationServer","summary":"Get well known oauth authorization server"}},"/api/v1/oauth/authorize":{"get":{"tags":["oauth"],"description":"MCP OAuth authorization endpoint. Reached by the browser through the web origin so the session cookie is sent. Validates the client (CIMD URL or registered id) and its exact redirect_uri first; until both are good it shows an error page and never redirects. Then PKCE (S256 only), resource and scope; those errors redirect to the client with error, state and iss. A signed-out browser is sent to /login, one that owes a passkey to /login/mfa, and a signed-in one to the consent page.","parameters":[{"schema":{"type":"string"},"in":"query","name":"response_type","required":false},{"schema":{"type":"string"},"in":"query","name":"client_id","required":false},{"schema":{"type":"string"},"in":"query","name":"redirect_uri","required":false},{"schema":{"type":"string"},"in":"query","name":"code_challenge","required":false},{"schema":{"type":"string"},"in":"query","name":"code_challenge_method","required":false},{"schema":{"type":"string"},"in":"query","name":"scope","required":false},{"schema":{"type":"string"},"in":"query","name":"state","required":false},{"schema":{"type":"string"},"in":"query","name":"resource","required":false}],"security":[],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"}},"operationId":"getOauthAuthorize","summary":"MCP OAuth authorization endpoint"}},"/api/v1/oauth/token":{"post":{"tags":["oauth"],"description":"MCP OAuth token endpoint, application/x-www-form-urlencoded. grant_type=authorization_code needs code, code_verifier, redirect_uri (exactly as on the authorize request), client_id and resource; grant_type=refresh_token needs refresh_token and client_id, and may narrow scope. Refresh tokens rotate on every use; replaying a rotated one revokes the whole grant. Errors are RFC 6749 §5.2 (invalid_grant, invalid_client, invalid_request, invalid_scope, invalid_target, unsupported_grant_type).","requestBody":{"required":true,"content":{"application/x-www-form-urlencoded":{"schema":{"type":"object","properties":{"grant_type":{"type":"string","maxLength":4096},"code":{"type":"string","maxLength":4096},"code_verifier":{"type":"string","maxLength":4096},"redirect_uri":{"type":"string","maxLength":4096},"client_id":{"type":"string","maxLength":4096},"resource":{"type":"string","maxLength":4096},"refresh_token":{"type":"string","maxLength":4096},"scope":{"type":"string","maxLength":4096}}}}}},"security":[],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"access_token":{"type":"string"},"token_type":{"type":"string","enum":["Bearer"]},"expires_in":{"type":"integer"},"refresh_token":{"type":"string"},"scope":{"type":"string"}}}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string"},"error_description":{"type":"string"}}}}}},"401":{"description":"No valid credential: UNAUTHORIZED. Send X-API-Key (or a web session); a revoked or expired key is refused the same way.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string"},"error_description":{"type":"string"}}}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"}},"operationId":"postOauthToken","summary":"MCP OAuth token endpoint, application/x-www-form-urlencoded"}},"/api/v1/oauth/register":{"post":{"tags":["oauth"],"description":"MCP OAuth Dynamic Client Registration (RFC 7591), the fallback for clients that do not use Client ID Metadata Documents. Open, rate limited per client IP and in total per day. Every client is registered as public (token_endpoint_auth_method none); PKCE and exact redirect matching bind the code to it. redirect_uris: 1 to 5, https, or http on 127.0.0.1, [::1] or localhost. Unknown fields are dropped. No registration_access_token is issued.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"redirect_uris":{"type":"array","items":{"type":"string"}},"client_name":{"type":"string"},"client_uri":{"type":"string"},"grant_types":{"type":"array","items":{"type":"string"}},"response_types":{"type":"array","items":{"type":"string"}},"application_type":{"type":"string"},"token_endpoint_auth_method":{"type":"string"}}}}}},"security":[],"responses":{"201":{"description":"Created. The new resource is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"client_id":{"type":"string"},"client_id_issued_at":{"type":"integer"},"client_name":{"type":"string"},"client_uri":{"type":"string"},"redirect_uris":{"type":"array","items":{"type":"string"}},"grant_types":{"type":"array","items":{"type":"string"}},"response_types":{"type":"array","items":{"type":"string"}},"token_endpoint_auth_method":{"type":"string"},"application_type":{"type":"string"}}}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string"},"error_description":{"type":"string"}}}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string"},"error_description":{"type":"string"}}}}}}},"operationId":"postOauthRegister","summary":"Create oauth register"}},"/api/v1/oauth/revoke":{"post":{"tags":["oauth"],"description":"MCP OAuth token revocation (RFC 7009), application/x-www-form-urlencoded: token, client_id, optional token_type_hint. Revoking an access or refresh token ends the whole connection (grant). Always 200, also for an unknown token or another client's.","requestBody":{"required":true,"content":{"application/x-www-form-urlencoded":{"schema":{"type":"object","properties":{"token":{"type":"string","maxLength":4096},"token_type_hint":{"type":"string","maxLength":4096},"client_id":{"type":"string","maxLength":4096}}}}}},"security":[],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{}}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string"},"error_description":{"type":"string"}}}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"}},"operationId":"postOauthRevoke","summary":"Create oauth revoke"}},"/api/v1/tenants/{tenantId}/oauth/authorization-requests/{requestId}":{"get":{"tags":["oauth"],"description":"MCP OAuth consent: what the app asks for, for the consent page. Browser session only, and only the session that started the sign-in at /oauth/authorize; another person gets 403 OAUTH_CONSENT_USER_MISMATCH. offeredScopes never includes orderflow:write below operator. 410 OAUTH_AUTHORIZATION_REQUEST_EXPIRED after 10 minutes or once answered.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"requestId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string"},"client":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string","description":"The name the app gave itself. Unverified unless verified is true."},"redirectHosts":{"type":"array","items":{"type":"string"}},"verified":{"type":"boolean"},"localApp":{"type":"boolean","description":"Every redirect is on this computer (loopback)."}}},"requestedScopes":{"type":"array","items":{"type":"string","enum":["orderflow:read","orderflow:write"]}},"offeredScopes":{"type":"array","items":{"type":"string","enum":["orderflow:read","orderflow:write"]}},"resource":{"type":"string"},"expiresAt":{"type":"string"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"description":"The credential is valid but may not do this: FORBIDDEN or ACCESS_DENIED (the key lacks the permission scope, or the role is too low, or the tenant in the path is not the key's tenant), TENANT_SUSPENDED for writes on a suspended account, MFA_REQUIRED for a session that owes a passkey.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"410":{"description":"Gone: the resource existed but has expired or been used.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getOauthAuthorizationRequestsByRequestId","summary":"MCP OAuth consent: what the app asks for, for the consent page"}},"/api/v1/tenants/{tenantId}/oauth/authorization-requests/{requestId}/approve":{"post":{"tags":["oauth"],"description":"MCP OAuth consent: approve. Creates the grant (bound to this person, this tenant, the app and the MCP resource), supersedes this person's earlier grant to the same app, issues a 60-second single-use code and writes oauth.grant.created, all in one transaction. scopes is what the person ticked: a subset of what the app asked for; orderflow:read is always included. A viewer submitting orderflow:write gets 403 OAUTH_SCOPE_NOT_ALLOWED. Returns the redirect to send the browser to. Browser session only.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"scopes":{"type":"array","items":{"type":"string","enum":["orderflow:read","orderflow:write"]}}},"additionalProperties":false}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"requestId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"redirectTo":{"type":"string","description":"Send the browser here: the app's redirect URI with the code (or error), state and iss."}}}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"description":"The credential is valid but may not do this: FORBIDDEN or ACCESS_DENIED (the key lacks the permission scope, or the role is too low, or the tenant in the path is not the key's tenant), TENANT_SUSPENDED for writes on a suspended account, MFA_REQUIRED for a session that owes a passkey.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"410":{"description":"Gone: the resource existed but has expired or been used.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postOauthAuthorizationRequestsByRequestIdApprove","summary":"MCP OAuth consent: approve"}},"/api/v1/tenants/{tenantId}/oauth/authorization-requests/{requestId}/deny":{"post":{"tags":["oauth"],"description":"MCP OAuth consent: cancel. Consumes the request, writes oauth.grant.denied and returns the redirect that tells the app access_denied. Browser session only.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{},"additionalProperties":false}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"requestId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"redirectTo":{"type":"string","description":"Send the browser here: the app's redirect URI with the code (or error), state and iss."}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"description":"The credential is valid but may not do this: FORBIDDEN or ACCESS_DENIED (the key lacks the permission scope, or the role is too low, or the tenant in the path is not the key's tenant), TENANT_SUSPENDED for writes on a suspended account, MFA_REQUIRED for a session that owes a passkey.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"410":{"description":"Gone: the resource existed but has expired or been used.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postOauthAuthorizationRequestsByRequestIdDeny","summary":"MCP OAuth consent: cancel"}},"/api/v1/tenants/{tenantId}/oauth/grants":{"get":{"tags":["oauth"],"description":"Connected apps: MCP clients signed in with OAuth. A session sees its own; an admin or owner sees every person's with all=true; an API key with api-keys:read sees all. includeRevoked adds revoked and expired ones with the reason.","parameters":[{"schema":{"type":"boolean","default":false},"in":"query","name":"all","required":false},{"schema":{"type":"boolean","default":false},"in":"query","name":"includeRevoked","required":false},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"grants":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string"},"userId":{"type":"string"},"client":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string","description":"The name the app gave itself. Unverified unless verified is true."},"redirectHosts":{"type":"array","items":{"type":"string"}},"verified":{"type":"boolean"},"localApp":{"type":"boolean","description":"Every redirect is on this computer (loopback)."}}},"scopes":{"type":"array","items":{"type":"string","enum":["orderflow:read","orderflow:write"]}},"resource":{"type":"string"},"createdAt":{"type":"string"},"lastUsedAt":{"type":"string","nullable":true},"expiresAt":{"type":"string"},"revokedAt":{"type":"string","nullable":true},"revokedReason":{"type":"string","nullable":true}}}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"description":"The credential is valid but may not do this: FORBIDDEN or ACCESS_DENIED (the key lacks the permission scope, or the role is too low, or the tenant in the path is not the key's tenant), TENANT_SUSPENDED for writes on a suspended account, MFA_REQUIRED for a session that owes a passkey.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getOauthGrants","summary":"Connected apps: MCP clients signed in with OAuth"}},"/api/v1/tenants/{tenantId}/oauth/grants/{grantId}":{"delete":{"tags":["oauth"],"description":"Disconnect a connected app: revokes the grant, so its next MCP call is refused with 401 and its refresh token with invalid_grant. A person may revoke their own; an admin or owner, or an API key with api-keys:write, anyone's in the tenant. Idempotent: 204 when already revoked. 404 OAUTH_GRANT_NOT_FOUND otherwise, including another tenant's id. Writes oauth.grant.revoked.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"grantId","required":true}],"responses":{"204":{"description":"Done. There is no body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"deleteOauthGrantsByGrantId","summary":"Delete oauth grant"}},"/api/v1/tenants/{tenantId}/sso/sessions":{"get":{"tags":["sso"],"description":"Active sessions of this tenant's users (keyset paginated by session id; the token itself is never returned).","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"query","name":"cursor","required":false},{"schema":{"type":"integer","minimum":1,"maximum":100,"default":100},"in":"query","name":"limit","required":false},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"sessions":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"userId":{"type":"string","format":"uuid"},"email":{"type":"string"},"createdAt":{"type":"string","format":"date-time"},"expires":{"type":"string","format":"date-time"},"authenticationProvider":{"type":"string","nullable":true}},"additionalProperties":true}},"nextCursor":{"type":"string","format":"uuid","nullable":true}},"required":["sessions","nextCursor"]}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"422":{"description":"The request is well formed but its values cannot be used, for example INVALID_PERMISSIONS on an API key.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"getSsoSessions","summary":"List sso sessions"}},"/api/v1/tenants/{tenantId}/sso/sessions/revoke-all":{"post":{"tags":["sso"],"description":"End every session in the tenant at once, including the caller's own. Raises the tenant session policy version, so sessions created concurrently are refused too, then deletes the session rows. API keys are not affected. Audited as session.revoked_all.","parameters":[{"schema":{"type":"string"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"sessionsRevoked":{"type":"integer"},"policyVersion":{"type":"integer"}},"required":["sessionsRevoked","policyVersion"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"postSsoSessionsRevokeAll","summary":"End every session in the tenant at once, including the caller's own"}},"/api/v1/tenants/{tenantId}/sso/sessions/{sessionId}":{"delete":{"tags":["sso"],"description":"Revoke one session.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"sessionId","required":true}],"responses":{"204":{"description":"Done. There is no body."},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"422":{"description":"The request is well formed but its values cannot be used, for example INVALID_PERMISSIONS on an API key.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"deleteSsoSessionsBySessionId","summary":"Revoke one session"}},"/api/v1/tenants/{tenantId}/sso/settings":{"get":{"tags":["sso"],"description":"The tenant's SSO settings (defaults when none are stored).","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"enabled":{"type":"boolean"},"enforced":{"type":"boolean"},"jitEnabled":{"type":"boolean"},"defaultRole":{"type":"string","enum":["viewer","operator","admin"]},"sessionMaxAgeSeconds":{"type":"integer"},"mfaRequired":{"type":"boolean","description":"A passkey is required from everyone who does not sign in through the identity provider."},"planIncludesSso":{"type":"boolean","description":"Whether the tenant's plan includes setting up single sign-on (Growth, Scale and Enterprise). When false, creating a connection, turning SSO on, requiring it or creating a SCIM directory answers 402 PLAN_LIMIT_EXCEEDED; SSO already set up keeps working."},"ssoAvailable":{"type":"boolean","description":"Whether this deployment runs single sign-on at all. When false, every SSO setup route answers 503 SSO_DISABLED, so a client need not call GET /sso/metadata."},"hasVerifiedDomain":{"type":"boolean"},"hasConnection":{"type":"boolean"},"canEnforce":{"type":"boolean"},"enforceBlockers":{"type":"array","items":{"type":"string","enum":["verified_domain","connection","sso_enabled","sso_sign_in","off_domain_admins"]},"description":"Empty when enforced may be turned on by this caller. sso_sign_in: no SSO sign-in by this caller (a session) or by an owner/admin in the last 30 days (an API key). off_domain_admins: an active owner or admin has an email that is not on one of the tenant's verified domains (listed in offDomainAdmins); enforcement applies to every user of the tenant, so they could never sign in. Demote or deactivate them first; someone who needs the role signs in through the IdP with a verified-domain address and is given it on that account."},"offDomainAdmins":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"email":{"type":"string"},"role":{"type":"string"}},"required":["id","email","role"]},"description":"GET only. Active owners and admins of this tenant whose email is not on a verified domain. Each one blocks enforcing (off_domain_admins)."},"offDomainMembers":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"email":{"type":"string"},"role":{"type":"string"}},"required":["id","email","role"]},"description":"GET only. Active operators and viewers of this tenant whose email is not on a verified domain (at most 50). They do not block enforcing, but cannot sign in while it is on."},"offDomainMemberCount":{"type":"integer","description":"GET only. How many active operators and viewers are not on a verified domain, in all."}},"required":["enabled","enforced","jitEnabled","defaultRole","sessionMaxAgeSeconds"]}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"422":{"description":"The request is well formed but its values cannot be used, for example INVALID_PERMISSIONS on an API key.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"getSsoSettings","summary":"The tenant's SSO settings (defaults when none are stored)"},"patch":{"tags":["sso"],"description":"Update the tenant's SSO settings (partial). Turning enabled off also turns enforced off in the same write (audited as sso.settings.updated with both changes). enforced requires every sign-in of every user of the tenant to go through the IdP, including people whose email is not on a verified domain; turning it on answers 409 SSO_OFF_DOMAIN_ADMINS (details.missing off_domain_admins, details.offDomainAdminCount) while an active owner or admin is not on a verified domain; sessionMaxAgeSeconds is an idle timeout (900 to 2592000); turning enabled or enforced on needs a plan that includes SSO (Growth, Scale, Enterprise; otherwise 402 PLAN_LIMIT_EXCEEDED, details.resource sso); turning either off never does; mfaRequired requires a passkey from everyone who does not sign in through the IdP (turning it off: 403 MFA_REQUIRED unless from a browser session that has proven a passkey or used SSO).","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"enabled":{"type":"boolean"},"enforced":{"type":"boolean"},"jitEnabled":{"type":"boolean"},"defaultRole":{"type":"string","enum":["viewer","operator","admin"]},"sessionMaxAgeSeconds":{"type":"integer","minimum":900,"maximum":2592000},"mfaRequired":{"type":"boolean"}}}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"enabled":{"type":"boolean"},"enforced":{"type":"boolean"},"jitEnabled":{"type":"boolean"},"defaultRole":{"type":"string","enum":["viewer","operator","admin"]},"sessionMaxAgeSeconds":{"type":"integer"},"mfaRequired":{"type":"boolean","description":"A passkey is required from everyone who does not sign in through the identity provider."},"planIncludesSso":{"type":"boolean","description":"Whether the tenant's plan includes setting up single sign-on (Growth, Scale and Enterprise). When false, creating a connection, turning SSO on, requiring it or creating a SCIM directory answers 402 PLAN_LIMIT_EXCEEDED; SSO already set up keeps working."},"ssoAvailable":{"type":"boolean","description":"Whether this deployment runs single sign-on at all. When false, every SSO setup route answers 503 SSO_DISABLED, so a client need not call GET /sso/metadata."},"hasVerifiedDomain":{"type":"boolean"},"hasConnection":{"type":"boolean"},"canEnforce":{"type":"boolean"},"enforceBlockers":{"type":"array","items":{"type":"string","enum":["verified_domain","connection","sso_enabled","sso_sign_in","off_domain_admins"]},"description":"Empty when enforced may be turned on by this caller. sso_sign_in: no SSO sign-in by this caller (a session) or by an owner/admin in the last 30 days (an API key). off_domain_admins: an active owner or admin has an email that is not on one of the tenant's verified domains (listed in offDomainAdmins); enforcement applies to every user of the tenant, so they could never sign in. Demote or deactivate them first; someone who needs the role signs in through the IdP with a verified-domain address and is given it on that account."},"offDomainAdmins":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"email":{"type":"string"},"role":{"type":"string"}},"required":["id","email","role"]},"description":"GET only. Active owners and admins of this tenant whose email is not on a verified domain. Each one blocks enforcing (off_domain_admins)."},"offDomainMembers":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"email":{"type":"string"},"role":{"type":"string"}},"required":["id","email","role"]},"description":"GET only. Active operators and viewers of this tenant whose email is not on a verified domain (at most 50). They do not block enforcing, but cannot sign in while it is on."},"offDomainMemberCount":{"type":"integer","description":"GET only. How many active operators and viewers are not on a verified domain, in all."}},"required":["enabled","enforced","jitEnabled","defaultRole","sessionMaxAgeSeconds"]}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"402":{"description":"The plan does not allow this: SUBSCRIPTION_REQUIRED (no active subscription) or PLAN_LIMIT_EXCEEDED (details.resource names the limit).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"422":{"description":"The request is well formed but its values cannot be used, for example INVALID_PERMISSIONS on an API key.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"patchSsoSettings","summary":"Update the tenant's SSO settings (partial)"}},"/api/v1/tenants/{tenantId}/sso/domains":{"get":{"tags":["sso"],"description":"Email domains claimed by this tenant and whether each is verified.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"domain":{"type":"string"},"verified":{"type":"boolean"},"verifiedAt":{"type":"string","format":"date-time","nullable":true},"createdAt":{"type":"string","format":"date-time"},"verificationToken":{"type":"string","nullable":true,"description":"The TXT record value to publish, until the domain is verified."}},"additionalProperties":true}}},"required":["data"]}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"422":{"description":"The request is well formed but its values cannot be used, for example INVALID_PERMISSIONS on an API key.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"getSsoDomains","summary":"Email domains claimed by this tenant and whether each is verified"},"post":{"tags":["sso"],"description":"Claim an email domain, or refresh this account's pending claim. Returns the DNS TXT record (verification.recordName / recordValue) to add, then call POST /domains/:id/verify within 30 days. 409 DOMAIN_TAKEN when this account already verified it.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"domain":{"type":"string","minLength":3,"maxLength":253}},"required":["domain"]}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"201":{"description":"Created. The new resource is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"domain":{"type":"string"},"verified":{"type":"boolean"},"verificationToken":{"type":"string"},"verification":{"type":"object","properties":{"method":{"type":"string"},"recordName":{"type":"string"},"recordValue":{"type":"string"}},"required":["method","recordName","recordValue"]}},"additionalProperties":true}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"422":{"description":"The request is well formed but its values cannot be used, for example INVALID_PERMISSIONS on an API key.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"postSsoDomains","summary":"Claim an email domain, or refresh this account's pending claim"}},"/api/v1/tenants/{tenantId}/sso/domains/{id}/verify":{"post":{"tags":["sso"],"description":"Check the DNS TXT record for a claimed domain and mark it verified. 422 DOMAIN_VERIFICATION_FAILED names the record still expected, or says the claim is over 30 days old; 409 DOMAIN_TAKEN when another account verified the domain first.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"id","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"domain":{"type":"string"},"verified":{"type":"boolean"},"verifiedAt":{"type":"string","format":"date-time","nullable":true},"createdAt":{"type":"string","format":"date-time"},"verificationToken":{"type":"string","nullable":true,"description":"The TXT record value to publish, until the domain is verified."}},"additionalProperties":true}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"422":{"description":"The request is well formed but its values cannot be used, for example INVALID_PERMISSIONS on an API key.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"postSsoDomainsByIdVerify","summary":"Check the DNS TXT record for a claimed domain and mark it verified"}},"/api/v1/tenants/{tenantId}/sso/domains/{id}":{"delete":{"tags":["sso"],"description":"Release a claimed domain. 409 SSO_PRECONDITION_FAILED for the last verified domain of an SSO-enabled tenant; 409 SSO_ENFORCED_OFF_DOMAIN while SSO is enforced and an active owner or admin has an email on this domain.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","format":"uuid"},"in":"path","name":"id","required":true}],"responses":{"204":{"description":"Done. There is no body."},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"422":{"description":"The request is well formed but its values cannot be used, for example INVALID_PERMISSIONS on an API key.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"deleteSsoDomainsById","summary":"Release a claimed domain"}},"/api/v1/tenants/{tenantId}/sso/metadata":{"get":{"tags":["sso"],"description":"The service-provider values the customer enters in their IdP: ACS URL, entity id and the callback URL.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"acsUrl":{"type":"string"},"entityId":{"type":"string"},"callbackUrl":{"type":"string"},"oidcRedirectUrl":{"type":"string","description":"The redirect URI to register in an OIDC IdP."}},"required":["acsUrl","entityId","callbackUrl","oidcRedirectUrl"]}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"422":{"description":"The request is well formed but its values cannot be used, for example INVALID_PERMISSIONS on an API key.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"getSsoMetadata","summary":"Get sso metadata"}},"/api/v1/tenants/{tenantId}/sso/scim":{"get":{"tags":["sso"],"description":"The tenant's SCIM directory: whether one exists, its endpoint, token prefix and last IdP request. The token itself is never returned.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"configured":{"type":"boolean"},"directoryId":{"type":"string"},"provider":{"type":"string","enum":["azure-scim-v2","okta-scim-v2","onelogin-scim-v2","jumpcloud-scim-v2","generic-scim-v2"]},"endpoint":{"type":"string","description":"The SCIM base URL to enter in the IdP."},"tokenPrefix":{"type":"string","description":"The first characters of the current token, to tell tokens apart."},"createdAt":{"type":"string","format":"date-time"},"rotatedAt":{"type":"string","format":"date-time","nullable":true},"lastRequestAt":{"type":"string","format":"date-time","nullable":true}},"required":["configured"]}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"422":{"description":"The request is well formed but its values cannot be used, for example INVALID_PERMISSIONS on an API key.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"getSsoScim","summary":"Get sso scim"},"post":{"tags":["sso"],"description":"Create the tenant's SCIM directory. Returns the endpoint and the bearer token for the IdP; the token is shown only here. People the IdP provisions are created only on the tenant's verified domains, never taken from another tenant, and deactivated when the IdP deactivates or deletes them. 409 SCIM_DIRECTORY_EXISTS when the tenant already has one. Needs a plan that includes SSO (Growth, Scale, Enterprise; otherwise 402 PLAN_LIMIT_EXCEEDED, details.resource sso); rotating the token or deleting the directory never does.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"provider":{"type":"string","enum":["azure-scim-v2","okta-scim-v2","onelogin-scim-v2","jumpcloud-scim-v2","generic-scim-v2"],"default":"generic-scim-v2"}}}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"201":{"description":"Created. The new resource is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"directoryId":{"type":"string"},"endpoint":{"type":"string"},"token":{"type":"string","description":"The bearer token for the IdP. Shown once; store it in the IdP now."},"tokenPrefix":{"type":"string"}},"required":["endpoint","token","tokenPrefix"]}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"402":{"description":"The plan does not allow this: SUBSCRIPTION_REQUIRED (no active subscription) or PLAN_LIMIT_EXCEEDED (details.resource names the limit).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"422":{"description":"The request is well formed but its values cannot be used, for example INVALID_PERMISSIONS on an API key.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"postSsoScim","summary":"Create the tenant's SCIM directory"},"delete":{"tags":["sso"],"description":"Delete the SCIM directory. The IdP can no longer provision or deprovision; existing users are left as they are.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"204":{"description":"Done. There is no body."},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"422":{"description":"The request is well formed but its values cannot be used, for example INVALID_PERMISSIONS on an API key.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"deleteSsoScim","summary":"Delete the SCIM directory"}},"/api/v1/tenants/{tenantId}/sso/scim/rotate-token":{"post":{"tags":["sso"],"description":"Replace the SCIM bearer token. The old one stops working at once; the endpoint is unchanged. The new token is shown only here.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"directoryId":{"type":"string"},"endpoint":{"type":"string"},"token":{"type":"string","description":"The bearer token for the IdP. Shown once; store it in the IdP now."},"tokenPrefix":{"type":"string"}},"required":["endpoint","token","tokenPrefix"]}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"422":{"description":"The request is well formed but its values cannot be used, for example INVALID_PERMISSIONS on an API key.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"postSsoScimRotateToken","summary":"Replace the SCIM bearer token"}},"/api/v1/tenants/{tenantId}/sso/connections":{"get":{"tags":["sso"],"description":"IdP connections (SAML and OIDC), secrets redacted.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"data":{"type":"array","items":{"type":"object","properties":{"clientID":{"type":"string"},"name":{"type":"string","nullable":true},"description":{"type":"string","nullable":true},"protocol":{"type":"string","enum":["saml","oidc"]},"defaultRedirectUrl":{"type":"string"},"redirectUrl":{"type":"array","items":{"type":"string"}}},"additionalProperties":true}}},"required":["data"]}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"422":{"description":"The request is well formed but its values cannot be used, for example INVALID_PERMISSIONS on an API key.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"getSsoConnections","summary":"IdP connections (SAML and OIDC), secrets redacted"}},"/api/v1/tenants/{tenantId}/sso/connections/saml":{"post":{"tags":["sso"],"description":"Create a SAML connection from the IdP metadata (rawMetadata XML or a metadataUrl; one is required). Owner only. Needs a plan that includes SSO (Growth, Scale, Enterprise; otherwise 402 PLAN_LIMIT_EXCEEDED, details.resource sso).","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string","maxLength":100},"description":{"type":"string","maxLength":500},"rawMetadata":{"type":"string"},"metadataUrl":{"type":"string","format":"uri"}}}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"201":{"description":"Created. The new resource is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"clientID":{"type":"string"},"name":{"type":"string","nullable":true},"description":{"type":"string","nullable":true},"protocol":{"type":"string","enum":["saml","oidc"]},"defaultRedirectUrl":{"type":"string"},"redirectUrl":{"type":"array","items":{"type":"string"}}},"additionalProperties":true}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"402":{"description":"The plan does not allow this: SUBSCRIPTION_REQUIRED (no active subscription) or PLAN_LIMIT_EXCEEDED (details.resource names the limit).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"422":{"description":"The request is well formed but its values cannot be used, for example INVALID_PERMISSIONS on an API key.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"postSsoConnectionsSaml","summary":"Create sso connection saml"}},"/api/v1/tenants/{tenantId}/sso/connections/oidc":{"post":{"tags":["sso"],"description":"Create an enterprise OIDC connection from the IdP discovery URL and client credentials. The client secret is write-only. Owner only. Needs a plan that includes SSO (Growth, Scale, Enterprise; otherwise 402 PLAN_LIMIT_EXCEEDED, details.resource sso).","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string","maxLength":100},"description":{"type":"string","maxLength":500},"oidcDiscoveryUrl":{"type":"string","format":"uri"},"oidcClientId":{"type":"string","minLength":1},"oidcClientSecret":{"type":"string","minLength":1}},"required":["oidcDiscoveryUrl","oidcClientId","oidcClientSecret"]}}}},"parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true}],"responses":{"201":{"description":"Created. The new resource is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"clientID":{"type":"string"},"name":{"type":"string","nullable":true},"description":{"type":"string","nullable":true},"protocol":{"type":"string","enum":["saml","oidc"]},"defaultRedirectUrl":{"type":"string"},"redirectUrl":{"type":"array","items":{"type":"string"}}},"additionalProperties":true}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"402":{"description":"The plan does not allow this: SUBSCRIPTION_REQUIRED (no active subscription) or PLAN_LIMIT_EXCEEDED (details.resource names the limit).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"422":{"description":"The request is well formed but its values cannot be used, for example INVALID_PERMISSIONS on an API key.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"postSsoConnectionsOidc","summary":"Create an enterprise OIDC connection from the IdP discovery URL and client credentials"}},"/api/v1/tenants/{tenantId}/sso/connections/{clientID}":{"delete":{"tags":["sso"],"description":"Delete an IdP connection by its clientID.","parameters":[{"schema":{"type":"string","format":"uuid"},"in":"path","name":"tenantId","required":true},{"schema":{"type":"string","minLength":1},"in":"path","name":"clientID","required":true}],"responses":{"204":{"description":"Done. There is no body."},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"description":"NOT_FOUND (or a more specific *_NOT_FOUND code): no such resource in this tenant.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"409":{"description":"The resource is not in a state that allows this: for example IDEMPOTENCY_KEY_REUSED, NOT_REVIEWABLE, or a review lock held by another person (details names the holder).","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"422":{"description":"The request is well formed but its values cannot be used, for example INVALID_PERMISSIONS on an API key.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"deleteSsoConnectionsByClientID","summary":"Delete an IdP connection by its clientID"}},"/api/v1/sso/resolve":{"get":{"tags":["sso"],"description":"Public: whether this email's domain is managed by enterprise SSO. The response is identical for every non-SSO email.","parameters":[{"schema":{"type":"string"},"in":"query","name":"email","required":false}],"security":[],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","properties":{"ssoRequired":{"type":"boolean"},"tenantId":{"type":"string","format":"uuid"},"enforced":{"type":"boolean"}},"required":["ssoRequired"],"additionalProperties":true}}}},"400":{"description":"The request is malformed or fails the schema: VALIDATION_ERROR (details lists each problem) or a more specific code such as DOCUMENT_REQUIRED.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"}},"operationId":"getSsoResolve","summary":"Public: whether this email's domain is managed by enterprise SSO"}},"/api/v1/sso/oauth/authorize":{"get":{"tags":["sso"],"description":"OAuth2 authorize endpoint of the embedded SSO engine, called by the application login flow with tenant and product=orderflow; redirects to the IdP.","parameters":[{"schema":{"type":"string"},"in":"query","name":"tenant","required":false},{"schema":{"type":"string"},"in":"query","name":"product","required":false}],"security":[],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"}},"operationId":"getSsoOauthAuthorize","summary":"Get sso oauth authorize"}},"/api/v1/sso/saml/acs":{"post":{"tags":["sso"],"description":"SAML assertion consumer service: the IdP posts the SAMLResponse here (form encoded). Redirects back into the application.","security":[],"responses":{"200":{"description":"OK. The result is in the body."},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"}},"operationId":"postSsoSamlAcs","summary":"SAML assertion consumer service: the IdP posts the SAMLResponse here (form encoded)"}},"/api/v1/sso/oidc/response":{"get":{"tags":["sso"],"description":"Enterprise OIDC redirect target: the IdP returns the user here; state, PKCE, nonce and signatures are verified by the engine.","parameters":[{"schema":"object","in":"query","name":"type"},{"schema":true,"in":"query","name":"additionalProperties"}],"security":[],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"}},"operationId":"getSsoOidcResponse","summary":"Get sso oidc response"}},"/api/v1/sso/oauth/token":{"post":{"tags":["sso"],"description":"OAuth2 token exchange (form encoded, single-use authorization code) for the application login flow. Error bodies follow RFC 6749 ({ error }), not the API shape.","security":[],"responses":{"200":{"description":"OK. The result is in the body."},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"}},"operationId":"postSsoOauthToken","summary":"Create sso oauth token"}},"/api/v1/sso/oauth/userinfo":{"get":{"tags":["sso"],"description":"OAuth2 userinfo for the application login flow: Bearer access token in the Authorization header.","security":[],"responses":{"200":{"description":"OK. The result is in the body.","content":{"application/json":{"schema":{"type":"object","additionalProperties":true}}}},"401":{"description":"No valid credential: UNAUTHORIZED. Send X-API-Key (or a web session); a revoked or expired key is refused the same way.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"SERVICE_BUSY or SERVICE_UNAVAILABLE: the API is at capacity or a dependency is down. Retry after Retry-After seconds.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}},"operationId":"getSsoOauthUserinfo","summary":"Get sso oauth userinfo"}},"/api/v1/scim/v2/{directoryId}/Users":{"get":{"tags":["scim"],"description":"SCIM 2.0 (RFC 7644) for the customer's identity provider. Authenticate with the directory's bearer token (Authorization: Bearer pop_scim_…), shown once when the directory is created. Answers use the SCIM error shape.","parameters":[{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"directoryId","required":true},{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"resourceId","required":true}],"security":[{"scimBearer":[]}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getScimV2ByDirectoryIdUsers","summary":"SCIM 2.0 (RFC 7644) for the customer's identity provider"},"delete":{"tags":["scim"],"description":"SCIM 2.0 (RFC 7644) for the customer's identity provider. Authenticate with the directory's bearer token (Authorization: Bearer pop_scim_…), shown once when the directory is created. Answers use the SCIM error shape.","parameters":[{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"directoryId","required":true},{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"resourceId","required":true}],"security":[{"scimBearer":[]}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"deleteScimV2ByDirectoryIdUsers","summary":"SCIM 2.0 (RFC 7644) for the customer's identity provider"},"post":{"tags":["scim"],"description":"SCIM 2.0 (RFC 7644) for the customer's identity provider. Authenticate with the directory's bearer token (Authorization: Bearer pop_scim_…), shown once when the directory is created. Answers use the SCIM error shape.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":true,"description":"A SCIM 2.0 User or Group resource (POST, PUT) or a PatchOp (PATCH), RFC 7643/7644."}}},"description":"A SCIM 2.0 User or Group resource (POST, PUT) or a PatchOp (PATCH), RFC 7643/7644."},"parameters":[{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"directoryId","required":true},{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"resourceId","required":true}],"security":[{"scimBearer":[]}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postScimV2ByDirectoryIdUsers","summary":"SCIM 2.0 (RFC 7644) for the customer's identity provider"},"put":{"tags":["scim"],"description":"SCIM 2.0 (RFC 7644) for the customer's identity provider. Authenticate with the directory's bearer token (Authorization: Bearer pop_scim_…), shown once when the directory is created. Answers use the SCIM error shape.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":true,"description":"A SCIM 2.0 User or Group resource (POST, PUT) or a PatchOp (PATCH), RFC 7643/7644."}}},"description":"A SCIM 2.0 User or Group resource (POST, PUT) or a PatchOp (PATCH), RFC 7643/7644."},"parameters":[{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"directoryId","required":true},{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"resourceId","required":true}],"security":[{"scimBearer":[]}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"putScimV2ByDirectoryIdUsers","summary":"SCIM 2.0 (RFC 7644) for the customer's identity provider"},"patch":{"tags":["scim"],"description":"SCIM 2.0 (RFC 7644) for the customer's identity provider. Authenticate with the directory's bearer token (Authorization: Bearer pop_scim_…), shown once when the directory is created. Answers use the SCIM error shape.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":true,"description":"A SCIM 2.0 User or Group resource (POST, PUT) or a PatchOp (PATCH), RFC 7643/7644."}}},"description":"A SCIM 2.0 User or Group resource (POST, PUT) or a PatchOp (PATCH), RFC 7643/7644."},"parameters":[{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"directoryId","required":true},{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"resourceId","required":true}],"security":[{"scimBearer":[]}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"patchScimV2ByDirectoryIdUsers","summary":"SCIM 2.0 (RFC 7644) for the customer's identity provider"}},"/api/v1/scim/v2/{directoryId}/Users/{resourceId}":{"get":{"tags":["scim"],"description":"SCIM 2.0 (RFC 7644) for the customer's identity provider. Authenticate with the directory's bearer token (Authorization: Bearer pop_scim_…), shown once when the directory is created. Answers use the SCIM error shape.","parameters":[{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"directoryId","required":true},{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"resourceId","required":true}],"security":[{"scimBearer":[]}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getScimV2ByDirectoryIdUsersByResourceId","summary":"SCIM 2.0 (RFC 7644) for the customer's identity provider"},"delete":{"tags":["scim"],"description":"SCIM 2.0 (RFC 7644) for the customer's identity provider. Authenticate with the directory's bearer token (Authorization: Bearer pop_scim_…), shown once when the directory is created. Answers use the SCIM error shape.","parameters":[{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"directoryId","required":true},{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"resourceId","required":true}],"security":[{"scimBearer":[]}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"deleteScimV2ByDirectoryIdUsersByResourceId","summary":"SCIM 2.0 (RFC 7644) for the customer's identity provider"},"post":{"tags":["scim"],"description":"SCIM 2.0 (RFC 7644) for the customer's identity provider. Authenticate with the directory's bearer token (Authorization: Bearer pop_scim_…), shown once when the directory is created. Answers use the SCIM error shape.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":true,"description":"A SCIM 2.0 User or Group resource (POST, PUT) or a PatchOp (PATCH), RFC 7643/7644."}}},"description":"A SCIM 2.0 User or Group resource (POST, PUT) or a PatchOp (PATCH), RFC 7643/7644."},"parameters":[{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"directoryId","required":true},{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"resourceId","required":true}],"security":[{"scimBearer":[]}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postScimV2ByDirectoryIdUsersByResourceId","summary":"SCIM 2.0 (RFC 7644) for the customer's identity provider"},"put":{"tags":["scim"],"description":"SCIM 2.0 (RFC 7644) for the customer's identity provider. Authenticate with the directory's bearer token (Authorization: Bearer pop_scim_…), shown once when the directory is created. Answers use the SCIM error shape.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":true,"description":"A SCIM 2.0 User or Group resource (POST, PUT) or a PatchOp (PATCH), RFC 7643/7644."}}},"description":"A SCIM 2.0 User or Group resource (POST, PUT) or a PatchOp (PATCH), RFC 7643/7644."},"parameters":[{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"directoryId","required":true},{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"resourceId","required":true}],"security":[{"scimBearer":[]}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"putScimV2ByDirectoryIdUsersByResourceId","summary":"SCIM 2.0 (RFC 7644) for the customer's identity provider"},"patch":{"tags":["scim"],"description":"SCIM 2.0 (RFC 7644) for the customer's identity provider. Authenticate with the directory's bearer token (Authorization: Bearer pop_scim_…), shown once when the directory is created. Answers use the SCIM error shape.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":true,"description":"A SCIM 2.0 User or Group resource (POST, PUT) or a PatchOp (PATCH), RFC 7643/7644."}}},"description":"A SCIM 2.0 User or Group resource (POST, PUT) or a PatchOp (PATCH), RFC 7643/7644."},"parameters":[{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"directoryId","required":true},{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"resourceId","required":true}],"security":[{"scimBearer":[]}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"patchScimV2ByDirectoryIdUsersByResourceId","summary":"SCIM 2.0 (RFC 7644) for the customer's identity provider"}},"/api/v1/scim/v2/{directoryId}/Groups":{"get":{"tags":["scim"],"description":"SCIM 2.0 (RFC 7644) for the customer's identity provider. Authenticate with the directory's bearer token (Authorization: Bearer pop_scim_…), shown once when the directory is created. Answers use the SCIM error shape.","parameters":[{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"directoryId","required":true},{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"resourceId","required":true}],"security":[{"scimBearer":[]}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getScimV2ByDirectoryIdGroups","summary":"SCIM 2.0 (RFC 7644) for the customer's identity provider"},"delete":{"tags":["scim"],"description":"SCIM 2.0 (RFC 7644) for the customer's identity provider. Authenticate with the directory's bearer token (Authorization: Bearer pop_scim_…), shown once when the directory is created. Answers use the SCIM error shape.","parameters":[{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"directoryId","required":true},{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"resourceId","required":true}],"security":[{"scimBearer":[]}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"deleteScimV2ByDirectoryIdGroups","summary":"SCIM 2.0 (RFC 7644) for the customer's identity provider"},"post":{"tags":["scim"],"description":"SCIM 2.0 (RFC 7644) for the customer's identity provider. Authenticate with the directory's bearer token (Authorization: Bearer pop_scim_…), shown once when the directory is created. Answers use the SCIM error shape.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":true,"description":"A SCIM 2.0 User or Group resource (POST, PUT) or a PatchOp (PATCH), RFC 7643/7644."}}},"description":"A SCIM 2.0 User or Group resource (POST, PUT) or a PatchOp (PATCH), RFC 7643/7644."},"parameters":[{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"directoryId","required":true},{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"resourceId","required":true}],"security":[{"scimBearer":[]}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postScimV2ByDirectoryIdGroups","summary":"SCIM 2.0 (RFC 7644) for the customer's identity provider"},"put":{"tags":["scim"],"description":"SCIM 2.0 (RFC 7644) for the customer's identity provider. Authenticate with the directory's bearer token (Authorization: Bearer pop_scim_…), shown once when the directory is created. Answers use the SCIM error shape.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":true,"description":"A SCIM 2.0 User or Group resource (POST, PUT) or a PatchOp (PATCH), RFC 7643/7644."}}},"description":"A SCIM 2.0 User or Group resource (POST, PUT) or a PatchOp (PATCH), RFC 7643/7644."},"parameters":[{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"directoryId","required":true},{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"resourceId","required":true}],"security":[{"scimBearer":[]}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"putScimV2ByDirectoryIdGroups","summary":"SCIM 2.0 (RFC 7644) for the customer's identity provider"},"patch":{"tags":["scim"],"description":"SCIM 2.0 (RFC 7644) for the customer's identity provider. Authenticate with the directory's bearer token (Authorization: Bearer pop_scim_…), shown once when the directory is created. Answers use the SCIM error shape.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":true,"description":"A SCIM 2.0 User or Group resource (POST, PUT) or a PatchOp (PATCH), RFC 7643/7644."}}},"description":"A SCIM 2.0 User or Group resource (POST, PUT) or a PatchOp (PATCH), RFC 7643/7644."},"parameters":[{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"directoryId","required":true},{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"resourceId","required":true}],"security":[{"scimBearer":[]}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"patchScimV2ByDirectoryIdGroups","summary":"SCIM 2.0 (RFC 7644) for the customer's identity provider"}},"/api/v1/scim/v2/{directoryId}/Groups/{resourceId}":{"get":{"tags":["scim"],"description":"SCIM 2.0 (RFC 7644) for the customer's identity provider. Authenticate with the directory's bearer token (Authorization: Bearer pop_scim_…), shown once when the directory is created. Answers use the SCIM error shape.","parameters":[{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"directoryId","required":true},{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"resourceId","required":true}],"security":[{"scimBearer":[]}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getScimV2ByDirectoryIdGroupsByResourceId","summary":"SCIM 2.0 (RFC 7644) for the customer's identity provider"},"delete":{"tags":["scim"],"description":"SCIM 2.0 (RFC 7644) for the customer's identity provider. Authenticate with the directory's bearer token (Authorization: Bearer pop_scim_…), shown once when the directory is created. Answers use the SCIM error shape.","parameters":[{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"directoryId","required":true},{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"resourceId","required":true}],"security":[{"scimBearer":[]}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"deleteScimV2ByDirectoryIdGroupsByResourceId","summary":"SCIM 2.0 (RFC 7644) for the customer's identity provider"},"post":{"tags":["scim"],"description":"SCIM 2.0 (RFC 7644) for the customer's identity provider. Authenticate with the directory's bearer token (Authorization: Bearer pop_scim_…), shown once when the directory is created. Answers use the SCIM error shape.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":true,"description":"A SCIM 2.0 User or Group resource (POST, PUT) or a PatchOp (PATCH), RFC 7643/7644."}}},"description":"A SCIM 2.0 User or Group resource (POST, PUT) or a PatchOp (PATCH), RFC 7643/7644."},"parameters":[{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"directoryId","required":true},{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"resourceId","required":true}],"security":[{"scimBearer":[]}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"postScimV2ByDirectoryIdGroupsByResourceId","summary":"SCIM 2.0 (RFC 7644) for the customer's identity provider"},"put":{"tags":["scim"],"description":"SCIM 2.0 (RFC 7644) for the customer's identity provider. Authenticate with the directory's bearer token (Authorization: Bearer pop_scim_…), shown once when the directory is created. Answers use the SCIM error shape.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":true,"description":"A SCIM 2.0 User or Group resource (POST, PUT) or a PatchOp (PATCH), RFC 7643/7644."}}},"description":"A SCIM 2.0 User or Group resource (POST, PUT) or a PatchOp (PATCH), RFC 7643/7644."},"parameters":[{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"directoryId","required":true},{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"resourceId","required":true}],"security":[{"scimBearer":[]}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"putScimV2ByDirectoryIdGroupsByResourceId","summary":"SCIM 2.0 (RFC 7644) for the customer's identity provider"},"patch":{"tags":["scim"],"description":"SCIM 2.0 (RFC 7644) for the customer's identity provider. Authenticate with the directory's bearer token (Authorization: Bearer pop_scim_…), shown once when the directory is created. Answers use the SCIM error shape.","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":true,"description":"A SCIM 2.0 User or Group resource (POST, PUT) or a PatchOp (PATCH), RFC 7643/7644."}}},"description":"A SCIM 2.0 User or Group resource (POST, PUT) or a PatchOp (PATCH), RFC 7643/7644."},"parameters":[{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"directoryId","required":true},{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"resourceId","required":true}],"security":[{"scimBearer":[]}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"patchScimV2ByDirectoryIdGroupsByResourceId","summary":"SCIM 2.0 (RFC 7644) for the customer's identity provider"}},"/api/v1/scim/v2/{directoryId}/ServiceProviderConfig":{"get":{"tags":["scim"],"description":"SCIM 2.0 (RFC 7644) for the customer's identity provider. Authenticate with the directory's bearer token (Authorization: Bearer pop_scim_…), shown once when the directory is created. Answers use the SCIM error shape.","parameters":[{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"directoryId","required":true},{"schema":{"type":"string","minLength":1,"maxLength":255},"in":"path","name":"resourceId","required":true}],"security":[{"scimBearer":[]}],"responses":{"200":{"description":"OK. The result is in the body."},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"$ref":"#/components/responses/ServiceUnavailable"}},"operationId":"getScimV2ByDirectoryIdServiceProviderConfig","summary":"SCIM 2.0 (RFC 7644) for the customer's identity provider"}}},"servers":[{"url":"https://api.poppelo.com","description":"Production"}],"security":[{"apiKey":[]},{"sessionCookie":[]},{"sessionBearer":[]}],"tags":[{"name":"health","description":"Health check endpoints"},{"name":"tenants","description":"Tenant management"},{"name":"channels","description":"Intake channels and mailbox connections"},{"name":"orders","description":"Order submission and retrieval"},{"name":"invoices","description":"Supplier invoice submission, retrieval and review"},{"name":"upload","description":"Manual document upload and reprocessing"},{"name":"review","description":"Human review queue"},{"name":"rules","description":"Learned mapping rules and reading hints"},{"name":"autonomy","description":"Per-customer autonomy: state, grant and revoke"},{"name":"summary","description":"Morning summary"},{"name":"metrics","description":"Processing metrics and analytics"},{"name":"profiles","description":"Customer profiles and learned patterns"},{"name":"golden-data","description":"Approved orders kept as ground truth, and partner checks that re-read them"},{"name":"reference-data","description":"Reference data sync and catalog management"},{"name":"business-entities","description":"Business entities (companies) of a tenant"},{"name":"integrations","description":"Destination connectors, delivery status and history"},{"name":"destination-rules","description":"Routing rules that choose a destination"},{"name":"double-post-findings","description":"Possible duplicate postings to a destination"},{"name":"order-acknowledgements","description":"Order acknowledgements sent to trading partners"},{"name":"approve-links","description":"Single-use approve links"},{"name":"webhooks","description":"Webhook subscription management"},{"name":"notifications","description":"Notification preferences"},{"name":"users","description":"User and team management"},{"name":"invitations","description":"Team invitation management"},{"name":"api-keys","description":"API key lifecycle management"},{"name":"oauth","description":"MCP OAuth: authorization server for the hosted MCP endpoint, consent and connected apps"},{"name":"sso","description":"Enterprise SSO: resolver, engine endpoints and tenant administration"},{"name":"scim","description":"SCIM 2.0 user provisioning called by the customer's identity provider"},{"name":"onboarding","description":"Tenant onboarding and setup"},{"name":"audit","description":"Audit log and activity history"},{"name":"privacy","description":"Privacy and data-subject requests"},{"name":"diagnostics","description":"Tenant diagnostics"},{"name":"billing","description":"Subscription and billing management"},{"name":"provisioning","description":"Headless tenant provisioning for agents; requires a Poppelo-issued x-provisioning-token. The public human signup flow lives under POST /api/v1/provision/signup"},{"name":"platform","description":"Account-wide summaries that need only tenant authentication"},{"name":"format-library","description":"Cross-tenant Format Library (off everywhere)"},{"name":"marketing","description":"Anonymous marketing-site events"}]}