openapi: 3.1.0
info:
  title: Intelligence Cloud Partner API
  version: "1.0"
  summary: Customer lifecycle and conversation intelligence for Intelligence Cloud partners.
  description: |
    The Intelligence Cloud API covers two jobs:

    - **Customer lifecycle**: create and run customer companies, locations, users, products,
      connectors, First Alert rules and Insights Hub setup. Use **admin credentials**
      (a reseller admin login).
    - **Conversation intelligence**: read calls, transcripts, alerts, tasks and insights with
      **frontline credentials** (a frontline user login), and receive the After Call and First Alert
      webhooks at addresses you set with admin credentials.

    ## Credentials
    Today every integration signs in with the email and password of a **dedicated integration
    user**. Turn MFA off for that user's company (`PATCH /companies/{companyId}` with
    `mfa_enforced: false`). **API keys arrive in December 2026.**

    The integration user's password follows the company's password policy, set by the reseller
    (`GET /companies/{companyId}/security-settings`). Rotate it before it expires and at least every
    90 days. On `password_expired`, stop the integration and alert an operator.

    Each operation carries `x-required-role`, the credential to use for it:
    `reseller_admin`, `customer_admin` or `frontline_user`.

    ## Transport
    - HTTPS only, TLS 1.2 or later. Bodies are JSON, UTF-8.
    - Send `Authorization: Bearer <access_token>` on every call except login and refresh.
    - Send a descriptive `User-Agent`, e.g. `riverbend-bi-sync/1.0`.
    - Send `X-Request-ID` to have your own id echoed back as `error.request_id`.
    - Identifiers are UUID strings. Don't depend on their version or order.
    - Times are RFC 3339 in UTC.
    - Phone numbers are usually E.164 (`+15555550142`). Staff lines appear as extensions (`2101`).
      Some records carry 10-digit numbers without `+1`. Normalise before you join.

    ## Rules every client must follow
    - **Unknown query parameters are silently ignored.** The API returns 200 with unfiltered data.
      Reject unsupported filters in your client before you send the request.
    - **Only the first value of a repeated parameter is read.** Use the comma form where a list is allowed.
    - **Out of scope is 404, not 403.** A record your login cannot see returns 404.
    - **Admin logins get empty lists from the conversation-data endpoints** (`/calls`, `/alerts`,
      `/tasks`) and 404 from call detail. Check `role` from `GET /me` at startup.
    - **Always call the API at `https://app.intelligence.cloud/api/v1`**, whatever domain your users
      sign in on.
    - **Many writes are full replacement** (marked in each operation). Read, merge, then write.
    - **Only user create is idempotent**, and there the `Idempotency-Key` header is required.
    - Query strings longer than about 2,000 characters are refused with a non-JSON 404.
      This caps `location_id` lists at about 50 ids per request.
    - **Never poll for new data.** Subscribe to the After Call webhook (every call) and the First
      Alert webhook (each alert as it fires) for anything that must happen as calls and alerts arrive.
      Read the API when a person asks for something or when a webhook tells you to fetch details.
      Run scheduled jobs (exports, digests, the nightly catch-up) no more than once a day, over a
      bounded date window.
    - v1 is stable. Fields, endpoints and enum values are added without notice: ignore unknown fields
      and treat unknown enum values as "other". At least 90 days' notice is given, by email to partner
      contacts and in the guide's changelog, before documented behaviour is removed or changed, except
      where a security, legal or abuse reason requires a faster change. Undocumented behaviour
      (unknown parameters, default windows, search ranking) may change: send only documented
      parameters and always send both dates.
    - Tokens, passwords, phone-system keys, webhook URLs and recording links are secrets. Never log them,
      email them or put them in tickets. Report a suspected exposure of a secret or of conversation
      data to security@tresic.cloud straight away, copying your Tresic contact, and rotate the secret.
      For help with an integration, write to support@tresic.cloud.

    ## Rate limits
    Login: 5 per minute per IP. Refresh: 20 per minute per IP. Log in once per job and reuse the
    token. On any endpoint, back off on 429 and 503 with jitter, honouring `Retry-After` when present.

    ## Terms
    Use of this API is governed by the API and SDK Terms (`termsOfService`), which supplement your
    agreement with Tresic or your provider.
  termsOfService: https://docs.intelligence.cloud/terms/api
  contact:
    name: Intelligence Cloud partner support
    url: https://tresic.cloud
    email: support@tresic.cloud
servers:
  - url: https://app.intelligence.cloud/api/v1
    description: Production
security:
  - bearerAuth: []
tags:
  - name: Authentication
    description: Sign in, renew and sign out. Access tokens last about 15 minutes.
  - name: Resellers
    description: Your reseller's branding and outbound email (SMTP) settings.
  - name: Companies
    description: Customer companies. Each customer is one company.
  - name: Single sign-on
    description: |
      Claim and verify the customer's email domain, then connect its OpenID Connect provider.
      Order: claim domain, customer publishes the DNS TXT record, verify, connect the provider.
      Reseller admins do this; customer admins cannot.
  - name: Products
    description: |
      Products are switched on at three levels and all three must be on: company, location, user.
      Product keys: `after-call-copilot`, `first-alert-copilot`, `insights-hub`.
  - name: Locations
    description: |
      Locations hold the customer's teams and departments. Full-product customers have a Management
      location, with no alert rules, for managers' own lines. A Base Intelligence Seat customer has one
      location: managers' own lines sit there, so their own calls can raise the two alerts.
      An extension belongs to exactly one location.
  - name: User groups
    description: Groups route alerts (for example "Upset Customers") and grant Insights Hub access ("Insights Hub Access").
  - name: Connectors
    description: |
      A connector links a location to the customer's phone system. Create returns 202 and the
      connector connects in the background: check `GET` every 10 seconds, for up to 10 minutes,
      until `status` is `active`.
  - name: First Alert
    description: Alert rules, monitored numbers, the location alert webhook, and each user's alert email.
  - name: Insights Hub
    description: Which numbers and groups a location's Insights Hub covers.
  - name: Users
    description: |
      People at a customer. Managers are frontline users on several locations, mapped to all
      lines at those locations. `customer_admin` users manage the company.
  - name: After Call settings
    description: Each user's After Call summary email, end-of-day recap and digest, and number mapping.
  - name: Account
    description: Who is signed in, and which locations the login can see.
  - name: Calls
    description: Every conversation the login can see, with summary, sentiment, transcript and recording link.
  - name: Alerts
    description: |
      First Alert hits, for look-ups by number, rule, date and location. Alerts as they fire arrive
      on the First Alert webhook.
  - name: Tasks
    description: Follow-up tasks from calls.
  - name: Insights
    description: Insights Hub dashboard and topic drill-down.
  - name: Events and webhooks
    description: |
      The After Call webhook (one URL per location, every call at the location) and the
      First Alert location webhook. Both are configured with admin credentials. Payloads are
      listed under Webhooks.
x-tagGroups:
  - name: Customer lifecycle (admin credentials)
    tags: [Authentication, Resellers, Companies, Single sign-on, Products, Locations, User groups, Connectors, First Alert, Insights Hub, Users, After Call settings]
  - name: Conversation intelligence (frontline credentials)
    tags: [Account, Calls, Alerts, Tasks, Insights, Events and webhooks]

paths:
  # ---------------------------------------------------------------- Authentication
  /auth/login:
    post:
      tags: [Authentication]
      operationId: login
      summary: Sign in
      x-required-role: frontline_user
      x-also-allowed-roles: [customer_admin, reseller_admin]
      security: []
      description: |
        Exchange the integration user's email and password for an access token and a refresh token.
        Limited to 5 per minute per IP.

        Integration users need MFA off. If MFA is on, the response is `{"status": "mfa_required", …}`
        with no tokens; treat it as a configuration error. An address that signs in through the
        company's own identity provider returns 409 `federated_address`: use a password user.
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/LoginRequest'}
            example: {email: integration@example.com, password: "<password>"}
      responses:
        '200':
          description: Signed in, or a second factor is required.
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: '#/components/schemas/TokenResponse'
                  - $ref: '#/components/schemas/MfaRequired'
              example:
                access_token: "<access token>"
                refresh_token: "<refresh token>"
                token_type: Bearer
                expires_in: 899
                user:
                  id: 0193b6c2-7c46-7d12-a3f9-8e2b6c1d4f57
                  user_type: company_user
                  reseller_id: null
                  email: integration@example.com
                  first_name: Data
                  last_name: Feed
                  display_name: Data Feed
                  role: frontline_user
                  scopes: [calls:read, alerts:read, insights:read]
        '400': {$ref: '#/components/responses/BadRequest'}
        '401':
          description: "`invalid_credentials`, `account_deactivated` or `account_not_activated`."
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Error'}
        '409':
          description: "`federated_address`: this address signs in through the company's identity provider."
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Error'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /auth/refresh:
    post:
      tags: [Authentication]
      operationId: refresh
      summary: Renew the access token
      x-required-role: frontline_user
      x-also-allowed-roles: [customer_admin, reseller_admin]
      security: []
      description: |
        Returns a new access token **and a new refresh token**. Store the new refresh token; the old
        one is spent. **Sending a spent refresh token again ends the session everywhere**
        (401 `renewal_replayed`), so never send the same refresh token twice and never share one
        between processes. Renew before `expires_in` runs out, or after a 401. If refresh fails, sign in again.
        Limited to 20 per minute per IP.
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/RefreshRequest'}
            example: {refresh_token: "<refresh token>"}
      responses:
        '200':
          description: Renewed. Same body as login.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/TokenResponse'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401':
          description: "`refresh_token_invalid`, `refresh_token_expired`, `session_revoked` or `renewal_replayed`. Sign in again."
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Error'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /auth/logout:
    post:
      tags: [Authentication]
      operationId: logout
      summary: Sign out
      x-required-role: frontline_user
      x-also-allowed-roles: [customer_admin, reseller_admin]
      description: |
        Ends **all** of the user's sessions, not just this one: every refresh token the user holds
        stops working. If several jobs share one integration user, a logout in one job signs out
        the others. Most integrations never need to call this.
      responses:
        '200':
          description: Signed out everywhere.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message: {type: string}
              example: {message: Logged out successfully}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}

  # ---------------------------------------------------------------- Resellers
  /resellers/{resellerId}/branding:
    parameters:
      - $ref: '#/components/parameters/resellerId'
    get:
      tags: [Resellers]
      operationId: getResellerBranding
      summary: Read reseller branding
      x-required-role: reseller_admin
      description: Branding used in the app and in emails for all your customers. A company can override it.
      responses:
        '200':
          description: Branding. Unset fields are null.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/ResellerBrandingResponse'}
              example:
                data:
                  type: reseller_branding
                  attributes:
                    reseller_id: 0193b6c2-41d8-7e0a-9c55-2f7d1e3a9b10
                    display_name: Harborview Intelligence
                    primary_accent_color: "#1F6FB2"
                    secondary_accent_color: "#4B5563"
                    support_email: support@example.com
                    support_portal_url: https://support.example.com
                    privacy_policy_url: https://example.com/privacy
                    terms_of_service_url: https://example.com/terms
                    copyright_text: © 2026 Harborview Communications
                    created_at: "2026-11-02T15:04:05Z"
                    updated_at: "2026-11-02T15:04:05Z"
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
    patch:
      tags: [Resellers]
      operationId: updateResellerBranding
      summary: Update reseller branding
      x-required-role: reseller_admin
      description: |
        Partial update: only the fields you send change. Colours are `#RRGGBB`. URLs are http(s).
        Logos, favicon and background images are set in the Admin UI (White-labeling), or by your Tresic contact.
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/ResellerBrandingUpdate'}
            example:
              display_name: Harborview Intelligence
              primary_accent_color: "#1F6FB2"
              support_email: support@example.com
      responses:
        '200':
          description: Updated branding.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/ResellerBrandingResponse'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '422': {$ref: '#/components/responses/Unprocessable'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /resellers/{resellerId}/smtp-settings:
    parameters:
      - $ref: '#/components/parameters/resellerId'
    get:
      tags: [Resellers]
      operationId: getResellerSmtpSettings
      summary: Read outbound email (SMTP) settings
      x-required-role: reseller_admin
      description: |
        One SMTP relay covers all your customers. With none set, email goes out from the platform
        sender with your branding in the message. The password is always masked.
      responses:
        '200':
          description: Settings.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/SmtpSettingsResponse'}
              example:
                data:
                  type: smtp_settings
                  attributes:
                    reseller_id: 0193b6c2-41d8-7e0a-9c55-2f7d1e3a9b10
                    smtp_host: smtp.example.com
                    smtp_port: 587
                    smtp_username: relay-user
                    smtp_password: "••••••••"
                    sender_name: Harborview Intelligence
                    sender_email: noreply@example.com
                    created_at: "2026-11-02T15:04:05Z"
                    updated_at: "2026-11-02T15:04:05Z"
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404':
          description: No SMTP settings are configured.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Error'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
    patch:
      tags: [Resellers]
      operationId: saveResellerSmtpSettings
      summary: Save outbound email (SMTP) settings
      x-required-role: reseller_admin
      description: |
        Saves the whole relay definition. The platform tests the connection and sign-in before saving:
        200 or 201 means tested and saved, 422 means the test failed (sign-in, TLS or connect).
        Use port 587 (STARTTLS) or 465 (implicit TLS). The test proves sign-in only; send a real
        email to confirm the relay accepts mail from `sender_email`.
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/SmtpSettingsUpdate'}
            example:
              smtp_host: smtp.example.com
              smtp_port: 587
              smtp_username: relay-user
              smtp_password: "<password>"
              sender_name: Harborview Intelligence
              sender_email: noreply@example.com
      responses:
        '200':
          description: Tested and saved (updated).
          content:
            application/json:
              schema: {$ref: '#/components/schemas/SmtpSettingsResponse'}
        '201':
          description: Tested and saved (first time).
          content:
            application/json:
              schema: {$ref: '#/components/schemas/SmtpSettingsResponse'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '422':
          description: The connection test failed. Nothing was saved.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Error'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
    delete:
      tags: [Resellers]
      operationId: deleteResellerSmtpSettings
      summary: Remove outbound email (SMTP) settings
      x-required-role: reseller_admin
      description: Email goes back to the platform sender.
      responses:
        '204': {description: Removed.}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}

  # ---------------------------------------------------------------- Companies
  /resellers/{resellerId}/companies:
    parameters:
      - $ref: '#/components/parameters/resellerId'
    get:
      tags: [Companies]
      operationId: listCompanies
      summary: List customer companies
      x-required-role: reseller_admin
      description: |
        Paging fields are at the **top level** of this response (no `pagination` object).
        Filters combine with AND.
      parameters:
        - name: search
          in: query
          description: Case-insensitive **prefix** match on `company_name` only. "Riverbend" matches "Riverbend Auto Group"; "Auto Group" does not.
          schema: {type: string}
        - name: is_active
          in: query
          description: "`true` for active companies, `false` for deactivated ones."
          schema: {type: boolean}
        - $ref: '#/components/parameters/limit20'
        - $ref: '#/components/parameters/cursor'
      responses:
        '200':
          description: One page of companies.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/CompanyList'}
              example:
                data:
                  - type: company
                    attributes:
                      id: 0193b6c2-5a11-7c3e-8f20-6d4b9e1c2a77
                      reseller_id: 0193b6c2-41d8-7e0a-9c55-2f7d1e3a9b10
                      reseller_name: Harborview Communications
                      company_name: Riverbend Auto Group
                      company_code: RIVERBEND
                      primary_admin_contact_name: Jordan Lee
                      primary_admin_contact_email: jordan.lee@example.com
                      primary_admin_contact_phone: "+15555550142"
                      enabled_products: [after-call-copilot, first-alert-copilot, insights-hub]
                      is_active: true
                      mfa_enforced: false
                      location_count: 3
                      user_count: 18
                      created_at: "2026-11-02T15:04:05Z"
                      updated_at: "2026-11-02T15:06:12Z"
                has_more: false
                total_count: 1
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
    post:
      tags: [Companies]
      operationId: createCompany
      summary: Create a customer company
      x-required-role: reseller_admin
      description: |
        Creates the company and **always emails an invitation** (7-day expiry) to the primary
        contact, who becomes the company's `customer_admin`.

        - `primary_admin_contact_email` must be unique across the whole platform (409).
        - Not idempotent: a retry after a lost response returns 409. Look the company up with
          `GET /resellers/{resellerId}/companies?search=<name>` before retrying.
        - MFA follows your reseller default. To turn it off for an integration user's company,
          `PATCH /companies/{companyId}` with `mfa_enforced: false` after create, then read it back.
        - `vertical` and `address` are set with PATCH after create.
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/CompanyCreate'}
            example:
              company_name: Riverbend Auto Group
              company_code: RIVERBEND
              primary_admin_contact_name: Jordan Lee
              primary_admin_contact_email: jordan.lee@example.com
              primary_admin_contact_phone: "+15555550142"
              enabled_products: [after-call-copilot, first-alert-copilot, insights-hub]
      responses:
        '201':
          description: Created. `invited_user` is the primary contact.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/CompanyCreated'}
              example:
                data:
                  type: company
                  attributes:
                    id: 0193b6c2-5a11-7c3e-8f20-6d4b9e1c2a77
                    reseller_id: 0193b6c2-41d8-7e0a-9c55-2f7d1e3a9b10
                    reseller_name: ""
                    company_name: Riverbend Auto Group
                    company_code: RIVERBEND
                    primary_admin_contact_name: Jordan Lee
                    primary_admin_contact_email: jordan.lee@example.com
                    primary_admin_contact_phone: "+15555550142"
                    enabled_products: [after-call-copilot, first-alert-copilot, insights-hub]
                    is_active: true
                    mfa_enforced: true
                    location_count: 0
                    user_count: 0
                    created_at: "2026-11-02T15:04:05Z"
                    updated_at: "2026-11-02T15:04:05Z"
                invited_user:
                  id: 0193b6c2-5a12-7c3e-8f20-6d4b9e1c2a78
                  email: jordan.lee@example.com
                  display_name: Jordan Lee
                  status: invited
                  role: customer_admin
                  invited_at: "2026-11-02T15:04:05Z"
                  invite_expires_at: "2026-11-09T15:04:05Z"
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '409':
          description: The contact email is already in use on the platform (this also catches a retried create).
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Error'}
        '422': {$ref: '#/components/responses/Unprocessable'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /resellers/{resellerId}/companies/mfa:
    parameters:
      - $ref: '#/components/parameters/resellerId'
    get:
      tags: [Companies]
      operationId: getCompaniesMfaSummary
      summary: Read the MFA default for new companies
      x-required-role: reseller_admin
      description: "`companies_mfa_default` is the `mfa_enforced` value every new company starts with."
      responses:
        '200':
          description: MFA summary.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: object
                    properties:
                      total_active: {type: integer}
                      with_mfa_required: {type: integer}
                      companies_mfa_default: {type: boolean}
                      mfa_available: {type: boolean}
              example: {data: {total_active: 6, with_mfa_required: 2, companies_mfa_default: true, mfa_available: true}}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /companies/{companyId}:
    parameters:
      - $ref: '#/components/parameters/companyId'
    get:
      tags: [Companies]
      operationId: getCompany
      summary: Read a company
      x-required-role: reseller_admin
      description: |
        `location_count` and `user_count` read 0 on this endpoint. Use the list row, or count
        locations and users yourself.
      responses:
        '200':
          description: The company.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/CompanyResponse'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
    patch:
      tags: [Companies]
      operationId: updateCompany
      summary: Update a company
      x-required-role: reseller_admin
      description: |
        Every field is optional.
        - **`enabled_products` is a full replacement.** Sending two keys turns the third product off.
          An empty list is ignored, so you cannot clear all products this way.
        - `mfa_enforced: false` turns MFA off for the company (required for integration users).
        - Works on a deactivated company.
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/CompanyUpdate'}
            example: {mfa_enforced: false, vertical: Auto dealership, address: "100 River Rd, Springfield, IL 62701"}
      responses:
        '200':
          description: Updated company.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/CompanyResponse'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '422': {$ref: '#/components/responses/Unprocessable'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /companies/{companyId}/deactivate:
    parameters:
      - $ref: '#/components/parameters/companyId'
    post:
      tags: [Companies]
      operationId: deactivateCompany
      summary: Deactivate a company
      x-required-role: reseller_admin
      description: Suspends the company and blocks its sign-ins. Reads and PATCH still work. There is no company delete.
      responses:
        '200':
          description: "Deactivated (`is_active: false`)."
          content:
            application/json:
              schema: {$ref: '#/components/schemas/CompanyResponse'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '409': {$ref: '#/components/responses/Conflict'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /companies/{companyId}/reactivate:
    parameters:
      - $ref: '#/components/parameters/companyId'
    post:
      tags: [Companies]
      operationId: reactivateCompany
      summary: Reactivate a company
      x-required-role: reseller_admin
      responses:
        '200':
          description: Reactivated.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/CompanyResponse'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '409': {$ref: '#/components/responses/Conflict'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /companies/{companyId}/security-settings:
    parameters:
      - $ref: '#/components/parameters/companyId'
    get:
      tags: [Companies]
      operationId: getCompanySecuritySettings
      summary: Read a company's security settings
      x-required-role: reseller_admin
      description: |
        The company's password policy, session timeout and sign-in IP ranges. Password policy fields
        are inherited from the reseller unless the company overrides them
        (`password_policy_source`, `password_policy_inherited_fields`). An integration user's password
        follows this policy: rotate it before `password_expiry_days` runs out, and at least every 90 days.
      responses:
        '200':
          description: The company's security settings.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/CompanySecuritySettingsResponse'}
              example:
                data: {min_password_length: 12, require_uppercase: true, require_numbers: true, require_special_chars: true, password_expiry_days: 90, session_timeout_minutes: 30, allowed_ip_ranges: [], password_policy_source: reseller, password_policy_inherited_fields: [min_password_length, require_uppercase, require_numbers, require_special_chars, password_expiry_days]}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '403': {$ref: '#/components/responses/Forbidden'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /companies/{companyId}/branding:
    parameters:
      - $ref: '#/components/parameters/companyId'
    get:
      tags: [Companies]
      operationId: getCompanyBranding
      summary: Read company branding overrides
      x-required-role: reseller_admin
      x-also-allowed-roles: [customer_admin]
      description: Company values override the reseller's. Null means the reseller value applies.
      responses:
        '200':
          description: Company branding.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/CompanyBrandingResponse'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
    patch:
      tags: [Companies]
      operationId: updateCompanyBranding
      summary: Update company branding overrides
      x-required-role: reseller_admin
      x-also-allowed-roles: [customer_admin]
      description: Partial update. Colours are `#RRGGBB`. Images are set in the Admin UI, or by your Tresic contact.
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/CompanyBrandingUpdate'}
            example: {display_name: Riverbend Insights, primary_accent_color: "#0B5D3B"}
      responses:
        '200':
          description: Updated.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/CompanyBrandingResponse'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '422': {$ref: '#/components/responses/Unprocessable'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}

  # ---------------------------------------------------------------- SSO
  /companies/{companyId}/domains:
    parameters:
      - $ref: '#/components/parameters/companyId'
    get:
      tags: [Single sign-on]
      operationId: listCompanyDomains
      summary: List claimed domains
      x-required-role: reseller_admin
      description: Not paged.
      responses:
        '200':
          description: Domains.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items: {$ref: '#/components/schemas/CompanyDomain'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
    post:
      tags: [Single sign-on]
      operationId: claimCompanyDomain
      summary: Claim a domain
      x-required-role: reseller_admin
      description: |
        Returns the DNS TXT record the customer must publish (`verification.name` and `verification.value`).
        Claiming the same domain again returns the same record (200). Never remove and re-add a claim:
        that issues a new value. Consumer mail domains are refused (409 `consumer_domain_not_allowed`).
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [domain]
              properties:
                domain: {type: string, maxLength: 253}
            example: {domain: riverbendauto.example.com}
      responses:
        '200':
          description: Already claimed. Same record.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/CompanyDomainResponse'}
        '201':
          description: Claimed. Pending verification.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/CompanyDomainResponse'}
              example:
                data:
                  id: 0193b6c3-1a2b-7c3d-8e4f-5a6b7c8d9e01
                  domain: riverbendauto.example.com
                  status: pending
                  verification: {type: TXT, name: _ic-verify.riverbendauto.example.com, value: 3f9a1c7e2b8d4f6a0c5e9b1d7a3f2c8e}
                  verified_at: null
                  last_checked_at: null
                  last_failure_reason: null
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '409': {$ref: '#/components/responses/Conflict'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /companies/{companyId}/domains/{domainId}:
    parameters:
      - $ref: '#/components/parameters/companyId'
      - $ref: '#/components/parameters/domainId'
    delete:
      tags: [Single sign-on]
      operationId: removeCompanyDomain
      summary: Remove a domain claim
      x-required-role: reseller_admin
      description: Returns 204, also when already removed.
      responses:
        '204': {description: Removed.}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /companies/{companyId}/domains/{domainId}/verifications:
    parameters:
      - $ref: '#/components/parameters/companyId'
      - $ref: '#/components/parameters/domainId'
    get:
      tags: [Single sign-on]
      operationId: listDomainVerifications
      summary: List verification attempts
      x-required-role: reseller_admin
      responses:
        '200':
          description: History, newest first.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items: {$ref: '#/components/schemas/DomainVerification'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
    post:
      tags: [Single sign-on]
      operationId: verifyDomain
      summary: Check the TXT record now
      x-required-role: reseller_admin
      description: |
        **A failed check is a 200** with `status: pending` and a `failure_reason`. DNS can take
        minutes, occasionally days, to show the record. Retry later.
      responses:
        '200':
          description: Check result.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: {$ref: '#/components/schemas/DomainVerification'}
              example:
                data: {checked_at: "2026-11-02T15:10:00Z", status: pending, failure_reason: No matching TXT record at _ic-verify.riverbendauto.example.com}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /companies/{companyId}/identity-provider:
    parameters:
      - $ref: '#/components/parameters/companyId'
    get:
      tags: [Single sign-on]
      operationId: getIdentityProvider
      summary: Read the identity provider connection
      x-required-role: reseller_admin
      description: 404 `not_found` when no provider is connected.
      responses:
        '200':
          description: The connection. The client secret is never returned.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/IdentityProviderResponse'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
    post:
      tags: [Single sign-on]
      operationId: connectIdentityProvider
      summary: Connect an OpenID Connect provider
      x-required-role: reseller_admin
      description: |
        Works with any OpenID Connect provider. Needs at least one **verified** domain first
        (422 `no_verified_domain`). One provider per company; one company per issuer.

        After connecting, give the customer's IdP admin the `link_callback_uri` and the steps in
        `instructions[]`. Then create users with `auth_method: sso`. Test sign-in and invitations
        on your own sign-in domain before adding users.
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/IdentityProviderCreate'}
            example:
              type: oidc
              display_name: Riverbend sign-in
              issuer: https://login.example.com/riverbend
              well_known_endpoint: https://login.example.com/riverbend/.well-known/openid-configuration
              client_id: 6c1f2e3d-4b5a-4978-8e1d-0a2b3c4d5e6f
              client_auth_method: client_secret
              client_secret: "<client secret>"
              acknowledgement: "true"
      responses:
        '201':
          description: Connected.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/IdentityProviderResponse'}
        '400':
          description: "`invalid_request`, `acknowledgement_required` or `unsafe_endpoint`."
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Error'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '409':
          description: "`already_connected` or `issuer_already_in_use`."
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Error'}
        '422':
          description: "`no_verified_domain`."
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Error'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
    delete:
      tags: [Single sign-on]
      operationId: disconnectIdentityProvider
      summary: Disconnect the identity provider
      x-required-role: reseller_admin
      description: Returns 204, also when nothing is connected.
      responses:
        '204': {description: Disconnected.}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /companies/{companyId}/identity-provider/test:
    parameters:
      - $ref: '#/components/parameters/companyId'
    post:
      tags: [Single sign-on]
      operationId: testIdentityProvider
      summary: Test the identity provider connection
      x-required-role: reseller_admin
      description: Checks that the provider is reachable and correctly described. 404 when nothing is connected.
      responses:
        '200':
          description: Test result.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: object
                    properties:
                      reachable: {type: boolean}
                      checks:
                        type: array
                        items:
                          type: object
                          properties:
                            name: {type: string}
                            outcome: {type: string}
                            detail: {type: string}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}

  # ---------------------------------------------------------------- Products
  /products:
    get:
      tags: [Products]
      operationId: listProducts
      summary: List products
      x-required-role: reseller_admin
      responses:
        '200':
          description: Product catalogue.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      type: object
                      properties:
                        key: {$ref: '#/components/schemas/ProductKey'}
                        name: {type: string}
              example:
                data:
                  - {key: after-call-copilot, name: After Call Co-Pilot}
                  - {key: first-alert-copilot, name: First Alert Co-Pilot}
                  - {key: insights-hub, name: Insights Hub}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /companies/{companyId}/products:
    parameters:
      - $ref: '#/components/parameters/companyId'
    get:
      tags: [Products]
      operationId: listCompanyProducts
      summary: Company products
      x-required-role: reseller_admin
      description: Change them with `PATCH /companies/{companyId}` (`enabled_products`, full replacement).
      responses:
        '200':
          description: Each product and whether it is on.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/ProductStateList'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /companies/{companyId}/users/{userId}/products:
    parameters:
      - $ref: '#/components/parameters/companyId'
      - $ref: '#/components/parameters/userId'
    get:
      tags: [Products]
      operationId: listUserProducts
      summary: A user's products
      x-required-role: reseller_admin
      description: A user's products are per user, not per location.
      responses:
        '200':
          description: Each product and whether it is on for the user.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/ProductStateList'}
              example:
                data:
                  - {product_key: after-call-copilot, name: After Call Co-Pilot, enabled: true, enabled_at: "2026-11-02T15:20:00Z", enabled_by: 0193b6c2-41d9-7e0a-9c55-2f7d1e3a9b11}
                  - {product_key: first-alert-copilot, name: First Alert Co-Pilot, enabled: false, enabled_at: null, enabled_by: null}
                  - {product_key: insights-hub, name: Insights Hub, enabled: false, enabled_at: null, enabled_by: null}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /locations/{locationId}/users/{userId}/products/{productKey}/enable:
    parameters:
      - $ref: '#/components/parameters/locationId'
      - $ref: '#/components/parameters/userId'
      - $ref: '#/components/parameters/productKey'
    post:
      tags: [Products]
      operationId: enableUserProduct
      summary: Turn a product on for a user
      x-required-role: reseller_admin
      description: |
        The product must be on for the company and the location. Idempotent: repeating returns 200.
        The user must be assigned to the location.
      responses:
        '200':
          description: Product state.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/ProductStateResponse'}
              example:
                data: {product_key: after-call-copilot, name: After Call Co-Pilot, enabled: true, enabled_at: "2026-11-02T15:20:00Z", enabled_by: 0193b6c2-41d9-7e0a-9c55-2f7d1e3a9b11}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '409': {$ref: '#/components/responses/Conflict'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /locations/{locationId}/users/{userId}/products/{productKey}/disable:
    parameters:
      - $ref: '#/components/parameters/locationId'
      - $ref: '#/components/parameters/userId'
      - $ref: '#/components/parameters/productKey'
    post:
      tags: [Products]
      operationId: disableUserProduct
      summary: Turn a product off for a user
      x-required-role: reseller_admin
      description: Idempotent. After a disable, `enabled_at` and `enabled_by` are null.
      responses:
        '200':
          description: Product state.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/ProductStateResponse'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}

  # ---------------------------------------------------------------- Locations
  /verticals:
    get:
      tags: [Locations]
      operationId: listVerticals
      summary: List industries
      x-required-role: reseller_admin
      description: Every location needs a `vertical_id` from this list.
      responses:
        '200':
          description: Industries.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      type: object
                      properties:
                        id: {type: string, format: uuid}
                        key: {type: string}
                        name: {type: string}
                        description: {type: string}
                        is_active: {type: boolean}
                        display_order: {type: integer}
              example:
                data:
                  - {id: 0193b6c2-0001-7000-8000-00000000c5b5, key: csps-msps, name: "CSPs & MSPs (Service Providers)", description: "Communications and managed service providers", is_active: true, display_order: 4}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /companies/{companyId}/locations:
    parameters:
      - $ref: '#/components/parameters/companyId'
    get:
      tags: [Locations]
      operationId: listCompanyLocations
      summary: List a company's locations
      x-required-role: reseller_admin
      description: Send `limit=100` and follow `next_cursor` while `has_more` is true. Filters combine with AND.
      parameters:
        - name: search
          in: query
          description: Case-insensitive **substring** match on `location_name`.
          schema: {type: string}
        - name: is_active
          in: query
          schema: {type: boolean}
        - $ref: '#/components/parameters/limit20'
        - $ref: '#/components/parameters/cursor'
        - $ref: '#/components/parameters/offset'
      responses:
        '200':
          description: One page of locations.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/LocationList'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
    post:
      tags: [Locations]
      operationId: createLocation
      summary: Create a location
      x-required-role: reseller_admin
      description: |
        A new location has no alert rules. `location_name` is unique within the company (409).
        `enabled_products` must be a subset of the company's products (422).
        Leave the support contact fields out: an email there invites that person as an admin.
        Not idempotent: on a lost response, list by `search` before retrying.
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/LocationCreate'}
            example:
              location_name: Riverbend - Service
              street: 100 River Rd
              city: Springfield
              state: IL
              country: United States
              zipcode: "62701"
              vertical_id: 0193b6c2-0001-7000-8000-00000000c5b5
              enabled_products: [after-call-copilot, first-alert-copilot, insights-hub]
      responses:
        '201':
          description: Created. Name fields (`company_name`, `reseller_name`, `vertical_name`) are empty here; GET fills them.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/LocationResponse'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404':
          description: Unknown `vertical_id`, or company not found.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Error'}
        '409': {$ref: '#/components/responses/Conflict'}
        '422': {$ref: '#/components/responses/Unprocessable'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /companies/{companyId}/locations/{locationId}:
    parameters:
      - $ref: '#/components/parameters/companyId'
      - $ref: '#/components/parameters/locationId'
    get:
      tags: [Locations]
      operationId: getLocation
      summary: Read a location
      x-required-role: reseller_admin
      responses:
        '200':
          description: The location.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/LocationResponse'}
              example:
                data:
                  type: location
                  attributes:
                    id: 0193b6c2-6b29-7a51-b0e4-1c8f3d5e7a02
                    company_id: 0193b6c2-5a11-7c3e-8f20-6d4b9e1c2a77
                    company_name: Riverbend Auto Group
                    reseller_name: Harborview Communications
                    location_name: Riverbend - Service
                    street: 100 River Rd
                    city: Springfield
                    state: IL
                    country: United States
                    zipcode: "62701"
                    support_contact_name: ""
                    support_contact_email: ""
                    support_contact_phone: ""
                    vertical_id: 0193b6c2-0001-7000-8000-00000000c5b5
                    vertical_name: "CSPs & MSPs (Service Providers)"
                    enabled_products: [after-call-copilot, first-alert-copilot, insights-hub]
                    is_active: true
                    created_at: "2026-11-02T15:12:00Z"
                    updated_at: "2026-11-02T15:12:00Z"
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
    patch:
      tags: [Locations]
      operationId: updateLocation
      summary: Update a location
      x-required-role: reseller_admin
      description: Every field is optional. **`enabled_products` is a full replacement.** Works on an inactive location.
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/LocationUpdate'}
            example: {location_name: Riverbend - Service Department}
      responses:
        '200':
          description: Updated.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/LocationResponse'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '409': {$ref: '#/components/responses/Conflict'}
        '422': {$ref: '#/components/responses/Unprocessable'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /companies/{companyId}/locations/{locationId}/deactivate:
    parameters:
      - $ref: '#/components/parameters/companyId'
      - $ref: '#/components/parameters/locationId'
    post:
      tags: [Locations]
      operationId: deactivateLocation
      summary: Deactivate a location
      x-required-role: reseller_admin
      description: |
        There is no location delete. While inactive, `GET /locations/{locationId}/users` returns 422;
        other reads and writes still work. Read `is_active` to tell whether a location is inactive.
      responses:
        '200':
          description: Deactivated.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/LocationResponse'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '409': {$ref: '#/components/responses/Conflict'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /companies/{companyId}/locations/{locationId}/reactivate:
    parameters:
      - $ref: '#/components/parameters/companyId'
      - $ref: '#/components/parameters/locationId'
    post:
      tags: [Locations]
      operationId: reactivateLocation
      summary: Reactivate a location
      x-required-role: reseller_admin
      responses:
        '200':
          description: Reactivated.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/LocationResponse'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '409': {$ref: '#/components/responses/Conflict'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}

  # ---------------------------------------------------------------- User groups
  /locations/{locationId}/user-groups:
    parameters:
      - $ref: '#/components/parameters/locationId'
    get:
      tags: [User groups]
      operationId: listUserGroups
      summary: List a location's groups
      x-required-role: reseller_admin
      description: Rows don't include members; read a single group for those.
      parameters:
        - name: search
          in: query
          description: Case-insensitive substring match on `group_name`.
          schema: {type: string}
        - $ref: '#/components/parameters/limit20'
        - $ref: '#/components/parameters/cursor'
      responses:
        '200':
          description: One page of groups.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/UserGroupList'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
    post:
      tags: [User groups]
      operationId: createUserGroup
      summary: Create a group
      x-required-role: reseller_admin
      description: "`group_name` is unique within the location (409). Not idempotent."
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [group_name]
              properties:
                group_name: {type: string, minLength: 2, maxLength: 200}
                member_ids:
                  type: array
                  description: Users assigned to this location.
                  items: {type: string, format: uuid}
            example: {group_name: Upset Customers}
      responses:
        '201':
          description: Created.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/UserGroupResponse'}
              example:
                data:
                  type: user_group
                  attributes: {id: 0193b6c2-8d51-74e0-9b6a-2c7e1f3d5a10, location_id: 0193b6c2-6b29-7a51-b0e4-1c8f3d5e7a02, group_name: Upset Customers, user_count: 0, created_at: "2026-11-02T15:14:00Z", updated_at: "2026-11-02T15:14:00Z"}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '409': {$ref: '#/components/responses/Conflict'}
        '422': {$ref: '#/components/responses/Unprocessable'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /locations/{locationId}/user-groups/{groupId}:
    parameters:
      - $ref: '#/components/parameters/locationId'
      - $ref: '#/components/parameters/groupId'
    get:
      tags: [User groups]
      operationId: getUserGroup
      summary: Read a group with its members
      x-required-role: reseller_admin
      responses:
        '200':
          description: The group and `members[]`.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/UserGroupResponse'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
    patch:
      tags: [User groups]
      operationId: updateUserGroup
      summary: Rename a group or set its members
      x-required-role: reseller_admin
      description: |
        **`member_ids` replaces the whole membership.** Read the group, merge, then write.
        Every id must be a user at this location (422).
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                group_name: {type: string, minLength: 2, maxLength: 200}
                member_ids:
                  type: array
                  items: {type: string, format: uuid}
            example: {member_ids: [0193b6c2-7c45-7d12-a3f9-8e2b6c1d4f56]}
      responses:
        '200':
          description: Updated.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/UserGroupResponse'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '409': {$ref: '#/components/responses/Conflict'}
        '422': {$ref: '#/components/responses/Unprocessable'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
    delete:
      tags: [User groups]
      operationId: deleteUserGroup
      summary: Delete a group
      x-required-role: reseller_admin
      description: Remove the group from alert rules first, or pass `force=true`.
      parameters:
        - name: force
          in: query
          description: Delete even when alert rules still route to the group.
          schema: {type: boolean, default: false}
      responses:
        '204': {description: Deleted.}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '409': {$ref: '#/components/responses/Conflict'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /locations/{locationId}/users/{userId}/group-membership:
    parameters:
      - $ref: '#/components/parameters/locationId'
      - $ref: '#/components/parameters/userId'
    get:
      tags: [User groups]
      operationId: getUserGroupMembership
      summary: A user's groups at a location
      x-required-role: reseller_admin
      description: "Lists every group at the location with `is_member`. The Insights Hub access group shows `product_keys: [\"insights-hub\"]`."
      responses:
        '200':
          description: Groups.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/GroupMembershipList'}
              example:
                data:
                  - {id: 0193b6c2-8d52-74e0-9b6a-2c7e1f3d5a11, name: Insights Hub Access, is_member: true, product_keys: [insights-hub]}
                  - {id: 0193b6c2-8d51-74e0-9b6a-2c7e1f3d5a10, name: Upset Customers, is_member: true, product_keys: []}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
    put:
      tags: [User groups]
      operationId: setUserGroupMembership
      summary: Set a user's groups at a location
      x-required-role: reseller_admin
      description: |
        **Full replacement** for this user at this location. `group_ids` is required; `[]` removes
        the user from every group. Set membership before per-alert email preferences.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [group_ids]
              properties:
                group_ids:
                  type: array
                  items: {type: string, format: uuid}
            example: {group_ids: [0193b6c2-8d51-74e0-9b6a-2c7e1f3d5a10, 0193b6c2-8d52-74e0-9b6a-2c7e1f3d5a11]}
      responses:
        '200':
          description: The user's groups after the change.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/GroupMembershipList'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '422': {$ref: '#/components/responses/Unprocessable'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}

  # ---------------------------------------------------------------- Connectors
  /connector-types:
    get:
      tags: [Connectors]
      operationId: listConnectorTypes
      summary: List connector types
      x-required-role: reseller_admin
      description: Use `netsapiens` for the phone system connector.
      responses:
        '200':
          description: Connector types.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      type: object
                      properties:
                        key: {type: string}
                        name: {type: string}
              example: {data: [{key: netsapiens, name: NetSapiens}]}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /locations/{locationId}/connectors/test:
    parameters:
      - $ref: '#/components/parameters/locationId'
    post:
      tags: [Connectors]
      operationId: testConnector
      summary: Dry-run a connector
      x-required-role: reseller_admin
      description: |
        Checks that the phone system is **reachable and the key authenticates**. Saves nothing.
        It does not check the key's write permissions; create reports those (`state_reason:
        invalid_permissions`). The key must be read/write. A failed test is a 200 with
        `success: false`. Show your own message rather than the `error` text.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [type, config]
              properties:
                type: {type: string, enum: [netsapiens]}
                config: {$ref: '#/components/schemas/NetSapiensConfigInput'}
                connector_id:
                  type: string
                  format: uuid
                  description: Test new settings for an existing connector.
            example:
              type: netsapiens
              config: {api_url: https://pbx.example.com/ns-api/v2, domain: riverbend.example, api_key: "<api key>"}
      responses:
        '200':
          description: Test result.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: object
                    properties:
                      success: {type: boolean}
              example: {data: {success: true}}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /locations/{locationId}/connectors:
    parameters:
      - $ref: '#/components/parameters/locationId'
    get:
      tags: [Connectors]
      operationId: listLocationConnectors
      summary: List a location's connectors
      x-required-role: reseller_admin
      parameters:
        - name: search
          in: query
          description: Substring match on the connector name.
          schema: {type: string}
        - name: status
          in: query
          description: One status. Invalid values return 400.
          schema: {$ref: '#/components/schemas/ConnectorStatus'}
        - $ref: '#/components/parameters/limit20'
        - $ref: '#/components/parameters/cursor'
      responses:
        '200':
          description: One page of connectors.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/ConnectorList'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
    post:
      tags: [Connectors]
      operationId: createConnector
      summary: Create a connector
      x-required-role: reseller_admin
      description: |
        Returns **202** with `status: connecting`. The platform then checks the key and subscribes
        to call records in the background. Check `GET /locations/{locationId}/connectors/{connectorId}`
        every 10 seconds, for up to 10 minutes, until `status` is `active` (calls flow) or `error` (read `state_reason` and `status_message`).

        - `api_url` is the full API root ending in `/ns-api/v2`.
        - The key must be read/write; a read-only key ends in `error` / `invalid_permissions`.
        - A domain-level key, or a reseller-level key with the domain set, both work.
        - Run the dry run first. Not idempotent: on a lost response, list connectors before retrying.
        - Connectors are never deleted; deactivate instead.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name, type, config]
              properties:
                name: {type: string}
                type: {type: string, enum: [netsapiens]}
                config: {$ref: '#/components/schemas/NetSapiensConfigInput'}
            example:
              name: Riverbend phone system
              type: netsapiens
              config: {api_url: https://pbx.example.com/ns-api/v2, domain: riverbend.example, api_key: "<api key>"}
      responses:
        '202':
          description: Accepted. Connecting in the background.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/ConnectorResponse'}
              example:
                data:
                  id: 4b7e9d2c-1a3f-4e8b-9c6d-2f5a8e1b3c70
                  location_id: 0193b6c2-6b29-7a51-b0e4-1c8f3d5e7a02
                  name: Riverbend phone system
                  type: netsapiens
                  type_display_name: NetSapiens
                  config: {api_url: https://pbx.example.com/ns-api/v2, domain: riverbend.example}
                  status: connecting
                  status_display: connecting
                  status_message: null
                  last_synced_at: null
                  created_at: "2026-11-02T15:16:00Z"
                  updated_at: "2026-11-02T15:16:00Z"
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '409': {$ref: '#/components/responses/Conflict'}
        '422': {$ref: '#/components/responses/Unprocessable'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /locations/{locationId}/connectors/{connectorId}:
    parameters:
      - $ref: '#/components/parameters/locationId'
      - $ref: '#/components/parameters/connectorId'
    get:
      tags: [Connectors]
      operationId: getConnector
      summary: Read a connector
      x-required-role: reseller_admin
      description: |
        Check this every 10 seconds, for up to 10 minutes, after create, update, deactivate or
        reactivate. The API key is never returned.
      responses:
        '200':
          description: The connector.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/ConnectorResponse'}
              example:
                data:
                  id: 4b7e9d2c-1a3f-4e8b-9c6d-2f5a8e1b3c70
                  location_id: 0193b6c2-6b29-7a51-b0e4-1c8f3d5e7a02
                  name: Riverbend phone system
                  type: netsapiens
                  type_display_name: NetSapiens
                  config: {api_url: https://pbx.example.com/ns-api/v2, domain: riverbend.example}
                  status: active
                  status_display: active
                  status_message: null
                  last_synced_at: "2026-11-02T15:16:20Z"
                  created_at: "2026-11-02T15:16:00Z"
                  updated_at: "2026-11-02T15:16:20Z"
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
    patch:
      tags: [Connectors]
      operationId: updateConnector
      summary: Update a connector
      x-required-role: reseller_admin
      description: |
        Rename it or change its settings. `type` cannot change. When moving to another server or domain,
        change `api_url` and `domain` first, then the key. Check `GET` afterwards until it settles.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                name: {type: string}
                config: {$ref: '#/components/schemas/NetSapiensConfigInput'}
            example: {name: Riverbend phone system (main)}
      responses:
        '200':
          description: Updated.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/ConnectorResponse'}
        '202':
          description: Accepted. Reconnecting in the background.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/ConnectorResponse'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '422': {$ref: '#/components/responses/Unprocessable'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /locations/{locationId}/connectors/{connectorId}/deactivate:
    parameters:
      - $ref: '#/components/parameters/locationId'
      - $ref: '#/components/parameters/connectorId'
    post:
      tags: [Connectors]
      operationId: deactivateConnector
      summary: Stop a connector
      x-required-role: reseller_admin
      description: |
        Returns 202 `deactivating`, then `inactive` within seconds. Calls stop flowing.
        Monitored-number settings are kept. Repeating returns 409.
      responses:
        '202':
          description: Stopping.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/ConnectorResponse'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '409': {$ref: '#/components/responses/Conflict'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /locations/{locationId}/connectors/{connectorId}/reactivate:
    parameters:
      - $ref: '#/components/parameters/locationId'
      - $ref: '#/components/parameters/connectorId'
    post:
      tags: [Connectors]
      operationId: reactivateConnector
      summary: Restart a connector
      x-required-role: reseller_admin
      description: Returns 202 `connecting`. Check its status every 10 seconds, for up to 10 minutes, until `active` or `error`.
      responses:
        '202':
          description: Restarting.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/ConnectorResponse'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '409': {$ref: '#/components/responses/Conflict'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /companies/{companyId}/connectors:
    parameters:
      - $ref: '#/components/parameters/companyId'
    get:
      tags: [Connectors]
      operationId: listCompanyConnectors
      summary: List a company's connectors
      x-required-role: reseller_admin
      description: "`errors[]` lists connectors in `error` with their message, for a health check."
      parameters:
        - name: search
          in: query
          description: Substring match on the connector name.
          schema: {type: string}
        - name: status
          in: query
          schema: {$ref: '#/components/schemas/ConnectorStatus'}
        - name: type
          in: query
          description: Connector type key. Invalid values return 400.
          schema: {type: string, enum: [netsapiens]}
        - $ref: '#/components/parameters/limit20'
        - $ref: '#/components/parameters/cursor'
      responses:
        '200':
          description: One page of connectors.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/CompanyConnectorList'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}

  # ---------------------------------------------------------------- First Alert
  /locations/{locationId}/first-alert/rules:
    parameters:
      - $ref: '#/components/parameters/locationId'
    get:
      tags: [First Alert]
      operationId: listAlertRules
      summary: List a location's alert rules
      x-required-role: reseller_admin
      description: Rows carry `trigger_types[]` only. Read a single rule for its triggers.
      parameters:
        - $ref: '#/components/parameters/limit25'
        - $ref: '#/components/parameters/cursor'
      responses:
        '200':
          description: One page of rules.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/AlertRuleList'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
    post:
      tags: [First Alert]
      operationId: createAlertRule
      summary: Create an alert rule
      x-required-role: reseller_admin
      description: |
        Create rules with `enabled: false` and enable them once numbers and recipients are set.
        `name` is unique within the location (409). Not idempotent.

        The Base Intelligence Seat uses two rules routed to the managers' group:
        - **Upset Customer**: `sentiment` `lt` −40, priority `high`.
        - **Customer Threat**: `sentiment` `lt` −20 AND `keyword_match` on the customer-threat phrases, `match_logic: all`, priority `critical`.
          The phrases are provided and maintained by Tresic; ask your Tresic contact for the current list.
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/AlertRuleCreate'}
            examples:
              upset:
                summary: Upset Customer
                value:
                  name: Upset Customer
                  priority: high
                  match_logic: any
                  enabled: false
                  triggers:
                    - {trigger_type: sentiment, config: {operator: lt, threshold: -40}}
                  group_ids: [0193b6c2-8d51-74e0-9b6a-2c7e1f3d5a10]
              threat:
                summary: Customer Threat
                value:
                  name: Customer Threat
                  priority: critical
                  match_logic: all
                  enabled: false
                  triggers:
                    - {trigger_type: sentiment, config: {operator: lt, threshold: -20}}
                    - {trigger_type: keyword_match, config: {match_logic: any, keywords: ["<phrase supplied by your Tresic contact>", "<phrase supplied by your Tresic contact>"]}}
                  group_ids: [0193b6c2-8d51-74e0-9b6a-2c7e1f3d5a10]
      responses:
        '201':
          description: Created.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/AlertRuleResponse'}
              example:
                data:
                  type: first_alert_rule
                  attributes:
                    id: 6f1c2e8a-3b4d-4c9e-a7f2-1d5e8b9c0a31
                    location_id: 0193b6c2-6b29-7a51-b0e4-1c8f3d5e7a02
                    name: Upset Customer
                    priority: high
                    match_logic: any
                    enabled: false
                    is_default: false
                    triggers:
                      - {id: 9a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d, trigger_type: sentiment, config: {operator: lt, threshold: -40}}
                    groups:
                      - {id: 0193b6c2-8d51-74e0-9b6a-2c7e1f3d5a10, group_name: Upset Customers}
                    created_at: "2026-11-02T15:18:00Z"
                    updated_at: "2026-11-02T15:18:00Z"
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '409': {$ref: '#/components/responses/Conflict'}
        '422': {$ref: '#/components/responses/Unprocessable'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /locations/{locationId}/first-alert/rules/{ruleId}:
    parameters:
      - $ref: '#/components/parameters/locationId'
      - $ref: '#/components/parameters/ruleId'
    get:
      tags: [First Alert]
      operationId: getAlertRule
      summary: Read an alert rule
      x-required-role: reseller_admin
      responses:
        '200':
          description: The full rule.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/AlertRuleResponse'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
    patch:
      tags: [First Alert]
      operationId: updateAlertRule
      summary: Update an alert rule
      x-required-role: reseller_admin
      description: |
        Every field is optional; omitted fields keep their value. **`triggers` replaces the whole
        trigger set. `group_ids` replaces the groups; `[]` clears them.** Send `{"enabled": true}` to switch a rule on.
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/AlertRuleUpdate'}
            example: {enabled: true}
      responses:
        '200':
          description: Updated.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/AlertRuleResponse'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '409': {$ref: '#/components/responses/Conflict'}
        '422': {$ref: '#/components/responses/Unprocessable'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
    delete:
      tags: [First Alert]
      operationId: deleteAlertRule
      summary: Delete an alert rule
      x-required-role: reseller_admin
      description: Platform default rules can't be deleted (409); disable them instead.
      responses:
        '204': {description: Deleted.}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '409': {$ref: '#/components/responses/Conflict'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /locations/{locationId}/first-alert/rules/{ruleId}/duplicate:
    parameters:
      - $ref: '#/components/parameters/locationId'
      - $ref: '#/components/parameters/ruleId'
    post:
      tags: [First Alert]
      operationId: duplicateAlertRule
      summary: Copy an alert rule
      x-required-role: reseller_admin
      description: Creates "<name> (Copy)", disabled, with the same triggers and groups.
      responses:
        '201':
          description: The copy.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/AlertRuleResponse'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '409': {$ref: '#/components/responses/Conflict'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /locations/{locationId}/first-alert/config:
    parameters:
      - $ref: '#/components/parameters/locationId'
    get:
      tags: [First Alert]
      operationId: getFirstAlertConfig
      summary: Read monitored numbers and the alert webhook
      x-required-role: reseller_admin
      responses:
        '200':
          description: Location First Alert configuration.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/FirstAlertConfigResponse'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
    put:
      tags: [First Alert]
      operationId: saveFirstAlertConfig
      summary: Set monitored numbers and the alert webhook
      x-required-role: reseller_admin
      description: |
        **Full replacement.** Send every monitored number and send `webhook_url` every time
        (omit it and it is cleared). `webhook_url` must be HTTPS; it receives each alert at this
        location (see the First Alert webhook). Numbers are the extensions and DIDs at this location,
        read from the phone system with your own key; this API cannot list them.
        This call does not check whether another location also monitors a number: keep each
        extension at exactly one location.
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/FirstAlertConfigUpdate'}
            example:
              webhook_url: https://hooks.example.com/riverbend/alerts
              connector_mappings:
                - connector_id: 4b7e9d2c-1a3f-4e8b-9c6d-2f5a8e1b3c70
                  monitored_numbers: ["2101", "2102", "2103", "+15555550142"]
      responses:
        '200':
          description: Saved.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/FirstAlertConfigResponse'}
              example:
                data:
                  webhook_url: https://hooks.example.com/riverbend/alerts
                  connector_mappings:
                    - id: 2d3e4f5a-6b7c-4d8e-9f0a-1b2c3d4e5f60
                      connector_id: 4b7e9d2c-1a3f-4e8b-9c6d-2f5a8e1b3c70
                      connector_name: Riverbend phone system
                      connector_type: netsapiens
                      monitored_numbers: ["2101", "2102", "2103", "+15555550142"]
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '422': {$ref: '#/components/responses/Unprocessable'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /locations/{locationId}/first-alert/config/test-webhook:
    parameters:
      - $ref: '#/components/parameters/locationId'
    post:
      tags: [First Alert]
      operationId: testFirstAlertWebhook
      summary: Test the alert webhook
      x-required-role: reseller_admin
      description: Sends a test request to `url` and reports whether your endpoint answered with 2xx.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [url]
              properties:
                url: {type: string, format: uri}
            example: {url: https://hooks.example.com/riverbend/alerts}
      responses:
        '200':
          description: Test result.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: object
                    properties:
                      success: {type: boolean}
                      status_code: {type: integer, description: HTTP status your endpoint returned.}
              example: {data: {success: true, status_code: 200}}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '422': {$ref: '#/components/responses/Unprocessable'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /locations/{locationId}/users/{userId}/first-alert/notification-preferences:
    parameters:
      - $ref: '#/components/parameters/locationId'
      - $ref: '#/components/parameters/userId'
    get:
      tags: [First Alert]
      operationId: getAlertNotificationPreferences
      summary: Read a user's alert email and digest
      x-required-role: reseller_admin
      description: |
        **camelCase and not wrapped in `data`.** `emailNotifications.alerts` lists the rules the user
        receives through group membership.
      responses:
        '200':
          description: Preferences.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/AlertNotificationPreferences'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /locations/{locationId}/users/{userId}/first-alert/email-preferences:
    parameters:
      - $ref: '#/components/parameters/locationId'
      - $ref: '#/components/parameters/userId'
    put:
      tags: [First Alert]
      operationId: setAlertEmailPreferences
      summary: Set a user's alert email
      x-required-role: reseller_admin
      description: |
        `masterEnabled: false` turns all alert email off (frontline users). For managers, set
        `masterEnabled: true` and list each rule. Omitting `alerts` keeps the per-rule toggles.
        A rule the user doesn't receive returns 400; set group membership first.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [masterEnabled]
              properties:
                masterEnabled: {type: boolean}
                alerts:
                  type: array
                  items:
                    type: object
                    required: [alertId, emailEnabled]
                    properties:
                      alertId: {type: string, format: uuid, description: Alert rule id.}
                      emailEnabled: {type: boolean}
            example:
              masterEnabled: true
              alerts:
                - {alertId: 6f1c2e8a-3b4d-4c9e-a7f2-1d5e8b9c0a31, emailEnabled: true}
                - {alertId: 6f1c2e8a-3b4d-4c9e-a7f2-1d5e8b9c0a32, emailEnabled: true}
      responses:
        '200':
          description: The full preferences object.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/AlertNotificationPreferences'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /locations/{locationId}/users/{userId}/first-alert/digest-preferences:
    parameters:
      - $ref: '#/components/parameters/locationId'
      - $ref: '#/components/parameters/userId'
    put:
      tags: [First Alert]
      operationId: setAlertDigestPreferences
      summary: Set a user's alert digest
      x-required-role: reseller_admin
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/AlertDigest'}
            example: {enabled: true, frequency: daily, sendTime: "08:00", timezone: America/Chicago, timeFormat: 12h}
      responses:
        '200':
          description: The full preferences object.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/AlertNotificationPreferences'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}

  # ---------------------------------------------------------------- Insights Hub
  /locations/{locationId}/insights-hub/setup:
    parameters:
      - $ref: '#/components/parameters/locationId'
    get:
      tags: [Insights Hub]
      operationId: getInsightsHubSetup
      summary: Read Insights Hub setup
      x-required-role: reseller_admin
      responses:
        '200':
          description: Numbers covered and groups with access.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/InsightsHubSetupResponse'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
    post:
      tags: [Insights Hub]
      operationId: saveInsightsHubSetup
      summary: Save Insights Hub setup
      x-required-role: reseller_admin
      description: |
        Upsert. **Both keys are required** (`[]` is allowed). A user sees Insights Hub when they are
        in a `group_access` group **and** have the `insights-hub` product.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [connector_mappings, group_access]
              properties:
                connector_mappings:
                  type: array
                  items: {$ref: '#/components/schemas/NumberMappingInput'}
                group_access:
                  type: array
                  items: {type: string, format: uuid}
            example:
              connector_mappings:
                - {connector_id: 4b7e9d2c-1a3f-4e8b-9c6d-2f5a8e1b3c70, monitored_numbers: ["2101", "2102", "2103"]}
              group_access: [0193b6c2-8d52-74e0-9b6a-2c7e1f3d5a11]
      responses:
        '201':
          description: Saved.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/InsightsHubSetupResponse'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '422': {$ref: '#/components/responses/Unprocessable'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
    patch:
      tags: [Insights Hub]
      operationId: updateInsightsHubSetup
      summary: Update Insights Hub setup
      x-required-role: reseller_admin
      description: Each key you send **replaces** that list; an omitted key is unchanged.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                connector_mappings:
                  type: array
                  items: {$ref: '#/components/schemas/NumberMappingInput'}
                group_access:
                  type: array
                  items: {type: string, format: uuid}
            example:
              connector_mappings:
                - {connector_id: 4b7e9d2c-1a3f-4e8b-9c6d-2f5a8e1b3c70, monitored_numbers: ["2101", "2102", "2103", "2104"]}
      responses:
        '200':
          description: Updated.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/InsightsHubSetupResponse'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '422': {$ref: '#/components/responses/Unprocessable'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /locations/{locationId}/insights-hub/config:
    parameters:
      - $ref: '#/components/parameters/locationId'
    get:
      tags: [Insights Hub]
      operationId: getInsightsHubConfig
      summary: Read Insights Hub coverage
      x-required-role: reseller_admin
      responses:
        '200':
          description: Coverage.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/InsightsHubConfigResponse'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
    patch:
      tags: [Insights Hub]
      operationId: updateInsightsHubConfig
      summary: Set Insights Hub coverage
      x-required-role: reseller_admin
      description: "`monitor_all_numbers: true` lets Insights Hub users at the location see every call there."
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [monitor_all_numbers]
              properties:
                monitor_all_numbers: {type: boolean}
            example: {monitor_all_numbers: true}
      responses:
        '200':
          description: Updated.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/InsightsHubConfigResponse'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /locations/{locationId}/users/{userId}/insights-hub/access:
    parameters:
      - $ref: '#/components/parameters/locationId'
      - $ref: '#/components/parameters/userId'
    get:
      tags: [Insights Hub]
      operationId: getUserInsightsHubAccess
      summary: Check a user's Insights Hub access
      x-required-role: reseller_admin
      responses:
        '200':
          description: Access state.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: object
                    properties:
                      type: {type: string, const: insights_hub_access}
                      attributes:
                        type: object
                        properties:
                          enabled: {type: boolean}
                          group_name: {type: [string, 'null']}
              example: {data: {type: insights_hub_access, attributes: {enabled: true, group_name: Insights Hub Access}}}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}

  # ---------------------------------------------------------------- Users
  /companies/{companyId}/users:
    parameters:
      - $ref: '#/components/parameters/companyId'
    get:
      tags: [Users]
      operationId: listCompanyUsers
      summary: List a company's users
      x-required-role: reseller_admin
      description: |
        Filters combine with AND. Rows don't carry products or groups; use
        `GET /locations/{locationId}/users` for those. There is no product filter.
      parameters:
        - name: search
          in: query
          description: Case-insensitive substring match on email, first name **or** last name (not the full name).
          schema: {type: string}
        - name: status
          in: query
          description: Case-insensitive. Invalid values return 422.
          schema: {type: string, enum: [invited, active, deactivated]}
        - name: role
          in: query
          description: Invalid values return 422.
          schema: {type: string, enum: [customer_admin, frontline_user]}
        - name: location_id
          in: query
          description: One location id, or a comma-separated list of up to 100. Malformed values return 400. Admins with no location are excluded.
          style: form
          explode: false
          schema:
            type: array
            maxItems: 100
            items: {type: string, format: uuid}
        - name: limit
          in: query
          description: Page size. Invalid values fall back to the default.
          schema: {type: integer, minimum: 1, maximum: 100, default: 25}
        - $ref: '#/components/parameters/cursor'
      responses:
        '200':
          description: One page of users.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/CompanyUserList'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '422': {$ref: '#/components/responses/Unprocessable'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
    post:
      tags: [Users]
      operationId: createCompanyUser
      summary: Create a user
      x-required-role: reseller_admin
      description: |
        **`Idempotency-Key` is required** (400 without it). Send a new UUID per user and reuse it on
        retries: a replay returns the original response.

        - `frontline_user` needs `location_ids`. Managers are frontline users on several locations.
        - `send_invitation: true` emails the invitation (7-day expiry). For a new customer, create
          with `send_invitation: false`, map the user's lines, then send the invitation with
          `POST /companies/{companyId}/users/{userId}/resend-invitation`.
        - `auth_method: sso` for companies with single sign-on connected.
        - `email` is unique on the platform (409).
        - **A 422 can leave the user behind.** After a 422, look the user up with
          `GET /companies/{companyId}/users?search=<email>` and fix it with PATCH rather than creating again.
        - The response can carry a one-time sign-in link for the invitee. Treat the whole response
          as secret and never log it.
      parameters:
        - name: Idempotency-Key
          in: header
          required: true
          description: A UUID per logical create. Reuse it when retrying the same create.
          schema: {type: string}
          example: 5f0c8a1e-2b3d-4c5e-8f9a-0b1c2d3e4f5a
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/UserCreate'}
            example:
              email: sam.ortiz@example.com
              first_name: Sam
              last_name: Ortiz
              phone_number: "+15555550143"
              role: frontline_user
              location_ids: [0193b6c2-6b29-7a51-b0e4-1c8f3d5e7a02]
              send_invitation: true
              auth_method: password
      responses:
        '201':
          description: Created, status `invited`.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/CompanyUserResponse'}
              example:
                data:
                  type: company_user
                  attributes:
                    id: 0193b6c2-7c44-7d12-a3f9-8e2b6c1d4f55
                    company_id: 0193b6c2-5a11-7c3e-8f20-6d4b9e1c2a77
                    reseller_id: 0193b6c2-41d8-7e0a-9c55-2f7d1e3a9b10
                    email: sam.ortiz@example.com
                    first_name: Sam
                    last_name: Ortiz
                    display_name: Sam Ortiz
                    phone_number: "+15555550143"
                    status: invited
                    role: frontline_user
                    auth_method: password
                    invited_at: "2026-11-02T15:20:00Z"
                    invite_expires_at: "2026-11-09T15:20:00Z"
                    created_at: "2026-11-02T15:20:00Z"
                    updated_at: "2026-11-02T15:20:00Z"
        '400':
          description: "Missing `Idempotency-Key` (the body is `{\"error\": \"<message>\"}`), or a malformed field."
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: '#/components/schemas/Error'
                  - $ref: '#/components/schemas/BareError'
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '409':
          description: The email is already in use.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Error'}
        '422':
          description: Invalid value (unknown location, role not assignable). The user may still have been created; see above.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Error'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /companies/{companyId}/users/{userId}:
    parameters:
      - $ref: '#/components/parameters/companyId'
      - $ref: '#/components/parameters/userId'
    get:
      tags: [Users]
      operationId: getCompanyUser
      summary: Read a user
      x-required-role: reseller_admin
      responses:
        '200':
          description: The user, with `locations[]`.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/CompanyUserResponse'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
    patch:
      tags: [Users]
      operationId: updateCompanyUser
      summary: Update a user, role or locations
      x-required-role: reseller_admin
      description: |
        Every field is optional.
        - **`location_ids` replaces the user's locations.** This is how you assign and move users.
        - Changing `frontline_user` to `customer_admin` drops all location assignments.
        - Changing to `frontline_user` needs `location_ids` in the same request (422 otherwise);
          redo group membership afterwards.
        - The email address cannot be changed.
        - Works on a deactivated user.
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/UserUpdate'}
            example: {location_ids: [0193b6c2-6b29-7a51-b0e4-1c8f3d5e7a02, 0193b6c2-6b30-7a51-b0e4-1c8f3d5e7a03]}
      responses:
        '200':
          description: Updated.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/CompanyUserResponse'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '422': {$ref: '#/components/responses/Unprocessable'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /companies/{companyId}/users/{userId}/deactivate:
    parameters:
      - $ref: '#/components/parameters/companyId'
      - $ref: '#/components/parameters/userId'
    post:
      tags: [Users]
      operationId: deactivateCompanyUser
      summary: Deactivate a user
      x-required-role: reseller_admin
      description: |
        Deactivates the user company-wide and blocks sign-in. **Products, group membership and number
        mappings are kept.** For a leaver, also clear groups (`PUT …/group-membership` with `[]`),
        disable products, and clear number mappings (`PUT …/connector-mappings` with `[]`).
      responses:
        '200':
          description: Deactivated.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/CompanyUserResponse'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '409': {$ref: '#/components/responses/Conflict'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /companies/{companyId}/users/{userId}/reactivate:
    parameters:
      - $ref: '#/components/parameters/companyId'
      - $ref: '#/components/parameters/userId'
    post:
      tags: [Users]
      operationId: reactivateCompanyUser
      summary: Reactivate a user
      x-required-role: reseller_admin
      description: |
        A user who never accepted the invitation comes back as `active` with no password.
        Resend the invitation for them.
      responses:
        '200':
          description: Reactivated.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/CompanyUserResponse'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '409': {$ref: '#/components/responses/Conflict'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /companies/{companyId}/users/{userId}/resend-invitation:
    parameters:
      - $ref: '#/components/parameters/companyId'
      - $ref: '#/components/parameters/userId'
    post:
      tags: [Users]
      operationId: resendInvitation
      summary: Resend the invitation email
      x-required-role: reseller_admin
      description: Emails a fresh invitation with a new 7-day expiry. 409 when the user has no pending invitation.
      responses:
        '202':
          description: Sent.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: object
                    properties:
                      type: {type: string, const: invitation_resend}
                      attributes:
                        type: object
                        properties:
                          user_id: {type: string, format: uuid}
                          email: {type: string, format: email}
                          invite_expires_at: {type: string, format: date-time}
                          message: {type: string}
              example:
                data:
                  type: invitation_resend
                  attributes: {user_id: 0193b6c2-7c44-7d12-a3f9-8e2b6c1d4f55, email: sam.ortiz@example.com, invite_expires_at: "2026-11-09T15:30:00Z", message: Invitation email resent successfully}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '409': {$ref: '#/components/responses/Conflict'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /companies/{companyId}/users/{userId}/reset-password:
    parameters:
      - $ref: '#/components/parameters/companyId'
      - $ref: '#/components/parameters/userId'
    post:
      tags: [Users]
      operationId: resetPassword
      summary: Send a password reset email
      x-required-role: reseller_admin
      description: For active password users. An invited user returns 409; resend the invitation instead.
      responses:
        '202':
          description: Reset email sent.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: object
                    properties:
                      type: {type: string, const: password_reset}
                      attributes:
                        type: object
                        properties:
                          user_id: {type: string, format: uuid}
                          email: {type: string, format: email}
                          message: {type: string}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '409': {$ref: '#/components/responses/Conflict'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /companies/{companyId}/users/{userId}/connector-mappings:
    parameters:
      - $ref: '#/components/parameters/companyId'
      - $ref: '#/components/parameters/userId'
    get:
      tags: [Users]
      operationId: getUserNumberMappings
      summary: Read a user's numbers
      x-required-role: reseller_admin
      description: The lines whose calls this user sees.
      responses:
        '200':
          description: Mappings.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items: {$ref: '#/components/schemas/NumberMapping'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
    put:
      tags: [Users]
      operationId: setUserNumberMappings
      summary: Set a user's numbers
      x-required-role: reseller_admin
      description: |
        **Full replacement, company-wide for this user.** `mappings: []` clears.
        - Frontline users get their own extension; managers get every line at their locations.
        - Extensions come from the phone system: read them there with your own key. This API
          cannot list them.
        - The connector must be `active` (422 otherwise).
        - **409: an extension is already monitored at another location.** Release it there first.
          Show your own message; don't display the response text.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [mappings]
              properties:
                mappings:
                  type: array
                  items: {$ref: '#/components/schemas/NumberMappingInput'}
            example:
              mappings:
                - {connector_id: 4b7e9d2c-1a3f-4e8b-9c6d-2f5a8e1b3c70, monitored_numbers: ["2101"]}
      responses:
        '200':
          description: Saved.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items: {$ref: '#/components/schemas/NumberMapping'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '409':
          description: An extension is already monitored at another location.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Error'}
        '422': {$ref: '#/components/responses/Unprocessable'}
        '503':
          description: The extension check is briefly unavailable. Retry.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Error'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
  /locations/{locationId}/users:
    parameters:
      - $ref: '#/components/parameters/locationId'
    get:
      tags: [Users]
      operationId: listLocationUsers
      summary: List a location's users with products and groups
      x-required-role: reseller_admin
      description: |
        Rows include `enabled_products[]` and `groups[]` (names), so one call per location gives a
        full seat view. Returns 422 on an inactive location.
      parameters:
        - name: search
          in: query
          description: Case-insensitive substring match on email, first name or last name.
          schema: {type: string}
        - name: status
          in: query
          schema: {type: string, enum: [invited, active, deactivated]}
        - $ref: '#/components/parameters/limit20'
        - $ref: '#/components/parameters/cursor'
      responses:
        '200':
          description: One page of users.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/LocationUserList'}
              example:
                data:
                  - type: location_user
                    attributes:
                      id: 0193b6c2-7c45-7d12-a3f9-8e2b6c1d4f56
                      company_id: 0193b6c2-5a11-7c3e-8f20-6d4b9e1c2a77
                      email: alex.kim@example.com
                      first_name: Alex
                      last_name: Kim
                      display_name: Alex Kim
                      phone_number: "+15555550144"
                      role: frontline_user
                      status: active
                      location_id: 0193b6c2-6b29-7a51-b0e4-1c8f3d5e7a02
                      groups: [Insights Hub Access, Upset Customers]
                      enabled_products: [after-call-copilot, first-alert-copilot, insights-hub]
                pagination: {has_more: false}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '422': {$ref: '#/components/responses/Unprocessable'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /locations/{locationId}/users/{userId}:
    parameters:
      - $ref: '#/components/parameters/locationId'
      - $ref: '#/components/parameters/userId'
    get:
      tags: [Users]
      operationId: getLocationUser
      summary: Read a user at a location
      x-required-role: reseller_admin
      description: Includes `enabled_products[]`. `groups` is null here; use the list or group membership.
      responses:
        '200':
          description: The user.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/LocationUserResponse'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}

  # ---------------------------------------------------------------- After Call settings
  /locations/{locationId}/users/{userId}/after-call-settings:
    parameters:
      - $ref: '#/components/parameters/locationId'
      - $ref: '#/components/parameters/userId'
    get:
      tags: [After Call settings]
      operationId: getUserAfterCallSettings
      summary: Read a user's After Call settings
      x-required-role: reseller_admin
      responses:
        '200':
          description: Settings and number mappings.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/AfterCallSettingsResponse'}
              example:
                data:
                  user_id: 0193b6c2-7c44-7d12-a3f9-8e2b6c1d4f55
                  eoc_enabled: true
                  eod_enabled: true
                  eod_timezone: America/Chicago
                  eod_time: "17:30"
                  digest_frequency: daily
                  digest_time_format: 12h
                  connector_mappings:
                    - {connector_id: 4b7e9d2c-1a3f-4e8b-9c6d-2f5a8e1b3c70, connector_name: Riverbend phone system, connector_status: active, monitored_numbers: ["2101"]}
                  last_changed_by: 0193b6c2-41d9-7e0a-9c55-2f7d1e3a9b11
                  last_changed_at: "2026-11-02T15:25:00Z"
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
    patch:
      tags: [After Call settings]
      operationId: updateUserAfterCallSettings
      summary: Update a user's After Call settings
      x-required-role: reseller_admin
      description: |
        Partial update: omitted keys keep their value.
        - `connector_mappings` is a full replacement of the user's numbers (same store as
          `PUT /companies/{companyId}/users/{userId}/connector-mappings`); `[]` clears. The connector
          must be `active` (422 `CONNECTOR_NOT_VALID`). 409 means an extension is already monitored at
          another location.
        - A `digest_frequency` other than `never` needs `eod_time` and `eod_timezone`.
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/AfterCallSettingsUpdate'}
            example: {eoc_enabled: true, eod_enabled: true, eod_time: "17:30", eod_timezone: America/Chicago, digest_frequency: daily}
      responses:
        '200':
          description: Updated.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/AfterCallSettingsResponse'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '409':
          description: An extension is already monitored at another location.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Error'}
        '422':
          description: "`CONNECTOR_NOT_VALID`, `INVALID_EOD_TIME`, `INVALID_TIMEZONE` or `INVALID_FREQUENCY`."
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Error'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503':
          description: The extension check is briefly unavailable. Retry.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Error'}

  # ---------------------------------------------------------------- Account (frontline)
  /me:
    get:
      tags: [Account]
      operationId: getMe
      summary: Who is signed in
      x-required-role: frontline_user
      x-also-allowed-roles: [customer_admin, reseller_admin]
      description: |
        Call at startup. Check `role`: conversation-data endpoints return empty lists to admin logins.
        `scopes[]` is the authoritative list of what this login may do.
      responses:
        '200':
          description: The signed-in user.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/Me'}
              example:
                data:
                  id: 0193b6c2-7c46-7d12-a3f9-8e2b6c1d4f57
                  email: integration@example.com
                  first_name: Data
                  last_name: Feed
                  display_name: Data Feed
                  user_type: company_user
                  role: frontline_user
                  status: active
                  scopes: [calls:read, alerts:read, insights:read]
                  reseller_id: 0193b6c2-41d8-7e0a-9c55-2f7d1e3a9b10
                  company_id: 0193b6c2-5a11-7c3e-8f20-6d4b9e1c2a77
                  location_ids: [0193b6c2-6b29-7a51-b0e4-1c8f3d5e7a02]
                  enabled_products: [after-call-copilot, first-alert-copilot, insights-hub]
                  mfa_available: true
        '401': {$ref: '#/components/responses/Unauthorized'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /locations:
    get:
      tags: [Account]
      operationId: listVisibleLocations
      summary: Locations this login can see
      x-required-role: frontline_user
      x-also-allowed-roles: [customer_admin, reseller_admin]
      description: |
        A frontline login sees its assigned locations; an admin login sees every location it manages.
        Use the ids for `location_id` filters.
      parameters:
        - name: search
          in: query
          description: Case-insensitive substring match on `location_name`.
          schema: {type: string}
        - name: is_active
          in: query
          description: "`true` or `false`. Other values return 422."
          schema: {type: boolean}
        - name: company_id
          in: query
          schema: {type: string, format: uuid}
        - name: limit
          in: query
          description: Values above 100 are capped.
          schema: {type: integer, minimum: 1, maximum: 100, default: 20}
        - $ref: '#/components/parameters/cursor'
        - $ref: '#/components/parameters/offset'
      responses:
        '200':
          description: One page of locations.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/LocationList'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '422': {$ref: '#/components/responses/Unprocessable'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}

  # ---------------------------------------------------------------- Calls
  /calls:
    get:
      tags: [Calls]
      operationId: listCalls
      summary: List calls
      x-required-role: frontline_user
      description: |
        Every conversation the login can see, newest first. All filters combine with **AND**.
        Default window: 00:00 UTC seven days ago until now. Page with `cursor` until `has_more` is false.
        Admin logins get an empty list.
      parameters:
        - $ref: '#/components/parameters/dateFrom'
        - $ref: '#/components/parameters/dateTo'
        - name: status
          in: query
          description: Call outcome. One value, case-sensitive. Invalid values return 422.
          schema: {type: string, enum: [completed, missed, voicemail, failed, cancelled]}
        - $ref: '#/components/parameters/sentimentBand'
        - name: has_open_tasks
          in: query
          description: Only `true` is recognised (calls with at least one open task). Any other value is ignored.
          schema: {type: string, enum: ["true"]}
        - name: multi_leg
          in: query
          description: "`true`: calls with more than one leg (`leg_count` > 1). `false`: single-leg calls. Accepts true/false/1/0/t/f; other values return 400."
          schema: {type: boolean}
        - $ref: '#/components/parameters/locationIds'
        - $ref: '#/components/parameters/companyIdFilter'
        - name: search
          in: query
          description: |
            Free text, at least 2 characters (shorter is ignored). Matches caller and callee names
            (typo-tolerant), numbers in any format including partial digits and extensions, the
            summary, key points and the transcript. Name and number matches come first.
            Call ids don't match; use `GET /calls/{callId}`.
          schema: {type: string, minLength: 2}
        - $ref: '#/components/parameters/cursor'
        - $ref: '#/components/parameters/limit10'
      responses:
        '200':
          description: One page of calls with totals for the whole filter.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/CallList'}
              example:
                data:
                  summary: {total_calls: 412, completed_calls: 361, missed_calls: 0, total_duration: 98140, tasks_done: 37, pending: 12, total_tasks: 49}
                  calls:
                    - id: 0193b6d0-1e2f-7a3b-8c4d-5e6f7a8b9c01
                      location_id: 0193b6c2-6b29-7a51-b0e4-1c8f3d5e7a02
                      call_date: "2026-11-02T16:41:07Z"
                      caller_timezone: UTC
                      caller_name: Morgan Diaz
                      caller_number: "+15555550142"
                      callee_name: Sam Ortiz
                      callee_number: "2101"
                      call_type: inbound
                      status: completed
                      sentiment: negative
                      sentiment_score: -46
                      sentiment_label: negative
                      summary: The caller's car was promised for Friday and is still not ready. Sam offered a loaner and a call back by noon.
                      top_highlight: Car not ready on promised date
                      highlights: [Car not ready on promised date, Loaner offered, Call back by noon]
                      duration: 284
                      leg_count: 1
                      task_count: 1
                      completed_task_count: 0
                meta: {has_more: true, next_cursor: eyJkIjoiMjAyNi0xMS0wMlQxNjo0MTowN1oifQ==, limit: 10}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '422': {$ref: '#/components/responses/Unprocessable'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /calls/{callId}:
    parameters:
      - $ref: '#/components/parameters/callId'
    get:
      tags: [Calls]
      operationId: getCall
      summary: Read a call
      x-required-role: frontline_user
      description: |
        Full detail: analysis, tasks and the call's recording link (inside the conversation
        record, `vcon.recording_url`). A call outside the login's view returns 404 (admin logins
        always get 404). A call linked to an alert you can see opens.

        **Recording link:** a signed HTTPS link to the WAV audio. Fetch it with a plain `GET` and
        no `Authorization` header; `Range` requests are supported. It expires 120 minutes after
        issue (`recording_url_expires_at`). The link is a secret: don't log it or store it, and
        call this endpoint again for a fresh link each time you need the audio.
      responses:
        '200':
          description: The call.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/CallDetailResponse'}
              example:
                data:
                  id: 0193b6d0-1e2f-7a3b-8c4d-5e6f7a8b9c01
                  call_date: "2026-11-02T16:41:07Z"
                  caller_timezone: UTC
                  caller_name: Morgan Diaz
                  caller_number: "+15555550142"
                  callee_name: Sam Ortiz
                  callee_number: "2101"
                  call_type: inbound
                  call_outcome: completed
                  duration: 284
                  leg_count: 1
                  platform: netsapiens
                  sentiment: negative
                  sentiment_score: -46
                  sentiment_label: negative
                  summary: The caller's car was promised for Friday and is still not ready. Sam offered a loaner and a call back by noon.
                  analysis:
                    summary:
                      text: The caller's car was promised for Friday and is still not ready. Sam offered a loaner and a call back by noon.
                      key_points: [Car not ready on promised date, Loaner offered]
                      action_items: [Call Morgan back by noon with a new date]
                    sentiment: {overall: negative}
                    topics: [{name: Service delay}]
                  vcon:
                    recording_url: "https://recordings.example.com/r/0193b6d0.wav?sig=EXAMPLE-SIGNATURE"
                    recording_url_expires_at: "2026-11-02T18:45:00Z"
                    recording_mime_type: audio/wav
                  tasks:
                    - id: 0193b6d0-3a4b-7c5d-8e6f-7a8b9c0d1e23
                      title: Call Morgan back by noon with a new date
                      description: null
                      status: pending
                      source: ai
                      assignee_user: {id: 0193b6c2-7c44-7d12-a3f9-8e2b6c1d4f55, display_name: Sam Ortiz, email: sam.ortiz@example.com}
                      due_date: "2026-11-03"
                  task_count: 1
                  has_more_tasks: false
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /calls/{callId}/transcript:
    parameters:
      - $ref: '#/components/parameters/callId'
    get:
      tags: [Calls]
      operationId: getCallTranscript
      summary: Read a call's transcript
      x-required-role: frontline_user
      description: Speakers are labelled "Speaker 1" … "Speaker N"; `name` carries the person when known.
      responses:
        '200':
          description: Transcript lines in order.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/TranscriptResponse'}
              example:
                data:
                  transcript:
                    - {time: 0.4, speaker: Speaker 1, name: Sam Ortiz, text: "Riverbend service, this is Sam."}
                    - {time: 2.9, speaker: Speaker 2, name: Morgan Diaz, text: "Hi Sam, I'm calling about my car. It was supposed to be ready Friday."}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}

  # ---------------------------------------------------------------- Alerts
  /alerts:
    get:
      tags: [Alerts]
      operationId: listAlerts
      summary: List alerts
      x-required-role: frontline_user
      description: |
        First Alert hits the login can see, newest first. All filters combine with **AND**.
        Default window: 00:00 UTC seven days ago until now.
        Use it for look-ups by number, rule, date and location, not as a feed: alerts as they fire
        arrive on the First Alert webhook. After your receiver was unavailable, read the missed window
        once (`date_from` 30 minutes before it went down, `date_to` when it came back) and
        de-duplicate on `id`.
        To read one alert, `GET /alerts?search=<alert id>` (lowercase id; no date window needed).
        Admin logins get an empty list.
      parameters:
        - $ref: '#/components/parameters/dateFrom'
        - $ref: '#/components/parameters/dateTo'
        - name: keyword
          in: query
          description: Exact alert rule **name**, case-sensitive, one value. This is how you filter by rule.
          schema: {type: string}
        - name: topic
          in: query
          description: Exact topic slug, one value.
          schema: {type: string}
        - name: numbers
          in: query
          description: |
            Comma-separated, up to 25 entries. Each entry is letters, digits, `@` or `#` only
            (no `+`, `-` or spaces; strip to digits first). Each entry is a substring match on the
            caller or callee number; entries are OR'ed together.
          style: form
          explode: false
          schema:
            type: array
            maxItems: 25
            items: {type: string, pattern: '^[A-Za-z0-9@#]+$'}
        - $ref: '#/components/parameters/sentimentBand'
        - name: search
          in: query
          description: Matches caller or callee name or number, summary text, or an exact lowercase alert id. Rule names don't match; use `keyword`.
          schema: {type: string}
        - $ref: '#/components/parameters/locationIds'
        - $ref: '#/components/parameters/companyIdFilter'
        - $ref: '#/components/parameters/cursor'
        - $ref: '#/components/parameters/limit10'
      responses:
        '200':
          description: One page of alerts. `summary.total` counts every match.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/AlertList'}
              example:
                data:
                  summary: {total: 3}
                  alerts:
                    - id: 0193b6d0-2f3a-7b4c-9d5e-6f7a8b9c0d12
                      call_id: 0193b6d0-1e2f-7a3b-8c4d-5e6f7a8b9c01
                      call_date: "2026-11-02T16:41:07Z"
                      caller_timezone: UTC
                      caller_name: Morgan Diaz
                      caller_number: "+15555550142"
                      callee_name: Sam Ortiz
                      callee_number: "2101"
                      summary: The caller's car was promised for Friday and is still not ready.
                      sentiment: negative
                      sentiment_score: -46
                      sentiment_label: negative
                      keywords: [Upset Customer]
                      topics: []
                meta: {has_more: false, next_cursor: null, limit: 10}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '422': {$ref: '#/components/responses/Unprocessable'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /alerts/dashboard:
    get:
      tags: [Alerts]
      operationId: getAlertsDashboard
      summary: Alert totals
      x-required-role: frontline_user
      description: Counts for the window. Default window as `/alerts`. Other `/alerts` filters don't apply here.
      parameters:
        - $ref: '#/components/parameters/dateFrom'
        - $ref: '#/components/parameters/dateTo'
        - $ref: '#/components/parameters/locationIds'
        - $ref: '#/components/parameters/companyIdFilter'
      responses:
        '200':
          description: Totals.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/AlertsDashboardResponse'}
              example:
                data:
                  kpis: {new_alerts: 3, monitored: 412, alert_rate: 0.73}
                  top_triggered: [{keyword: Upset Customer, count: 2}, {keyword: Customer Threat, count: 1}]
                  recent_alerts: []
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '422': {$ref: '#/components/responses/Unprocessable'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}

  # ---------------------------------------------------------------- Tasks
  /tasks:
    get:
      tags: [Tasks]
      operationId: listTasks
      summary: List tasks
      x-required-role: frontline_user
      description: |
        Follow-up tasks from calls, newest first. Filters combine with AND. **No default window.**
        Errors on this endpoint use `error.type` instead of `error.code`, and bad values return 400.
        Admin logins get an empty list.
      parameters:
        - name: status
          in: query
          description: |
            Display status: `done` (completed); `pending` (not done, no due date); `in_progress`
            (not done, due today or later); `overdue` (not done, due before today); `open` (not done).
            `summary` counts ignore this filter.
          schema: {type: string, enum: [pending, in_progress, done, overdue, open]}
        - name: today_start
          in: query
          description: Your local midnight as a full RFC 3339 timestamp, e.g. `2026-11-02T00:00:00-06:00`. Sets the boundary for `overdue` and `in_progress`.
          schema: {type: string, format: date-time}
        - name: call_id
          in: query
          description: Tasks of one call.
          schema: {type: string, format: uuid}
        - name: task_id
          in: query
          description: One task. Can't be combined with `due_on`.
          schema: {type: string, format: uuid}
        - name: due_on
          in: query
          description: Tasks due on this calendar date (`YYYY-MM-DD`).
          schema: {type: string, format: date}
        - name: date_from
          in: query
          description: Created at or after. Full RFC 3339 timestamp required. No default.
          schema: {type: string, format: date-time}
        - name: date_to
          in: query
          description: Created at or before. Full RFC 3339 timestamp required. `date_from` after `date_to` returns an empty list.
          schema: {type: string, format: date-time}
        - name: search
          in: query
          description: Substring match on title and description.
          schema: {type: string}
        - $ref: '#/components/parameters/locationIds'
        - $ref: '#/components/parameters/companyIdFilter'
        - $ref: '#/components/parameters/cursor'
        - $ref: '#/components/parameters/limit20'
      responses:
        '200':
          description: One page of tasks.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/TaskList'}
              example:
                data:
                  - id: 0193b6d0-3a4b-7c5d-8e6f-7a8b9c0d1e23
                    call_id: 0193b6d0-1e2f-7a3b-8c4d-5e6f7a8b9c01
                    company_id: 0193b6c2-5a11-7c3e-8f20-6d4b9e1c2a77
                    location_id: 0193b6c2-6b29-7a51-b0e4-1c8f3d5e7a02
                    title: Call Morgan back by noon with a new date
                    description: null
                    status: pending
                    source: ai
                    assignee_user: {id: 0193b6c2-7c44-7d12-a3f9-8e2b6c1d4f55, display_name: Sam Ortiz, email: sam.ortiz@example.com}
                    due_date: "2026-11-03"
                    completed_at: null
                    created_at: "2026-11-02T16:46:00Z"
                    updated_at: "2026-11-02T16:46:00Z"
                meta: {has_more: false, next_cursor: null, limit: 20}
                summary: {total: 49, done: 37, in_progress: 4, pending: 6, overdue: 2}
        '400':
          description: Malformed or invalid parameter.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/TaskError'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}

  # ---------------------------------------------------------------- Insights
  /insights/dashboard:
    get:
      tags: [Insights]
      operationId: getInsightsDashboard
      summary: Insights Hub dashboard
      x-required-role: frontline_user
      description: Call volume, trending topics and topic volumes for a window. `start` and `end` are required.
      parameters:
        - name: start
          in: query
          required: true
          description: Window start. Full RFC 3339 timestamp required.
          schema: {type: string, format: date-time}
        - name: end
          in: query
          required: true
          description: Window end. Full RFC 3339 timestamp required. At most 366 days after `start` (422).
          schema: {type: string, format: date-time}
        - name: trending_limit
          in: query
          description: Number of trending topics, 1 to 10. Values above 10 return 10; values below 1, or not a number, fall back to the default of 4. Neither returns an error.
          schema: {type: integer, minimum: 1, maximum: 10, default: 4}
        - $ref: '#/components/parameters/locationIds'
        - $ref: '#/components/parameters/companyIdFilter'
      responses:
        '200':
          description: Dashboard.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/InsightsDashboardResponse'}
              example:
                data:
                  stats: {total_calls: 412, answered_calls: 361, unanswered_calls: 51}
                  trending_topics:
                    - slug: service-delay
                      name: Service delay
                      call_count: 38
                      previous_call_count: 22
                      percentage_change: 73
                      trend_data: [{day: "2026-10-27", current: 4, previous: 3}]
                  topic_call_volumes: [{slug: service-delay, name: Service delay, call_count: 38}]
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '422': {$ref: '#/components/responses/Unprocessable'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /insights/topics/{slug}/calls:
    parameters:
      - name: slug
        in: path
        required: true
        description: Topic slug from the dashboard's `topic_call_volumes[].slug`. An unknown slug returns an empty list.
        schema: {type: string}
    get:
      tags: [Insights]
      operationId: listTopicCalls
      summary: Calls for one topic
      x-required-role: frontline_user
      description: Default window 00:00 UTC seven days ago until now. Filters combine with AND.
      parameters:
        - $ref: '#/components/parameters/topicDateFrom'
        - $ref: '#/components/parameters/topicDateTo'
        - name: sentiment
          in: query
          description: Coarse band only. Other values return 422.
          schema: {type: string, enum: [positive, neutral, negative]}
        - name: outcome
          in: query
          description: Other values return 422.
          schema: {type: string, enum: [completed, missed, pending]}
        - name: search
          in: query
          description: Same matching as `/calls` `search`.
          schema: {type: string}
        - $ref: '#/components/parameters/locationIds'
        - $ref: '#/components/parameters/companyIdFilter'
        - $ref: '#/components/parameters/cursor'
        - name: limit
          in: query
          schema: {type: integer, minimum: 1, maximum: 100, default: 25}
      responses:
        '200':
          description: One page of calls.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/TopicCallList'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '422': {$ref: '#/components/responses/Unprocessable'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}

  # ---------------------------------------------------------------- Events and webhooks
  /locations/{locationId}/after-call/automation:
    parameters:
      - $ref: '#/components/parameters/locationId'
    get:
      tags: [Events and webhooks]
      operationId: getAfterCallWebhook
      summary: Read the After Call webhook
      x-required-role: reseller_admin
      x-also-allowed-roles: [customer_admin]
      description: |
        `{"data": null}` when no webhook is set. Read it with admin credentials. Rotate the address's
        path token every 90 days and
        when someone with access to the location leaves.
      responses:
        '200':
          description: The webhook, or null.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/AfterCallWebhookResponse'}
              example:
                data: {id: 0193b6c4-0a1b-7c2d-8e3f-4a5b6c7d8e90, location_id: 0193b6c2-6b29-7a51-b0e4-1c8f3d5e7a02, webhook_url: https://hooks.example.com/riverbend/calls, enabled: true, created_at: "2026-11-02T15:30:00Z", updated_at: "2026-11-02T15:30:00Z"}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
    put:
      tags: [Events and webhooks]
      operationId: saveAfterCallWebhook
      summary: Set the After Call webhook
      x-required-role: reseller_admin
      x-also-allowed-roles: [customer_admin]
      description: |
        One HTTPS URL per location. It receives **every call at the location**, whatever users'
        number mappings say. `enabled` defaults to `true`. There is no delete: pause with
        `enabled: false`. Frontline logins get 403. Treat the URL as a secret.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [webhook_url]
              properties:
                webhook_url: {type: string, format: uri, maxLength: 2048, description: "HTTPS only. Private and loopback addresses are refused."}
                enabled: {type: boolean, default: true}
            example: {webhook_url: https://hooks.example.com/riverbend/calls, enabled: true}
      responses:
        '200':
          description: Saved.
          content:
            application/json:
              schema: {$ref: '#/components/schemas/AfterCallWebhookResponse'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '403': {$ref: '#/components/responses/Forbidden'}
        '404': {$ref: '#/components/responses/NotFound'}
        '422': {$ref: '#/components/responses/Unprocessable'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}
  /locations/{locationId}/after-call/automation/test:
    parameters:
      - $ref: '#/components/parameters/locationId'
    post:
      tags: [Events and webhooks]
      operationId: testAfterCallWebhook
      summary: Send a test After Call event
      x-required-role: reseller_admin
      x-also-allowed-roles: [customer_admin]
      description: |
        Sends the test payload (`is_test: true`) to the **saved** URL, even while paused.
        A URL in the request body is ignored.
      responses:
        '200':
          description: Test result.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: object
                    properties:
                      success: {type: boolean}
                      http_status: {type: integer, description: HTTP status your endpoint returned.}
                      response_time_ms: {type: integer}
              example: {data: {success: true, http_status: 200, response_time_ms: 182}}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '403': {$ref: '#/components/responses/Forbidden'}
        '404': {$ref: '#/components/responses/NotFound'}
        '429': {$ref: '#/components/responses/TooManyRequests'}
        '503': {$ref: '#/components/responses/ServiceUnavailable'}

webhooks:
  afterCallSummary:
    post:
      tags: [Events and webhooks]
      operationId: afterCallSummaryEvent
      summary: After Call summary (end_of_call_summary)
      x-required-role: reseller_admin
      description: |
        Sent to the location's After Call webhook URL after each call is processed, for **every call
        at the location**.

        - `POST` with `Content-Type: application/json` and `User-Agent: IntelligenceCloud-ACCWebhook/1.0`.
        - Answer 2xx within 2 seconds; queue the work. Redirects (3xx) count as failures.
        - Don't authenticate on the `User-Agent`: anyone can send it. The path token is the credential.
        - Three attempts in all (backoff 1 s, then 2 s), then the delivery is dropped. There is no replay.
        - Requests are not signed. Use a long, unguessable URL and treat it as a secret.
        - No ordering guarantee. **Expect repeats** (retries, and calls with several legs): upsert on
          `call.id`, and when an id repeats, read the call again and update your record.
        - Treat the event as a notification: read `GET /calls/{call.id}` before you write anything from
          it into another system. A 404 means drop it.
        - Answer 2xx to any JSON body and ignore event types you don't handle.
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/AfterCallSummaryEvent'}
            example:
              version: "1.0"
              type: end_of_call_summary
              is_test: false
              location_id: 0193b6c2-6b29-7a51-b0e4-1c8f3d5e7a02
              timestamp: "2026-11-02T16:46:12Z"
              call:
                id: 0193b6d0-1e2f-7a3b-8c4d-5e6f7a8b9c01
                caller_name: Morgan Diaz
                caller_number: "+15555550142"
                callee_name: Sam Ortiz
                callee_number: "2101"
                call_type: inbound
                duration_seconds: 284
                call_date: "2026-11-02"
                platform: netsapiens
              summary:
                text: The caller's car was promised for Friday and is still not ready. Sam offered a loaner and a call back by noon.
                sentiment: negative
              location:
                id: 0193b6c2-6b29-7a51-b0e4-1c8f3d5e7a02
                company_id: 0193b6c2-5a11-7c3e-8f20-6d4b9e1c2a77
                connector_id: 4b7e9d2c-1a3f-4e8b-9c6d-2f5a8e1b3c70
      responses:
        '200':
          description: Any 2xx acknowledges the delivery.
  firstAlert:
    post:
      tags: [Events and webhooks]
      operationId: firstAlertEvent
      summary: First Alert (location webhook)
      x-required-role: reseller_admin
      description: |
        Sent to the `webhook_url` in the location's First Alert configuration
        (`PUT /locations/{locationId}/first-alert/config`) when an alert fires at the location.
        Test it with `POST /locations/{locationId}/first-alert/config/test-webhook`.

        The payload describes the alert: alert id, rule, location, call and time. Answer 2xx quickly,
        then read the alert with `GET /alerts?search=<alert id>` and the call with `GET /calls/{callId}`.
        De-duplicate on the alert id. If your receiver was unavailable, read the missed window of
        `GET /alerts` once and skip ids you have already handled.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              description: The alert that fired (alert id, rule, location, call, time).
              additionalProperties: true
      responses:
        '200':
          description: Any 2xx acknowledges the delivery.

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: |
        The `access_token` from `POST /auth/login` (lasts about 15 minutes; see `expires_in`).
        Renew it with `POST /auth/refresh`. API keys arrive in December 2026.

  parameters:
    resellerId:
      name: resellerId
      in: path
      required: true
      description: Your reseller id (`reseller_id` from `GET /me`).
      schema: {type: string, format: uuid}
    companyId:
      name: companyId
      in: path
      required: true
      schema: {type: string, format: uuid}
    locationId:
      name: locationId
      in: path
      required: true
      schema: {type: string, format: uuid}
    userId:
      name: userId
      in: path
      required: true
      schema: {type: string, format: uuid}
    groupId:
      name: groupId
      in: path
      required: true
      schema: {type: string, format: uuid}
    ruleId:
      name: ruleId
      in: path
      required: true
      schema: {type: string, format: uuid}
    connectorId:
      name: connectorId
      in: path
      required: true
      schema: {type: string, format: uuid}
    domainId:
      name: domainId
      in: path
      required: true
      schema: {type: string, format: uuid}
    callId:
      name: callId
      in: path
      required: true
      description: Call id. Malformed ids return 400.
      schema: {type: string, format: uuid}
    productKey:
      name: productKey
      in: path
      required: true
      schema: {$ref: '#/components/schemas/ProductKey'}
    cursor:
      name: cursor
      in: query
      description: Opaque `next_cursor` from the previous page. URL-encode it (it can contain `+`, `/` and `=`). A malformed cursor returns 400.
      schema: {type: string}
    offset:
      name: offset
      in: query
      description: Rows to skip. Prefer `cursor`.
      schema: {type: integer, minimum: 0}
    limit10:
      name: limit
      in: query
      description: Page size. Out-of-range values return 400. Use 100 for exports.
      schema: {type: integer, minimum: 1, maximum: 100, default: 10}
    limit20:
      name: limit
      in: query
      description: Page size. Send 100 and follow `next_cursor`.
      schema: {type: integer, minimum: 1, maximum: 100, default: 20}
    limit25:
      name: limit
      in: query
      schema: {type: integer, minimum: 1, maximum: 100, default: 25}
    dateFrom:
      name: date_from
      in: query
      description: |
        Start of the window (inclusive), on the call date. **Full RFC 3339 timestamp required**,
        e.g. `2026-11-01T00:00:00Z` or `2026-11-01T00:00:00-06:00`; a date alone returns 400.
        Default: 00:00 UTC seven days ago. `date_from` after `date_to` returns 422; a span over
        366 days returns 422 when both are sent.
      schema: {type: string, format: date-time}
      example: "2026-11-01T00:00:00Z"
    dateTo:
      name: date_to
      in: query
      description: |
        End of the window (inclusive). **Full RFC 3339 timestamp required.** Default: now.
        A `date_to` alone that is older than the default start returns an empty list.
      schema: {type: string, format: date-time}
      example: "2026-11-08T00:00:00Z"
    topicDateFrom:
      name: date_from
      in: query
      description: |
        Start of the window, on the call date. **Full RFC 3339 timestamp required**, e.g.
        `2026-11-01T00:00:00Z` or `2026-11-01T00:00:00-06:00`; a date alone returns 400.
        Default: 00:00 UTC seven days ago.
      schema: {type: string, format: date-time}
      example: "2026-11-01T00:00:00Z"
    topicDateTo:
      name: date_to
      in: query
      description: |
        End of the window. **Full RFC 3339 timestamp required**; a date alone returns 400. Default: now.
      schema: {type: string, format: date-time}
      example: "2026-11-08T00:00:00Z"
    sentimentBand:
      name: sentiment
      in: query
      description: |
        One sentiment band. Score bands: `crisis` ≤ −80; `very_negative` −79 to −60; `negative` −59 to −40;
        `mildly_negative` −39 to −20; `below_neutral` −19 to −1; `neutral` 0; `positive` ≥ 1.
        `negative`, `neutral` and `positive` also match records with that label and no score.
        `none` matches records with no sentiment. Invalid values return 422.
      schema:
        type: string
        enum: [crisis, very_negative, negative, mildly_negative, below_neutral, neutral, positive, none]
    locationIds:
      name: location_id
      in: query
      description: |
        One location id or a comma-separated list. A location you can't see matches nothing.
        Malformed ids return 400. Keep lists to about 50 ids (URL length).
      style: form
      explode: false
      schema:
        type: array
        maxItems: 100
        items: {type: string, format: uuid}
    companyIdFilter:
      name: company_id
      in: query
      description: Narrow to one company.
      schema: {type: string, format: uuid}

  responses:
    BadRequest:
      description: Malformed request (bad UUID, bad cursor, date without time, limit out of range, missing field).
      content:
        application/json:
          schema: {$ref: '#/components/schemas/Error'}
    Unauthorized:
      description: Token missing, invalid or expired. Refresh or sign in again, then retry once. Rejections before the service use the flat edge shape.
      content:
        application/json:
          schema:
            oneOf:
              - $ref: '#/components/schemas/Error'
              - $ref: '#/components/schemas/EdgeError'
    Forbidden:
      description: This login's role cannot do this (`FORBIDDEN`).
      content:
        application/json:
          schema: {$ref: '#/components/schemas/Error'}
    NotFound:
      description: Not found, or outside what this login may see. Treat as absent.
      content:
        application/json:
          schema: {$ref: '#/components/schemas/Error'}
    Conflict:
      description: Conflict (duplicate name or email, already active or inactive). Read the message.
      content:
        application/json:
          schema: {$ref: '#/components/schemas/Error'}
    Unprocessable:
      description: Valid shape, invalid value (enum, date order, range, unknown reference).
      content:
        application/json:
          schema: {$ref: '#/components/schemas/Error'}
    ServiceUnavailable:
      description: Temporarily unavailable. Back off with jitter and retry, honouring `Retry-After` if it is present.
      headers:
        Retry-After:
          description: Seconds to wait, when sent.
          schema: {type: integer}
      content:
        application/json:
          schema: {$ref: '#/components/schemas/Error'}
    TooManyRequests:
      description: Rate limited. Back off with jitter, and honour `Retry-After` if it is present.
      headers:
        Retry-After:
          description: Seconds to wait, when sent.
          schema: {type: integer}
      content:
        application/json:
          schema: {$ref: '#/components/schemas/Error'}

  schemas:
    # ------------------------------------------------ errors
    Error:
      type: object
      description: |
        Standard error. Branch on the HTTP status, then on `error.code`. Codes include
        `BAD_REQUEST`, `VALIDATION_ERROR`, `CONFLICT`, `NOT_FOUND`, `FORBIDDEN`,
        `ROLE_NOT_ASSIGNABLE`, `CONNECTOR_NOT_VALID`, `INVALID_EOD_TIME`, `INVALID_TIMEZONE`,
        `INVALID_FREQUENCY`, and lower-case codes on sign-in and single sign-on. Some 422s carry no
        `request_id`. Show your own message to end users.
      required: [error]
      properties:
        error:
          type: object
          properties:
            code: {type: string}
            message: {type: string}
            request_id: {type: string}
            details: {}
      example: {error: {code: VALIDATION_ERROR, message: "Invalid sentiment. Must be one of: crisis, very_negative, negative, mildly_negative, below_neutral, neutral, positive, none", request_id: 7b1e2c3d-4f5a-4b6c-8d9e-0f1a2b3c4d5e}}
    TaskError:
      type: object
      description: Error shape on `/tasks` (`error.type` is `invalid_parameter` or `validation_error`).
      properties:
        error:
          type: object
          properties:
            type: {type: string}
            message: {type: string}
            request_id: {type: string}
    EdgeError:
      type: object
      description: Flat shape for requests rejected before they reach the service.
      properties:
        statusCode: {type: integer}
        message: {type: string}
    BareError:
      type: object
      description: Used only for a missing Idempotency-Key.
      properties:
        error: {type: string}

    # ------------------------------------------------ auth
    LoginRequest:
      type: object
      required: [email, password]
      properties:
        email: {type: string, format: email}
        password: {type: string, format: password}
    RefreshRequest:
      type: object
      required: [refresh_token]
      properties:
        refresh_token: {type: string}
    CompanySecuritySettingsResponse:
      type: object
      properties:
        data:
          type: object
          properties:
            min_password_length: {type: integer, description: Minimum password length.}
            require_uppercase: {type: boolean}
            require_numbers: {type: boolean}
            require_special_chars: {type: boolean}
            password_expiry_days: {type: [integer, "null"], description: Days until a password expires; null when passwords don't expire.}
            session_timeout_minutes: {type: integer, description: Idle minutes before a web sign-in ends.}
            allowed_ip_ranges: {type: array, items: {type: string}, description: CIDR ranges allowed to sign in. Empty means any address.}
            password_policy_source: {type: string, description: "`reseller` when the policy is inherited from the reseller, otherwise `company`."}
            password_policy_inherited_fields: {type: array, items: {type: string}, description: Password policy fields inherited from the reseller.}
    TokenResponse:
      type: object
      required: [access_token, refresh_token, token_type, expires_in, user]
      properties:
        access_token: {type: string, description: "Send as `Authorization: Bearer <access_token>`. Never log it."}
        refresh_token: {type: string, description: Single use. Store the new one after every refresh. Never log it.}
        token_type: {type: string, const: Bearer}
        expires_in: {type: integer, description: Seconds until the access token expires (about 900).}
        user:
          type: object
          properties:
            id: {type: string, format: uuid}
            user_type: {type: string, enum: [company_user, reseller_user]}
            reseller_id: {type: [string, 'null'], format: uuid}
            email: {type: string, format: email}
            first_name: {type: string}
            last_name: {type: string}
            display_name: {type: string}
            role: {$ref: '#/components/schemas/Role'}
            scopes: {type: array, items: {type: string}}
        password_expired: {type: boolean, description: "Present and true when the password must be changed in the app. An integration must stop and alert an operator; a person sets a new password for the integration user in the app, then the secrets manager is updated and the integration signs in again."}
    MfaRequired:
      type: object
      description: The user has MFA on. No tokens are issued. Integration users need MFA off.
      required: [status]
      properties:
        status: {type: string, const: mfa_required}
    Role:
      type: string
      enum: [frontline_user, customer_admin, reseller_admin, reseller_support]
      description: "`reseller_support` has an admin's reach but is read-only."

    # ------------------------------------------------ common
    ProductKey:
      type: string
      enum: [after-call-copilot, first-alert-copilot, insights-hub]
    ProductState:
      type: object
      properties:
        product_key: {$ref: '#/components/schemas/ProductKey'}
        name: {type: string}
        enabled: {type: boolean}
        enabled_at: {type: [string, 'null'], format: date-time}
        enabled_by: {type: [string, 'null'], format: uuid}
    ProductStateList:
      type: object
      properties:
        data:
          type: array
          items: {$ref: '#/components/schemas/ProductState'}
    ProductStateResponse:
      type: object
      properties:
        data: {$ref: '#/components/schemas/ProductState'}
    Pagination:
      type: object
      properties:
        has_more: {type: boolean}
        next_cursor: {type: [string, 'null']}
        total_count: {type: integer}
    Meta:
      type: object
      description: Paging for conversation data. Stop when `has_more` is false.
      properties:
        has_more: {type: boolean}
        next_cursor: {type: [string, 'null']}
        limit: {type: integer}
    NumberMappingInput:
      type: object
      required: [connector_id, monitored_numbers]
      properties:
        connector_id: {type: string, format: uuid}
        monitored_numbers:
          type: array
          description: Extensions or DIDs, as the phone system shows them.
          items: {type: string}
    NumberMapping:
      type: object
      properties:
        connector_id: {type: string, format: uuid}
        connector_name: {type: string}
        connector_type: {type: string}
        monitored_numbers: {type: array, items: {type: string}}

    # ------------------------------------------------ resellers
    ResellerBrandingUpdate:
      type: object
      properties:
        display_name: {type: string, maxLength: 200, description: Product name shown in the app and in emails.}
        primary_accent_color: {type: string, pattern: '^#[0-9A-Fa-f]{6}$'}
        secondary_accent_color: {type: string, pattern: '^#[0-9A-Fa-f]{6}$'}
        support_email: {type: string, format: email, maxLength: 255}
        support_portal_url: {type: string, format: uri, maxLength: 2048}
        privacy_policy_url: {type: string, format: uri, maxLength: 2048}
        terms_of_service_url: {type: string, format: uri, maxLength: 2048}
        copyright_text: {type: string, maxLength: 500}
    ResellerBrandingResponse:
      type: object
      properties:
        data:
          type: object
          properties:
            type: {type: string}
            attributes:
              type: object
              properties:
                reseller_id: {type: string, format: uuid}
                display_name: {type: [string, 'null']}
                primary_accent_color: {type: [string, 'null']}
                secondary_accent_color: {type: [string, 'null']}
                support_email: {type: [string, 'null']}
                support_portal_url: {type: [string, 'null']}
                privacy_policy_url: {type: [string, 'null']}
                terms_of_service_url: {type: [string, 'null']}
                copyright_text: {type: [string, 'null']}
                main_logo_url: {type: [string, 'null'], description: Set in the Admin UI, or by your Tresic contact.}
                favicon_url: {type: [string, 'null'], description: Set in the Admin UI, or by your Tresic contact.}
                email_logo_url: {type: [string, 'null'], description: Set in the Admin UI, or by your Tresic contact.}
                created_at: {type: [string, 'null'], format: date-time}
                updated_at: {type: [string, 'null'], format: date-time}
    SmtpSettingsUpdate:
      type: object
      required: [smtp_host, smtp_port, sender_name, sender_email]
      properties:
        smtp_host: {type: string}
        smtp_port: {type: integer, minimum: 1, maximum: 65535, description: 587 (STARTTLS) is recommended; 465 is implicit TLS.}
        smtp_username: {type: string}
        smtp_password: {type: string, format: password, description: Stored encrypted. Never returned.}
        sender_name: {type: string, maxLength: 200}
        sender_email: {type: string, format: email}
    SmtpSettingsResponse:
      type: object
      properties:
        data:
          type: object
          properties:
            type: {type: string}
            attributes:
              type: object
              properties:
                reseller_id: {type: string, format: uuid}
                smtp_host: {type: string}
                smtp_port: {type: integer}
                smtp_username: {type: string}
                smtp_password: {type: string, description: Always masked.}
                sender_name: {type: string}
                sender_email: {type: string, format: email}
                created_at: {type: string, format: date-time}
                updated_at: {type: string, format: date-time}

    # ------------------------------------------------ companies
    Company:
      type: object
      properties:
        id: {type: string, format: uuid}
        reseller_id: {type: string, format: uuid}
        reseller_name: {type: string, description: Empty in the create response.}
        company_name: {type: string}
        company_code: {type: [string, 'null']}
        vertical: {type: [string, 'null']}
        address: {type: [string, 'null']}
        primary_admin_contact_name: {type: string}
        primary_admin_contact_email: {type: string, format: email}
        primary_admin_contact_phone: {type: string}
        enabled_products: {type: array, items: {$ref: '#/components/schemas/ProductKey'}}
        is_active: {type: boolean}
        mfa_enforced: {type: boolean}
        mfa_available: {type: boolean, description: Single read only.}
        location_count: {type: integer, description: Correct on list rows; 0 on single reads.}
        user_count: {type: integer, description: Correct on list rows; 0 on single reads.}
        created_at: {type: string, format: date-time}
        updated_at: {type: string, format: date-time}
    CompanyResource:
      type: object
      properties:
        type: {type: string, const: company}
        attributes: {$ref: '#/components/schemas/Company'}
    CompanyResponse:
      type: object
      properties:
        data: {$ref: '#/components/schemas/CompanyResource'}
    CompanyList:
      type: object
      properties:
        data:
          type: array
          items: {$ref: '#/components/schemas/CompanyResource'}
        has_more: {type: boolean}
        next_cursor: {type: [string, 'null']}
        total_count: {type: integer}
    CompanyCreate:
      type: object
      required: [company_name, primary_admin_contact_name, primary_admin_contact_email, primary_admin_contact_phone]
      properties:
        company_name: {type: string, minLength: 2, maxLength: 200}
        company_code: {type: string, maxLength: 50}
        primary_admin_contact_name: {type: string, minLength: 2, maxLength: 100}
        primary_admin_contact_email: {type: string, format: email, description: Unique on the platform. This person is invited as customer admin.}
        primary_admin_contact_phone: {type: string}
        enabled_products: {type: array, items: {$ref: '#/components/schemas/ProductKey'}}
    CompanyCreated:
      type: object
      properties:
        data: {$ref: '#/components/schemas/CompanyResource'}
        invited_user:
          type: object
          properties:
            id: {type: string, format: uuid}
            email: {type: string, format: email}
            display_name: {type: string}
            status: {type: string, const: invited}
            role: {type: string, const: customer_admin}
            invited_at: {type: string, format: date-time}
            invite_expires_at: {type: string, format: date-time}
    CompanyUpdate:
      type: object
      properties:
        company_name: {type: string, minLength: 2, maxLength: 200}
        company_code: {type: string, maxLength: 50}
        primary_admin_contact_name: {type: string, minLength: 2, maxLength: 100}
        primary_admin_contact_email: {type: string, format: email}
        primary_admin_contact_phone: {type: string}
        enabled_products: {type: array, minItems: 1, items: {$ref: '#/components/schemas/ProductKey'}, description: Full replacement.}
        vertical: {type: string, maxLength: 100, description: Free text label.}
        address: {type: string, maxLength: 500}
        mfa_enforced: {type: boolean, description: Must be a JSON boolean.}
    CompanyBrandingUpdate:
      type: object
      properties:
        display_name: {type: string, maxLength: 200}
        primary_accent_color: {type: string, pattern: '^#[0-9A-Fa-f]{6}$'}
        secondary_accent_color: {type: string, pattern: '^#[0-9A-Fa-f]{6}$'}
        support_email: {type: string, format: email, maxLength: 255}
        privacy_policy_url: {type: string, format: uri, maxLength: 2048}
        terms_of_service_url: {type: string, format: uri, maxLength: 2048}
        copyright_text: {type: string, maxLength: 500}
    CompanyBrandingResponse:
      type: object
      properties:
        data:
          type: object
          properties:
            type: {type: string, const: company_branding}
            attributes:
              type: object
              properties:
                company_id: {type: string, format: uuid}
                display_name: {type: [string, 'null']}
                primary_accent_color: {type: [string, 'null']}
                secondary_accent_color: {type: [string, 'null']}
                support_email: {type: [string, 'null']}
                privacy_policy_url: {type: [string, 'null']}
                terms_of_service_url: {type: [string, 'null']}
                copyright_text: {type: [string, 'null']}
                company_logo_url: {type: [string, 'null'], description: Set in the Admin UI, or by your Tresic contact.}
                favicon_url: {type: [string, 'null'], description: Set in the Admin UI, or by your Tresic contact.}
                email_header_logo_url: {type: [string, 'null'], description: Set in the Admin UI, or by your Tresic contact.}
                created_at: {type: [string, 'null'], format: date-time}
                updated_at: {type: [string, 'null'], format: date-time}

    # ------------------------------------------------ SSO
    CompanyDomain:
      type: object
      properties:
        id: {type: string, format: uuid}
        domain: {type: string}
        status: {type: string, description: "`pending` until the TXT record is found, then `verified`."}
        verification:
          type: object
          properties:
            type: {type: string, const: TXT}
            name: {type: string, description: "Record name, `_ic-verify.<domain>`."}
            value: {type: string}
        verified_at: {type: [string, 'null'], format: date-time}
        last_checked_at: {type: [string, 'null'], format: date-time}
        last_failure_reason: {type: [string, 'null']}
    CompanyDomainResponse:
      type: object
      properties:
        data: {$ref: '#/components/schemas/CompanyDomain'}
    DomainVerification:
      type: object
      properties:
        checked_at: {type: string, format: date-time}
        status: {type: string}
        failure_reason: {type: [string, 'null']}
    IdentityProviderCreate:
      type: object
      required: [type, display_name, issuer, well_known_endpoint, client_id, acknowledgement]
      properties:
        type: {type: string, const: oidc, description: OpenID Connect only.}
        display_name: {type: string, maxLength: 200}
        issuer: {type: string}
        well_known_endpoint: {type: string, format: uri, description: "Full HTTPS address of the provider's `/.well-known/openid-configuration`."}
        client_id: {type: string}
        client_auth_method: {type: string, enum: [client_secret, none], default: client_secret, description: "`none` for a public client (PKCE only)."}
        client_secret: {type: string, format: password, description: "Required with `client_secret`. Write-only."}
        secret_expires_at: {type: string, format: date-time}
        acknowledgement:
          type: string
          enum: ["true", "yes", "acknowledged", "1"]
          description: |
            Sending it confirms: anyone who can sign in at this login system will be able to sign in to
            Intelligence Cloud as a member of this company, and the checks that decide who that is,
            including any second factor, are made by this login system and not by Intelligence Cloud.
    IdentityProviderResponse:
      type: object
      properties:
        data:
          type: object
          properties:
            id: {type: string, format: uuid}
            display_name: {type: string}
            type: {type: string}
            is_active: {type: boolean}
            issuer: {type: string}
            well_known_endpoint: {type: string}
            client_id: {type: string}
            client_auth_method: {type: string}
            supported_client_auth_methods: {type: array, items: {type: string}}
            secret_held: {type: boolean}
            link_callback_uri: {type: string, description: The reply URL the customer registers with its provider.}
            instructions: {type: array, items: {type: string}, description: Steps for the customer's IdP admin.}
            created_at: {type: string, format: date-time}

    # ------------------------------------------------ locations
    Location:
      type: object
      properties:
        id: {type: string, format: uuid}
        company_id: {type: string, format: uuid}
        company_name: {type: string}
        reseller_name: {type: string}
        location_name: {type: string}
        street: {type: string}
        city: {type: string}
        state: {type: string}
        country: {type: string}
        zipcode: {type: string}
        support_contact_name: {type: string}
        support_contact_email: {type: string}
        support_contact_phone: {type: string}
        vertical_id: {type: string, format: uuid}
        vertical_name: {type: string}
        enabled_products: {type: array, items: {$ref: '#/components/schemas/ProductKey'}}
        is_active: {type: boolean}
        user_count: {type: integer, description: On list rows.}
        created_at: {type: string, format: date-time}
        updated_at: {type: string, format: date-time}
    LocationResource:
      type: object
      properties:
        type: {type: string, const: location}
        attributes: {$ref: '#/components/schemas/Location'}
    LocationResponse:
      type: object
      properties:
        data: {$ref: '#/components/schemas/LocationResource'}
    LocationList:
      type: object
      properties:
        data:
          type: array
          items: {$ref: '#/components/schemas/LocationResource'}
        pagination: {$ref: '#/components/schemas/Pagination'}
    LocationCreate:
      type: object
      required: [location_name, street, city, state, country, zipcode, vertical_id]
      properties:
        location_name: {type: string, minLength: 2, maxLength: 200, description: Unique within the company.}
        street: {type: string, minLength: 1, maxLength: 200}
        city: {type: string, minLength: 1, maxLength: 100}
        state: {type: string, minLength: 1, maxLength: 100}
        country: {type: string, minLength: 1, maxLength: 100}
        zipcode: {type: string, minLength: 1, maxLength: 20}
        vertical_id: {type: string, format: uuid, description: "From `GET /verticals`."}
        enabled_products: {type: array, items: {$ref: '#/components/schemas/ProductKey'}, description: Must be a subset of the company's products.}
    LocationUpdate:
      type: object
      properties:
        location_name: {type: string, minLength: 2, maxLength: 200}
        street: {type: string, maxLength: 200}
        city: {type: string, maxLength: 100}
        state: {type: string, maxLength: 100}
        country: {type: string, maxLength: 100}
        zipcode: {type: string, maxLength: 20}
        vertical_id: {type: string, format: uuid}
        enabled_products: {type: array, items: {$ref: '#/components/schemas/ProductKey'}, description: Full replacement.}

    # ------------------------------------------------ groups
    UserGroup:
      type: object
      properties:
        id: {type: string, format: uuid}
        location_id: {type: string, format: uuid}
        group_name: {type: string}
        user_count: {type: integer}
        members:
          type: array
          description: On single reads.
          items:
            type: object
            properties:
              id: {type: string, format: uuid}
              email: {type: string, format: email}
              first_name: {type: string}
              last_name: {type: string}
              display_name: {type: string}
        created_at: {type: string, format: date-time}
        updated_at: {type: string, format: date-time}
    UserGroupResource:
      type: object
      properties:
        type: {type: string, const: user_group}
        attributes: {$ref: '#/components/schemas/UserGroup'}
    UserGroupResponse:
      type: object
      properties:
        data: {$ref: '#/components/schemas/UserGroupResource'}
    UserGroupList:
      type: object
      properties:
        data:
          type: array
          items: {$ref: '#/components/schemas/UserGroupResource'}
        pagination: {$ref: '#/components/schemas/Pagination'}
    GroupMembershipList:
      type: object
      properties:
        data:
          type: array
          items:
            type: object
            properties:
              id: {type: string, format: uuid}
              name: {type: string}
              is_member: {type: boolean}
              product_keys: {type: array, items: {$ref: '#/components/schemas/ProductKey'}}

    # ------------------------------------------------ connectors
    ConnectorStatus:
      type: string
      enum: [connecting, active, error, deactivating, inactive]
      description: |
        `connecting` → `active` (calls flow) or `error`. Deactivate: `deactivating` → `inactive`.
        Reactivate: back to `connecting`.
    NetSapiensConfigInput:
      type: object
      required: [api_url, domain, api_key]
      properties:
        api_url: {type: string, format: uri, description: "Full API root ending in `/ns-api/v2`."}
        domain: {type: string, description: The customer's phone-system domain.}
        api_key: {type: string, format: password, description: Read/write key. Write-only; never returned.}
    Connector:
      type: object
      properties:
        id: {type: string, format: uuid}
        location_id: {type: string, format: uuid}
        name: {type: string}
        type: {type: string}
        type_display_name: {type: string}
        config:
          type: object
          description: Settings without the key.
          properties:
            api_url: {type: string}
            domain: {type: string}
        status: {$ref: '#/components/schemas/ConnectorStatus'}
        status_display: {type: string}
        status_message: {type: [string, 'null'], description: "What went wrong, when `status` is `error`."}
        state_reason: {type: string, description: "Why the connector is in this status, e.g. `invalid_permissions`. Omitted when there is none."}
        last_synced_at: {type: [string, 'null'], format: date-time}
        created_at: {type: string, format: date-time}
        updated_at: {type: string, format: date-time}
    ConnectorResponse:
      type: object
      description: Not wrapped in `type`/`attributes`.
      properties:
        data: {$ref: '#/components/schemas/Connector'}
    ConnectorListItem:
      type: object
      properties:
        id: {type: string, format: uuid}
        location_id: {type: string, format: uuid, description: Company list only.}
        location_name: {type: string, description: Company list only.}
        name: {type: string}
        type: {type: string}
        type_display_name: {type: string}
        status: {$ref: '#/components/schemas/ConnectorStatus'}
        status_display: {type: string}
        status_message: {type: [string, 'null']}
        state_reason: {type: string}
        last_synced_at: {type: [string, 'null'], format: date-time}
        created_at: {type: string, format: date-time}
        updated_at: {type: string, format: date-time}
    ConnectorList:
      type: object
      properties:
        data:
          type: array
          items: {$ref: '#/components/schemas/ConnectorListItem'}
        pagination: {$ref: '#/components/schemas/Pagination'}
    CompanyConnectorList:
      type: object
      properties:
        data:
          type: array
          items: {$ref: '#/components/schemas/ConnectorListItem'}
        pagination: {$ref: '#/components/schemas/Pagination'}
        errors:
          type: array
          description: Connectors in `error`.
          items:
            type: object
            properties:
              id: {type: string, format: uuid}
              name: {type: string}
              type: {type: string}
              location_name: {type: string}
              status_message: {type: [string, 'null']}

    # ------------------------------------------------ First Alert
    Trigger:
      type: object
      required: [trigger_type, config]
      description: |
        - `sentiment`: `{operator: lt|gt|eq, threshold: -100..100}`
        - `keyword_match`: `{keywords: [..], match_logic: any|all|exact_phrase}` (`match_logic` required here)
        - `conversation_topic`: `{topics: [slug, ..]}`
      properties:
        id: {type: string, format: uuid, description: In responses.}
        trigger_type: {type: string, enum: [sentiment, keyword_match, conversation_topic]}
        config:
          oneOf:
            - title: sentiment
              type: object
              required: [operator, threshold]
              properties:
                operator: {type: string, enum: [lt, gt, eq]}
                threshold: {type: integer, minimum: -100, maximum: 100}
            - title: keyword_match
              type: object
              required: [keywords, match_logic]
              properties:
                keywords: {type: array, minItems: 1, items: {type: string, minLength: 1}}
                match_logic: {type: string, enum: [any, all, exact_phrase]}
            - title: conversation_topic
              type: object
              required: [topics]
              properties:
                topics: {type: array, minItems: 1, items: {type: string}}
    AlertRuleCreate:
      type: object
      required: [name, priority, triggers]
      properties:
        name: {type: string, minLength: 1, maxLength: 200}
        priority: {type: string, enum: [critical, high, medium, low]}
        match_logic: {type: string, enum: [any, all], default: any, description: How the rule's triggers combine.}
        enabled: {type: boolean}
        triggers: {type: array, minItems: 1, items: {$ref: '#/components/schemas/Trigger'}}
        group_ids: {type: array, items: {type: string, format: uuid}, description: Groups at this location that receive the alert.}
    AlertRuleUpdate:
      type: object
      properties:
        name: {type: string, minLength: 1, maxLength: 200}
        priority: {type: string, enum: [critical, high, medium, low]}
        match_logic: {type: string, enum: [any, all]}
        enabled: {type: boolean}
        triggers: {type: array, minItems: 1, items: {$ref: '#/components/schemas/Trigger'}, description: Replaces every trigger.}
        group_ids: {type: array, items: {type: string, format: uuid}, description: "Replaces the groups. `[]` clears."}
    AlertRule:
      type: object
      properties:
        id: {type: string, format: uuid}
        location_id: {type: string, format: uuid}
        name: {type: string}
        priority: {type: string, enum: [critical, high, medium, low]}
        match_logic: {type: string}
        enabled: {type: boolean}
        is_default: {type: boolean, description: A platform default rule (can't be deleted).}
        triggers: {type: array, items: {$ref: '#/components/schemas/Trigger'}, description: Single reads.}
        trigger_types: {type: array, items: {type: string}, description: List rows.}
        groups:
          type: array
          items:
            type: object
            properties:
              id: {type: string, format: uuid}
              group_name: {type: string}
        created_at: {type: string, format: date-time}
        updated_at: {type: string, format: date-time}
    AlertRuleResource:
      type: object
      properties:
        type: {type: string, const: first_alert_rule}
        attributes: {$ref: '#/components/schemas/AlertRule'}
    AlertRuleResponse:
      type: object
      properties:
        data: {$ref: '#/components/schemas/AlertRuleResource'}
    AlertRuleList:
      type: object
      properties:
        data:
          type: array
          items: {$ref: '#/components/schemas/AlertRuleResource'}
        pagination: {$ref: '#/components/schemas/Pagination'}
    FirstAlertConfigUpdate:
      type: object
      required: [connector_mappings]
      properties:
        webhook_url: {type: [string, 'null'], format: uri, description: HTTPS only. Send it on every PUT or it is cleared.}
        connector_mappings:
          type: array
          items: {$ref: '#/components/schemas/NumberMappingInput'}
    FirstAlertConfigResponse:
      type: object
      properties:
        data:
          type: object
          properties:
            webhook_url: {type: [string, 'null']}
            connector_mappings:
              type: array
              items:
                allOf:
                  - $ref: '#/components/schemas/NumberMapping'
                  - type: object
                    properties:
                      id: {type: string, format: uuid}
    AlertDigest:
      type: object
      required: [enabled, frequency, sendTime, timezone]
      properties:
        enabled: {type: boolean}
        frequency: {type: string, enum: [daily, weekly, both, never]}
        sendTime: {type: string, pattern: '^\d{2}:\d{2}$', description: "24-hour `HH:MM`."}
        timezone: {type: string, description: "IANA zone, e.g. `America/Chicago`."}
        timeFormat: {type: string, enum: [12h, 24h]}
    AlertNotificationPreferences:
      type: object
      description: camelCase, not wrapped in `data`.
      properties:
        emailNotifications:
          type: object
          properties:
            masterEnabled: {type: boolean}
            alerts:
              type: array
              items:
                type: object
                properties:
                  alertId: {type: string, format: uuid}
                  alertName: {type: string}
                  trigger: {type: string, description: Readable summary of the rule's triggers.}
                  severity: {type: string}
                  description: {type: string}
                  emailEnabled: {type: boolean}
        digest:
          type: object
          properties:
            enabled: {type: boolean}
            frequency: {type: string}
            sendTime: {type: string}
            timezone: {type: string}
            timeFormat: {type: string}

    # ------------------------------------------------ Insights Hub setup
    InsightsHubSetupResponse:
      type: object
      properties:
        data:
          type: object
          properties:
            type: {type: string, const: insights_hub_setup}
            attributes:
              type: object
              properties:
                connector_mappings: {type: array, items: {$ref: '#/components/schemas/NumberMapping'}}
                group_access: {type: array, items: {type: string, format: uuid}}
                available_connectors:
                  type: array
                  items:
                    type: object
                    properties:
                      id: {type: string, format: uuid}
                      name: {type: string}
                      type: {type: string}
                groups:
                  type: array
                  items:
                    type: object
                    properties:
                      id: {type: string, format: uuid}
                      group_name: {type: string}
                      has_access: {type: boolean}
    InsightsHubConfigResponse:
      type: object
      properties:
        data:
          type: object
          properties:
            type: {type: string, const: insights_hub_config}
            attributes:
              type: object
              properties:
                monitor_all_numbers: {type: boolean}

    # ------------------------------------------------ users
    CompanyUser:
      type: object
      properties:
        id: {type: string, format: uuid}
        company_id: {type: string, format: uuid}
        reseller_id: {type: string, format: uuid}
        email: {type: string, format: email}
        first_name: {type: string}
        last_name: {type: string}
        display_name: {type: string}
        phone_number: {type: string}
        department: {type: string}
        status: {type: string, enum: [invited, active, deactivated]}
        role: {type: string, enum: [customer_admin, frontline_user]}
        auth_method: {type: string, enum: [password, sso]}
        invited_at: {type: [string, 'null'], format: date-time}
        invite_expires_at: {type: [string, 'null'], format: date-time}
        activated_at: {type: [string, 'null'], format: date-time}
        last_login_at: {type: [string, 'null'], format: date-time}
        locations:
          type: array
          description: Single reads.
          items:
            type: object
            properties:
              location_id: {type: string, format: uuid}
              assigned_at: {type: string, format: date-time}
        created_at: {type: string, format: date-time}
        updated_at: {type: string, format: date-time}
    CompanyUserResource:
      type: object
      properties:
        type: {type: string, const: company_user}
        attributes: {$ref: '#/components/schemas/CompanyUser'}
    CompanyUserResponse:
      type: object
      properties:
        data: {$ref: '#/components/schemas/CompanyUserResource'}
    CompanyUserList:
      type: object
      properties:
        data:
          type: array
          items: {$ref: '#/components/schemas/CompanyUserResource'}
        pagination: {$ref: '#/components/schemas/Pagination'}
    UserCreate:
      type: object
      required: [email, first_name, last_name, role]
      properties:
        email: {type: string, format: email, description: Unique on the platform.}
        first_name: {type: string, minLength: 1, maxLength: 100}
        last_name: {type: string, minLength: 1, maxLength: 100}
        phone_number: {type: string, maxLength: 50}
        role: {type: string, enum: [customer_admin, frontline_user]}
        location_ids: {type: array, items: {type: string, format: uuid}, description: "Required for `frontline_user`."}
        send_invitation: {type: boolean, description: Email the invitation now.}
        auth_method: {type: string, enum: [password, sso], default: password}
    UserUpdate:
      type: object
      properties:
        first_name: {type: string, minLength: 1, maxLength: 100}
        last_name: {type: string, minLength: 1, maxLength: 100}
        phone_number: {type: string, maxLength: 50}
        department: {type: string, maxLength: 255}
        role: {type: string, enum: [customer_admin, frontline_user]}
        location_ids: {type: array, items: {type: string, format: uuid}, description: Replaces the user's locations.}
    LocationUser:
      type: object
      properties:
        id: {type: string, format: uuid}
        company_id: {type: string, format: uuid}
        email: {type: string, format: email}
        first_name: {type: string}
        last_name: {type: string}
        display_name: {type: string}
        phone_number: {type: string}
        role: {type: string, enum: [customer_admin, frontline_user]}
        status: {type: string, enum: [invited, active, deactivated]}
        invited_at: {type: [string, 'null'], format: date-time}
        created_at: {type: string, format: date-time}
        location_id: {type: string, format: uuid}
        location_name: {type: string}
        assigned_at: {type: string, format: date-time}
        locations:
          type: [array, 'null']
          items:
            type: object
            properties:
              location_id: {type: string, format: uuid}
              assigned_at: {type: string, format: date-time}
        groups: {type: [array, 'null'], items: {type: string}, description: Group names. Filled on list rows.}
        enabled_products: {type: [array, 'null'], items: {$ref: '#/components/schemas/ProductKey'}}
    LocationUserResource:
      type: object
      properties:
        type: {type: string, const: location_user}
        attributes: {$ref: '#/components/schemas/LocationUser'}
    LocationUserResponse:
      type: object
      properties:
        data: {$ref: '#/components/schemas/LocationUserResource'}
    LocationUserList:
      type: object
      properties:
        data:
          type: array
          items: {$ref: '#/components/schemas/LocationUserResource'}
        pagination: {$ref: '#/components/schemas/Pagination'}

    # ------------------------------------------------ After Call settings
    AfterCallSettingsUpdate:
      type: object
      properties:
        eoc_enabled: {type: boolean, description: Email a summary after each call.}
        eod_enabled: {type: boolean, description: Send the end-of-day recap.}
        eod_time: {type: string, pattern: '^\d{2}:\d{2}$', description: "24-hour `HH:MM`."}
        eod_timezone: {type: string, description: IANA zone.}
        digest_frequency: {type: string, enum: [daily, weekly, both, never]}
        digest_time_format: {type: string, enum: [12h, 24h]}
        connector_mappings:
          type: array
          description: Replaces the user's numbers. `[]` clears.
          items: {$ref: '#/components/schemas/NumberMappingInput'}
    AfterCallSettingsResponse:
      type: object
      properties:
        data:
          type: object
          properties:
            user_id: {type: string, format: uuid}
            eoc_enabled: {type: boolean}
            eod_enabled: {type: boolean}
            eod_timezone: {type: [string, 'null']}
            eod_time: {type: [string, 'null']}
            digest_frequency: {type: string}
            digest_time_format: {type: string}
            connector_mappings:
              type: array
              items:
                type: object
                properties:
                  connector_id: {type: string, format: uuid}
                  connector_name: {type: string}
                  connector_status: {$ref: '#/components/schemas/ConnectorStatus'}
                  monitored_numbers: {type: array, items: {type: string}}
            last_changed_by: {type: [string, 'null'], format: uuid}
            last_changed_at: {type: [string, 'null'], format: date-time}

    # ------------------------------------------------ conversation data
    Me:
      type: object
      properties:
        data:
          type: object
          properties:
            id: {type: string, format: uuid}
            email: {type: string, format: email}
            first_name: {type: string}
            last_name: {type: string}
            display_name: {type: string}
            user_type: {type: string, enum: [company_user, reseller_user]}
            role: {$ref: '#/components/schemas/Role'}
            status: {type: string}
            scopes: {type: array, items: {type: string}}
            reseller_id: {type: [string, 'null'], format: uuid}
            company_id: {type: [string, 'null'], format: uuid}
            location_ids: {type: [array, 'null'], items: {type: string, format: uuid}}
            enabled_products: {type: [array, 'null'], items: {$ref: '#/components/schemas/ProductKey'}}
            mfa_available: {type: boolean}
    CallSentiment:
      type: [string, 'null']
      enum: [positive, neutral, negative, null]
    CallListItem:
      type: object
      properties:
        id: {type: string, format: uuid}
        location_id: {type: string, format: uuid}
        call_date: {type: string, format: date-time}
        caller_timezone: {type: [string, 'null']}
        caller_name: {type: [string, 'null']}
        caller_number: {type: [string, 'null']}
        callee_name: {type: [string, 'null']}
        callee_number: {type: [string, 'null']}
        call_type: {type: string, enum: [inbound, outbound, internal, missed, forwarded, unknown]}
        status: {type: string, enum: [completed, missed, voicemail, failed, cancelled]}
        sentiment: {$ref: '#/components/schemas/CallSentiment'}
        sentiment_score: {type: [integer, 'null'], minimum: -100, maximum: 100}
        sentiment_label: {type: string}
        summary: {type: [string, 'null']}
        top_highlight: {type: [string, 'null']}
        highlights: {type: array, items: {type: string}}
        duration: {type: integer, description: Seconds.}
        leg_count: {type: integer}
        task_count: {type: integer}
        completed_task_count: {type: integer}
    CallList:
      type: object
      properties:
        data:
          type: object
          properties:
            summary:
              type: object
              description: Totals for every call matching the filters (all pages).
              properties:
                total_calls: {type: integer}
                completed_calls: {type: integer}
                missed_calls: {type: integer}
                total_duration: {type: integer}
                tasks_done: {type: integer}
                pending: {type: integer}
                total_tasks: {type: integer}
            calls:
              type: array
              items: {$ref: '#/components/schemas/CallListItem'}
        meta: {$ref: '#/components/schemas/Meta'}
    TaskUser:
      type: [object, 'null']
      properties:
        id: {type: string, format: uuid}
        display_name: {type: string}
        email: {type: string, format: email}
    Task:
      type: object
      properties:
        id: {type: string, format: uuid}
        call_id: {type: string, format: uuid}
        company_id: {type: string, format: uuid}
        location_id: {type: string, format: uuid}
        title: {type: string}
        description: {type: [string, 'null']}
        status: {type: string, enum: [pending, in_progress, completed, cancelled], description: Stored status.}
        source: {type: string, enum: [ai, manual]}
        assignee_user: {$ref: '#/components/schemas/TaskUser'}
        due_date: {type: [string, 'null']}
        completed_at: {type: [string, 'null'], format: date-time}
        created_at: {type: string, format: date-time}
        updated_at: {type: string, format: date-time}
    TaskList:
      type: object
      properties:
        data:
          type: array
          items: {$ref: '#/components/schemas/Task'}
        meta: {$ref: '#/components/schemas/Meta'}
        summary:
          type: object
          description: Counts by display status. Honours every filter except `status`.
          properties:
            total: {type: integer}
            done: {type: integer}
            in_progress: {type: integer}
            pending: {type: integer}
            overdue: {type: integer}
    CallDetailResponse:
      type: object
      properties:
        data:
          type: object
          properties:
            id: {type: string, format: uuid}
            call_date: {type: string, format: date-time}
            caller_timezone: {type: [string, 'null']}
            caller_name: {type: [string, 'null']}
            caller_number: {type: [string, 'null']}
            callee_name: {type: [string, 'null']}
            callee_number: {type: [string, 'null']}
            call_type: {type: string}
            call_outcome: {type: string, description: "Same values as `status` on the list."}
            duration: {type: integer}
            leg_count: {type: integer}
            platform: {type: string, description: "Phone system type, e.g. `netsapiens`."}
            sentiment: {$ref: '#/components/schemas/CallSentiment'}
            sentiment_score: {type: [integer, 'null']}
            sentiment_label: {type: string}
            summary: {type: [string, 'null']}
            analysis:
              type: [object, 'null']
              properties:
                summary:
                  type: object
                  properties:
                    text: {type: string}
                    key_points: {type: array, items: {type: string}}
                    action_items: {type: array, items: {type: string}}
                sentiment:
                  type: object
                  properties:
                    overall: {type: string}
                topics:
                  type: [array, 'null']
                  items:
                    type: object
                    properties:
                      name: {type: string}
            vcon:
              type: object
              description: The call's recording link (inside the conversation record). Only the fields below are documented; ignore anything else in this object.
              properties:
                recording_url:
                  type: [string, 'null']
                  format: uri
                  description: "Signed HTTPS link to the call audio (WAV). Plain GET, no Authorization header; Range requests supported. Expires 120 minutes after issue. A secret: never log or store it; request the call again for a fresh link. Null when the call has no recording."
                recording_url_expires_at:
                  type: [string, 'null']
                  format: date-time
                  description: When `recording_url` stops working.
                recording_mime_type:
                  type: [string, 'null']
                  description: "`audio/wav`."
            tasks:
              type: array
              description: Up to 100. See `has_more_tasks`.
              items:
                type: object
                properties:
                  id: {type: string, format: uuid}
                  title: {type: string}
                  description: {type: [string, 'null']}
                  status: {type: string}
                  source: {type: string}
                  assignee_user: {$ref: '#/components/schemas/TaskUser'}
                  due_date: {type: [string, 'null']}
            task_count: {type: integer}
            has_more_tasks: {type: boolean}
    TranscriptResponse:
      type: object
      properties:
        data:
          type: object
          properties:
            transcript:
              type: array
              items:
                type: object
                properties:
                  time: {type: number, description: Seconds from the start of the call.}
                  speaker: {type: string, description: '"Speaker 1" … "Speaker N".'}
                  name: {type: string}
                  text: {type: string}
    Alert:
      type: object
      properties:
        id: {type: string, format: uuid}
        call_id: {type: string, format: uuid, description: "Open with `GET /calls/{callId}`."}
        call_date: {type: string, format: date-time}
        caller_timezone: {type: string}
        caller_name: {type: string}
        caller_number: {type: string}
        callee_name: {type: string}
        callee_number: {type: string}
        summary: {type: string}
        sentiment: {type: string}
        sentiment_score: {type: [integer, 'null']}
        sentiment_label: {type: string}
        keywords: {type: array, items: {type: string}, description: Names of the rules that fired.}
        topics: {type: array, items: {type: string}}
    AlertList:
      type: object
      properties:
        data:
          type: object
          properties:
            summary:
              type: object
              properties:
                total: {type: integer, description: "Every match, all pages."}
            alerts:
              type: array
              items: {$ref: '#/components/schemas/Alert'}
        meta: {$ref: '#/components/schemas/Meta'}
    AlertsDashboardResponse:
      type: object
      properties:
        data:
          type: object
          properties:
            kpis:
              type: object
              properties:
                new_alerts: {type: integer}
                monitored: {type: integer, description: Calls in the window.}
                alert_rate: {type: number, description: new_alerts / monitored × 100.}
            top_triggered:
              type: array
              maxItems: 10
              items:
                type: object
                properties:
                  keyword: {type: string, description: Rule name.}
                  count: {type: integer}
            recent_alerts:
              type: array
              maxItems: 5
              items: {$ref: '#/components/schemas/Alert'}
    InsightsDashboardResponse:
      type: object
      properties:
        data:
          type: object
          properties:
            stats:
              type: object
              properties:
                total_calls: {type: integer}
                answered_calls: {type: integer}
                unanswered_calls: {type: integer}
            trending_topics:
              type: array
              items:
                type: object
                properties:
                  slug: {type: string}
                  name: {type: string}
                  call_count: {type: integer}
                  previous_call_count: {type: integer}
                  percentage_change: {type: integer}
                  trend_data:
                    type: array
                    items:
                      type: object
                      properties:
                        day: {type: string}
                        current: {type: integer}
                        previous: {type: integer}
            topic_call_volumes:
              type: array
              items:
                type: object
                properties:
                  slug: {type: string}
                  name: {type: string}
                  call_count: {type: integer}
    TopicCallList:
      type: object
      properties:
        data:
          type: array
          items:
            type: object
            properties:
              id: {type: string, format: uuid}
              date: {type: string, format: date-time}
              caller_name: {type: [string, 'null']}
              summary: {type: [string, 'null']}
              phone_number: {type: [string, 'null']}
              sentiment: {type: [string, 'null']}
              sentiment_label: {type: string}
              outcome: {type: string}
        meta:
          type: object
          properties:
            total: {type: integer}
            has_more: {type: boolean}
            next_cursor: {type: [string, 'null']}

    # ------------------------------------------------ webhooks
    AfterCallWebhookResponse:
      type: object
      properties:
        data:
          type: [object, 'null']
          properties:
            id: {type: string, format: uuid}
            location_id: {type: string, format: uuid}
            webhook_url: {type: string}
            enabled: {type: boolean}
            created_at: {type: string, format: date-time}
            updated_at: {type: string, format: date-time}
    AfterCallSummaryEvent:
      type: object
      required: [version, type, is_test, location_id, timestamp, call, location]
      properties:
        version: {type: string, const: "1.0"}
        type: {type: string, const: end_of_call_summary}
        is_test: {type: boolean, description: "`true` only for test sends."}
        location_id: {type: string, format: uuid}
        timestamp: {type: string, format: date-time, description: "When Intelligence Cloud created the conversation record (UTC). Not the call time or the delivery time."}
        call:
          type: object
          required: [id, call_type, duration_seconds, call_date]
          properties:
            id: {type: string, format: uuid, description: "Same id as `GET /calls/{callId}` and an alert's `call_id`. Upsert on it."}
            caller_name: {type: string, description: Omitted when empty.}
            caller_number: {type: string, description: Omitted when empty.}
            callee_name: {type: string, description: Omitted when empty.}
            callee_number: {type: string, description: Omitted when empty.}
            call_type: {type: string, enum: [inbound, outbound, internal, missed, forwarded, unknown]}
            duration_seconds: {type: integer}
            call_date: {type: string, format: date, description: Date only (UTC).}
            platform: {type: string, description: Phone system type. Omitted when empty.}
        summary:
          type: object
          description: Omitted when the call has no summary.
          properties:
            text: {type: string}
            sentiment: {type: string, description: "Usually `positive`, `neutral` or `negative`."}
            key_points: {type: array, items: {type: string}, description: Test sends only.}
            action_items: {type: array, items: {type: string}, description: Test sends only.}
        location:
          type: object
          properties:
            id: {type: string, format: uuid}
            company_id: {type: string, format: uuid}
            connector_id: {type: string, format: uuid}
