openapi: '3.1.0'
info:
  title: PORTREX Public API
  version: '1'
  description: |
    PORTREX Public API — MF-1 strip (P1 surface).
    12-month deprecation guarantee on breaking changes.
    Full reference: developers.portrex.io

    SCOPE: this document is the CURATED EXTERNAL/PUBLIC API contract (integrator
    OAuth clients + API keys). Which routes appear is curated, not exhaustive —
    many internal tenant-admin web routes are intentionally EXCLUDED (e.g.
    /v1/roles, /v1/teams, /v1/account-invites), while a few otherwise-internal
    routes (parts of /sub-accounts, /customer-portal-invitations, /staff) DO
    appear where a partner-facing surface needs them. Presence or absence here is
    by design, not spec drift. `openapi:strict` validates this document; it does
    not require every route to appear.
  contact:
    url: https://developers.portrex.io

servers:
  - url: https://api.portrex.io/v1
    description: Production
  - url: http://localhost:3001/v1
    description: Local dev

security:
  - bearerToken: []
  - sessionCookie: []

components:
  securitySchemes:
    sessionCookie:
      type: apiKey
      in: cookie
      name: portrex_session
    staffBetterAuthCookie:
      type: apiKey
      in: cookie
      name: __Host-ptx_s.session_token
    staffHmacSessionCookie:
      type: apiKey
      in: cookie
      name: __Host-ptx-staff-session
    partnerBetterAuthCookie:
      type: apiKey
      in: cookie
      name: __Host-ptx_a.session_token
    bearerToken:
      type: http
      scheme: bearer
      bearerFormat: opaque
      description: |
        API key (`ptx_live_sk_*`) or OAuth 2.1 access token (`oat_*`). Send it as
        `Authorization: Bearer <token>`.
        An API key is `ptx_live_sk_` followed by 32 URL-safe characters (44 in total).
        An OAuth 2.1 access token (`oat_*`) is issued by `POST /v1/oauth/token` via
        `authorization_code`, `refresh_token`, or `client_credentials` (Integration User).
        Neither credential is a JWT; both are opaque and verified by SHA-256 hash.
        The full API key is shown once, when you create or rotate it. The key list shows
        only the first 16 characters; that prefix is not a key and the server answers 401.
        Operations that need a sensitive scope refuse API keys; use OAuth 2.1 user consent
        or an Integration User (`client_credentials`) for those scopes.
        After a Postman import, create a variable named `bearerToken` and set
        its Current value to the key; the import does not create it.

  responses:
    Forbidden:
      description: The authenticated principal or exact lifecycle binding is not authorized.
    IdempotencyConflict:
      description: |
        `idempotency_key_conflict` — this Idempotency-Key was already used with a
        different method, path, query or body. Send a fresh key for a new request.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/IdempotencyKeyConflictError' }
    SecretOperationConflict:
      description: |
        `idempotency_in_progress` means the reservation is still active; retry the same
        request and key after Retry-After. `idempotency_secret_response_unavailable`
        means a completed secret response cannot be replayed, including a legacy
        stored JSON response. The handler does not run again. Do not automatically
        retry a creation or rotation with a fresh key; inspect the resource first.
      headers:
        Cache-Control:
          schema: { type: string, enum: [no-store] }
        Retry-After:
          description: Present for an active reservation, not for an unavailable secret response.
          schema: { type: string }
      content:
        application/json:
          schema: { $ref: '#/components/schemas/SecretOperationConflictError' }
    GithubControlTokenMissing:
      description: The PORTREX_GITHUB_CONTROL_TOKEN secret is not configured; release mutations are unavailable.
      content:
        application/json:
          schema:
            type: object
            required: [error]
            properties:
              error: { type: string, enum: [github_control_token_missing] }
              code: { type: string, enum: [github_control_token_missing] }

  parameters:
    cursor:
      name: cursor
      in: query
      schema: { type: string }
      description: Opaque cursor for pagination. Never use OFFSET.
    limit:
      name: limit
      in: query
      schema: { type: integer, minimum: 1, maximum: 100, default: 25 }
    idempotencyKey:
      name: Idempotency-Key
      in: header
      required: true
      schema: { type: string, maxLength: 64 }
      description: |
        Client-generated unique key. Required on POST, PUT, and PATCH mutating operations, and on
        DELETE for Lead and Customer record-collaborator removals (idempotent replay
        rechecks authorization before returning a cached response).
        Secret-returning operations retain only a completion marker. A completed
        key returns `idempotency_secret_response_unavailable` instead of a secret replay.
    invoiceExpectedStatus:
      name: X-Portrex-Invoice-Expected-Status
      in: header
      required: false
      schema:
        type: string
        enum: [draft, sent, viewed, partial, paid, void, overdue]
      description: |
        Optional optimistic precondition for lead invoice actions. Under the same
        invoice row lock as the mutation, require this exact current status and
        zero recorded paid cents. Return 409 invoice_changed if either changed.
        Omitting the header preserves existing Billing mutation behavior.
    activeSubAccountId:
      name: X-Portrex-Sub-Account-Id
      in: header
      required: false
      schema:
        oneOf:
          - type: string
            format: uuid
          - type: string
            enum: [parent, account, rollup, all, 'null']
      description: |
        Optional active workspace scope. Parent account owners/admins may pass
        an active child sub-account UUID to operate inside that child scope,
        or one of parent/account/rollup/all/null for parent roll-up scope.
        Child-scoped users cannot use this header to clear or change their
        assigned sub-account scope.

  schemas:
    AgreementSigningProgress:
      type: object
      additionalProperties: false
      required: [runId, state, repSignedAt, homeownerSignedAt, archiveError, deliveryState]
      properties:
        runId: { type: string, format: uuid }
        state: { type: string, enum: [queued, awaiting_rep, archiving_rep, awaiting_homeowner, completed, stopped] }
        repSignedAt: { type: string, format: date-time, nullable: true }
        homeownerSignedAt: { type: string, format: date-time, nullable: true }
        repSignedObservedAt: { type: string, format: date-time, nullable: true, description: First time Portrex verified the rep signature. Zoho sends no signing time. }
        homeownerSignedObservedAt: { type: string, format: date-time, nullable: true, description: First time Portrex verified the homeowner signature. Zoho sends no signing time. }
        repSignedVerified: { type: boolean }
        homeownerSignedVerified: { type: boolean }
        archiveError: { type: string, nullable: true }
        deliveryState: { type: string, enum: [held, queued, sent, failed] }
      description: Verified signer facts are independent of nullable provider signing timestamps.
    AgreementArtifactView:
      type: object
      additionalProperties: false
      required: [id, purpose, stage, estimateId, contentRevision, contractId, runId, pdfAttachmentId, sha256, evidenceAttachmentId, certificateAttachmentId, createdAt, preview_url, download_url, evidence_url, certificate_url]
      properties:
        id: { type: string, format: uuid }
        purpose: { type: string, enum: [agreement, proposal_acknowledgment] }
        stage: { type: string, enum: [unsigned, rep_signed, fully_signed, acknowledged] }
        estimateId: { type: string, format: uuid }
        contentRevision: { type: integer, minimum: 0 }
        contractId: { type: string, format: uuid, nullable: true }
        runId: { type: string, format: uuid, nullable: true }
        pdfAttachmentId: { type: string, format: uuid }
        sha256: { type: string, pattern: '^[0-9a-f]{64}$' }
        evidenceAttachmentId: { type: string, format: uuid, nullable: true }
        certificateAttachmentId: { type: string, format: uuid, nullable: true }
        createdAt: { type: string, format: date-time }
        preview_url: { type: string, pattern: '^/v1/agreements/' }
        download_url: { type: string, pattern: '^/v1/agreements/' }
        evidence_url: { type: string, nullable: true, pattern: '^/v1/agreements/' }
        certificate_url: { type: string, nullable: true, pattern: '^/v1/agreements/' }
      description: An immutable original estimate/revision artifact. Signature stages do not create commercial revisions. Proposal acknowledgment is a distinct purpose with acknowledged stage and no signing run.
    AgreementArtifactsReply:
      type: object
      additionalProperties: false
      required: [data, progress]
      properties:
        data: { type: array, items: { $ref: '#/components/schemas/AgreementArtifactView' } }
        progress: { $ref: '#/components/schemas/AgreementSigningProgress', nullable: true }
    # --- Referral partner portal (design 2026-09-17) ---------------------------
    PartnerNotificationPreferences:
      type: object
      additionalProperties: false
      description: Notification classes a partner may opt out of. Security mail and invitation delivery are not preferences.
      properties:
        referral_accepted: { type: boolean }
        company_signed_up: { type: boolean }
        reward_earned: { type: boolean }
        payment_sent: { type: boolean }
    PartnerProfile:
      type: object
      required: [display_name, email, phone, notification_preferences, agreement_accepted_at]
      additionalProperties: false
      properties:
        display_name: { type: string }
        email: { type: string }
        phone: { type: string, nullable: true }
        notification_preferences: { $ref: '#/components/schemas/PartnerNotificationPreferences' }
        agreement_accepted_at:
          type: string
          nullable: true
          description: >-
            When this partner last accepted an agreement, or null if it never has. Read-only:
            acceptance moves only through POST /v1/affiliate/agreement/accept.
    PartnerReferralCreate:
      type: object
      required: [company_name, contact_name, contact_email, trades, relationship]
      additionalProperties: false
      properties:
        company_name: { type: string, minLength: 1, maxLength: 160 }
        website: { type: string, maxLength: 200 }
        contact_name: { type: string, minLength: 1, maxLength: 120 }
        contact_email: { type: string, format: email }
        contact_phone: { type: string, nullable: true }
        trades: { type: array, minItems: 1, items: { type: string } }
        approx_users: { type: string }
        relationship: { type: string, maxLength: 2000 }
        next_step: { type: string }
    PartnerReferralEdit:
      type: object
      additionalProperties: false
      description: >-
        Company name and contact email are absent by design; they are frozen once an
        invitation carries them to the prospect.
      properties:
        contact_name: { type: string, minLength: 1, maxLength: 120 }
        contact_phone: { type: string, nullable: true }
        website: { type: string, maxLength: 200 }
        relationship: { type: string, maxLength: 2000 }
        next_step: { type: string }
    PartnerInvitationRow:
      type: object
      required: [id, delivery, status_label, issued_at, expires_at]
      additionalProperties: false
      properties:
        id: { type: string, format: uuid }
        delivery: { type: string, enum: [portrex_email, affiliate_link] }
        status_label: { type: string }
        issued_at: { type: string, nullable: true }
        expires_at: { type: string, nullable: true }
    PartnerReferralRow:
      type: object
      description: >-
        The partner-facing projection. Conflict reasons other than self-referral, staff
        notes, registration evidence, and the referred account id are not carried.
      required:
        [id, company_name, contact_name, contact_email, review_label, stage_label,
         ineligible_reason, registered_at, accepted_at, attribution_expires_at,
         stage_changed_at, invitations]
      additionalProperties: false
      properties:
        id: { type: string, format: uuid }
        company_name: { type: string }
        contact_name: { type: string }
        contact_email: { type: string }
        review_label: { type: string }
        stage_label: { type: string }
        ineligible_reason: { type: string, enum: [self_referral], nullable: true }
        registered_at: { type: string }
        accepted_at: { type: string, nullable: true }
        attribution_expires_at: { type: string, nullable: true }
        stage_changed_at: { type: string }
        invitations:
          type: array
          items: { $ref: '#/components/schemas/PartnerInvitationRow' }
    PartnerActivityEvent:
      type: object
      description: >-
        One row of the partner-safe projection of `affiliate_audit_events` (migration 0578).
        `kind` is drawn from a fixed allowlist of action names; staff actor ids, free-text
        reasons, and conflict/mismatch metadata are not carried. Every mail-delivery action
        is excluded, so a suppressed recipient's invitation produces the same stream as a
        delivered one.
      required: [id, kind, occurred_at, referral_id, invitation_id, company_name, summary]
      additionalProperties: false
      properties:
        id: { type: string, format: uuid }
        kind:
          type: string
          enum:
            [affiliate.referral.registered, affiliate.referral.accepted,
             affiliate.referral.marked_ineligible, affiliate.referral.stage_set,
             affiliate.referral.expired, affiliate.attribution.attributed,
             affiliate.invitation.issued, affiliate.invitation.replaced,
             affiliate.invitation.revoked, affiliate.invitation.bound,
             affiliate.agreement.accepted, affiliate.profile.updated,
             affiliate.profile.avatar_updated, affiliate.email_change.confirmed,
             affiliate.suspended, affiliate.reactivated]
        occurred_at: { type: string }
        referral_id: { type: string, format: uuid, nullable: true }
        invitation_id: { type: string, format: uuid, nullable: true }
        company_name: { type: string, nullable: true }
        summary:
          type: string
          description: Fixed English built in SQL from partner-visible fields only.
    PartnerAttentionItem:
      type: object
      required: [kind, referral_id, invitation_id, company_name, at]
      additionalProperties: false
      properties:
        kind:
          type: string
          enum: [invitation_expiring, invitation_bounced, agreement_required]
        referral_id: { type: string, format: uuid, nullable: true }
        invitation_id: { type: string, format: uuid, nullable: true }
        company_name: { type: string, nullable: true }
        at: { type: string }
    PartnerDashboard:
      type: object
      description: >-
        `registered`/`invited`/`signed_up` count referral stages while
        `under_review`/`not_eligible`/`expired` count review statuses, so the six do not sum
        to `total`. `sent_today`/`sent_this_month` are a report; the caps are enforced by the
        keyed rate-limit buckets.
      required: [counts, invitations, attention, recent_activity]
      additionalProperties: false
      properties:
        counts:
          type: object
          required: [registered, under_review, invited, signed_up, not_eligible, expired, total]
          additionalProperties: false
          properties:
            registered: { type: integer, minimum: 0 }
            under_review: { type: integer, minimum: 0 }
            invited: { type: integer, minimum: 0 }
            signed_up: { type: integer, minimum: 0 }
            not_eligible: { type: integer, minimum: 0 }
            expired: { type: integer, minimum: 0 }
            total: { type: integer, minimum: 0 }
        invitations:
          type: object
          required:
            [issued, accepted, revoked, expired, sent_today, daily_cap,
             sent_this_month, monthly_cap]
          additionalProperties: false
          properties:
            issued: { type: integer, minimum: 0 }
            accepted: { type: integer, minimum: 0 }
            revoked: { type: integer, minimum: 0 }
            expired: { type: integer, minimum: 0 }
            sent_today: { type: integer, minimum: 0 }
            daily_cap: { type: integer, minimum: 0 }
            sent_this_month: { type: integer, minimum: 0 }
            monthly_cap: { type: integer, minimum: 0 }
        attention:
          type: array
          items: { $ref: '#/components/schemas/PartnerAttentionItem' }
        recent_activity:
          type: array
          maxItems: 10
          items: { $ref: '#/components/schemas/PartnerActivityEvent' }
    PartnerInvitationListRow:
      type: object
      description: >-
        `invited_email` is the contact the partner itself registered, so it is inside the
        partner projection. Mail delivery state is never exposed — and not only by omission:
        `status`, `issued_at` and `expires_at` are the PARTNER-VISIBLE projection, not the
        stored columns. A Portrex send to a suppressed address gets no mail job and would
        otherwise stay `created` with null dates while a delivered one becomes `issued` with
        real ones, so every live `portrex_email` invitation is reported as `issued` with
        `issued_at` = the request time and `expires_at` = request time + 30 days (the nominal
        window), whatever the mail job is doing. `created` is therefore not a value this row
        can carry.
      required:
        [id, referral_id, company_name, invited_contact_name, invited_email, delivery,
         status, issued_at, expires_at, revoked_at, bound_at, opened_at, created_at]
      additionalProperties: false
      properties:
        id: { type: string, format: uuid }
        referral_id: { type: string, format: uuid }
        company_name: { type: string }
        invited_contact_name: { type: string }
        invited_email: { type: string }
        delivery: { type: string, enum: [portrex_email, affiliate_link] }
        status: { type: string, enum: [issued, bound, expired, revoked] }
        issued_at: { type: string, nullable: true }
        expires_at: { type: string, nullable: true }
        revoked_at: { type: string, nullable: true }
        bound_at: { type: string, nullable: true }
        opened_at:
          type: string
          nullable: true
          description: >-
            When the recipient first opened the invitation link
            (`affiliate_invitations.first_opened_at`). The prospect's own action, which the
            referrals projection already surfaces as the "Opened" label.
        created_at: { type: string }
    PartnerInvitationIssued:
      type: object
      required: [invitation_id, status, delivery, url, expires_at]
      additionalProperties: false
      properties:
        invitation_id: { type: string, format: uuid }
        status: { type: string, enum: [created, issued, bound, expired, revoked] }
        delivery: { type: string, enum: [portrex_email, affiliate_link] }
        url:
          type: string
          format: uri
          nullable: true
          description: Non-null for `affiliate_link` only, and shown exactly once.
        expires_at: { type: string, nullable: true }
    JoinResolveResponse:
      type: object
      description: The join landing projection. The referring partner's id is deliberately absent.
      required: [invitation_id, partner_display_name, company_name, contact_name, contact_email, expires_at]
      additionalProperties: false
      properties:
        invitation_id: { type: string, format: uuid }
        partner_display_name: { type: string }
        company_name: { type: string }
        contact_name: { type: string }
        contact_email: { type: string }
        expires_at: { type: string, nullable: true }
    PartnerInvitationOptOut:
      type: object
      description: Signed one-click opt-out payload; `e` is the sha256 of the address, never the address.
      required: [e, t, s]
      additionalProperties: false
      properties:
        e: { type: string, pattern: '^[0-9a-f]{64}$' }
        t: { type: string, pattern: '^[0-9]+$' }
        s: { type: string, pattern: '^[0-9a-f]{64}$' }
    StaffPartnerApplication:
      type: object
      additionalProperties: true
      required: [id, status, full_name, email, role, contractor_count, terms_version, expires_at, created_at]
      properties:
        id: { type: string, format: uuid }
        status: { type: string, enum: [pending, provisioning, approved, rejected, withdrawn, expired] }
        full_name: { type: string }
        email: { type: string }
        phone: { type: string, nullable: true }
        company: { type: string, nullable: true }
        role: { type: string }
        contractor_count: { type: string }
        how_did_you_hear: { type: string, nullable: true }
        notes: { type: string, nullable: true }
        terms_version: { type: string }
        accepted_terms_at: { type: string, nullable: true }
        attribution: { type: object, additionalProperties: true }
        reviewed_by_staff_user_id: { type: string, format: uuid, nullable: true }
        reviewed_at: { type: string, nullable: true }
        decision_reason: { type: string, nullable: true }
        partner_id: { type: string, format: uuid, nullable: true }
        expires_at: { type: string, nullable: true }
        created_at: { type: string, nullable: true }
        client_ip: { type: string, nullable: true }
        user_agent: { type: string, nullable: true }
        browser: { type: string, nullable: true }
        os: { type: string, nullable: true }
        device_type: { type: string, enum: [Mobile, Desktop, Tablet, unknown], nullable: true }
        geo_country: { type: string, nullable: true }
        geo_region: { type: string, nullable: true }
        geo_city: { type: string, nullable: true }
        accept_language: { type: string, nullable: true }
        timezone: { type: string, nullable: true }
    StaffPartnerApplicationNote:
      type: object
      additionalProperties: true
      required: [id, application_id, body, created_by_staff_user_id, created_at]
      properties:
        id: { type: string, format: uuid }
        application_id: { type: string, format: uuid }
        body: { type: string }
        created_by_staff_user_id: { type: string, format: uuid }
        created_at: { type: string, nullable: true }
    StaffPartnerApplicationTask:
      type: object
      additionalProperties: true
      required: [id, application_id, title, status, created_by_staff_user_id, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        application_id: { type: string, format: uuid }
        title: { type: string }
        status: { type: string, enum: [open, done] }
        due_at: { type: string, nullable: true }
        assigned_to_staff_user_id: { type: string, format: uuid, nullable: true }
        created_by_staff_user_id: { type: string, format: uuid }
        created_at: { type: string, nullable: true }
        updated_at: { type: string, nullable: true }
    StaffPartnerApplicationEvent:
      type: object
      additionalProperties: true
      required: [id, application_id, title, starts_at, created_by_staff_user_id, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        application_id: { type: string, format: uuid }
        title: { type: string }
        starts_at: { type: string, nullable: true }
        ends_at: { type: string, nullable: true }
        notes: { type: string, nullable: true }
        created_by_staff_user_id: { type: string, format: uuid }
        created_at: { type: string, nullable: true }
        updated_at: { type: string, nullable: true }
    StaffPartnerRow:
      type: object
      additionalProperties: true
      required: [id, display_name, email, partner_code, status, tax_status, invitation_daily_cap, invitation_monthly_cap]
      properties:
        id: { type: string, format: uuid }
        display_name: { type: string }
        legal_name: { type: string, nullable: true }
        email: { type: string }
        phone: { type: string, nullable: true }
        company_key: { type: string, nullable: true }
        company_domain: { type: string, nullable: true }
        partner_code: { type: string }
        status: { type: string, enum: [active, suspended, closed] }
        agreement_version: { type: string, nullable: true }
        agreement_accepted_at: { type: string, nullable: true }
        tax_status: { type: string, enum: [missing, w9_on_file, exempt] }
        invitation_daily_cap: { type: integer }
        invitation_monthly_cap: { type: integer }
        created_at: { type: string, nullable: true }
    StaffReferralRow:
      type: object
      additionalProperties: true
      description: The full internal referral row. Never returned on a partner session.
      required: [id, company_name, company_key, contact_name, contact_email, review_status, conflict, stage]
      properties:
        id: { type: string, format: uuid }
        partner_id: { type: string, format: uuid, nullable: true }
        partner_display_name: { type: string, nullable: true }
        company_name: { type: string }
        company_key: { type: string }
        company_domain: { type: string, nullable: true }
        website: { type: string, nullable: true }
        contact_name: { type: string }
        contact_email: { type: string }
        contact_phone: { type: string, nullable: true }
        trades: { type: array, items: { type: string } }
        registration_evidence: { type: object, additionalProperties: true }
        review_status: { type: string, enum: [pending, accepted, ineligible, expired] }
        accepted_at: { type: string, nullable: true }
        attribution_expires_at: { type: string, nullable: true }
        conflict: { type: string, enum: [none, duplicate, existing_customer, self_referral] }
        stage: { type: string, enum: [registered, invited, signed_up, qualifying, qualified, lost] }
        staff_notes: { type: string, nullable: true }
    StaffPartnerMismatchRow:
      type: object
      additionalProperties: true
      description: >-
        One unresolved invitation mismatch: a signup bound an invitation whose immutable
        details disagreed with what was submitted. Attribution for that application stays
        `deferred` until staff confirm or decline the referral.
      required: [invitation_id, referral_id, partner_id, partner_display_name, partner_code, mismatch_kinds]
      properties:
        invitation_id: { type: string, format: uuid }
        referral_id: { type: string, format: uuid }
        partner_id: { type: string, format: uuid }
        partner_display_name: { type: string }
        partner_code: { type: string }
        invited_company_name: { type: string }
        invited_email: { type: string }
        mismatch_kinds:
          type: array
          items: { type: string, enum: [email, domain, company_name] }
        bound_at: { type: string, nullable: true }
        signup_application_id: { type: string, format: uuid, nullable: true }
        application_email: { type: string, nullable: true }
        application_company_name: { type: string, nullable: true }
        application_status: { type: string, nullable: true }
        application_created_at: { type: string, nullable: true }
        referral_company_name: { type: string, nullable: true }
        referral_review_status: { type: string, nullable: true }
        referral_stage: { type: string, nullable: true }
    StaffInvitationRow:
      type: object
      additionalProperties: true
      required: [id, referral_id, partner_id, invited_company_name, invited_email, delivery, status, open_count, mismatch_kinds]
      properties:
        id: { type: string, format: uuid }
        referral_id: { type: string, format: uuid }
        partner_id: { type: string, format: uuid }
        partner_display_name: { type: string, nullable: true }
        invited_company_name: { type: string }
        invited_company_domain: { type: string, nullable: true }
        invited_contact_name: { type: string }
        invited_email: { type: string }
        delivery: { type: string, enum: [portrex_email, affiliate_link] }
        status: { type: string, enum: [created, issued, bound, expired, revoked] }
        revoke_reason: { type: string, nullable: true }
        replaced_by_invitation_id: { type: string, format: uuid, nullable: true }
        issued_at: { type: string, nullable: true }
        first_opened_at: { type: string, nullable: true }
        open_count: { type: integer }
        bound_at: { type: string, nullable: true }
        bound_signup_application_id: { type: string, format: uuid, nullable: true }
        mismatch_kinds: { type: array, items: { type: string } }
        expires_at: { type: string, nullable: true }
        revoked_at: { type: string, nullable: true }
    StaffSuppressionRow:
      type: object
      additionalProperties: false
      description: Hash only. The plaintext address is never stored beside the keyed digest.
      required: [email_lookup_hash, scope, reason, created_at]
      properties:
        email_lookup_hash: { type: string }
        scope: { type: string }
        reason: { type: string, nullable: true }
        created_at: { type: string, nullable: true }
    StaffPartnerActivityRow:
      type: object
      additionalProperties: false
      required: [id, occurred_at, actor_kind, actor_id, partner_id, entity_type, entity_id, action, reason, metadata]
      properties:
        id: { type: string, format: uuid }
        occurred_at: { type: string, nullable: true }
        actor_kind: { type: string, enum: [affiliate_user, portrex_staff, system] }
        actor_id: { type: string, nullable: true }
        partner_id: { type: string, format: uuid, nullable: true }
        entity_type: { type: string }
        entity_id: { type: string, format: uuid, nullable: true }
        action: { type: string }
        reason: { type: string, nullable: true }
        metadata: { type: object, additionalProperties: true }
    ShowroomEstimateSummary:
      type: object
      additionalProperties: true
      required: [id, estimate_number, showroom_key, status, total_cents, created_at, updated_at, has_showroom_config, customer_id, lead_id]
      properties:
        id: { type: string, format: uuid }
        estimate_number: { type: string }
        showroom_key: { type: string, enum: [adu, hvac, renovation], nullable: true }
        status: { type: string }
        total_cents: { type: integer, nullable: true }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }
        has_showroom_config: { type: boolean }
        customer_id: { type: string, format: uuid }
        lead_id: { type: string, format: uuid, nullable: true }
        root_estimate_id: { type: string, format: uuid, nullable: true }
        parent_estimate_id: { type: string, format: uuid, nullable: true }
        version_number: { type: integer, minimum: 1, nullable: true }
        content_revision: { type: integer, minimum: 0 }
        content_sha256: { type: string, pattern: '^[a-f0-9]{64}$' }
        saved_draft_sha256: { type: string, pattern: '^[a-f0-9]{64}$', nullable: true }
        saved_draft_hash_version: { type: integer, minimum: 1, nullable: true }
        lifecycle_mode: { type: string, enum: [versioned_draft_v1], nullable: true }
    ShowroomRecoveryView:
      type: object
      additionalProperties: false
      required: [id, base_estimate_id, base_content_revision, status, snapshot, resolved_estimate_id, expires_at, created_at]
      properties:
        id: { type: string, format: uuid }
        base_estimate_id: { type: string, format: uuid }
        base_content_revision: { type: integer, minimum: 0 }
        status: { type: string, enum: [pending, resolved, discarded] }
        snapshot:
          type: object
          nullable: true
          additionalProperties: true
          description: Typed recovery snapshot returned only for the caller-owned recovery record. No recovery snapshot example is published.
        resolved_estimate_id: { type: string, format: uuid, nullable: true }
        expires_at: { type: string, format: date-time }
        created_at: { type: string, format: date-time }
    ShowroomEstimateSyncResult:
      allOf:
        - $ref: '#/components/schemas/ShowroomEstimateSummary'
        - type: object
          required: [action, lead_status]
          properties:
            action: { type: string, enum: [insert, update] }
            pricing: { $ref: '#/components/schemas/AgreementPricing' }
            agreement_pricing: { $ref: '#/components/schemas/ShowroomAgreementPricingPreview' }
            lead_status: { type: string }
            discount_policy_version: { type: integer, enum: [1], description: Current server discount eligibility generation. }
            subtotal_cents: { type: integer, nullable: true }
            discount_cents: { type: integer, nullable: true, description: Applied catalog/header discount after the embedded showroom adjustment. }
            tax_cents: { type: integer, nullable: true }
            sales_adjustment_cents: { type: integer, minimum: 0, description: Booked embedded showroom customer discounts. }
            content_sha256:
              type: string
              pattern: '^[a-f0-9]{64}$'
              description: Content hash of the returned estimate (non-roofing). Clients echo it as base_content_sha256 and never compute it.
            reconciled:
              type: string
              enum: [already_current, rebased]
              description: Present when an out-of-date write was fast-forwarded onto the current head instead of conflicting.
            max_sales_discount_percent:
              type: number
              minimum: 0
              maximum: 100
              description: HVAC only. The most the rep may discount this quote, in percent - the lower of the seat maximum and the rep baseline limit.
            sales_discount_binding:
              type: string
              enum: [seat_cap, baseline]
              description: HVAC only. Which limit max_sales_discount_percent is. A tie is seat_cap.
    AgreementPricingRow:
      type: object
      additionalProperties: false
      required: [label, amount_cents]
      description: Customer-safe recorded selling amount. A parent_line_id marks an included component whose amount is not added again.
      properties:
        id: { type: string }
        label: { type: string }
        amount_cents: { type: integer }
        parent_line_id: { type: string }
        sku: { type: string }
        detail: { type: string }
        quantity: { type: string }
        category: { type: string, enum: [equipment, addon, service, fee, credit, sales_discount, financing_fee, other] }
        origin: { type: string, enum: [showroom, office] }
        cart_line_id: { type: string }
        discount_percent: { type: number, minimum: 0, maximum: 100 }
        discount_reason: { type: string }
        discount_scope: { type: string, enum: [equipment, quote] }
    AgreementPricing:
      type: object
      additionalProperties: false
      required: [rows, subtotal_cents, discount_cents, tax_cents, total_cents]
      description: Recorded cents only. Top-level rows sum to subtotal; subtotal minus discount plus tax equals total. No cost or baseline values.
      properties:
        rows: { type: array, minItems: 1, items: { $ref: '#/components/schemas/AgreementPricingRow' } }
        subtotal_cents: { type: integer, minimum: 0 }
        discount_cents: { type: integer, minimum: 0 }
        tax_cents: { type: integer, minimum: 0 }
        total_cents: { type: integer, minimum: 0 }
        header_discount:
          type: object
          additionalProperties: false
          required: [label, kind, value]
          description: Optional recorded discount details verified against the booked amount.
          properties:
            label: { type: string }
            kind: { type: string, enum: [percent, fixed] }
            value: { type: number, minimum: 0 }
            scope: { type: string, enum: [equipment, whole_quote] }
    ShowroomAgreementPricingPreview:
      description: Optional current partner-contract projection. Ready pricing contains only selling amounts payable under the seller contract; separately contracted partner work has informational zero-amount rows. Unavailable blocks agreement actions until pricing can be resolved. The full estimate pricing remains unchanged.
      oneOf:
        - type: object
          additionalProperties: false
          required: [status, pricing]
          properties:
            status: { type: string, enum: [ready] }
            pricing: { $ref: '#/components/schemas/AgreementPricing' }
        - type: object
          additionalProperties: false
          required: [status]
          properties:
            status: { type: string, enum: [unavailable] }
    ShowroomEstimateSyncConflict:
      type: object
      additionalProperties: true
      required: [error]
      properties:
        error: { type: string, enum: [stale_version] }
        current: { $ref: '#/components/schemas/ShowroomEstimateSyncResult' }
        recovery: { $ref: '#/components/schemas/ShowroomRecoveryView' }
      description: stale_version includes current and recovery; other runtime 409 lifecycle errors return an error code only.
    ShowroomEstimateHeadChanged:
      type: object
      additionalProperties: false
      required: [error, head]
      properties:
        error: { type: string, enum: [head_changed] }
        head:
          type: object
          additionalProperties: false
          required: [id, content_revision, status, version_number, parent_estimate_id, saved_draft_sha256]
          properties:
            id: { type: string, format: uuid }
            content_revision: { type: integer, minimum: 0 }
            status: { type: string }
            version_number: { type: integer, nullable: true }
            parent_estimate_id: { type: string, format: uuid, nullable: true }
            saved_draft_sha256: { type: string, nullable: true }
      description: Returned unwritten when the request names estimate_id and the family's current head is a different estimate.
    ShowroomSetAsideBy:
      description: Whose copy keep-mine set aside, relative to the caller. A full name or nothing, never an email.
      oneOf:
        - type: object
          additionalProperties: false
          required: [kind]
          properties:
            kind: { type: string, enum: [you] }
        - type: object
          additionalProperties: false
          required: [kind, name]
          properties:
            kind: { type: string, enum: [person] }
            name: { type: string, minLength: 1 }
    ShowroomVersionResult:
      type: object
      additionalProperties: false
      required: [estimate, recovery]
      properties:
        estimate: { $ref: '#/components/schemas/ShowroomEstimateSummary' }
        recovery:
          allOf:
            - $ref: '#/components/schemas/ShowroomRecoveryView'
          nullable: true
        set_aside_by:
          description: 'preserve_stale_edits only: the superseded head''s last content editor. Null when no tenant editor was recorded, and for historical mode.'
          allOf:
            - $ref: '#/components/schemas/ShowroomSetAsideBy'
          nullable: true
    ShowroomInitializeResult:
      type: object
      additionalProperties: false
      required: [action, customer_id, person_id, customer_created, person_attached, lead_status, estimate, agreement_skeleton]
      properties:
        action: { type: string, enum: [insert_v1, reuse, clone] }
        customer_id: { type: string, format: uuid }
        person_id: { type: string, format: uuid }
        customer_created: { type: boolean }
        person_attached: { type: boolean }
        lead_status: { type: string }
        estimate:
          type: object
          additionalProperties: false
          required: [id, estimate_number, root_estimate_id, parent_estimate_id, version_number, content_revision, showroom_key, total_cents, line_items, showroom_config, lifecycle_mode]
          properties:
            id: { type: string, format: uuid }
            estimate_number: { type: string }
            root_estimate_id: { type: string, format: uuid }
            parent_estimate_id: { type: string, format: uuid, nullable: true }
            version_number: { type: integer, minimum: 1 }
            content_revision: { type: integer, minimum: 0 }
            showroom_key: { type: string, enum: [adu, hvac, renovation] }
            total_cents: { type: integer, nullable: true }
            line_items: { type: array, items: {} }
            showroom_config: { type: object, additionalProperties: true, nullable: true }
            lifecycle_mode: { type: string, enum: [versioned_draft_v1] }
            content_sha256: { type: string, pattern: '^[a-f0-9]{64}$', description: Content hash of the head (non-roofing). }
            saved_draft_sha256: { type: string, pattern: '^[a-f0-9]{64}$', nullable: true }
            recoveries:
              type: array
              description: The caller's own unsaved changes on this head from the last 24 hours that differ from it (non-roofing).
              items: { $ref: '#/components/schemas/ShowroomRecoveryView' }
        agreement_skeleton:
          type: object
          additionalProperties: true
          description: Editable non-signature agreement skeleton.
    ShowroomAgreementSaveDraft:
      type: object
      additionalProperties: false
      required: [lead_id, client, address, cart, signing_mode]
      description: Canonical signature-free draft eligible for the explicit legal Save boundary.
      properties:
        lead_id: { type: string, format: uuid }
        client:
          type: object
          additionalProperties: false
          properties:
            matched_customer_id: { type: string, format: uuid }
            matched_person_id: { type: string, format: uuid }
            contact_email: { type: string, format: email }
            contact_phone: { type: string }
            new_contact:
              type: object
              additionalProperties: false
              required: [name, email, phone]
              properties:
                name: { type: string, minLength: 1 }
                email: { type: string, format: email }
                phone: { type: string, minLength: 1 }
        address:
          type: object
          additionalProperties: false
          required: [street, city, state, zip]
          properties:
            street: { type: string, minLength: 1 }
            city: { type: string, minLength: 1 }
            state: { type: string, minLength: 1 }
            zip: { type: string, minLength: 1 }
            country: { type: string }
            lat: { type: string, nullable: true }
            lng: { type: string, nullable: true }
        property: { type: object, additionalProperties: true, nullable: true }
        cart:
          type: object
          additionalProperties: false
          required: [model, total_cents, source]
          properties:
            model:
              type: object
              additionalProperties: false
              required: [item_id, name, price_cents]
              properties:
                item_id: { type: string, format: uuid, nullable: true }
                name: { type: string, minLength: 1 }
                price_cents: { type: integer, minimum: 0 }
            addons:
              type: array
              items:
                type: object
                additionalProperties: false
                required: [id, item_id, name, price_cents]
                properties:
                  id: { type: string }
                  item_id: { type: string, format: uuid, nullable: true }
                  name: { type: string, minLength: 1 }
                  price_cents: { type: integer, minimum: 0 }
            total_cents: { type: integer, minimum: 1 }
            source: { type: string, enum: [pricebook] }
            configuration: { type: object, additionalProperties: true }
        document:
          type: object
          additionalProperties: false
          description: Optional document snapshot with signatures omitted; signature artifacts are forbidden at Save.
          required: [company, client, salesRepName, contractDate, paymentType, deposit_cents, total_cents, lineItems]
          properties:
            trade: { type: string, enum: [adu, hvac, remodeling] }
            company:
              type: object
              additionalProperties: false
              required: [name]
              properties:
                name: { type: string, minLength: 1 }
                license: { type: string }
                address: { type: string }
                phone: { type: string }
                email: { type: string }
                representativeName: { type: string }
                contractorRegistration: { type: string }
                tradeLicense: { type: string }
                insurance: { type: string }
            client:
              type: object
              additionalProperties: false
              required: [name]
              properties:
                name: { type: string, minLength: 1 }
                address: { type: string }
                city: { type: string }
                state: { type: string }
                zip: { type: string }
                email: { type: string }
                phone: { type: string }
            salesRepName: { type: string, minLength: 1 }
            agreementNumber: { type: string }
            projectType: { type: string, minLength: 1 }
            contractDate: { type: string, minLength: 1 }
            paymentType: { type: string, minLength: 1 }
            deposit_cents: { type: integer, minimum: 0 }
            total_cents: { type: integer, minimum: 0 }
            projectSchedule:
              type: object
              additionalProperties: false
              properties:
                startDate: { type: string }
                substantialCompletionDate: { type: string }
            legal: { type: object, additionalProperties: true }
            rebates: { type: object, additionalProperties: true }
            paymentSchedule:
              type: array
              items:
                type: object
                additionalProperties: false
                required: [label, amount_cents, dueDate]
                properties:
                  label: { type: string, minLength: 1 }
                  amount_cents: { type: integer, minimum: 0 }
                  dueDate: { type: string, minLength: 1 }
            configuration:
              type: array
              items:
                type: object
                additionalProperties: false
                required: [label, value]
                properties:
                  label: { type: string, minLength: 1 }
                  value: { type: string, minLength: 1 }
            lineItems:
              type: array
              minItems: 1
              items:
                type: object
                additionalProperties: false
                required: [label, price_cents]
                properties:
                  label: { type: string, minLength: 1 }
                  price_cents: { type: integer, minimum: 0 }
                  detail: { type: string }
                  quantity: { type: string }
            scopeText: { type: string }
            warrantyText: { type: string }
            termsText: { type: string }
        signing_mode: { type: string, enum: [single] }
    ShowroomAgreementSaveRequest:
      type: object
      additionalProperties: false
      required: [estimate_id, expected_content_revision, draft]
      properties:
        estimate_id: { type: string, format: uuid }
        expected_content_revision: { type: integer, minimum: 0 }
        draft: { $ref: '#/components/schemas/ShowroomAgreementSaveDraft' }
    ShowroomAgreementSaveResult:
      type: object
      additionalProperties: false
      required: [lead_id, estimate_id, status, content_revision, saved_draft_sha256, saved_draft_hash_version]
      properties:
        lead_id: { type: string, format: uuid }
        estimate_id: { type: string, format: uuid }
        status: { type: string, enum: [agreement_pending] }
        content_revision: { type: integer, minimum: 0 }
        saved_draft_sha256: { type: string, pattern: '^[a-f0-9]{64}$' }
        saved_draft_hash_version: { type: integer, minimum: 1 }
    ShowroomAgreementCancelDraftRequest:
      type: object
      additionalProperties: false
      required: [estimate_id, expected_content_revision, saved_draft_sha256]
      properties:
        estimate_id: { type: string, format: uuid }
        expected_content_revision: { type: integer, minimum: 0 }
        saved_draft_sha256: { type: string, pattern: '^[a-f0-9]{64}$' }
    ShowroomAgreementCancelDraftResult:
      type: object
      additionalProperties: false
      required: [lead_id, estimate_id, content_revision, saved_draft_sha256, saved_draft_hash_version, agreement_draft, showroom_agreement_state, status]
      properties:
        lead_id: { type: string, format: uuid }
        estimate_id: { type: string, format: uuid }
        content_revision: { type: integer, minimum: 0 }
        saved_draft_sha256: { type: 'null' }
        saved_draft_hash_version: { type: 'null' }
        agreement_draft: { type: 'null' }
        showroom_agreement_state: { type: string, enum: [working] }
        status: { type: string, enum: [appointment_held, agreement_pending] }
    ShowroomEstimateRestore:
      type: object
      additionalProperties: false
      required: [estimate_id, has_linked_contract, lead_id, customer_id, showroom_key, config, root_estimate_id, parent_estimate_id, version_number, content_revision, saved_draft_sha256, saved_draft_hash_version, lifecycle_mode, is_current, read_only, allowed_version_action, current_head, recoveries]
      properties:
        has_linked_contract: { type: boolean, description: Authoritative live contract presence for this visible estimate. Includes draft contracts and contracts whose detail is restricted; false only when no live account-bound link exists. }
        pricing: { $ref: '#/components/schemas/AgreementPricing' }
        agreement_pricing: { $ref: '#/components/schemas/ShowroomAgreementPricingPreview' }
        contract_pricing: { $ref: '#/components/schemas/AgreementPricing' }
        contract_recorded_pricing_rows: { type: array, items: { $ref: '#/components/schemas/AgreementPricingRow' } }
        contract_total_cents: { type: integer, minimum: 0, description: Actual estimate-bound contract amount, including only booked financing fees. }
        contract_payment_type: { type: string, description: Recorded frozen contract payment type, including LightReach reference-pricing semantics. }
        discount_policy_version: { type: integer, enum: [1] }
        total_cents: { type: integer, nullable: true }
        subtotal_cents: { type: integer, nullable: true }
        discount_cents: { type: integer, nullable: true }
        tax_cents: { type: integer, nullable: true }
        sales_adjustment_cents: { type: integer, minimum: 0 }
        estimate_id: { type: string, format: uuid }
        lead_id: { type: string, format: uuid, nullable: true }
        customer_id: { type: string, format: uuid }
        showroom_key: { type: string, enum: [adu, hvac, renovation, generac, roofing, water-filtration, solar] }
        config: { type: object, additionalProperties: true }
        root_estimate_id: { type: string, format: uuid, nullable: true }
        parent_estimate_id: { type: string, format: uuid, nullable: true }
        version_number: { type: integer, minimum: 1, nullable: true }
        content_revision: { type: integer, minimum: 0 }
        saved_draft_sha256: { type: string, pattern: '^[a-f0-9]{64}$', nullable: true }
        saved_draft_hash_version: { type: integer, minimum: 1, nullable: true }
        content_sha256: { type: string, pattern: '^[a-f0-9]{64}$', description: Content hash of this estimate (non-roofing). }
        lifecycle_mode: { type: string, enum: [versioned_draft_v1], nullable: true }
        is_current: { type: boolean }
        read_only: { type: boolean }
        allowed_version_action: { type: string, enum: [edit, create_from_historical, none] }
        current_head:
          type: object
          additionalProperties: false
          nullable: true
          required: [id, content_revision, status, version_number]
          properties:
            id: { type: string, format: uuid }
            content_revision: { type: integer, minimum: 0 }
            status: { type: string }
            version_number: { type: integer, minimum: 1 }
        recoveries:
          type: array
          items: { $ref: '#/components/schemas/ShowroomRecoveryView' }
    PalmettoOrganizationMapping:
      type: object
      additionalProperties: false
      required:
        - id
        - accountId
        - connectionId
        - subAccountId
        - environment
        - remoteOrganizationId
        - remoteOrganizationAlias
        - friendlyName
        - status
        - contractorLicenseStates
        - verifiedAt
        - lastVisibilityCheckAt
        - lastErrorCode
        - createdAt
        - updatedAt
      properties:
        id: { type: string, format: uuid }
        accountId: { type: string, format: uuid }
        connectionId: { type: string, format: uuid }
        subAccountId: { type: string, format: uuid, nullable: true }
        environment: { type: string, enum: [next, production] }
        remoteOrganizationId: { type: string }
        remoteOrganizationAlias: { type: string }
        friendlyName: { type: string }
        status: { type: string, enum: [pending, active, error, disabled] }
        contractorLicenseStates:
          type: array
          items: { type: string, minLength: 2, maxLength: 2 }
        verifiedAt: { type: string, format: date-time, nullable: true }
        lastVisibilityCheckAt: { type: string, format: date-time, nullable: true }
        lastErrorCode: { type: string, nullable: true }
        createdAt: { type: string, format: date-time }
        updatedAt: { type: string, format: date-time }
    PalmettoMappingScopeBinding:
      type: object
      additionalProperties: false
      required:
        - subAccountId
        - environment
        - mode
        - organizationMappingId
        - organizationReady
      properties:
        subAccountId: { type: string, format: uuid }
        environment: { type: string, enum: [sandbox, production] }
        mode: { type: string, enum: [branch_override, account_inheritance, fail_closed] }
        organizationMappingId: { type: string, format: uuid, nullable: true }
        organizationReady: { type: boolean }
    # ── GoodLeap financing (plan 2026-08-08-001, U6) ──────────────────────
    GoodLeapOrganizationMapping:
      type: object
      additionalProperties: false
      required:
        - id
        - accountId
        - connectionId
        - subAccountId
        - environment
        - channel
        - categoryId
        - friendlyName
        - status
        - providerOrganizationId
        - licensedStates
        - promotionIds
        - offerSnapshotTtlSeconds
        - verifiedAt
        - lastOfferRefreshAt
        - lastErrorCode
        - createdAt
        - updatedAt
      properties:
        id: { type: string, format: uuid }
        accountId: { type: string, format: uuid }
        connectionId: { type: string, format: uuid }
        subAccountId: { type: string, format: uuid, nullable: true }
        environment: { type: string, enum: [sandbox, production] }
        # The GoodLeap pricing channel BD builds in Origin. Globally unique per
        # environment: two tenants on one channel would cross-authorize offers.
        channel: { type: string }
        categoryId: { type: string }
        # The GoodLeap organization the mapping's calls act for. Opaque to
        # Portrex — GoodLeap formats it — so no format is asserted. `null` means
        # the mapping predates the binding and cannot originate work.
        providerOrganizationId: { type: string, maxLength: 128, nullable: true }
        friendlyName: { type: string }
        status: { type: string, enum: [pending_validation, active, disabled, error] }
        licensedStates:
          type: array
          items: { type: string, pattern: '^[A-Z]{2}$' }
        promotionIds: { type: array, items: { type: string } }
        # Mirrors the DB CHECK goodleap_organization_mappings_ttl_chk.
        offerSnapshotTtlSeconds: { type: integer, minimum: 60, maximum: 86400 }
        verifiedAt: { type: string, format: date-time, nullable: true }
        # Written by the async offer-refresh rail; null until it first runs.
        lastOfferRefreshAt: { type: string, format: date-time, nullable: true }
        lastErrorCode: { type: string, nullable: true }
        createdAt: { type: string, format: date-time }
        updatedAt: { type: string, format: date-time }

    GoodLeapOrganizationMappingsPage:
      type: object
      additionalProperties: false
      required: [items, page]
      properties:
        items:
          type: array
          maxItems: 100
          items: { $ref: '#/components/schemas/GoodLeapOrganizationMapping' }
        page:
          type: object
          additionalProperties: false
          required: [nextCursor, hasMore, limit, total]
          properties:
            nextCursor: { type: string, format: uuid, nullable: true }
            hasMore: { type: boolean }
            limit: { type: integer, minimum: 1, maximum: 100 }
            total: { type: integer, minimum: 0 }

    AccountBillingPolicy:
      type: object
      required: [account_id, enforcement_mode, price_cents, currency, billing_interval, trial_days, enforcement_starts_at, grace_days, exempt_roles, notes, updated_by_staff_user_id, created_at, updated_at]
      properties:
        account_id: { type: string, format: uuid }
        enforcement_mode:
          type: string
          enum: [off, soft, hard]
          description: >-
            `off` never warns or blocks; `soft` shows banners but never blocks; `hard`
            answers 402 and redirects members to the payment page once their
            trial, deadline or grace period has passed.
        price_cents: { type: integer }
        currency: { type: string }
        billing_interval: { type: string, enum: [month] }
        trial_days: { type: integer }
        enforcement_starts_at: { type: string, format: date-time, nullable: true }
        grace_days: { type: integer }
        exempt_roles:
          type: array
          items: { type: string }
        notes: { type: string, nullable: true }
        updated_by_staff_user_id: { type: string, format: uuid, nullable: true }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    StaffAccountBillingPolicyInput:
      type: object
      required: [reason]
      additionalProperties: false
      description: Patch semantics — every policy key is optional; the reason is not.
      properties:
        enforcement_mode: { type: string, enum: [off, soft, hard] }
        price_cents: { type: integer, minimum: 0 }
        currency: { type: string }
        trial_days: { type: integer, minimum: 0, maximum: 365 }
        enforcement_starts_at: { type: string, format: date-time, nullable: true }
        grace_days: { type: integer, minimum: 0, maximum: 90 }
        exempt_roles:
          type: array
          items: { type: string }
        notes: { type: string, nullable: true }
        reason: { type: string, minLength: 8, maxLength: 500 }
        confirm_immediate_lock:
          type: boolean
          description: Confirms a change that locks people at once (plan 2026-11-19-003 § 6.4). Never sent to the policy function.
        confirmed_lock_count:
          type: integer
          minimum: 0
          maximum: 1000000
          description: The count the staff user confirmed (newly_locked_count + newly_locked_soon_count of the 409). More people locked now answers 409 again; a confirm without it covers 0 people. Never sent to the policy function.

    StaffImmediateLockError:
      type: object
      additionalProperties: false
      required: [error, code, newly_locked_count, newly_locked_soon_count]
      properties:
        error: { type: string, enum: [immediate_lock_not_confirmed] }
        code: { type: string, enum: [immediate_lock_not_confirmed] }
        newly_locked_count: { type: integer, minimum: 0, description: People locked after the change who were not locked before }
        newly_locked_soon_count: { type: integer, minimum: 0, description: 'People locked within 3 days after the change (at now + 3 days), not before, and not in newly_locked_count' }

    StaffTenantDeadline:
      type: object
      additionalProperties: false
      required: [subject, sub_account_id, sub_account_name, deadline_date, deadline_at, time_zone, time_zone_source, set_by_user_id, set_by_name, set_at]
      properties:
        subject: { type: string, enum: [members, dues] }
        sub_account_id: { type: string, format: uuid, nullable: true }
        sub_account_name: { type: string, nullable: true }
        deadline_date: { type: string, format: date }
        deadline_at: { type: string, format: date-time }
        time_zone: { type: string }
        time_zone_source: { type: string }
        set_by_user_id: { type: string, format: uuid }
        set_by_name: { type: string, nullable: true }
        set_at: { type: string, format: date-time }

    StaffClearBillingDeadlineInput:
      type: object
      additionalProperties: false
      required: [subject, sub_account_id, reason]
      properties:
        subject: { type: string, enum: [members, dues] }
        sub_account_id: { type: string, format: uuid, nullable: true, description: 'null = the company date; required for dues' }
        reason: { type: string, minLength: 8, maxLength: 500 }
        confirm_immediate_lock: { type: boolean }
        confirmed_lock_count: { type: integer, minimum: 0, maximum: 1000000, description: The count the staff user confirmed (as on the policy PUT) }

    StaffClearBillingDeadlineResult:
      type: object
      additionalProperties: false
      required: [changed, newly_locked_count, locked_now, tenant_deadlines]
      properties:
        changed: { type: boolean }
        newly_locked_count: { type: integer, minimum: 0 }
        locked_now: { type: integer, minimum: 0 }
        tenant_deadlines:
          type: array
          items: { $ref: '#/components/schemas/StaffTenantDeadline' }

    StaffAccountBilling:
      type: object
      required: [policy, connection_scope, connect_accounts, member_counts, tenant_deadlines, locked_now]
      properties:
        policy:
          allOf: [{ $ref: '#/components/schemas/AccountBillingPolicy' }]
          nullable: true
        connection_scope: { type: string, enum: [company, branch] }
        connect_accounts:
          type: array
          items: { $ref: '#/components/schemas/StripeConnectAccountSummary' }
        member_counts: { $ref: '#/components/schemas/StripeMemberBillingCounts' }
        tenant_deadlines:
          type: array
          items: { $ref: '#/components/schemas/StaffTenantDeadline' }
        locked_now: { type: integer, minimum: 0, description: People the access engine locks at the database clock }
        square_subscriptions_agreement:
          allOf: [{ $ref: '#/components/schemas/SquareSubscriptionsAgreementState' }]
          nullable: true
          description: 'Plan 2026-11-19-002 § 7.6 (W3): the tenant''s agreement to member billing on Square. `can_agree` is always false here.'

    StaffUserSubscriptionRow:
      type: object
      required: [user_id, email, full_name, role, sub_account_id, sub_account_name, membership_active, status, access_state, trial_ends_at, current_period_end, cancel_at_period_end, last_payment_failed_at, grace_ends_at, locked_at, payment_method, stripe_subscription_id, updated_at, effective_deadline_at, deadline_source, payment_group]
      properties:
        user_id: { type: string, format: uuid }
        email: { type: string }
        full_name: { type: string }
        role: { type: string }
        sub_account_id: { type: string, format: uuid, nullable: true }
        sub_account_name: { type: string, nullable: true }
        membership_active: { type: boolean }
        status: { type: string, enum: [none, trialing, active, past_due, unpaid, canceled, incomplete] }
        access_state: { type: string, enum: [not_required, pending_setup, trial, active, grace, locked] }
        trial_ends_at: { type: string, format: date-time, nullable: true }
        current_period_end: { type: string, format: date-time, nullable: true }
        cancel_at_period_end: { type: boolean }
        last_payment_failed_at: { type: string, format: date-time, nullable: true }
        grace_ends_at: { type: string, format: date-time, nullable: true }
        locked_at: { type: string, format: date-time, nullable: true }
        payment_method:
          type: object
          nullable: true
          required: [brand, last4, exp_month, exp_year, expiring]
          properties:
            brand: { type: string, nullable: true }
            last4: { type: string, nullable: true }
            exp_month: { type: integer, nullable: true }
            exp_year: { type: integer, nullable: true }
            expiring: { type: boolean }
        stripe_subscription_id: { type: string, nullable: true }
        updated_at: { type: string, format: date-time, nullable: true }
        effective_deadline_at: { type: string, format: date-time, nullable: true }
        deadline_source: { type: string, enum: [branch, company, staff, joined], nullable: true }
        payment_group: { type: string, enum: [paid, failing, unpaid, cannot_pay, not_billed] }
        processor:
          type: string
          enum: [stripe, square]
          nullable: true
          description: 'Plan 2026-11-19-002 § 7.6 (W3): the processor of the member''s binding; null when neither processor can serve the member.'

    UserSubscription:
      type: object
      required: [status, trial_ends_at, current_period_start, current_period_end, cancel_at_period_end, canceled_at, last_payment_failed_at, grace_ends_at, locked_at, has_stripe_customer, has_stripe_subscription, payment_method]
      properties:
        status: { type: string, enum: [none, trialing, active, past_due, unpaid, canceled, incomplete] }
        trial_ends_at: { type: string, format: date-time, nullable: true }
        current_period_start: { type: string, format: date-time, nullable: true }
        current_period_end: { type: string, format: date-time, nullable: true }
        cancel_at_period_end: { type: boolean }
        canceled_at: { type: string, format: date-time, nullable: true }
        last_payment_failed_at: { type: string, format: date-time, nullable: true }
        grace_ends_at: { type: string, format: date-time, nullable: true }
        locked_at: { type: string, format: date-time, nullable: true }
        has_stripe_customer: { type: boolean }
        has_stripe_subscription: { type: boolean }
        payment_method:
          type: object
          nullable: true
          required: [brand, last4, exp_month, exp_year, expiring]
          properties:
            brand: { type: string, nullable: true }
            last4: { type: string, nullable: true }
            exp_month: { type: integer, nullable: true }
            exp_year: { type: integer, nullable: true }
            expiring:
              type: boolean
              description: The card expires this calendar month or has already expired.

    UserBillingAccess:
      type: object
      required: [state, required, locked, enforcementMode, reasons, trialEndsAt, graceEndsAt, enforcementStartsAt, nextRenewalAt, priceCents, currency, payUrl]
      properties:
        state: { type: string, enum: [not_required, pending_setup, trial, active, grace, locked] }
        required: { type: boolean }
        locked: { type: boolean }
        enforcementMode: { type: string, enum: [off, soft, hard] }
        reasons:
          type: array
          items: { type: string }
        trialEndsAt: { type: string, format: date-time, nullable: true }
        graceEndsAt: { type: string, format: date-time, nullable: true }
        enforcementStartsAt: { type: string, format: date-time, nullable: true }
        nextRenewalAt: { type: string, format: date-time, nullable: true }
        priceCents: { type: integer, nullable: true }
        currency: { type: string, nullable: true }
        payUrl: { type: string }
        deadlineDate:
          type: string
          format: date
          nullable: true
          description: 'Plan 2026-11-19-003 D4: the calendar day of enforcementStartsAt in the deadline zone (the day the admin picked; a staff date in the account zone).'
        deadlineTimeZone: { type: string, nullable: true, description: 'The zone of deadlineDate.' }

    UserBillingInvoice:
      type: object
      required: [stripe_invoice_id, amount_cents, amount_paid_cents, currency, status, hosted_url, pdf_url, period_start, period_end, due_at, paid_at, created_at]
      properties:
        id:
          type: string
          format: uuid
          description: 'Plan 2026-11-19-002 § 7.1 (W3): the Portrex id of the row. Use it as the list key: a Square row has no Stripe id.'
        processor: { type: string, enum: [stripe, square], description: Which processor collected the invoice. }
        stripe_invoice_id: { type: string, nullable: true, description: Null for a Square period invoice. }
        receipt_url:
          type: string
          format: uri
          nullable: true
          description: Square's receipt of the paid payment; null for a Stripe row and an unpaid Square row.
        amount_cents: { type: integer }
        amount_paid_cents: { type: integer }
        currency: { type: string }
        status: { type: string, enum: [draft, open, paid, void, uncollectible] }
        hosted_url: { type: string, nullable: true }
        pdf_url: { type: string, nullable: true }
        period_start: { type: string, format: date-time, nullable: true }
        period_end: { type: string, format: date-time, nullable: true }
        due_at: { type: string, format: date-time, nullable: true }
        paid_at: { type: string, format: date-time, nullable: true }
        created_at: { type: string, format: date-time }

    UserBillingMe:
      type: object
      required: [access, subscription, policy, merchant, actions]
      properties:
        access: { $ref: '#/components/schemas/UserBillingAccess' }
        subscription:
          allOf: [{ $ref: '#/components/schemas/UserSubscription' }]
          nullable: true
        policy:
          allOf: [{ $ref: '#/components/schemas/StripeBillingPolicySummary' }]
          nullable: true
        merchant:
          type: object
          nullable: true
          required: [display_name, business_name, livemode]
          description: The tenant's connected Stripe account — the merchant of record.
          properties:
            display_name: { type: string, nullable: true }
            business_name: { type: string, nullable: true }
            livemode: { type: boolean }
        actions:
          type: object
          required: [can_checkout, can_open_portal, can_cancel]
          properties:
            can_checkout: { type: boolean, description: Stripe Checkout; true only when the binding says Stripe. }
            can_open_portal: { type: boolean }
            can_cancel: { type: boolean }
            cancel_ends_now: { type: boolean, description: 'W3: a cancel ends the subscription now, not at the period end (a failed payment, a first payment not made, or a paid period that has ended).' }
            can_subscribe: { type: boolean, description: 'W3: the Square card page in mode "new card" for a first subscription; true only when the binding says Square.' }
            can_change_card: { type: boolean, description: 'W3: the Square card page in mode "new card" for a live Square subscription.' }
            can_pay: { type: boolean, description: 'W3: the Square card page in mode "pay": an open invoice, a stored card and no open attempt.' }
            can_resume: { type: boolean, description: 'W7: "Keep subscription" (`POST /v1/billing/me/resume`), on both processors: a live subscription that is set to end and whose paid period has not ended.' }
        processor:
          type: string
          enum: [stripe, square]
          nullable: true
          description: 'Plan 2026-11-19-002 § 4.1 (W3): the processor of the member''s binding; null when neither processor can serve the member.'
        card_setup:
          allOf: [{ $ref: '#/components/schemas/CardSetupState' }]
          description: The block of the Square card page. Present only when the binding says Square and has a connection; absent for a Stripe payer, a demo account and the house account.
        open_attempt:
          type: string
          enum: [none, in_progress]
          description: An attempt in `claimed` or `unknown` for the member's open Square invoice.
        payment_account_disconnected:
          type: boolean
          enum: [true]
          description: 'Critic m-F: the company disconnected the payment account (Stripe account or Square seller) of the member''s live subscription; the card cannot change. `merchant` is still that account. Present only when true.'
        subscribe_blocked:
          type: object
          additionalProperties: false
          required: [reason, retry_after]
          description: 'Why `actions.can_subscribe` is false while every other fact allows it. `stripe_checkout_open`: a Stripe Checkout of the member''s row can still complete; `retry_after` is the end of that window. Present only then.'
          properties:
            reason: { type: string, enum: [stripe_checkout_open] }
            retry_after: { type: string, format: date-time }

    MemberBillingNotReadyReason:
      type: string
      description: |
        Why a member cannot pay now: the reason of the member billing binding
        (plan 2026-11-19-002 § 4.1). The reason of the `pending_setup` access
        answer and of `409 not_ready` on the Square card routes.
      enum: [stripe_not_connected, stripe_charges_disabled, stripe_end_not_confirmed, square_not_connected, square_permission_missing, square_agreement_missing, seller_unavailable]

    CardSetupState:
      type: object
      additionalProperties: false
      description: The view model of a Square card page (plan 2026-11-19-002 § 7.1). No token is part of it.
      required: [processor, card_form, seller_name, amount_cents, currency, interval, card, open_attempt, actions]
      properties:
        processor: { type: string, enum: [square] }
        card_form:
          type: object
          additionalProperties: false
          required: [application_id, location_id, environment]
          description: The public ids of Square's Web Payments SDK. A `sandbox-` application id goes with `sandbox` only.
          properties:
            application_id: { type: string, pattern: '^(?:sandbox-)?sq0id[a-z]-[A-Za-z0-9_-]{1,80}$' }
            location_id: { type: string, pattern: '^[A-Za-z0-9]{1,32}$' }
            environment: { type: string, enum: [sandbox, production] }
        seller_name: { type: string, minLength: 1, maxLength: 200, description: '"Paid to <seller>".' }
        amount_cents: { type: integer, minimum: 1 }
        currency: { type: string, pattern: '^[a-z]{3}$' }
        interval: { type: string, enum: [month, year] }
        card:
          type: object
          nullable: true
          additionalProperties: false
          required: [id, brand, last4, exp_month, exp_year]
          properties:
            id: { type: string, pattern: '^ccof:[A-Za-z0-9_-]{1,120}$' }
            brand: { type: string, minLength: 1, maxLength: 40 }
            last4: { type: string, pattern: '^[0-9]{4}$' }
            exp_month: { type: integer, minimum: 1, maximum: 12 }
            exp_year: { type: integer, minimum: 2000, maximum: 2100 }
        first_charge_on:
          type: string
          nullable: true
          pattern: '^[0-9]{4}-[0-9]{2}-[0-9]{2}$'
          description: 'W5, the platform payer only: the calendar day (account time zone) of the first charge when a trial comes first. Null or absent when the first charge is the payer-present charge of the open invoice.'
        trial_days:
          type: integer
          nullable: true
          minimum: 1
          maximum: 365
          description: 'W5, the platform payer only: the days of a trial that starts when setup finishes, while its end day is not fixed. Present only when the row is not live, the wizard is not completed and no trial end is written.'
        open_attempt: { type: string, enum: [none, in_progress] }
        actions:
          type: object
          additionalProperties: false
          required: [can_subscribe, can_change_card, can_pay]
          properties:
            can_subscribe: { type: boolean }
            can_change_card: { type: boolean }
            can_pay: { type: boolean }

    CardSaveRequest:
      type: object
      additionalProperties: false
      required: [card_token, consent, consent_version]
      properties:
        card_token: { type: string, pattern: '^cnon:[A-Za-z0-9_:-]{1,250}$', description: 'The one-time token of `card.tokenize({ intent: ''STORE'' })`.' }
        consent: { type: boolean, enum: [true] }
        consent_version:
          type: string
          pattern: '^[a-z0-9][a-z0-9-]{0,99}$'
          description: The version of the consent text the page showed. A value that is not the API's version answers `409 consent_version_mismatch`.
        amount_cents:
          type: integer
          minimum: 1
          description: 'Optional: the amount that the consent text on the page named. Another amount than the API names now answers `409 amount_changed`; no card is stored.'
        interval:
          type: string
          enum: [month, year]
          description: 'Optional: the interval that the consent text on the page named. Another interval than the API names now answers `409 amount_changed`; no card is stored.'

    CardPayRequest:
      type: object
      additionalProperties: false
      required: [verification_token, amount_cents, currency]
      properties:
        verification_token: { type: string, pattern: '^verf:[A-Za-z0-9_:-]{1,250}$', description: The token of the bank check for the stored card. Used one time. }
        amount_cents: { type: integer, minimum: 1, description: The amount the page verified. A different balance answers `409 amount_changed`. }
        currency: { type: string, pattern: '^[a-z]{3}$' }

    CardSaveResult:
      type: object
      additionalProperties: false
      required: [result, card_setup]
      properties:
        result:
          type: string
          enum: [trialing, payment_required, saved, payment_pending]
          description: |
            `trialing`: the first charge is at the trial end. `payment_required`:
            the period invoice is open, so the page runs the bank check and calls
            `/pay`. `saved`: a card change with nothing to charge now.
            `payment_pending`: an attempt is open; no new charge starts.
        card_setup: { $ref: '#/components/schemas/CardSetupState' }

    CardPayResult:
      type: object
      additionalProperties: false
      required: [result, invoice_id]
      properties:
        result: { type: string, enum: [paid, payment_pending] }
        invoice_id: { type: string, format: uuid }

    CardRouteError:
      type: object
      required: [error]
      description: No answer carries a token or Square's `detail` text.
      properties:
        error:
          type: string
          enum: [invalid_body, idempotency_key_required, impersonation_forbidden, service_role_forbidden, billing_not_enabled, billing_price_invalid, not_ready, consent_version_mismatch, already_subscribed, no_subscription, card_refused, card_declined, verify_again, amount_changed, charge_in_progress, no_open_invoice, demo_account, db_unavailable, processor_mismatch, house_account, onboarding_not_complete, owner_required, onboarding_already_completed]
        reason:
          type: string
          pattern: '^[a-z_]{1,64}$'
          description: '`not_ready` only: the binding reason (`MemberBillingNotReadyReason` for a member, `PlatformSellerNotReadyReason` for the platform payer).'
        request_id: { type: string }

    PlatformSellerNotReadyReason:
      type: string
      description: Why Portrex's own Square account cannot take a company's card now (plan 2026-11-19-002 § 17.4).
      enum: [not_configured, environment_mismatch, token_refused, permission_missing, location_not_usable, square_unreachable]

    PlatformSeatChange:
      type: object
      additionalProperties: false
      required: [seats, starts_at, amount_cents, currency]
      description: 'W7 (§ 7.4): a seat count that starts at the next period. No charge is made at the change.'
      properties:
        seats: { type: integer, minimum: 1, maximum: 10000 }
        starts_at: { type: string, format: date-time, description: The start of the next period. }
        amount_cents: { type: integer, minimum: 1, description: The amount of one period with the new count. }
        currency: { type: string, pattern: '^[a-z]{3}$' }

    PlatformBillingPlanResult:
      type: object
      additionalProperties: false
      required: [seats, seat_change, changed]
      properties:
        seats: { type: integer, minimum: 1, description: The seats of today. }
        seat_change:
          allOf: [{ $ref: '#/components/schemas/PlatformSeatChange' }]
          nullable: true
        changed: { type: boolean, description: False when nothing changed. }

    PlatformBillingResumeResult:
      type: object
      additionalProperties: false
      required: [cancel_at_period_end, changed]
      description: '"Keep subscription" (W7): the subscription is no longer set to end and renews at the period end. No charge is made now.'
      properties:
        cancel_at_period_end: { type: boolean, enum: [false] }
        changed: { type: boolean, description: False when the subscription was not set to end (a second call changes nothing). }

    PlatformBillingCancelResult:
      type: object
      additionalProperties: false
      required: [cancel_at_period_end, ended, ends_at, changed]
      description: |
        `ended: at_period_end`: an active or trialing row whose paid period runs and that has no open
        invoice. A local stamp, no Square call; the subscription ends at `ends_at` with no charge.
        `ended: now`: a failed or unpaid state, or an open invoice. The subscription ended in this call
        (the open invoice is void, the card is disabled); `ends_at` is the time it ended.
      properties:
        cancel_at_period_end: { type: boolean, description: 'True for `ended: at_period_end`; false for `ended: now`.' }
        ended: { type: string, enum: [now, at_period_end] }
        ends_at: { type: string, format: date-time, description: 'At the period end: the end of the current period, or the trial end of a trialing row. Now: the time it ended.' }
        changed: { type: boolean, description: False when the row was already set to end. }

    ProcessorMismatchError:
      type: object
      additionalProperties: false
      required: [error]
      description: The company pays Portrex through the other processor (plan 2026-11-19-002 § 17.2.5).
      properties:
        error: { type: string, enum: [processor_mismatch] }
        request_id: { type: string }

    StripeConnectAccountSummary:
      type: object
      required: [id, sub_account_id, sub_account_name, stripe_account_id_masked, status, livemode, charges_enabled, details_submitted, payouts_enabled, display_name, business_name, account_email, default_currency, connected_at, last_synced_at, last_sync_error]
      properties:
        id: { type: string, format: uuid }
        sub_account_id: { type: string, format: uuid, nullable: true }
        sub_account_name: { type: string, nullable: true }
        stripe_account_id_masked:
          type: string
          description: Masked connected account id (`acct_…1234`). The full id never leaves the server.
        status: { type: string, enum: [active, disconnected, deauthorized] }
        livemode: { type: boolean }
        charges_enabled:
          type: boolean
          description: Stripe reports that the account can charge, and the connection is active. False for a disconnected or deauthorized connection.
        details_submitted: { type: boolean }
        payouts_enabled: { type: boolean }
        display_name: { type: string, nullable: true }
        business_name: { type: string, nullable: true }
        account_email: { type: string, nullable: true }
        default_currency: { type: string, nullable: true }
        connected_at: { type: string, format: date-time }
        last_synced_at: { type: string, format: date-time, nullable: true }
        last_sync_error:
          type: string
          nullable: true
          description: A stable code (`stripe_status_unavailable`), not provider text. Older rows can still hold text.
        live_member_subscriptions:
          type: integer
          minimum: 0
          description: 'Plan 2026-11-19-002 § 5.7 (W3): the member subscriptions of this connection that are live on Stripe, for the disconnect confirm text.'
        live_dues_subscriptions:
          type: integer
          minimum: 0
          description: 'W4: the sub-company dues obligations of this connection that are live on Stripe, only where the caller can disconnect it.'

    StripeBranchConnectionRow:
      type: object
      required: [sub_account_id, sub_account_name, connection, can_connect]
      properties:
        sub_account_id: { type: string, format: uuid }
        sub_account_name: { type: string }
        connection:
          allOf: [{ $ref: '#/components/schemas/StripeConnectAccountSummary' }]
          nullable: true
        can_connect: { type: boolean }

    SquareConnectAccountSummary:
      type: object
      required: [id, sub_account_id, sub_account_name, merchant_id_masked, status, livemode, charges_enabled, business_name, country, default_currency, location_id, location_name, connected_at, last_synced_at, last_sync_error]
      properties:
        id: { type: string, format: uuid }
        sub_account_id: { type: string, format: uuid, nullable: true }
        sub_account_name: { type: string, nullable: true }
        merchant_id_masked:
          type: string
          description: Masked Square merchant id. The full id never leaves the server.
        status: { type: string, enum: [active, disconnected, deauthorized] }
        livemode:
          type: boolean
          description: True for Square Production, false for Square Sandbox.
        charges_enabled:
          type: boolean
          description: The selected location is active, takes cards and settles in USD.
        business_name: { type: string, nullable: true }
        country: { type: string, nullable: true }
        default_currency: { type: string, nullable: true }
        location_id: { type: string, nullable: true }
        location_name: { type: string, nullable: true }
        connected_at: { type: string, format: date-time }
        last_synced_at: { type: string, format: date-time, nullable: true }
        last_sync_error:
          type: string
          nullable: true
          description: A stable code (`square_reconnect_required`, `square_status_unavailable`), not a sentence.
        subscriptions_ready:
          type: boolean
          description: 'Plan 2026-11-19-002 § 7.3 (W3): the connection can serve member billing: active, its location takes cards, every permission of member billing, and the tenant agreed.'
        permissions_missing:
          type: array
          items: { type: string, pattern: '^[A-Z][A-Z0-9_]{0,63}$' }
          description: Square permissions of member billing that the stored grant lacks. A connection whose permissions were not read yet lists them all.
        live_member_subscriptions:
          type: integer
          minimum: 0
          description: Live Square member subscriptions of this seller, for the disconnect confirm text.
        live_dues_subscriptions:
          type: integer
          minimum: 0
          description: 'W4: live Square sub-company dues obligations of this seller, for the same text.'

    SquareBranchConnectionRow:
      type: object
      required: [sub_account_id, sub_account_name, connection, can_connect]
      properties:
        sub_account_id: { type: string, format: uuid }
        sub_account_name: { type: string }
        connection:
          allOf: [{ $ref: '#/components/schemas/SquareConnectAccountSummary' }]
          nullable: true
        can_connect: { type: boolean }

    SquareConnectStatus:
      type: object
      required: [configured, webhook_configured, platform_environment, connection_scope, can_manage, company, branches, redirect_uri]
      properties:
        configured: { type: boolean }
        webhook_configured:
          type: boolean
          description: The platform can verify Square webhooks. A payment link is not created without it.
        platform_environment: { type: string, enum: [sandbox, production], nullable: true }
        connection_scope: { type: string, enum: [company, branch] }
        can_manage: { type: boolean }
        company:
          allOf: [{ $ref: '#/components/schemas/SquareConnectAccountSummary' }]
          nullable: true
        branches:
          type: array
          items: { $ref: '#/components/schemas/SquareBranchConnectionRow' }
        redirect_uri: { type: string, format: uri }
        subscriptions_agreement:
          allOf: [{ $ref: '#/components/schemas/SquareSubscriptionsAgreementState' }]
          description: 'Plan 2026-11-19-002 § 4.1, § 7.3 (W3): the tenant''s agreement to member billing on Square.'
        policy:
          allOf: [{ $ref: '#/components/schemas/StripeBillingPolicySummary' }]
          nullable: true
          description: 'W3: the member billing policy (the same block as on the Stripe status); null when staff set none.'
        member_counts:
          allOf: [{ $ref: '#/components/schemas/StripeMemberBillingCounts' }]
          nullable: true
          description: 'W3: the member rollup; null while member billing is not enabled.'

    SquareSubscriptionsAgreementState:
      type: object
      additionalProperties: false
      required: [agreed, agreed_at, agreement_version, current_version, can_agree]
      properties:
        agreed: { type: boolean, description: An agreement with `current_version` is stored. }
        agreed_at: { type: string, format: date-time, nullable: true }
        agreement_version: { type: string, nullable: true, pattern: '^[a-z0-9][a-z0-9-]{0,99}$' }
        current_version: { type: string, pattern: '^[a-z0-9][a-z0-9-]{0,99}$' }
        can_agree: { type: boolean, description: 'Owner/Admin, account-level seat, not impersonated, not the house account.' }

    SquareSubscriptionsAgreementInput:
      type: object
      additionalProperties: false
      required: [agreement_version]
      properties:
        agreement_version:
          type: string
          pattern: '^[a-z0-9][a-z0-9-]{0,99}$'
          description: The version of the sentence the page showed. Another version answers `409 agreement_version_mismatch`.

    SquareSubscriptionsAgreementResult:
      type: object
      additionalProperties: false
      required: [changed, agreement]
      properties:
        changed: { type: boolean, description: False when the same version was already stored. }
        agreement: { $ref: '#/components/schemas/SquareSubscriptionsAgreementState' }

    SquareSubscriptionsAgreementError:
      type: object
      required: [error]
      properties:
        error: { type: string, enum: [invalid_body, owner_or_admin_required, forbidden, impersonation_forbidden, agreement_version_mismatch, house_account, db_unavailable] }
        code: { type: string }
        request_id: { type: string }

    StripeConfirmEndedInput:
      type: object
      additionalProperties: false
      required: [connect_account_id]
      properties:
        connect_account_id: { type: string, format: uuid }

    StripeConfirmEndedResult:
      type: object
      additionalProperties: false
      required: [confirmed]
      properties:
        confirmed: { type: integer, minimum: 0, description: 'Rows of that connection, live on Stripe, that now carry `stripe_ended_confirmed_at`.' }
        confirmed_dues: { type: integer, minimum: 0, description: 'W4: the sub-company dues obligations of that connection, live on Stripe, that now carry `stripe_ended_confirmed_at`.' }

    StripeConfirmEndedError:
      type: object
      required: [error]
      properties:
        error: { type: string, enum: [invalid_body, owner_or_admin_required, forbidden, impersonation_forbidden, connection_not_found, stripe_connection_active, db_unavailable] }
        code: { type: string }
        request_id: { type: string }

    StripeSubscriptionsNotEndedError:
      type: object
      required: [error, set_to_end, not_set]
      description: '`not_set` + `dues_not_set` is above 0.'
      properties:
        error: { type: string, enum: [stripe_subscriptions_not_ended] }
        set_to_end: { type: integer, minimum: 0, description: Live member subscriptions now set to end at their period end. They stay set; a second try skips them. }
        not_set: { type: integer, minimum: 0 }
        dues_set_to_end: { type: integer, minimum: 0, description: 'W4: live dues subscriptions of this company connection now set to end at their period end.' }
        dues_not_set: { type: integer, minimum: 0, description: 'W4: live dues subscriptions of this company connection that are not set to end.' }
        request_id: { type: string }

    StripeMemberCheckoutsActiveError:
      type: object
      required: [error, in_progress]
      properties:
        error: { type: string, enum: [member_checkouts_active] }
        in_progress: { type: integer, minimum: 1, description: Member Checkout sessions of this connection that are in progress. }
        request_id: { type: string }

    StripeDuesCheckoutsActiveError:
      type: object
      required: [error, in_progress]
      properties:
        error: { type: string, enum: [dues_checkouts_active] }
        in_progress: { type: integer, minimum: 1, description: 'W4: sub-company dues Checkout sessions of this company connection that are in progress.' }
        request_id: { type: string }

    InternalBillingSweep:
      type: object
      additionalProperties: false
      required: [findings, opened]
      properties:
        findings: { type: integer, minimum: 0 }
        opened: { type: integer, minimum: 0, description: New findings; each wrote one `billing_finding_opened` alert line. }

    InternalBillingTickInput:
      type: object
      additionalProperties: false
      properties:
        after: { type: string, format: uuid, description: The `next_cursor` of the previous page. }

    InternalBillingTickResult:
      type: object
      additionalProperties: false
      required: [sweep, due, next_cursor]
      properties:
        sweep: { $ref: '#/components/schemas/InternalBillingSweep' }
        due:
          type: array
          items:
            type: object
            additionalProperties: false
            required: [payer_kind, payer_id, due_reason]
            properties:
              payer_kind: { type: string, enum: [member, platform, sub_company] }
              payer_id: { type: string, format: uuid }
              due_reason: { type: string, enum: [charge, recover] }
        next_cursor: { type: string, format: uuid, nullable: true }

    InternalBillingChargeDueInput:
      type: object
      additionalProperties: false
      required: [payer_kind, payer_id]
      properties:
        payer_kind: { type: string, enum: [member, platform, sub_company] }
        payer_id: { type: string, format: uuid }

    InternalBillingChargeDueResult:
      type: object
      additionalProperties: false
      required: [payer_kind, payer_id, path, outcome, attempt_id]
      properties:
        payer_kind: { type: string, enum: [member, platform, sub_company] }
        payer_id: { type: string, format: uuid }
        path: { type: string, enum: [charge, recover] }
        outcome:
          type: string
          enum: [not_found, not_due, in_flight, blocked_unknown, canceled, period_ended_unpaid, needs_new_card, seller_unavailable, paid, failed, unknown, pending, not_open, recover_instead, too_young, could_not_read, not_final]
        attempt_id: { type: string, format: uuid, nullable: true }

    InternalBillingReconcileResult:
      type: object
      additionalProperties: false
      required: [sellers, sweep, renewal_notices, failed_steps]
      properties:
        sellers:
          type: object
          additionalProperties: false
          required: [total, complete, failed, payments_seen, findings, cards_disabled]
          properties:
            total: { type: integer, minimum: 0 }
            complete: { type: integer, minimum: 0 }
            failed: { type: integer, minimum: 0 }
            payments_seen: { type: integer, minimum: 0 }
            findings: { type: integer, minimum: 0 }
            cards_disabled: { type: integer, minimum: 0 }
        sweep:
          allOf: [{ $ref: '#/components/schemas/InternalBillingSweep' }]
          nullable: true
        renewal_notices: { type: integer, minimum: 0, nullable: true }
        platform_seller:
          type: object
          nullable: true
          additionalProperties: false
          required: [payers, payments_seen, findings, cards_disabled, renewal_notices]
          description: 'W5: the step `platform_seller` at Portrex''s own Square location. Null when the step failed or did not run (Portrex''s seller is not ready).'
          properties:
            payers: { type: integer, minimum: 0 }
            payments_seen: { type: integer, minimum: 0 }
            findings: { type: integer, minimum: 0 }
            cards_disabled: { type: integer, minimum: 0 }
            renewal_notices: { type: integer, minimum: 0 }
        failed_steps:
          type: array
          items: { type: string, enum: [sellers, sweep, renewal_notices, disputes, platform_seller, platform_disputes] }

    InternalBillingError:
      type: object
      required: [error]
      properties:
        error: { type: string, enum: [unauthorized, billing_run_not_configured, invalid_body, db_unavailable] }
        request_id: { type: string }

    StaffBillingFindingRow:
      type: object
      additionalProperties: false
      required: [id, finding_ids, kinds, account_id, account_name, payer_kind, invoice_id, attempt_id, attempt_state, square_payment_id, square_location_id, details, state, first_seen_at, last_seen_at, resolution, resolved_at, actions]
      description: One row for one attempt; the two findings of one attempt share a row.
      properties:
        id: { type: string, format: uuid, description: The finding the actions of this row address. }
        finding_ids:
          type: array
          minItems: 1
          items: { type: string, format: uuid }
        kinds:
          type: array
          minItems: 1
          items: { type: string, enum: [attempt_unknown, attempt_open_too_long, payment_without_attempt, state_mismatch, unbilled_period, seller_unavailable, payment_disputed, platform_subscription_unpaid] }
        account_id: { type: string, format: uuid, nullable: true, description: 'Null for a finding of Portrex''s own Square seller with no company (W5): `seller_unavailable`, `payment_without_attempt`, `payment_disputed`.' }
        account_name: { type: string, nullable: true }
        payer_kind: { type: string, enum: [member, platform, sub_company], nullable: true }
        invoice_id: { type: string, format: uuid, nullable: true }
        attempt_id: { type: string, format: uuid, nullable: true }
        attempt_state: { type: string, enum: [claimed, succeeded, failed, unknown], nullable: true }
        square_payment_id: { type: string, nullable: true }
        square_location_id: { type: string, nullable: true }
        details:
          type: object
          description: Amounts, states and codes only. No personal data, no provider text.
          additionalProperties:
            nullable: true
            oneOf:
              - { type: string }
              - { type: number }
              - { type: boolean }
        state: { type: string, enum: [open, resolved] }
        first_seen_at: { type: string, format: date-time }
        last_seen_at: { type: string, format: date-time }
        resolution: { type: string, enum: [payment_applied, set_failed, set_without_square_read, refunded, closed], nullable: true }
        resolved_at: { type: string, format: date-time, nullable: true }
        actions:
          type: object
          additionalProperties: false
          required: [can_resolve, can_refund]
          properties:
            can_resolve: { type: boolean }
            can_refund: { type: boolean }
            close_only: { type: boolean, description: 'True when Resolve only closes the finding with the reason and reads no Square: a finding with no company, with no charge, or of a close-only kind (W5). It does not depend on the role. Missing = false.' }

    StaffBillingFindingResolveInput:
      type: object
      additionalProperties: false
      required: [reason]
      properties:
        reason: { type: string, minLength: 8, maxLength: 500 }
        result_without_square_read:
          type: string
          enum: [succeeded, failed]
          description: Only when Square cannot be read, with the tenant's written statement in `reason`.

    StaffBillingFindingResolveResult:
      type: object
      additionalProperties: false
      required: [finding_ids, resolution, attempt_state, card_disabled]
      properties:
        finding_ids:
          type: array
          minItems: 1
          items: { type: string, format: uuid }
        resolution: { type: string, enum: [payment_applied, set_failed, set_without_square_read, refunded, closed] }
        attempt_state: { type: string, enum: [claimed, succeeded, failed, unknown], nullable: true }
        card_disabled: { type: boolean }

    StaffBillingFindingRefundInput:
      type: object
      additionalProperties: false
      required: [reason]
      properties:
        reason: { type: string, minLength: 8, maxLength: 500 }

    StaffBillingFindingRefundResult:
      type: object
      additionalProperties: false
      required: [finding_id, square_refund_id, refund_status, amount_cents, currency]
      properties:
        finding_id: { type: string, format: uuid }
        square_refund_id: { type: string, minLength: 1, maxLength: 192 }
        refund_status: { type: string, enum: [PENDING, COMPLETED, REJECTED, FAILED] }
        amount_cents: { type: integer, minimum: 1 }
        currency: { type: string, pattern: '^[a-z]{3}$' }

    StaffBillingFindingError:
      type: object
      required: [error, code]
      description: The staff session, scope and step-up gates answer with their own codes.
      properties:
        error: { type: string }
        code:
          type: string
          enum: [invalid_request, invalid_finding_id, idempotency_key_required, forbidden, finding_not_found, account_not_found, finding_resolved, square_unreadable, payment_not_final, refund_not_allowed, payment_mismatch, nothing_to_refund, refund_amount_invalid, payment_provider_unavailable, db_unavailable]

    StaffPlatformProcessorsState:
      type: object
      additionalProperties: false
      required: [stripe, square]
      description: Whether each processor can take a new company now. No credential value.
      properties:
        stripe:
          type: object
          additionalProperties: false
          required: [configured, reason]
          properties:
            configured: { type: boolean }
            reason: { type: string, enum: [not_configured], nullable: true }
        square:
          type: object
          additionalProperties: false
          required: [configured, reason]
          properties:
            configured: { type: boolean }
            reason:
              type: string
              nullable: true
              enum: [not_configured, environment_mismatch, token_refused, permission_missing, location_not_usable, square_unreachable]

    StaffPlatformBillingProcessor:
      type: object
      additionalProperties: false
      required: [new_subscription_processor, processors, updated_at, can_change]
      properties:
        new_subscription_processor: { type: string, enum: [stripe, square] }
        processors: { $ref: '#/components/schemas/StaffPlatformProcessorsState' }
        updated_at: { type: string, format: date-time }
        can_change: { type: boolean, description: 'True for platform_admin: the screen shows the change button.' }

    StaffPlatformBillingProcessorInput:
      type: object
      additionalProperties: false
      required: [processor, reason]
      properties:
        processor: { type: string, enum: [stripe, square] }
        reason: { type: string, minLength: 8, maxLength: 500 }

    StaffAccountPlatformBillingProcessorResult:
      type: object
      additionalProperties: false
      required: [account_id, platform_billing_processor, changed]
      properties:
        account_id: { type: string, format: uuid }
        platform_billing_processor: { type: string, enum: [stripe, square] }
        changed: { type: boolean, description: 'False: the company already had this processor; nothing was written.' }

    StaffPlatformBillingError:
      type: object
      required: [error, code]
      description: The staff session, scope and step-up gates answer with their own codes.
      properties:
        error: { type: string }
        code:
          type: string
          enum: [invalid_request, invalid_account_id, idempotency_key_required, forbidden, account_not_found, processor_not_configured, subscription_exists, checkout_in_progress, onboarding_state_missing, processor_terms_not_allowed, db_unavailable]
        processors: { $ref: '#/components/schemas/StaffPlatformProcessorsState' }
        problems:
          type: array
          minItems: 1
          items:
            type: object
            required: [code, field, message]
            properties:
              code: { type: string }
              field: { type: string }
              message: { type: string }
              reason: { type: string }

    SquareLocation:
      type: object
      required: [id, name, status, currency, can_take_payments]
      properties:
        id: { type: string }
        name: { type: string, nullable: true }
        status: { type: string, nullable: true }
        currency: { type: string, nullable: true }
        can_take_payments: { type: boolean }

    InvoicePaymentProcessorState:
      type: object
      required: [selected, effective, can_manage, processors]
      properties:
        selected:
          type: string
          enum: [stripe, square]
          nullable: true
          description: The tenant's explicit choice. Null means automatic.
        effective:
          type: string
          enum: [stripe, square]
          nullable: true
          description: The processor a new payment link uses now. Null when none is connected.
        can_manage: { type: boolean }
        processors:
          type: array
          items:
            type: object
            required: [provider, connected, ready, management_href]
            properties:
              provider: { type: string, enum: [stripe, square] }
              connected: { type: boolean }
              ready:
                type: boolean
                description: |
                  At least one active connection can take a payment, AND the
                  platform can run a checkout on this processor (Stripe: client
                  and Connect webhook secret; Square: application credential and
                  webhook signature key). The payment-link route refuses the
                  processor otherwise.
              management_href: { type: string }
              subscriptions_ready:
                type: boolean
                description: 'Plan 2026-11-19-002 § 7.3 (W3): this processor can collect NEW member subscriptions now (Square: a connection with `subscriptions_ready`).'

    StripeMemberBillingCounts:
      type: object
      required: [members, active, trial, grace, locked, not_started, not_required]
      properties:
        members: { type: integer }
        active: { type: integer }
        trial: { type: integer }
        grace: { type: integer }
        locked: { type: integer }
        not_started: { type: integer }
        not_required: { type: integer }

    StripeBillingPolicySummary:
      type: object
      description: Read-only view of the commercial and enforcement policy for this tenant.
      required: [enforcement_mode, price_cents, currency, billing_interval, trial_days, enforcement_starts_at, grace_days, exempt_roles]
      properties:
        enforcement_mode: { type: string, enum: [off, soft, hard] }
        price_cents: { type: integer }
        currency: { type: string }
        billing_interval: { type: string, enum: [month] }
        trial_days: { type: integer }
        enforcement_starts_at: { type: string, format: date-time, nullable: true }
        grace_days: { type: integer }
        exempt_roles:
          type: array
          items: { type: string }

    MattermostSettingsResponse:
      type: object
      required: [site_url, team_id, has_bot_token, bot_token_last4, has_webhook_secret, inbound_webhook_path, enabled, status, health, last_error, connected_at, updated_at]
      additionalProperties: false
      properties:
        site_url: { type: string, format: uri }
        team_id: { type: string, nullable: true }
        team_slug: { type: string, nullable: true }
        has_bot_token: { type: boolean }
        bot_token_last4: { type: string, nullable: true }
        bot_username: { type: string, nullable: true }
        has_webhook_secret: { type: boolean }
        inbound_webhook_path: { type: string, nullable: true, description: 'Account-scoped mm-inbound-relay POST target (no secret in response).' }
        enabled: { type: boolean }
        status: { type: string }
        health:
          type: object
          required: [ping_ok, auth_ok]
          properties:
            ping_ok: { type: boolean, nullable: true }
            auth_ok: { type: boolean, nullable: true }
        last_error:
          type: object
          nullable: true
          properties:
            code: { type: string, nullable: true }
            message: { type: string, nullable: true }
        connected_at: { type: string, format: date-time, nullable: true }
        updated_at: { type: string, format: date-time, nullable: true }

    MattermostNotificationsSettings:
      type: object
      required: [default_channel, events, mention_dms]
      additionalProperties: false
      properties:
        default_channel: { type: string, nullable: true }
        mention_dms:
          type: object
          required: [enabled, include_preview]
          properties:
            enabled: { type: boolean }
            include_preview: { type: boolean }
        events:
          type: object
          additionalProperties: false
          properties:
            conversation.mention.created: { $ref: '#/components/schemas/MattermostNotifyEventSetting' }
            estimate.accepted: { $ref: '#/components/schemas/MattermostNotifyEventSetting' }
            estimate.declined: { $ref: '#/components/schemas/MattermostNotifyEventSetting' }
            contract.fully_signed: { $ref: '#/components/schemas/MattermostNotifyEventSetting' }
            project.status_changed: { $ref: '#/components/schemas/MattermostNotifyEventSetting' }

    MattermostNotifyEventSetting:
      type: object
      required: [enabled, channel]
      additionalProperties: false
      properties:
        enabled: { type: boolean }
        channel: { type: string, nullable: true }

    MattermostChannelSummary:
      type: object
      required: [id, name, display_name, type]
      additionalProperties: false
      properties:
        id: { type: string }
        name: { type: string }
        display_name: { type: string }
        type: { type: string }

    # Slice E1 — Mattermost member provisioning (translations of the Zod DTOs
    # in packages/types/src/integrations/mattermost.ts).
    MattermostMembersReconciliationRow:
      type: object
      required: [portrex_user_id, email, role, name, mm_user_id, in_team, action, error]
      additionalProperties: false
      properties:
        portrex_user_id: { type: string, format: uuid }
        email: { type: string, format: email }
        role: { type: string }
        name: { type: string, nullable: true }
        mm_user_id: { type: string, nullable: true }
        in_team: { type: boolean, nullable: true }
        action: { type: string, enum: [in_sync, add_to_team, create_user, no_mm_email_match] }
        error: { type: string, nullable: true }

    MattermostMembersReconciliation:
      type: object
      required: [rows, generated_at, team_id, truncated]
      additionalProperties: false
      properties:
        rows:
          type: array
          items: { $ref: '#/components/schemas/MattermostMembersReconciliationRow' }
        generated_at: { type: string, format: date-time }
        team_id: { type: string }
        truncated: { type: boolean }

    MattermostMembersSyncRequest:
      type: object
      additionalProperties: false

    MattermostMembersSyncResult:
      type: object
      required: [portrex_user_id, outcome, error]
      additionalProperties: false
      properties:
        portrex_user_id: { type: string, format: uuid }
        outcome: { type: string, enum: [in_sync, added, add_failed, needs_user_creation, no_mm_email_match] }
        error: { type: string, nullable: true }

    MattermostMembersSyncResponse:
      type: object
      required: [results, summary]
      additionalProperties: false
      properties:
        results:
          type: array
          items: { $ref: '#/components/schemas/MattermostMembersSyncResult' }
        summary:
          type: object
          required: [in_sync, added, failed, needs_user_creation]
          additionalProperties: false
          properties:
            in_sync: { type: integer, minimum: 0 }
            added: { type: integer, minimum: 0 }
            failed: { type: integer, minimum: 0 }
            needs_user_creation: { type: integer, minimum: 0 }

    MattermostSupportChannelsSettings:
      type: object
      required: [portrex_support_channel, tenant_support_channel, tenant_support_conversation_id]
      additionalProperties: false
      properties:
        portrex_support_channel: { type: string, nullable: true }
        tenant_support_channel: { type: string, nullable: true }
        tenant_support_conversation_id: { type: string, format: uuid, nullable: true }

    MattermostSupportChannelsPutRequest:
      type: object
      required: [portrex_support_channel, tenant_support_channel]
      additionalProperties: false
      properties:
        portrex_support_channel: { type: string, nullable: true }
        tenant_support_channel: { type: string, nullable: true }

    StripeConnectStatus:
      type: object
      required: [configured, webhook_configured, platform_environment, connection_scope, can_manage, company, branches, policy, member_counts, redirect_uri]
      properties:
        configured:
          type: boolean
          description: The platform has a Stripe Connect client id and secret key.
        webhook_configured:
          type: boolean
          description: |
            The platform can verify Connect webhooks (`STRIPE_CONNECT_WEBHOOK_SECRET`
            is set), so a payment can settle an invoice. A payment link is not
            created without it. Same meaning as the Square field.
        platform_environment:
          type: string
          enum: [test, live]
          nullable: true
          description: Non-secret mode derived from the server-side Stripe credential.
        connection_scope: { type: string, enum: [company, branch] }
        can_manage:
          type: boolean
          description: The caller may change the scope and manage the company connection.
        company:
          allOf: [{ $ref: '#/components/schemas/StripeConnectAccountSummary' }]
          nullable: true
        branches:
          type: array
          items: { $ref: '#/components/schemas/StripeBranchConnectionRow' }
        policy:
          allOf: [{ $ref: '#/components/schemas/StripeBillingPolicySummary' }]
          nullable: true
        member_counts:
          allOf: [{ $ref: '#/components/schemas/StripeMemberBillingCounts' }]
          nullable: true
        redirect_uri:
          type: string
          format: uri
          description: The redirect URI that must be registered in the platform's Stripe Connect settings.

    StripeMemberBillingRow:
      type: object
      required: [user_id, full_name, email, role, sub_account_id, sub_account_name, state, subscription_status, current_period_end, grace_ends_at, trial_ends_at]
      properties:
        user_id: { type: string, format: uuid }
        full_name: { type: string }
        email: { type: string }
        role: { type: string }
        sub_account_id: { type: string, format: uuid, nullable: true }
        sub_account_name: { type: string, nullable: true }
        state: { type: string, enum: [not_required, pending_setup, trial, active, grace, locked] }
        subscription_status: { type: string, enum: [none, trialing, active, past_due, unpaid, canceled, incomplete] }
        current_period_end: { type: string, format: date-time, nullable: true }
        grace_ends_at: { type: string, format: date-time, nullable: true }
        trial_ends_at: { type: string, format: date-time, nullable: true }

    # Plan 2026-11-19-003 D2 — tenant member billing (packages/types/src/member-billing.ts).
    MemberPaymentGroup:
      type: string
      enum: [paid, failing, unpaid, cannot_pay, not_billed]
    MemberPaymentGroupCounts:
      type: object
      additionalProperties: false
      required: [paid, failing, unpaid, cannot_pay, not_billed, total]
      properties:
        paid: { type: integer, minimum: 0 }
        failing: { type: integer, minimum: 0 }
        unpaid: { type: integer, minimum: 0 }
        cannot_pay: { type: integer, minimum: 0 }
        not_billed: { type: integer, minimum: 0 }
        total: { type: integer, minimum: 0, description: 'paid + failing + unpaid + cannot_pay' }
    BillingMemberRow:
      type: object
      additionalProperties: false
      required: [user_id, full_name, email, role, sub_account_id, sub_account_name, state, subscription_status, current_period_end, grace_ends_at, trial_ends_at, effective_deadline_at, deadline_source, payment_group, last_reminded_at, reminded_today, can_remind]
      properties:
        user_id: { type: string, format: uuid }
        full_name: { type: string }
        email: { type: string }
        role: { type: string }
        sub_account_id: { type: string, format: uuid, nullable: true }
        sub_account_name: { type: string, nullable: true }
        state: { type: string, enum: [not_required, pending_setup, trial, active, grace, locked] }
        subscription_status: { type: string, enum: [none, trialing, active, past_due, unpaid, canceled, incomplete] }
        current_period_end: { type: string, format: date-time, nullable: true }
        grace_ends_at: { type: string, format: date-time, nullable: true }
        trial_ends_at: { type: string, format: date-time, nullable: true }
        effective_deadline_at: { type: string, format: date-time, nullable: true }
        deadline_source: { type: string, enum: [branch, company, staff, joined], nullable: true }
        payment_group: { $ref: '#/components/schemas/MemberPaymentGroup' }
        last_reminded_at: { type: string, format: date-time, nullable: true }
        reminded_today: { type: boolean }
        can_remind: { type: boolean }
        processor:
          type: string
          enum: [stripe, square]
          nullable: true
          description: 'Plan 2026-11-19-002 § 7.3 (W3): the processor of the member''s binding; null when neither processor can serve the member.'
        deadline_date:
          type: string
          format: date
          nullable: true
          description: 'Plan 003 (Critic MJ-A): the member''s own pay-by day, the last full calendar day before effective_deadline_at in deadline_time_zone (the rule of deadlineDate on /v1/billing/me). Null when no date exists.'
        deadline_time_zone:
          type: string
          nullable: true
          description: 'Plan 003 (Critic MJ-A): the IANA zone of deadline_date — the time_zone of the base row (branch or company), also for a late joiner; the current account zone for a staff date. Null when no date exists.'
    BillingMembersResponse:
      type: object
      additionalProperties: false
      required: [enabled, data, next_cursor]
      properties:
        enabled: { type: boolean }
        data:
          type: array
          items: { $ref: '#/components/schemas/BillingMemberRow' }
        next_cursor: { type: string, nullable: true, enum: [null] }
    MemberBillingDeadline:
      type: object
      additionalProperties: false
      required: [deadline_date, deadline_at]
      properties:
        deadline_date: { type: string, format: date }
        deadline_at: { type: string, format: date-time }
        time_zone:
          type: string
          description: 'Plan 003 (Critic MJ-A): the IANA zone the row was written in (billing_deadlines.time_zone). deadline_date is a day in this zone; it can differ from the current company or branch zone after a zone change.'
    MemberBillingBranch:
      type: object
      additionalProperties: false
      required: [sub_account_id, sub_account_name, deadline, base_deadline_at, base_source, counts]
      properties:
        sub_account_id: { type: string, format: uuid }
        sub_account_name: { type: string }
        deadline:
          allOf: [{ $ref: '#/components/schemas/MemberBillingDeadline' }]
          nullable: true
        base_deadline_at: { type: string, format: date-time, nullable: true }
        base_source: { type: string, enum: [branch, company, staff], nullable: true }
        base_time_zone:
          type: string
          nullable: true
          description: 'Plan 003 (Critic MJ-A): the zone of base_deadline_at — the branch row zone, else the company row zone, else the current account zone for a staff date; null when there is no base.'
        counts:
          allOf: [{ $ref: '#/components/schemas/MemberPaymentGroupCounts' }]
          nullable: true
        time_zone: { type: string, description: 'D4: the branch zone; a branch date is the end of the picked day in it' }
        time_zone_source: { type: string }
        today: { type: string, format: date, description: 'Today in the branch zone, database clock' }
        earliest_allowed_date: { type: string, format: date, nullable: true }
        latest_allowed_date: { type: string, format: date, nullable: true }
        actions:
          type: object
          additionalProperties: false
          required: [can_set_date, can_send_reminders]
          properties:
            can_set_date: { type: boolean }
            can_send_reminders: { type: boolean }
    MemberBillingDeadlinesResponse:
      type: object
      additionalProperties: false
      required: [enabled, enforcement_mode, effect, time_zone, time_zone_source, today, earliest_allowed_date, latest_allowed_date, company_deadline, staff_deadline_at, base_deadline_at, base_source, base_passed, branches, counts, caller, cannot_pay_reason, actions]
      properties:
        enabled: { type: boolean }
        enforcement_mode: { type: string, enum: ['off', soft, hard], nullable: true }
        effect:
          type: object
          nullable: true
          additionalProperties: false
          required: [after_deadline, trial_days]
          properties:
            after_deadline: { type: string, enum: [lose_access, reminder] }
            trial_days: { type: integer, minimum: 1, nullable: true }
        time_zone: { type: string }
        time_zone_source: { type: string }
        today: { type: string, format: date }
        earliest_allowed_date: { type: string, format: date, nullable: true }
        latest_allowed_date: { type: string, format: date, nullable: true }
        company_deadline:
          allOf: [{ $ref: '#/components/schemas/MemberBillingDeadline' }]
          nullable: true
        staff_deadline_at: { type: string, format: date-time, nullable: true }
        base_deadline_at: { type: string, format: date-time, nullable: true }
        base_source: { type: string, enum: [company, staff], nullable: true }
        base_time_zone:
          type: string
          nullable: true
          description: 'Plan 003 (Critic MJ-A): the zone of base_deadline_at — company_deadline.time_zone, else the current account zone for a staff date; null when there is no base.'
        base_passed: { type: boolean }
        branches:
          type: array
          items: { $ref: '#/components/schemas/MemberBillingBranch' }
        counts:
          allOf: [{ $ref: '#/components/schemas/MemberPaymentGroupCounts' }]
          nullable: true
        caller:
          type: object
          additionalProperties: false
          required: [payment_group, included]
          properties:
            payment_group: { $ref: '#/components/schemas/MemberPaymentGroup' }
            included: { type: boolean }
        cannot_pay_reason: { type: string, enum: [no_price, no_connection], nullable: true }
        actions:
          type: object
          additionalProperties: false
          required: [can_set_company_date, can_set_branch_date, can_send_reminders]
          properties:
            can_set_company_date: { type: boolean }
            can_set_branch_date: { type: boolean }
            can_send_reminders: { type: boolean }
        stripe_ends_not_confirmed:
          type: array
          description: |
            Plan 002 § 5.7 (Critic W3 NEW-2): each Stripe connection that is not
            active whose members have the binding reason
            `stripe_end_not_confirmed` (a live Stripe subscription, not set to
            end, no confirm stamp, and no active connection of the same Stripe
            account). Sent only to an Owner or Admin with an account-level
            seat, not impersonated, with `integrations:connection:write` (the
            fence of `POST /v1/integrations/stripe/member-subscriptions/confirm-ended`).
          items:
            type: object
            additionalProperties: false
            required: [connect_account_id, sub_account_id, stripe_account_id_masked, members]
            properties:
              connect_account_id: { type: string, format: uuid }
              sub_account_id: { type: string, format: uuid, nullable: true }
              stripe_account_id_masked: { type: string }
              members: { type: integer, minimum: 0, description: 'Members with this reason; 0 when only dues wait. `members` + `dues` is above 0.' }
              dues: { type: integer, minimum: 1, description: 'W4: dues obligations of live sub-companies whose dues binding has this reason. Absent when 0.' }
    MemberBillingDeadlineInput:
      type: object
      additionalProperties: false
      required: [sub_account_id, deadline_date]
      properties:
        sub_account_id: { type: string, format: uuid, nullable: true, description: 'null = the company date; a uuid = that branch date (D4)' }
        deadline_date: { type: string, format: date, nullable: true }
    MemberBillingDeadlineError:
      type: object
      required: [error, request_id]
      properties:
        error: { type: string }
        earliest_allowed_date: { type: string, format: date, nullable: true }
        request_id: { type: string }
    # Plan 2026-11-19-003 D4 — dues routes (packages/types/src/sub-account-billing.ts).
    SubAccountDuesDeadlineInput:
      type: object
      additionalProperties: false
      required: [deadline_date]
      properties:
        deadline_date: { type: string, format: date, nullable: true, description: 'null clears the dues date (always permitted)' }
    SubAccountDuesReminderResult:
      type: object
      additionalProperties: false
      required: [sent, skipped]
      properties:
        sent: { type: integer, minimum: 0 }
        skipped:
          type: object
          additionalProperties: false
          required: [reminded_today]
          properties:
            reminded_today: { type: integer, minimum: 0 }
    SubAccountDuesError:
      type: object
      required: [error]
      properties:
        error:
          type: string
          enum: [invalid_request, owner_or_admin_required, forbidden, impersonation_forbidden, missing_scope, not_found, billing_not_enabled, cannot_pay, paid, no_branch_admin, deadline_too_soon, deadline_in_past, deadline_too_far, db_unavailable]
        earliest_allowed_date: { type: string, format: date, nullable: true }
        code: { type: string }
        request_id: { type: string }
    # Plan 2026-11-19-003 D3 — POST /v1/billing/member-reminders (packages/types/src/member-billing.ts).
    MemberReminderInput:
      type: object
      additionalProperties: false
      required: [target]
      properties:
        target:
          oneOf:
            - type: object
              additionalProperties: false
              required: [kind, user_id]
              properties:
                kind: { type: string, enum: [member] }
                user_id: { type: string, format: uuid }
            - type: object
              additionalProperties: false
              required: [kind]
              properties:
                kind: { type: string, enum: [unpaid] }
            - type: object
              additionalProperties: false
              required: [kind, sub_account_id]
              properties:
                kind: { type: string, enum: [branch] }
                sub_account_id: { type: string, format: uuid }
    MemberReminderResult:
      type: object
      additionalProperties: false
      required: [sent, skipped]
      properties:
        sent: { type: integer, minimum: 0, description: Notices given to the notification system }
        skipped:
          type: object
          additionalProperties: false
          required: [reminded_today, paid, cannot_pay]
          properties:
            reminded_today: { type: integer, minimum: 0 }
            paid: { type: integer, minimum: 0 }
            cannot_pay: { type: integer, minimum: 0 }
    MemberReminderError:
      type: object
      required: [error]
      properties:
        error:
          type: string
          enum: [invalid_request, owner_or_admin_required, forbidden, impersonation_forbidden, missing_scope, not_found, billing_not_enabled, reminded_today, paid, cannot_pay, not_billed, branch_scope_mismatch, db_unavailable]
        next_allowed_on: { type: string, format: date, description: '`reminded_today` only: the first day on which an admin may remind this person again' }
        next_allowed_time_zone: { type: string, description: 'The zone of next_allowed_on: the account zone (the zone of the daily limit)' }
        code: { type: string }
        request_id: { type: string }

    # Flow 2 — first-class sub-company payer obligations. These schemas are
    # deliberately separate from UserSubscription (employee payer) and the
    # account billing schemas (PORTREX payer).
    SubAccountBillingObligation:
      type: object
      additionalProperties: false
      required: [id, sub_account_id, sub_account_name, status, price_cents, currency, billing_interval, trial_ends_at, current_period_start, current_period_end, cancel_at_period_end, canceled_at, last_payment_failed_at, last_invoice_status, has_stripe_customer, has_stripe_subscription, payment_method, actions]
      properties:
        id: { type: string, format: uuid, nullable: true }
        sub_account_id: { type: string, format: uuid }
        sub_account_name: { type: string, nullable: true }
        status: { type: string, enum: [none, trialing, active, past_due, unpaid, canceled, incomplete] }
        price_cents: { type: integer, minimum: 0 }
        currency: { type: string, pattern: '^[a-z]{3}$' }
        billing_interval: { type: string, enum: [month] }
        trial_ends_at: { type: string, format: date-time, nullable: true }
        current_period_start: { type: string, format: date-time, nullable: true }
        current_period_end: { type: string, format: date-time, nullable: true }
        cancel_at_period_end: { type: boolean }
        canceled_at: { type: string, format: date-time, nullable: true }
        last_payment_failed_at: { type: string, format: date-time, nullable: true }
        last_invoice_status: { type: string, nullable: true }
        has_stripe_customer: { type: boolean }
        has_stripe_subscription: { type: boolean }
        payment_method:
          type: object
          nullable: true
          required: [brand, last4, exp_month, exp_year, expiring]
          properties:
            brand: { type: string, nullable: true }
            last4: { type: string, nullable: true }
            exp_month: { type: integer, nullable: true }
            exp_year: { type: integer, nullable: true }
            expiring: { type: boolean }
        actions:
          type: object
          required: [can_checkout, can_open_portal, can_cancel]
          properties:
            can_checkout: { type: boolean }
            can_open_portal: { type: boolean }
            can_cancel: { type: boolean }
            can_set_dues_date: { type: boolean }
            can_subscribe: { type: boolean, description: 'W4: the Square card page in mode "new card" for an obligation that is not live; only for a Square binding.' }
            can_change_card: { type: boolean, description: 'W4: the Square card page in mode "new card" for a live Square obligation.' }
            can_pay: { type: boolean, description: 'W4: the Square card page in mode "pay": an open invoice, a stored card and no open attempt.' }
            cancel_ends_now: { type: boolean, description: 'W4: a cancel ends the dues now, not at the period end (as `actions.cancel_ends_now` of `GET /v1/billing/me`). The API decides it.' }
            can_resume: { type: boolean, description: 'W4-C: "Keep renewal" (`POST /v1/billing/sub-companies/{subAccountId}/resume`), both processors: a live row set to end whose paid period has not ended.' }
        processor: { type: string, enum: [stripe, square], nullable: true, description: 'W4: the processor of the dues binding; null when neither processor can serve the sub-company.' }
        not_ready_reason:
          type: string
          nullable: true
          enum: [stripe_not_connected, stripe_charges_disabled, stripe_end_not_confirmed, square_not_connected, square_permission_missing, square_agreement_missing, seller_unavailable, house_account, square_not_configured, stripe_checkout_open]
          description: 'W4: why the sub-company cannot pay its dues now; null when it can. `stripe_checkout_open`: a Stripe Checkout of the row can still complete, so no Square subscription may start yet.'
        retry_after:
          type: string
          format: date-time
          description: 'Only with `not_ready_reason: stripe_checkout_open`: the end of the window in which that Stripe Checkout can still complete.'
        card_setup:
          allOf: [{ $ref: '#/components/schemas/CardSetupState' }]
          description: 'W4: the block of the card page. Absent for a demo account, the house account, a Stripe binding and an instance with no Square application.'
        open_attempt: { type: string, enum: [none, in_progress], description: 'W4: an attempt in `claimed` or `unknown` for the open Square dues invoice.' }
        open_invoice_period:
          type: object
          nullable: true
          additionalProperties: false
          required: [start, end]
          description: 'W4: the period of the open Square dues invoice; null when none is open.'
          properties:
            start: { type: string, format: date-time }
            end: { type: string, format: date-time }
        last_receipt_url: { type: string, format: uri, nullable: true, description: 'W4: Square''s receipt of the newest paid dues invoice.' }
        dues_deadline_at: { type: string, format: date-time, nullable: true, description: 'D4: the end of the dues day ("Pay by")' }
        dues_deadline_date: { type: string, format: date, nullable: true }
        dues_deadline_time_zone: { type: string, nullable: true }
        overdue: { type: boolean, description: 'The dues date passed and the sub-company owes (remind only, no lock)' }
        payment_group: { type: string, enum: [paid, failing, unpaid, cannot_pay] }
        last_reminded_at: { type: string, format: date-time, nullable: true }
        has_branch_admin: { type: boolean }
        can_remind: { type: boolean }
        today: { type: string, format: date, nullable: true, description: 'D4: today in the sub-company zone on the database clock (the dues date dialog)' }
        earliest_allowed_date: { type: string, format: date, nullable: true, description: 'D4: the earliest dues date of plan 003 § 3.3 (today + 3, or the current dues day when it has not passed and is sooner)' }
        latest_allowed_date: { type: string, format: date, nullable: true, description: 'D4: the latest dues date (today + 365)' }

    SubAccountBillingList:
      type: object
      additionalProperties: false
      required: [data, policy, merchant, company_connected]
      properties:
        data:
          type: array
          items: { $ref: '#/components/schemas/SubAccountBillingObligation' }
        policy:
          allOf: [{ $ref: '#/components/schemas/StripeBillingPolicySummary' }]
          nullable: true
        merchant:
          type: object
          nullable: true
          required: [display_name, business_name, livemode]
          properties:
            display_name: { type: string, nullable: true }
            business_name: { type: string, nullable: true }
            livemode: { type: boolean }
        company_connected: { type: boolean }

    SubAccountBillingCheckout:
      type: object
      additionalProperties: false
      required: [session_id, url]
      properties:
        session_id: { type: string, minLength: 1 }
        url: { type: string, format: uri, nullable: true }

    SubAccountBillingMutation:
      type: object
      additionalProperties: false
      required: [data]
      properties:
        data: { $ref: '#/components/schemas/SubAccountBillingObligation' }

    SubAccountCardRouteError:
      type: object
      required: [error]
      description: 'W4: the errors of the three Square card routes of dues. No answer carries a token or Square''s `detail` text.'
      properties:
        error:
          type: string
          enum: [invalid_body, idempotency_key_required, impersonation_forbidden, service_role_forbidden, billing_not_enabled, billing_price_invalid, not_ready, consent_version_mismatch, already_subscribed, no_subscription, card_refused, card_declined, verify_again, amount_changed, charge_in_progress, no_open_invoice, demo_account, db_unavailable, processor_mismatch, house_account, onboarding_not_complete, owner_required, onboarding_already_completed, not_found, owner_or_admin_required, branch_scope_mismatch, missing_scope, square_unavailable]
        reason:
          type: string
          pattern: '^[a-z_]{1,64}$'
          description: '`not_ready` only: the reason of the dues binding (`not_ready_reason` of the dues row).'
        request_id: { type: string }

    GoodLeapConnectionHealth:
      type: object
      additionalProperties: false
      required:
        - environment
        - connectionEnabled
        - connectionStatus
        - credentialBindingMode
        - credentialConfigured
        - credentialValid
        - platformCredentialConfigured
        - platformCredentialValid
        - webhookRegistrationRecorded
        - lastWebhookDeliveryAt
        - lastHealthCheckAt
        - lastErrorCode
        - mappings
        - capabilities
      properties:
        environment: { type: string, enum: [sandbox, production] }
        connectionEnabled: { type: boolean }
        connectionStatus: { type: string, enum: [connected, disabled, error, not_connected] }
        credentialBindingMode:
          type: string
          enum: [tenant_byo, legacy_platform]
          nullable: true
        credentialConfigured: { type: boolean }
        credentialValid: { type: boolean }
        platformCredentialConfigured: { type: boolean }
        platformCredentialValid: { type: boolean }
        # GoodLeap has NO webhook-management API: an endpoint is enabled by
        # GoodLeap staff, so this records a human step rather than a probe.
        webhookRegistrationRecorded: { type: boolean }
        lastWebhookDeliveryAt: { type: string, format: date-time, nullable: true }
        lastHealthCheckAt: { type: string, format: date-time, nullable: true }
        lastErrorCode: { type: string, nullable: true }
        mappings:
          type: array
          items: { $ref: '#/components/schemas/GoodLeapOrganizationMapping' }
        capabilities: { $ref: '#/components/schemas/GoodLeapCapabilities' }

    GoodLeapCapabilities:
      type: object
      additionalProperties: false
      description: |
        v1 capability record. Direct full submission and completion milestones
        plus the documented Home Improvement lifecycle rails are ordinary
        runtime booleans matching `GoodLeapCapabilitiesSchema`. Per-case
        provider state and authorization still fence each action.
      required:
        - offers
        - payments
        - shareApp
        - statusSync
        - fullSubmission
        - documents
        - milestones
        - changeOrders
        - stipulations
        - confirmLoanDetails
        - sendLoanDocuments
        - changeLoanOffer
        - changeLoanAmount
        - changeLoanChannel
        - changeLoanAutopay
        - cancelLoan
      properties:
        offers: { type: boolean }
        payments: { type: boolean }
        shareApp: { type: boolean }
        statusSync: { type: boolean }
        fullSubmission: { type: boolean }
        documents: { type: boolean }
        milestones: { type: boolean }
        changeOrders: { type: boolean }
        stipulations: { type: boolean }
        confirmLoanDetails: { type: boolean }
        sendLoanDocuments: { type: boolean }
        changeLoanOffer: { type: boolean }
        changeLoanAmount: { type: boolean }
        changeLoanChannel: { type: boolean }
        changeLoanAutopay: { type: boolean }
        cancelLoan: { type: boolean }

    GoodLeapOffersResponse:
      type: object
      additionalProperties: false
      description: |
        Mirrors `GoodLeapOffersResponseSchema` in
        `packages/types/src/goodleap-finance.ts`, which the route parses its own
        response through. Keep the two in lockstep — the web client consumes the
        exported type, and an inline-only shape is what let it drift before.
      required:
        - projectId
        - leadId
        - customerId
        - organizationMappingId
        - propertyState
        - propertyStateSource
        - customerPersonId
        - applicantName
        - applicantFirstName
        - applicantLastName
        - estimateId
        - estimateTotalCents
        - snapshot
        - stale
        - refreshEnqueued
        - issues
      properties:
        projectId: { type: string, format: uuid, nullable: true }
        leadId: { type: string, format: uuid, nullable: true }
        customerId: { type: string, format: uuid, nullable: true }
        organizationMappingId: { type: string, format: uuid, nullable: true }
        # The state actually used to filter — the `state` override when supplied.
        propertyState: { type: string, pattern: '^[A-Z]{2}$', nullable: true }
        propertyStateSource: { type: string, enum: [service_address, override] }
        customerPersonId: { type: string, format: uuid, nullable: true }
        applicantName: { type: string, minLength: 1, maxLength: 500, nullable: true }
        applicantFirstName: { type: string, minLength: 1, maxLength: 500, nullable: true }
        applicantLastName: { type: string, minLength: 1, maxLength: 500, nullable: true }
        applicantEmailMasked: { type: string, nullable: true }
        applicantRecipientConfirmation: { type: string, pattern: '^[a-f0-9]{64}$', nullable: true }
        estimateId: { type: string, format: uuid, nullable: true }
        estimateTotalCents: { type: integer, minimum: 0, nullable: true }
        # Staleness is a property of the READ, not of the immutable snapshot.
        snapshot:
          nullable: true
          allOf: [{ $ref: '#/components/schemas/GoodLeapOfferSnapshot' }]
        stale: { type: boolean }
        refreshEnqueued: { type: boolean }
        issues:
          type: array
          maxItems: 50
          items: { $ref: '#/components/schemas/GoodLeapPreflightIssue' }

    GoodLeapOffer:
      type: object
      additionalProperties: false
      required:
        - remoteOfferId
        - offerName
        - productCode
        - promotionId
        - aprBasisPoints
        - termMonths
        - monthlyPaymentCents
        - dealerFeeBasisPoints
        - disclaimerText
        - offerHash
      properties:
        remoteOfferId: { type: string }
        offerName: { type: string }
        productCode: { type: string, nullable: true }
        promotionId: { type: string, nullable: true }
        aprBasisPoints: { type: integer, minimum: 0, nullable: true }
        termMonths: { type: integer, minimum: 1 }
        monthlyPaymentCents: { type: integer, minimum: 0, nullable: true }
        dealerFeeBasisPoints: { type: integer, minimum: 0, nullable: true }
        disclaimerText: { type: string, nullable: true }
        offerHash: { type: string, pattern: '^[a-f0-9]{64}$' }

    GoodLeapOfferSnapshot:
      type: object
      additionalProperties: false
      description: |
        Immutable audit record of the offer set displayed to a customer for one
        (mapping, jurisdiction) pair. `filteredState` always equals the response's
        `propertyState`.
      required:
        - id
        - organizationMappingId
        - environment
        - channel
        - categoryId
        - filteredState
        - quotedAmountCents
        - snapshotHash
        - observedAt
        - expiresAt
        - offers
      properties:
        id: { type: string, format: uuid }
        organizationMappingId: { type: string, format: uuid }
        environment: { type: string, enum: [sandbox, production] }
        channel: { type: string }
        categoryId: { type: string }
        filteredState: { type: string, pattern: '^[A-Z]{2}$' }
        quotedAmountCents: { type: integer, minimum: 0, nullable: true }
        snapshotHash: { type: string, pattern: '^[a-f0-9]{64}$' }
        observedAt: { type: string, format: date-time }
        expiresAt: { type: string, format: date-time, nullable: true }
        offers:
          type: array
          maxItems: 100
          items: { $ref: '#/components/schemas/GoodLeapOffer' }

    GoodLeapPreflightIssue:
      type: object
      additionalProperties: false
      required: [code, message, owningSurface, href]
      properties:
        code:
          type: string
          description: |
            Machine code the UI renders, e.g. `missing_property_state`,
            `missing_applicant_email`, `applicant_not_on_customer`,
            `state_not_licensed`, `mapping_branch_mismatch`,
            `missing_organization_mapping`, `stale_offer_snapshot`.
        message: { type: string }
        owningSurface:
          type: string
          enum: [project, lead, estimate, customer, connection, mapping, property_address, offer_snapshot]
        href: { type: string, nullable: true }

    GoodLeapPreflightResponse:
      type: object
      additionalProperties: false
      required:
        - projectId
        - leadId
        - ready
        - issues
        - organizationMappingId
        - propertyState
        - offerSnapshotId
        - offerSnapshotExpiresAt
      properties:
        projectId: { type: string, format: uuid, nullable: true }
        leadId: { type: string, format: uuid, nullable: true }
        ready: { type: boolean }
        issues:
          type: array
          items: { $ref: '#/components/schemas/GoodLeapPreflightIssue' }
        organizationMappingId: { type: string, format: uuid, nullable: true }
        propertyState: { type: string, pattern: '^[A-Z]{2}$', nullable: true }
        offerSnapshotId: { type: string, format: uuid, nullable: true }
        offerSnapshotExpiresAt: { type: string, format: date-time, nullable: true }

    GoodLeapCreditDisclosurePreview:
      type: object
      additionalProperties: false
      description: Current renderable disclosure text. Never includes the provider consent token.
      required: [disclosureId, name, sections, contentSha256]
      properties:
        disclosureId: { type: string, minLength: 1, maxLength: 200 }
        name: { type: string, minLength: 1, maxLength: 200, nullable: true }
        contentSha256: { type: string, pattern: '^[a-f0-9]{64}$' }
        sections:
          type: array
          minItems: 1
          items:
            type: object
            additionalProperties: false
            required: [text, sort, boldText, checkbox, signatureBox, componentName]
            properties:
              text: { type: string, minLength: 1, maxLength: 100000 }
              sort: { type: number, nullable: true }
              boldText: { type: boolean }
              checkbox: { type: boolean }
              signatureBox: { type: boolean }
              componentName: { type: string, minLength: 1, maxLength: 200, nullable: true }

    GoodLeapIntent:
      type: object
      additionalProperties: false
      required: [id, caseId, operation, status, idempotencyKey, requestHash, providerRequestId, httpStatus, errorCode, createdAt, updatedAt]
      properties:
        id: { type: string, format: uuid }
        caseId: { type: string, format: uuid, nullable: true }
        operation: { type: string, enum: [refresh_offers, create_share_link, resend_share_link, reconcile_case, submit_milestone, execute_lifecycle_command] }
        status: { type: string, enum: [pending, leased, succeeded, unknown, retryable_failed, terminal_failed, manual_review, cancelled] }
        idempotencyKey: { type: string, minLength: 1, maxLength: 200 }
        requestHash: { type: string, pattern: '^[a-f0-9]{64}$' }
        providerRequestId: { type: string, minLength: 1, maxLength: 200, nullable: true }
        httpStatus: { type: integer, minimum: 100, maximum: 599, nullable: true }
        errorCode: { type: string, minLength: 1, maxLength: 200, nullable: true }
        createdAt: { type: string, format: date-time }
        updatedAt: { type: string, format: date-time }

    GoodLeapSubmitMilestoneInput:
      type: object
      additionalProperties: false
      required: [idempotencyKey, milestone, completedAt]
      properties:
        idempotencyKey: { type: string, format: uuid }
        milestone: { type: string, enum: [INSTALL_COMPLETE, PTO_COMPLETE] }
        completedAt: { type: string, format: date-time }

    GoodLeapSubmitMilestoneResponse:
      type: object
      additionalProperties: false
      required: [intent]
      properties:
        intent: { $ref: '#/components/schemas/GoodLeapIntent' }

    GoodLeapLoanLifecycleProjection:
      type: object
      additionalProperties: false
      required: [remoteLoanId, loanStatusRaw, offerId, amountCents, providerChannel, providerEnrollments, providerEnrollmentsKnown, signedDocumentsAvailable, providerChangeCount, docsSentAt, loanConfirmedAt, canceledAt, observedAt, projectionHash]
      properties:
        remoteLoanId: { type: string, minLength: 1, maxLength: 200 }
        loanStatusRaw: { type: string, minLength: 1, maxLength: 200, nullable: true }
        offerId: { type: string, nullable: true }
        amountCents: { type: integer, minimum: 0, maximum: 3518437208883199, nullable: true }
        providerChannel: { type: string, minLength: 1, maxLength: 128, nullable: true }
        providerEnrollments:
          type: array
          maxItems: 32
          items: { type: string, pattern: '^[A-Z0-9_:-]{1,120}$' }
        providerEnrollmentsKnown: { type: boolean }
        signedDocumentsAvailable:
          type: boolean
          description: True only after the primary applicant and every applicable co-applicant have signed loan documents.
        providerChangeCount: { type: integer, minimum: 0 }
        docsSentAt: { type: string, format: date-time, nullable: true }
        loanConfirmedAt: { type: string, format: date-time, nullable: true }
        canceledAt: { type: string, format: date-time, nullable: true }
        observedAt: { type: string, format: date-time }
        projectionHash: { type: string, pattern: '^[a-f0-9]{64}$' }

    GoodLeapLoanLifecycleConfirmationPredicate:
      oneOf:
        - type: object
          additionalProperties: false
          required: [kind, offerId, amountCents]
          properties:
            kind: { type: string, enum: [offer_amount_and_loan_confirmed] }
            offerId: { type: string }
            amountCents: { type: integer, minimum: 1, maximum: 3518437208883199 }
        - type: object
          additionalProperties: false
          required: [kind]
          properties:
            kind: { type: string, enum: [docs_sent_at_present] }
        - type: object
          additionalProperties: false
          description: Provider accepted a signed-copy resend, but no authoritative GET field distinguishes that resend from the earlier first send.
          required: [kind]
          properties:
            kind: { type: string, enum: [signed_docs_resend_submitted] }
        - type: object
          additionalProperties: false
          required: [kind, offerId, baselineProviderChangeCount]
          properties:
            kind: { type: string, enum: [offer_equal_after_change] }
            offerId: { type: string }
            baselineProviderChangeCount: { type: integer, minimum: 0 }
        - type: object
          additionalProperties: false
          required: [kind, amountCents, baselineProviderChangeCount]
          properties:
            kind: { type: string, enum: [amount_equal_after_change] }
            amountCents: { type: integer, minimum: 1, maximum: 3518437208883199 }
            baselineProviderChangeCount: { type: integer, minimum: 0 }
        - type: object
          additionalProperties: false
          required: [kind, channel, baselineProviderChangeCount]
          properties:
            kind: { type: string, enum: [channel_equal_after_change] }
            channel: { type: string, minLength: 1, maxLength: 128 }
            baselineProviderChangeCount: { type: integer, minimum: 0 }
        - type: object
          additionalProperties: false
          required: [kind, enabled, baselineProviderChangeCount]
          properties:
            kind: { type: string, enum: [autopay_membership_equal_after_change] }
            enabled: { type: boolean }
            baselineProviderChangeCount: { type: integer, minimum: 0 }
        - type: object
          additionalProperties: false
          required: [kind]
          properties:
            kind: { type: string, enum: [canceled_at_present] }

    GoodLeapLoanLifecycleCommand:
      type: object
      additionalProperties: false
      required: [id, caseId, action, status, idempotencyKey, requestHash, preconditionProjectionHash, confirmedProjectionHash, confirmationPredicate, documentDeliveryMode, signingStrategy, providerRequestId, errorCode, claimedAt, submittedAt, confirmedAt, unknownAt, createdAt, updatedAt]
      properties:
        id: { type: string, format: uuid }
        caseId: { type: string, format: uuid }
        action: { type: string, enum: [confirm_loan_details, send_loan_documents, change_loan_offer, change_loan_amount, change_loan_channel, change_loan_autopay, cancel_loan] }
        status: { type: string, enum: [pending, claimed, submitted, confirmed, unknown, terminal_failed, cancelled] }
        idempotencyKey: { type: string, format: uuid }
        requestHash: { type: string, pattern: '^[a-f0-9]{64}$' }
        preconditionProjectionHash: { type: string, pattern: '^[a-f0-9]{64}$' }
        confirmedProjectionHash: { type: string, pattern: '^[a-f0-9]{64}$', nullable: true }
        confirmationPredicate: { $ref: '#/components/schemas/GoodLeapLoanLifecycleConfirmationPredicate' }
        documentDeliveryMode: { type: string, enum: [FIRST_SEND, RESEND_SIGNED_COPIES], nullable: true }
        signingStrategy: { type: string, enum: [REMOTE, EMBEDDED], nullable: true }
        providerRequestId: { type: string, minLength: 1, maxLength: 200, nullable: true }
        errorCode: { type: string, pattern: '^[a-z0-9][a-z0-9_.:-]{0,119}$', nullable: true }
        claimedAt: { type: string, format: date-time, nullable: true }
        submittedAt: { type: string, format: date-time, nullable: true }
        confirmedAt: { type: string, format: date-time, nullable: true }
        unknownAt: { type: string, format: date-time, nullable: true }
        createdAt: { type: string, format: date-time }
        updatedAt: { type: string, format: date-time }

    GoodLeapLoanLifecycleResponse:
      type: object
      additionalProperties: false
      required: [projection, commands]
      properties:
        projection:
          nullable: true
          allOf: [{ $ref: '#/components/schemas/GoodLeapLoanLifecycleProjection' }]
        commands:
          type: array
          maxItems: 100
          items: { $ref: '#/components/schemas/GoodLeapLoanLifecycleCommand' }

    GoodLeapEmbeddedSigningRequest:
      type: object
      additionalProperties: false
      properties:
        documentRole:
          type: string
          enum: [Borrower, CoBorrower]
          description: Omit to use GoodLeap's documented Borrower default.

    GoodLeapEmbeddedSigningResponse:
      type: object
      additionalProperties: false
      required: [url, expiresAt]
      properties:
        url:
          type: string
          format: uri
          description: Short-lived one-time signing capability; never persisted or logged.
        expiresAt: { type: string, format: date-time }

    GoodLeapCreateLoanLifecycleCommand:
      oneOf:
        - type: object
          additionalProperties: false
          required: [action, idempotencyKey, expectedProjectionHash, offerId, amountCents]
          properties:
            action: { type: string, enum: [confirm_loan_details] }
            idempotencyKey: { type: string, format: uuid }
            expectedProjectionHash: { type: string, pattern: '^[a-f0-9]{64}$' }
            offerId: { type: string }
            amountCents: { type: integer, minimum: 1, maximum: 3518437208883199 }
        - type: object
          additionalProperties: false
          description: FIRST_SEND supports REMOTE or EMBEDDED. RESEND_SIGNED_COPIES is REMOTE-only and remains an honest submitted receipt after provider 204 because no GET readback field distinguishes the resend.
          required: [action, idempotencyKey, expectedProjectionHash, documentDeliveryMode, signingStrategy, documentsAcknowledged]
          properties:
            action: { type: string, enum: [send_loan_documents] }
            idempotencyKey: { type: string, format: uuid }
            expectedProjectionHash: { type: string, pattern: '^[a-f0-9]{64}$' }
            documentDeliveryMode: { type: string, enum: [FIRST_SEND, RESEND_SIGNED_COPIES] }
            signingStrategy: { type: string, enum: [REMOTE, EMBEDDED] }
            documentsAcknowledged: { type: boolean, enum: [true] }
        - type: object
          additionalProperties: false
          required: [action, idempotencyKey, expectedProjectionHash, offerId, baselineProviderChangeCount]
          properties:
            action: { type: string, enum: [change_loan_offer] }
            idempotencyKey: { type: string, format: uuid }
            expectedProjectionHash: { type: string, pattern: '^[a-f0-9]{64}$' }
            offerId: { type: string }
            baselineProviderChangeCount: { type: integer, minimum: 0 }
        - type: object
          additionalProperties: false
          required: [action, idempotencyKey, expectedProjectionHash, amountCents, baselineProviderChangeCount]
          properties:
            action: { type: string, enum: [change_loan_amount] }
            idempotencyKey: { type: string, format: uuid }
            expectedProjectionHash: { type: string, pattern: '^[a-f0-9]{64}$' }
            amountCents: { type: integer, minimum: 1, maximum: 3518437208883199 }
            baselineProviderChangeCount: { type: integer, minimum: 0 }
        - type: object
          additionalProperties: false
          required: [action, idempotencyKey, expectedProjectionHash, channel, baselineProviderChangeCount]
          properties:
            action: { type: string, enum: [change_loan_channel] }
            idempotencyKey: { type: string, format: uuid }
            expectedProjectionHash: { type: string, pattern: '^[a-f0-9]{64}$' }
            channel: { type: string, minLength: 1, maxLength: 128 }
            baselineProviderChangeCount: { type: integer, minimum: 0 }
        - type: object
          additionalProperties: false
          required: [action, idempotencyKey, expectedProjectionHash, enabled, baselineProviderChangeCount]
          properties:
            action: { type: string, enum: [change_loan_autopay] }
            idempotencyKey: { type: string, format: uuid }
            expectedProjectionHash: { type: string, pattern: '^[a-f0-9]{64}$' }
            enabled: { type: boolean }
            baselineProviderChangeCount: { type: integer, minimum: 0 }
        - type: object
          additionalProperties: false
          required: [action, idempotencyKey, expectedProjectionHash, cancellationAcknowledged]
          properties:
            action: { type: string, enum: [cancel_loan] }
            idempotencyKey: { type: string, format: uuid }
            expectedProjectionHash: { type: string, pattern: '^[a-f0-9]{64}$' }
            cancellationAcknowledged: { type: boolean, enum: [true] }

    GoodLeapLoanStipulationsResponse:
      type: object
      additionalProperties: false
      required: [items, lastSyncedAt]
      properties:
        lastSyncedAt: { type: string, format: date-time, nullable: true }
        items:
          type: array
          maxItems: 200
          items:
            type: object
            additionalProperties: false
            required: [id, caseId, providerStipulationId, statusRaw, status, typeRaw, type, appliesToRaw, appliesTo, domainRaw, domain, deferred, clearingDocuments, attachments, observedAt]
            properties:
              id: { type: string, format: uuid }
              caseId: { type: string, format: uuid }
              providerStipulationId: { type: string, nullable: true }
              statusRaw: { type: string, nullable: true }
              status: { type: string, enum: [APPROVED, DOCUMENTS_RECEIVED, REJECTED, CREATED], nullable: true }
              typeRaw: { type: string, nullable: true }
              type: { type: string, enum: [ID_VALIDATION, MORTGAGE_PAYMENT_VERIFICATION, INCOME_VERIFICATION], nullable: true }
              appliesToRaw: { type: string, nullable: true }
              appliesTo: { type: string, enum: [BORROWER, CO_BORROWER], nullable: true }
              domainRaw: { type: string, nullable: true }
              domain: { type: string, enum: [CONSUMER], nullable: true }
              deferred: { type: boolean, nullable: true }
              clearingDocuments:
                type: array
                maxItems: 100
                items:
                  type: object
                  additionalProperties: false
                  required: [typeRaw, type]
                  properties:
                    typeRaw: { type: string, nullable: true }
                    type: { type: string, nullable: true }
              attachments:
                type: array
                maxItems: 100
                items:
                  type: object
                  additionalProperties: false
                  required: [extensionRaw, extension, typeRaw, type, statusRaw]
                  properties:
                    extensionRaw: { type: string, nullable: true }
                    extension: { type: string, enum: [JPG, JPEG, PNG, PDF, UNKNOWN], nullable: true }
                    typeRaw: { type: string, nullable: true }
                    type: { type: string, nullable: true }
                    statusRaw: { type: string, nullable: true }
              observedAt: { type: string, format: date-time }

    GoodLeapChangeOrderOptionsResponse:
      type: object
      additionalProperties: false
      required: [observedAt, hicThreshold, channels, products]
      properties:
        observedAt: { type: string, format: date-time }
        hicThreshold:
          type: object
          additionalProperties: false
          required: [requiresHic, thresholdValue]
          properties:
            requiresHic: { type: boolean, nullable: true }
            thresholdValue: { type: number, nullable: true }
        channels:
          type: array
          maxItems: 200
          items:
            type: object
            additionalProperties: false
            required: [name, states]
            properties:
              name: { type: string, minLength: 1, maxLength: 128 }
              states:
                type: array
                maxItems: 60
                items: { type: string, enum: [AK, AL, AR, AZ, CA, CO, CT, DC, DE, FL, GA, HI, IA, ID, IL, IN, KS, KY, LA, MA, MD, ME, MI, MISSING, MN, MO, MS, MT, NC, ND, NE, NH, NJ, NM, NV, NY, OH, OK, OR, PA, PR, RI, SC, SD, TN, TX, UT, VA, VT, WA, WI, WV, WY] }
        products:
          type: array
          maxItems: 500
          items:
            type: object
            additionalProperties: false
            required: [id, code, categoryId, name, assumedPaydownMonth, assumedPaydownPercentage, offers]
            properties:
              id: { type: string, nullable: true }
              code: { type: string, nullable: true }
              categoryId: { type: string, nullable: true }
              name: { type: string, nullable: true }
              assumedPaydownMonth: { type: number, nullable: true }
              assumedPaydownPercentage: { type: number, nullable: true }
              offers:
                type: array
                maxItems: 500
                items:
                  type: object
                  additionalProperties: false
                  required: [id, name, term, rate, rateMinimum, rateMaximum, productId, promotions]
                  properties:
                    id: { type: string, nullable: true }
                    name: { type: string, nullable: true }
                    term: { type: number, nullable: true }
                    rate: { type: number, nullable: true }
                    rateMinimum: { type: number, nullable: true }
                    rateMaximum: { type: number, nullable: true }
                    productId: { type: string, nullable: true }
                    promotions:
                      type: array
                      maxItems: 100
                      items:
                        type: object
                        additionalProperties: false
                        required: [promotionId, name, rate, rateMinimum, rateMaximum]
                        properties:
                          promotionId: { type: string, nullable: true }
                          name: { type: string, nullable: true }
                          rate: { type: number, nullable: true }
                          rateMinimum: { type: number, nullable: true }
                          rateMaximum: { type: number, nullable: true }

    GoodLeapApplicationAddress:
      type: object
      additionalProperties: false
      required: [street, city, state, zip]
      properties:
        street: { type: string, minLength: 1, maxLength: 200 }
        street2: { type: string, minLength: 1, maxLength: 200 }
        city: { type: string, minLength: 1, maxLength: 100 }
        state: { type: string, pattern: '^[A-Z]{2}$' }
        zip: { type: string, pattern: '^\d{5}(-\d{4})?$' }

    GoodLeapSubmitApplicationInput:
      type: object
      additionalProperties: false
      required: [idempotencyKey, acceptedDisclosure, applicant, subjectPropertyAddress, isMobileOrManufacturedHome, applicantSignature]
      properties:
        idempotencyKey: { type: string, format: uuid }
        acceptedDisclosure:
          type: object
          additionalProperties: false
          required: [disclosureId, contentSha256, acknowledged]
          properties:
            disclosureId: { type: string, minLength: 1, maxLength: 200 }
            contentSha256: { type: string, pattern: '^[a-f0-9]{64}$' }
            acknowledged: { type: boolean, enum: [true] }
        applicant:
          type: object
          additionalProperties: false
          required: [firstName, lastName, dob, ssn, annualIncomeCents, email, primaryPhoneNumber, electronicConsent, homeOccupancy, homeOwnership, address, employmentStatus, citizenshipStatus, spokenLanguage]
          properties:
            firstName: { type: string, minLength: 1, maxLength: 100 }
            lastName: { type: string, minLength: 1, maxLength: 100 }
            dob: { type: string, pattern: '^\d{4}-\d{2}-\d{2}$' }
            ssn: { type: string, pattern: '^(\d{4}|\d{9})$' }
            annualIncomeCents: { type: integer, minimum: 1, maximum: 10000000000 }
            email: { type: string, format: email, maxLength: 320 }
            primaryPhoneNumber: { type: string, minLength: 1, maxLength: 20 }
            primaryPhoneType: { type: string, enum: [MOBILE, HOME, WORK] }
            electronicConsent: { type: boolean, enum: [true] }
            homeOccupancy: { type: string, enum: [PRIMARY, SECONDARY, INVESTMENT, OTHER] }
            homeOwnership: { type: string, enum: [NOT_OWNED, OWNED_WITH_MORTGAGE, OWNED_FREE_AND_CLEAR] }
            address: { $ref: '#/components/schemas/GoodLeapApplicationAddress' }
            employmentStatus: { type: string, enum: [EMPLOYED, RETIRED, NOT_EMPLOYED, OTHER] }
            citizenshipStatus: { type: string, enum: [US_CITIZEN, LAWFUL_PERMANENT_RESIDENT_ALIEN, OTHER] }
            spokenLanguage: { type: string, enum: [ENGLISH, SPANISH] }
            employer: { type: string, minLength: 1, maxLength: 200 }
            occupation: { type: string, minLength: 1, maxLength: 200 }
            employmentDuration: { type: integer, minimum: 0, maximum: 1200 }
        subjectPropertyAddress: { $ref: '#/components/schemas/GoodLeapApplicationAddress' }
        isMobileOrManufacturedHome:
          type: boolean
          description: Applicant-confirmed classification of the financed property required by GoodLeap.
        mortgageTotalBalancesCents:
          type: integer
          minimum: 1
          maximum: 3518437208883199
        mortgageTotalPaymentsCents:
          type: integer
          minimum: 1
          maximum: 3518437208883199
        applicantSignature:
          type: string
          maxLength: 2000000
          pattern: '^data:image/(png|jpeg|jpg);base64,[A-Za-z0-9+/=]+$'
          description: Ephemeral data-image signature; never stored or returned.
        amountCents: { type: integer, minimum: 1, maximum: 3518437208883199 }

    GoodLeapSubmitApplicationResponse:
      type: object
      additionalProperties: false
      required: [caseId, loanId, status, referenceNumber, approvedAmountCents, maxAmountCents, stipulationCount, pendingCaseCount]
      properties:
        caseId: { type: string, format: uuid }
        loanId: { type: string, minLength: 1, maxLength: 200 }
        status: { type: string, minLength: 1, maxLength: 200, nullable: true }
        referenceNumber: { type: string, minLength: 1, maxLength: 200, nullable: true }
        approvedAmountCents: { type: integer, nullable: true }
        maxAmountCents: { type: integer, nullable: true }
        stipulationCount: { type: integer, minimum: 0 }
        pendingCaseCount: { type: integer, minimum: 0 }

    PalmettoConnectionHealth:
      type: object
      additionalProperties: false
      required:
        - environment
        - environmentProvisioned
        - connectionEnabled
        - connectionStatus
        - tenantCredentialConfigured
        - tenantCredentialValid
        - rootOrganizationVisible
        - webhookConfigurationVerified
        - webhookSubscriptionActive
        - lastHealthCheckAt
        - lastDeliveryAt
        - lastErrorCode
        - mappings
        - capabilities
      properties:
        environment: { type: string, enum: [next, production] }
        connectionEnabled: { type: boolean }
        connectionStatus: { type: string, enum: [connected, disabled, error, not_connected] }
        environmentProvisioned: { type: boolean }
        tenantCredentialConfigured: { type: boolean }
        tenantCredentialValid: { type: boolean }
        rootOrganizationVisible: { type: boolean }
        webhookConfigurationVerified: { type: boolean }
        webhookSubscriptionActive: { type: boolean }
        lastHealthCheckAt: { type: string, format: date-time, nullable: true }
        lastDeliveryAt: { type: string, format: date-time, nullable: true }
        lastErrorCode: { type: string, nullable: true }
        mappings:
          type: array
          items: { $ref: '#/components/schemas/PalmettoOrganizationMapping' }
        mappingScopeBindings:
          type: array
          items: { $ref: '#/components/schemas/PalmettoMappingScopeBinding' }
        capabilities:
          type: object
          additionalProperties: false
          required: [account, design, pricing, quote, hostedApplication, contract, documents, install, funding]
          properties:
            account: { type: boolean }
            design: { type: boolean }
            pricing: { type: boolean }
            quote: { type: boolean }
            hostedApplication: { type: boolean }
            contract: { type: boolean, enum: [false] }
            documents: { type: boolean, enum: [true] }
            install: { type: boolean, enum: [false] }
            funding: { type: boolean, enum: [false] }
    PalmettoProviderStatus:
      type: object
      additionalProperties: false
      required: [raw, known]
      properties:
        raw: { type: string, minLength: 1, maxLength: 200 }
        known: { type: boolean }
    PalmettoCursorPage:
      type: object
      additionalProperties: false
      required: [nextCursor, hasMore, limit]
      properties:
        nextCursor: { type: string, nullable: true, maxLength: 500 }
        hasMore: { type: boolean }
        limit: { type: integer, minimum: 1, maximum: 100 }
        total: { type: integer, minimum: 0 }
    PalmettoCaseListItem:
      type: object
      additionalProperties: false
      required:
        - id
        - leadId
        - projectId
        - customerId
        - customerDisplayName
        - projectReference
        - displayBucket
        - syncStatus
        - origin
        - accountStatus
        - applicationStatus
        - creditApplicationAttemptState
        - totalFinancedAmountCents
        - attentionCodes
        - assignedUserId
        - lastSuccessfulSyncAt
        - createdAt
        - updatedAt
      properties:
        id: { type: string, format: uuid }
        leadId: { type: string, format: uuid, nullable: true }
        projectId: { type: string, format: uuid, nullable: true }
        customerId: { type: string, format: uuid, nullable: true }
        customerDisplayName: { type: string, minLength: 1, maxLength: 200 }
        projectReference: { type: string, minLength: 1, maxLength: 200, nullable: true }
        displayBucket: { type: string, enum: [application, contract, install, funded] }
        syncStatus: { type: string, enum: [current, dirty, reconciling, unconfirmed, error, needs_review] }
        origin:
          type: string
          enum: [portrex, orphaned, external]
          description: Where the provider account was created. `external` was created in Palmetto and adopted; `orphaned` was minted by Portrex but its original local case row is missing.
        accountStatus: { $ref: '#/components/schemas/PalmettoProviderStatus', nullable: true }
        applicationStatus: { $ref: '#/components/schemas/PalmettoProviderStatus', nullable: true }
        creditApplicationAttemptState:
          type: string
          enum: [started, retryable, succeeded, unknown]
          nullable: true
        totalFinancedAmountCents: { type: integer, minimum: 0, nullable: true }
        attentionCodes:
          type: array
          maxItems: 32
          items:
            type: string
            enum:
              - stipulations_required
              - confirmation_pending
              - sync_unconfirmed
              - unmapped_provider_status
              - unsupported_provider_state
              - provider_degraded
              - mapping_error
              - multiple_application_candidates
              - manual_review
        assignedUserId: { type: string, format: uuid, nullable: true }
        lastSuccessfulSyncAt: { type: string, format: date-time, nullable: true }
        createdAt: { type: string, format: date-time }
        updatedAt: { type: string, format: date-time }
    PalmettoCaseListResponse:
      type: object
      additionalProperties: false
      required: [items, page]
      properties:
        items:
          type: array
          maxItems: 100
          items: { $ref: '#/components/schemas/PalmettoCaseListItem' }
        page: { $ref: '#/components/schemas/PalmettoCursorPage' }
    PalmettoPreflightIssue:
      type: object
      additionalProperties: false
      required: [code, message, owningSurface, href]
      properties:
        code: { type: string, minLength: 1, maxLength: 200 }
        message: { type: string, minLength: 1, maxLength: 500 }
        owningSurface:
          type: string
          enum:
            - project_hvac
            - estimate
            - connection
            - mapping
            - license
            - equipment_catalog
            - synthetic_fixture
            - lead
            - customer
            - property
            - showroom
        href: { type: string, minLength: 1, maxLength: 500, nullable: true }
    PalmettoPreflightResponse:
      type: object
      additionalProperties: false
      required:
        - projectId
        - leadId
        - ready
        - issues
        - organizationMappingId
        - finalHvacDesignId
        - finalHvacDesignRevision
      properties:
        projectId: { type: string, format: uuid, nullable: true }
        leadId: { type: string, format: uuid, nullable: true }
        ready: { type: boolean }
        issues:
          type: array
          maxItems: 50
          items: { $ref: '#/components/schemas/PalmettoPreflightIssue' }
        organizationMappingId: { type: string, format: uuid, nullable: true }
        finalHvacDesignId: { type: string, format: uuid, nullable: true }
        finalHvacDesignRevision: { type: integer, minimum: 1, nullable: true }
    PalmettoShowroomSourceCorrection:
      type: object
      additionalProperties: false
      required: [applicant, property]
      properties:
        applicant:
          type: object
          additionalProperties: false
          required: [firstName, lastName, email, phone, address]
          properties:
            firstName: { type: string, minLength: 1, maxLength: 100 }
            lastName: { type: string, minLength: 1, maxLength: 100 }
            email: { type: string, format: email, maxLength: 320 }
            phone: { type: string, minLength: 7, maxLength: 32 }
            address:
              type: object
              additionalProperties: false
              required: [address1, address2, city, state, zip]
              properties:
                address1: { type: string, minLength: 1, maxLength: 200 }
                address2: { type: string, maxLength: 200, nullable: true }
                city: { type: string, minLength: 1, maxLength: 100 }
                state: { type: string, minLength: 2, maxLength: 2 }
                zip: { type: string, minLength: 3, maxLength: 20 }
        property:
          type: object
          additionalProperties: false
          required: [homeSizeSqFt, conditionedAreaSqFt, existingSystems, systemsBeingInstalled]
          properties:
            homeSizeSqFt: { type: integer, minimum: 1, maximum: 1000000 }
            conditionedAreaSqFt: { type: integer, minimum: 1, maximum: 1000000 }
            existingSystems: { type: integer, minimum: 0, maximum: 100 }
            systemsBeingInstalled: { type: integer, minimum: 1, maximum: 100 }
    PalmettoDocumentFile:
      type: object
      additionalProperties: false
      required: [id, attachmentId, ordinal, originalFilename, contentType, sizeBytes, transferStatus, lastErrorCode]
      properties:
        id: { type: string, format: uuid }
        attachmentId: { type: string, format: uuid }
        ordinal: { type: integer, minimum: 0, maximum: 24 }
        originalFilename: { type: string, minLength: 1, maxLength: 255 }
        contentType: { type: string, enum: [application/pdf, image/jpeg, image/png] }
        sizeBytes: { type: integer, minimum: 1, maximum: 52428800 }
        transferStatus: { type: string, enum: [pending, uploading, confirmed, unknown, terminal_failed] }
        lastErrorCode: { type: string, nullable: true, maxLength: 200 }
    PalmettoDocumentSubmission:
      type: object
      additionalProperties: false
      required: [id, caseId, type, grouped, externalReference, status, fileCount, remoteJobId, lastErrorCode, createdAt, updatedAt]
      properties:
        id: { type: string, format: uuid }
        caseId: { type: string, format: uuid }
        type: { type: string, minLength: 1, maxLength: 200 }
        grouped: { type: boolean }
        externalReference: { type: string, pattern: '^ptx-pal-d-[0-9a-f-]{36}$' }
        status: { type: string, enum: [pending, uploading, confirmed, unknown, terminal_failed, needs_review, cancelled] }
        fileCount: { type: integer, minimum: 1, maximum: 25 }
        remoteJobId: { type: string, nullable: true, maxLength: 200 }
        lastErrorCode: { type: string, nullable: true, maxLength: 200 }
        createdAt: { type: string, format: date-time }
        updatedAt: { type: string, format: date-time }
    PalmettoCaseDocument:
      type: object
      additionalProperties: false
      required: [id, caseId, submissionId, remoteDocumentId, status, archived, type, externalReference, rejectionReasons, rowVersion, files, observedAt, createdAt, updatedAt]
      properties:
        id: { type: string, format: uuid }
        caseId: { type: string, format: uuid }
        submissionId: { type: string, format: uuid, nullable: true }
        remoteDocumentId: { type: string, minLength: 1, maxLength: 200 }
        status: { type: string, enum: [pending, approved, rejected] }
        archived: { type: boolean }
        type: { type: string, minLength: 1, maxLength: 200 }
        externalReference: { type: string, nullable: true, maxLength: 200 }
        rejectionReasons:
          type: array
          maxItems: 21
          items: { type: string, minLength: 1, maxLength: 200 }
        rowVersion: { type: integer, minimum: 1, maximum: 2147483647 }
        files:
          type: array
          maxItems: 25
          items: { $ref: '#/components/schemas/PalmettoDocumentFile' }
        observedAt: { type: string, format: date-time }
        createdAt: { type: string, format: date-time }
        updatedAt: { type: string, format: date-time }
    PalmettoDocumentListResponse:
      type: object
      additionalProperties: false
      required: [items, submissions]
      properties:
        items:
          type: array
          maxItems: 500
          items: { $ref: '#/components/schemas/PalmettoCaseDocument' }
        submissions:
          type: array
          maxItems: 500
          items: { $ref: '#/components/schemas/PalmettoDocumentSubmission' }
    HvacFinalDesignUpsert:
      type: object
      additionalProperties: false
      required: [estimateId, systems]
      properties:
        estimateId: { type: string, format: uuid }
        systems:
          type: array
          minItems: 1
          maxItems: 20
          items:
            type: object
            additionalProperties: false
            required: [systemCategory, conditionedAreaSqft, components]
            properties:
              systemCategory: { type: string }
              name: { type: string, nullable: true }
              conditionedAreaSqft: { type: number, exclusiveMinimum: 0 }
              ahriNumber: { type: string, nullable: true }
              components:
                type: array
                minItems: 1
                items:
                  type: object
                  additionalProperties: false
                  required: [groupType, componentType, name, quantity]
                  properties:
                    groupType: { type: string, enum: [equipment, accessory, site_prep, discount] }
                    componentType: { type: string }
                    localCatalogProductId: { type: string, format: uuid, nullable: true }
                    sku: { type: string, nullable: true }
                    name: { type: string }
                    manufacturer: { type: string }
                    model: { type: string }
                    quantity: { type: number, exclusiveMinimum: 0 }
                    sizeValue: { type: string, nullable: true }
                    sizeUnit: { type: string, nullable: true }
                    efficiencyValue: { type: string, nullable: true }
                    efficiencyUnit: { type: string, nullable: true }
                    unitCostCents: { type: integer, nullable: true }
                    totalCostCents: { type: integer, nullable: true }
    HvacRebateProgramSettingsItem:
      type: object
      required:
        - id
        - program_external_id
        - state
        - name
        - pathway
        - stackable
        - is_hear
        - source_status
        - enabled
        - amount
        - eligibility
        - effective_from
        - effective_to
        - source_url
        - source_label
        - last_verified_on
        - version
        - created_at
        - updated_at
        - updated_by
      properties:
        id: { type: [string, 'null'], format: uuid }
        program_external_id: { type: string }
        state: { type: string, minLength: 2, maxLength: 2 }
        name: { type: string }
        pathway:
          type: [string, 'null']
          enum: [mid_stream, point_of_sale, instant_invoice, downstream, null]
        stackable: { type: [boolean, 'null'] }
        is_hear: { type: boolean }
        source_status:
          type: string
          enum: [active, live, unpublished, not_launched, not_deployed]
        enabled: { type: boolean }
        amount:
          type: object
          description: Canonical discriminated amount specification; money fields are source dollars.
          required: [type]
          additionalProperties: true
        eligibility:
          type: [object, 'null']
          additionalProperties: true
        effective_from: { type: [string, 'null'], format: date }
        effective_to: { type: [string, 'null'], format: date }
        source_url: { type: [string, 'null'], format: uri, pattern: '^https://' }
        source_label: { type: [string, 'null'] }
        last_verified_on: { type: [string, 'null'], format: date }
        admin_notes:
          type: [string, 'null']
          description: Present only when the caller may manage pricebooks.
        version:
          type: integer
          minimum: 0
          description: 0 means the untouched curated program; tenant versions begin at 1.
        created_at: { type: [string, 'null'], format: date-time }
        updated_at: { type: [string, 'null'], format: date-time }
        updated_by: { type: [string, 'null'], format: uuid }

    HvacRebateProgramSettingsPatch:
      type: object
      additionalProperties: false
      required: [expected_version]
      properties:
        expected_version: { type: integer, minimum: 0 }
        enabled: { type: boolean }
        name: { type: string, minLength: 1, maxLength: 240 }
        amount: { type: object, additionalProperties: true }
        eligibility: { type: [object, 'null'], additionalProperties: true }
        effective_from: { type: [string, 'null'], format: date }
        effective_to: { type: [string, 'null'], format: date }
        source_url: { type: [string, 'null'], format: uri, pattern: '^https://' }
        source_label: { type: [string, 'null'], maxLength: 240 }
        last_verified_on: { type: [string, 'null'], format: date }
        admin_notes: { type: [string, 'null'], maxLength: 2000 }

    HvacRebateProgramVersionConflict:
      type: object
      required: [error, current]
      properties:
        error: { type: string, enum: [rebate_program_version_conflict] }
        current: { $ref: '#/components/schemas/HvacRebateProgramSettingsItem' }

    HvacCatalogFee:
      type: object
      additionalProperties: false
      required: [label, amount_cents]
      properties:
        label: { type: string, minLength: 1, maxLength: 60 }
        amount_cents: { type: integer, minimum: 0 }

    HvacCatalogRow:
      type: object
      additionalProperties: false
      description: >
        One size (BTU; tons are derived) in one table. A null price means not set, never zero.
        The override is a signed adjustment to SRP, as override_percent or override_amount_cents
        (at most one; never 0; both null = no override). Customer price is srp_cents plus
        override_amount_cents, or srp_cents plus round(srp_cents * override_percent / 100) with
        ties away from zero. No SRP means no customer price. Writes may omit both override fields (null).
      required: [btu, srp_cents]
      properties:
        part:
          type: string
          enum: [system, indoor, outdoor]
          default: system
        btu: { type: integer, minimum: 1000, maximum: 1000000 }
        install_cents:
          type: [integer, 'null']
          minimum: 0
          description: >
            Our install cost. Absent from every response except for an account-level Owner or Admin holding
            pricebook:cost:read (POR-2457; the Sub-Account Admin, the CFO and every other seat read the baseline instead).
            In a PUT body an absent value keeps the stored install price.
        baseline_cents:
          type: [integer, 'null']
          minimum: 1
          description: >
            The rep baseline. Required in a PUT body. Returned by GET /v1/hvac-price-catalog to every seat that reads
            the catalog, with or without pricebook:cost:read.
        srp_cents: { type: [integer, 'null'], minimum: 1 }
        override_percent:
          type: [number, 'null']
          exclusiveMinimum: -100
          maximum: 1000
          description: Signed percent adjustment to SRP, at most 2 decimals, never 0.
        override_amount_cents:
          type: [integer, 'null']
          description: Signed dollar adjustment to SRP in cents, never 0.
        my_override_percent:
          type: [number, 'null']
          exclusiveMinimum: -100
          maximum: 1000
          readOnly: true
          description: >
            Response only, and only for a price-only seat (pricebook:prices:write without pricebooks:write):
            the caller's OWN personal override on this size. Never accepted in a PUT body.
        my_override_amount_cents:
          type: [integer, 'null']
          readOnly: true
          description: Response only, for a price-only seat. The caller's own personal dollar override.
        my_override_inactive:
          type: boolean
          readOnly: true
          description: >
            Response only, price-only seat: true when the caller's saved personal override does not apply to
            a quote right now (no SRP, a customer price at or below $0, or below the rep baseline), so
            quotes use the company price for this size.
        sub_price_cents:
          type: [integer, 'null']
          minimum: 1
          readOnly: true
          description: >
            POR-2497, response only, a seat that does not edit the structure: the branch price of this size as ONE absolute
            number (the branch percent is already included; a legacy percent or amount override is converted for display).
            The Sub-Account Admin gets it whether or not it applies (null when none). Every other seat gets it only while it
            applies. Never accepted in a PUT body.
        sub_price_inactive:
          type: boolean
          readOnly: true
          description: >
            POR-2497, response only, same seats: true when the branch price is saved but prices nothing right now (below the
            COMPANY baseline), so quotes use the next layer. Another seat gets no figure with it.
        sub_customer_price_cents:
          type: [integer, 'null']
          minimum: 1
          readOnly: true
          description: >
            POR-2497 (R12), response only: the Customer price of this size, the reps' STARTING QUOTE and the basis of their own
            overrides (the branch percent is already included). sub_price_cents is then the Company price, the reps' floor
            only. A rep gets each figure only while it applies and, for a rep, srp_cents is the Customer price while it
            applies, else the SRP raised by the percent. The Sub-Account Admin gets what it typed (null when none).
        sub_customer_price_inactive:
          type: boolean
          readOnly: true
          description: >
            POR-2497 (R12), response only: the Customer price is saved but prices nothing right now (under the company
            baseline or under the floor). A rep gets no figure with it.
        sub_price_legacy:
          type: boolean
          readOnly: true
          description: >
            POR-2497 (R12), response only: the size was saved in the legacy relative form (before POR-2497); sub_price_cents is
            then its converted price, both the starting quote and the floor.
        branch_default_customer_cents:
          type: [integer, 'null']
          minimum: 1
          readOnly: true
          description: >
            POR-2497 (R12), response only, the Sub-Account Admin: the default Customer price (no typed Customer price): the SRP
            raised by the branch percent with the company layers. The placeholder of the Customer price field.
        branch_default_cents:
          type: [integer, 'null']
          minimum: 1
          readOnly: true
          description: >
            POR-2497, response only, the Sub-Account Admin of its own sub-account (can_edit_sub_account): the default Company
            price of this size when no branch price is typed, that is the company baseline raised by the branch percent and
            never below the baseline. Null when the size has no baseline.
        company_baseline_cents:
          type: [integer, 'null']
          minimum: 1
          readOnly: true
          description: >
            POR-2458, response only, the Sub-Account Admin of its own sub-account (can_edit_sub_account): the raw COMPANY rep
            baseline. For a seat that does not edit the structure, baseline_cents is its Company price (POR-2497): the
            enforced floor with the branch percent included, that is the branch price while it applies, else the default.
            A seat other than the Sub-Account Admin also gets srp_cents already raised by its percent. Never the Install price.
        effective: { $ref: '#/components/schemas/HvacCatalogEffective' }

    HvacCatalogEffective:
      type: object
      additionalProperties: false
      required: [override_percent, override_amount_cents, source, customer_cents]
      readOnly: true
      description: >
        A22: response only. The override that actually prices this size for the reading seat, and the customer
        price it gives. Per size the first layer that applies wins: rep size override (rep_size), the rep's
        default percent (rep_default), the sub-account (branch) size override (sub_account_size), the company size
        override (company_size), the company default percent (company_default), plain SRP (none). A price-only
        seat sees its own layers; any other seat sees the
        company layers. A default applies only where the price stays above $0 and at or above the rep baseline;
        a default that was considered and did not apply is listed in default_skipped.
      properties:
        override_percent: { type: [number, 'null'], exclusiveMinimum: -100, maximum: 1000 }
        override_amount_cents: { type: [integer, 'null'] }
        source: { type: string, enum: [rep_size, rep_default, sub_account_size, company_size, company_default, none] }
        customer_cents: { type: [integer, 'null'], description: "SRP plus the effective override; null without an SRP. On the reading seat's quote basis: the SRP is raised by the seat's branch percent first, then the override applies, and the price is never under the seat's sub-account price." }
        default_skipped:
          type: array
          description: Defaults that were considered for this size and did not apply, in precedence order. Omitted when empty.
          items:
            type: object
            additionalProperties: false
            required: [layer, reason]
            properties:
              layer: { type: string, enum: [rep_default, company_default] }
              reason: { type: string, enum: [no_srp, not_positive, below_baseline] }

    HvacCatalogDefaults:
      type: object
      additionalProperties: false
      required: [company, mine]
      description: >
        A22: the default override percents the reading seat can see. company = the company default (every seat that
        reads the catalog sees the percent, never who set it); mine = the reader's own default, always null for a
        seat with pricebooks:write (it sets only the company default).
      properties:
        company: { type: [number, 'null'], exclusiveMinimum: -100, maximum: 1000 }
        mine: { type: [number, 'null'], exclusiveMinimum: -100, maximum: 1000 }

    HvacCatalogDefaultOverridePut:
      type: object
      additionalProperties: false
      required: [override_percent]
      description: >
        A22: one signed percent adjustment to the SRP of every size that has no size override of its own. At most 2
        decimals, above -100, at most 1000, never 0. null clears the default.
      properties:
        override_percent:
          type: [number, 'null']
          exclusiveMinimum: -100
          maximum: 1000

    HvacCatalogDefaultOverrideResponse:
      type: object
      additionalProperties: false
      required: [scope, override_percent]
      properties:
        scope: { type: string, enum: [mine, company] }
        override_percent: { type: [number, 'null'], description: 'The percent now stored; null = cleared.' }

    HvacCatalogDefaultEntry:
      type: object
      additionalProperties: false
      required: [scope, owner, percent, set_by, updated_at]
      description: >-
        A22: one stored default override percent (structure seats only). owner null = the company default.
      properties:
        scope: { type: string, enum: [company, rep] }
        owner:
          oneOf:
            - { $ref: '#/components/schemas/HvacCatalogPerson' }
            - { type: 'null' }
        percent: { type: number }
        set_by:
          oneOf:
            - { $ref: '#/components/schemas/HvacCatalogPerson' }
            - { type: 'null' }
        updated_at: { type: [string, 'null'], format: date-time }

    HvacCatalogTable:
      type: object
      additionalProperties: false
      required: [id, state, fees, rows, version]
      properties:
        id: { type: string, format: uuid }
        state:
          type: [string, 'null']
          minLength: 2
          maxLength: 2
          description: Null is the All states base table.
        fees:
          type: array
          maxItems: 8
          items: { $ref: '#/components/schemas/HvacCatalogFee' }
        rows:
          type: array
          maxItems: 40
          items: { $ref: '#/components/schemas/HvacCatalogRow' }
        version: { type: integer, minimum: 1 }
        personal_override_count:
          type: integer
          minimum: 0
          readOnly: true
          description: >
            Response only, structure seats (pricebooks:write): how many personal rep overrides sit on this
            table's open sizes. A number only; never who or what.
        sub_account_override_count:
          type: integer
          minimum: 0
          readOnly: true
          description: >
            POR-2458, response only, structure seats (pricebooks:write): how many sub-account (branch) overrides, over every
            branch, sit on this table's open sizes. A number only; the list is GET /hvac-price-catalog/overrides.

    HvacCatalogLine:
      type: object
      additionalProperties: false
      required: [id, brand, install_type, zone_type, name, series_aliases, sort_order, tables]
      properties:
        id: { type: string, format: uuid }
        brand: { type: string, minLength: 1, maxLength: 80 }
        install_type: { type: string, enum: [ducted, ductless] }
        zone_type: { type: [string, 'null'], enum: [single, multi, single_multi, null] }
        name: { type: [string, 'null'], minLength: 1, maxLength: 120, description: Null is an unnamed line (name needed). }
        series_aliases:
          type: array
          maxItems: 10
          items: { type: string, minLength: 1, maxLength: 120 }
          description: >-
            Showroom series, besides the name, whose systems use this line's prices (exact match after
            folding case and punctuation).
        sort_order: { type: integer }
        additional_zone:
          oneOf:
            - $ref: '#/components/schemas/HvacCatalogAdditionalZone'
            - type: 'null'
          description: >-
            A20: the Additional zone price of a ducted, single-zone line (null for every other line). Charged for
            each system after the largest on the line in one quote.
        tables:
          type: array
          minItems: 1
          description: The All states base table first, then state overrides A-Z. Customer tables only.
          items: { $ref: '#/components/schemas/HvacCatalogTable' }
        installer_tables:
          type: array
          description: >-
            A21: installer install-cost tables, ordered by installer name then state. Cost data: present only for a seat
            holding pricebook:cost:read; the key is absent (not empty) for every other seat. Never part of `tables`.
          items: { $ref: '#/components/schemas/HvacCatalogInstallerTable' }

    HvacCatalogInstallerTable:
      type: object
      additionalProperties: false
      required: [id, state, contractor_id, contractor_name, rows, version]
      description: >-
        A21: one installer's install cost for a product line in ONE state. Install cost only: the customer price is the
        same whoever installs. Never "All states", never fees.
      properties:
        id: { type: string, format: uuid }
        state: { type: string, minLength: 2, maxLength: 2 }
        contractor_id: { type: string, format: uuid }
        contractor_name: { type: string }
        rows:
          type: array
          maxItems: 40
          items: { $ref: '#/components/schemas/HvacCatalogInstallerRow' }
        version: { type: integer, minimum: 1 }

    HvacCatalogInstallerRow:
      type: object
      additionalProperties: false
      required: [part, btu, install_cents]
      properties:
        part: { type: string, enum: [system, indoor, outdoor] }
        btu: { type: integer, minimum: 1000, maximum: 1000000 }
        install_cents: { type: integer, minimum: 0, description: 0 is a valid cost. }

    HvacCatalogInstaller:
      type: object
      additionalProperties: false
      required: [id, name]
      description: A live (not deleted, not archived) contractor a cost table can be created for.
      properties:
        id: { type: string, format: uuid }
        name: { type: string }

    HvacCatalogInstallerTableCreate:
      type: object
      additionalProperties: false
      required: [contractor_id, states, start_from]
      properties:
        contractor_id: { type: string, format: uuid }
        states:
          type: array
          minItems: 1
          maxItems: 51
          uniqueItems: true
          items: { type: string, minLength: 2, maxLength: 2 }
        start_from:
          oneOf:
            - { type: string, enum: [blank] }
            - type: object
              additionalProperties: false
              required: [table_id]
              properties:
                table_id: { type: string, format: uuid }
          description: Copy install cost (only) from a table of this line, or start empty.

    HvacCatalogInstallerTablePut:
      type: object
      additionalProperties: false
      required: [rows, expected_version]
      description: >-
        PUT body for an installer table: install cost only. A customer body (fees, srp, baseline, override) is a 400.
        A size left out has no cost for this installer.
      properties:
        rows:
          type: array
          maxItems: 40
          items: { $ref: '#/components/schemas/HvacCatalogInstallerRow' }
        expected_version: { type: integer, minimum: 1 }

    HvacCatalogInstallerTableResponse:
      type: object
      additionalProperties: false
      required: [table]
      properties:
        table: { $ref: '#/components/schemas/HvacCatalogInstallerTable' }

    HvacCatalogAdditionalZone:
      type: object
      additionalProperties: false
      required: [effective_cents]
      properties:
        effective_cents:
          type: [integer, 'null']
          minimum: 1
          description: >-
            What a quote charges for each additional system on the line: the stored value, else the default
            (the install price of the line's largest size). Null when the line has neither.
        explicit_cents:
          type: [integer, 'null']
          minimum: 1
          description: >-
            The stored value; null means the default is in use. Sent only to a seat holding
            pricebook:cost:read (while the default is in use, it is an install price).

    HvacCatalogPricingLine:
      type: object
      additionalProperties: false
      required: [id, brand, install_type, zone_type, name, series_aliases, tables]
      description: A catalog line as the showroom prices from it. Customer cents only.
      properties:
        id: { type: string, format: uuid }
        brand: { type: string }
        install_type: { type: string, enum: [ducted, ductless] }
        zone_type: { type: [string, 'null'], enum: [single, multi, single_multi, null] }
        name: { type: [string, 'null'] }
        series_aliases: { type: array, items: { type: string } }
        additional_zone_cents:
          type: integer
          minimum: 1
          description: >-
            A20: the effective Additional zone price of a ducted, single-zone line that has one. A number only; it never
            says whether it is the default. Omitted otherwise.
        tables:
          type: array
          items:
            type: object
            additionalProperties: false
            required: [id, state, fees, rows]
            properties:
              id: { type: string, format: uuid }
              state: { type: [string, 'null'], description: Null is the All states table. }
              fees:
                type: array
                items:
                  type: object
                  additionalProperties: false
                  required: [label, amount_cents]
                  properties:
                    label: { type: string }
                    amount_cents: { type: integer, minimum: 0 }
              rows:
                type: array
                items:
                  type: object
                  additionalProperties: false
                  required: [part, btu, customer_cents]
                  properties:
                    part: { type: string, enum: [system, indoor, outdoor] }
                    btu: { type: integer }
                    customer_cents: { type: [integer, 'null'] }
                    install_set: { type: boolean, enum: [true], description: Present when the row has an Install Price; the amount never reaches the browser. }

    HvacCatalogResponse:
      type: object
      additionalProperties: false
      required: [lines, brands, can_see_cost, can_edit_structure, can_edit_prices]
      properties:
        lines:
          type: array
          items: { $ref: '#/components/schemas/HvacCatalogLine' }
        brands:
          type: array
          items: { type: string }
        installers:
          type: array
          description: >-
            A21: live contractors a cost table can be created for. Present only for a seat holding
            pricebook:cost:read.
          items: { $ref: '#/components/schemas/HvacCatalogInstaller' }
        defaults: { $ref: '#/components/schemas/HvacCatalogDefaults' }
        can_see_cost: { type: boolean }
        can_edit_structure: { type: boolean }
        can_edit_prices: { type: boolean }
        can_see_install_price:
          type: boolean
          description: >-
            True when the seat reads install_cents, that is, is an account-level Owner or Admin holding pricebook:cost:read (the CFO is excluded,
            POR-2457). Absent on a response from before A24; read a missing key as false.
        can_edit_sub_account:
          type: boolean
          description: >-
            POR-2458: the seat is the Sub-Account Admin of its OWN sub-account (role sub_account_admin, a sub-account on the
            session and scope hvac_catalog:sub_account_override:write), so it may set the branch price with
            PUT /hvac-price-catalog/sub-account-overrides/tables/{tableId}. Absent on a response from before POR-2458.
        sub_account:
          type: object
          additionalProperties: false
          required: [id, name]
          description: >-
            POR-2458: the seat's own sub-account, for a seat with a sub-account that does not edit the structure.
            unsigned_agreement_count is present only with can_edit_sub_account: an UPPER BOUND on the HVAC agreements of this
            sub-account (draft, sent or partially signed, not deleted) whose saved price may differ after a branch price
            change; the UI says "up to N".
          properties:
            id: { type: string, format: uuid }
            name: { type: string }
            unsigned_agreement_count: { type: integer, minimum: 0 }
        price_adjustment:
          type: object
          additionalProperties: false
          required: [percent, source, branch_name]
          description: >-
            The viewer's effective company/branch price adjustment (POR-2411): the seat's branch percent when
            the branch sets one, else the company default. A branch customer price is the SRP raised by this
            percent, then the row's override. POR-2497: absent for a seat that does not edit the structure and is not the
            Sub-Account Admin (a rep): its rows are already on that basis.
          properties:
            percent: { type: number, minimum: 0, maximum: 100 }
            source: { type: string, enum: [company, branch] }
            branch_name: { type: string, nullable: true }

    HvacCatalogRowWrite:
      type: object
      description: >
        A size row in a table PUT body. Same fields as HvacCatalogRow, and baseline_cents is
        required here.
      allOf:
        - $ref: '#/components/schemas/HvacCatalogRow'
        - type: object
          required: [baseline_cents]

    HvacCatalogTablePut:
      type: object
      additionalProperties: false
      required: [rows, fees, expected_version]
      properties:
        rows:
          type: array
          maxItems: 40
          items: { $ref: '#/components/schemas/HvacCatalogRowWrite' }
        fees:
          type: array
          maxItems: 8
          items: { $ref: '#/components/schemas/HvacCatalogFee' }
        expected_version: { type: integer, minimum: 1 }

    HvacCatalogSubAccountPricesPut:
      type: object
      additionalProperties: false
      required: [rows]
      description: >
        POR-2497 (R12). The Sub-Account Admin's two absolute branch prices per size, each already including the branch
        percent: price_cents the Company price (the reps' floor) and customer_price_cents the Customer price (their starting
        quote and the basis of their own overrides). Both keys are required; null clears that value, and a row with both null
        removes the size's branch override. Unlisted sizes are unchanged. There is no percent, amount, SRP, baseline, install
        or version field.
      properties:
        rows:
          type: array
          maxItems: 40
          items:
            type: object
            additionalProperties: false
            required: [part, btu, price_cents, customer_price_cents]
            properties:
              part: { type: string, enum: [system, indoor, outdoor] }
              btu: { type: integer, minimum: 1000, maximum: 1000000 }
              price_cents: { type: [integer, 'null'], minimum: 1 }
              customer_price_cents: { type: [integer, 'null'], minimum: 1 }

    HvacCatalogPricesPut:
      type: object
      additionalProperties: false
      required: [rows]
      description: >
        The caller's PERSONAL overrides (A17 B2). Each listed size sets (override_percent or
        override_amount_cents, never both) or clears (both null) the caller's override; unlisted sizes are
        unchanged. There is no SRP, baseline, install or version field.
      properties:
        rows:
          type: array
          maxItems: 40
          items:
            type: object
            additionalProperties: false
            required: [part, btu]
            properties:
              part: { type: string, enum: [system, indoor, outdoor] }
              btu: { type: integer, minimum: 1000, maximum: 1000000 }
              override_percent:
                type: [number, 'null']
                exclusiveMinimum: -100
                maximum: 1000
              override_amount_cents: { type: [integer, 'null'] }

    HvacCatalogPerson:
      type: object
      additionalProperties: false
      required: [id, name]
      properties:
        id: { type: string, format: uuid }
        name: { type: string }
        email: { type: string }
        role: { type: string, description: Membership role key, for example sales_rep. }

    HvacCatalogOverrideFields:
      type: object
      additionalProperties: false
      required: [percent, amount_cents]
      properties:
        percent: { type: [number, 'null'] }
        amount_cents: { type: [integer, 'null'] }

    HvacCatalogBranchOverrideFields:
      type: object
      additionalProperties: false
      required: [percent, amount_cents]
      description: >
        POR-2497: a sub-account (branch) size. price_cents is the ABSOLUTE branch price (the branch percent is already
        included); the key is present only on that form. A row written before POR-2497 has a percent or an amount.
      properties:
        percent: { type: [number, 'null'] }
        amount_cents: { type: [integer, 'null'] }
        price_cents: { type: [integer, 'null'], minimum: 1 }
        customer_price_cents: { type: [integer, 'null'], minimum: 1, description: The Customer price (the reps' starting quote); price_cents is then the Company price (the floor). }

    HvacCatalogOverrideEntry:
      type: object
      additionalProperties: false
      required: [kind, owner, set_by, line, table, row, account_override, personal, customer_cents, company_customer_cents, rep_earns_cents, active, updated_at]
      description: >
        One open override. kind company = the table's own override (prices everyone, owner null); kind personal =
        a rep's override (prices only quotes whose rep is owner). set_by.user is null with source null when the
        override was set before tracking began; source import = a workbook import. A price-only seat gets
        personal entries of its own only, with no baseline_cents or install_cents on the row, and set_by.by_admin
        true (user null) when an admin set it.
      properties:
        kind: { type: string, enum: [company, personal] }
        owner:
          oneOf:
            - { $ref: '#/components/schemas/HvacCatalogPerson' }
            - { type: 'null' }
        set_by:
          type: object
          additionalProperties: false
          required: [user, source, at]
          properties:
            user:
              oneOf:
                - { $ref: '#/components/schemas/HvacCatalogPerson' }
                - { type: 'null' }
            source: { type: [string, 'null'], enum: [user, import, null] }
            at: { type: [string, 'null'], format: date-time }
            by_admin: { type: boolean }
        line:
          type: object
          additionalProperties: false
          required: [id, brand, install_type, zone_type, name]
          properties:
            id: { type: string, format: uuid }
            brand: { type: string }
            install_type: { type: string, enum: [ducted, ductless] }
            zone_type: { type: [string, 'null'], enum: [single, multi, single_multi, null] }
            name: { type: [string, 'null'] }
        table:
          type: object
          additionalProperties: false
          required: [id, state]
          properties:
            id: { type: string, format: uuid }
            state: { type: [string, 'null'], description: null = All states }
        row:
          type: object
          additionalProperties: false
          required: [part, btu, srp_cents]
          properties:
            part: { type: string, enum: [system, indoor, outdoor] }
            btu: { type: integer }
            srp_cents: { type: [integer, 'null'] }
            baseline_cents: { type: [integer, 'null'] }
            install_cents: { type: [integer, 'null'] }
        account_override: { $ref: '#/components/schemas/HvacCatalogOverrideFields' }
        personal:
          oneOf:
            - { $ref: '#/components/schemas/HvacCatalogOverrideFields' }
            - { type: 'null' }
        customer_cents: { type: [integer, 'null'] }
        company_customer_cents: { type: [integer, 'null'], description: 'The customer price with the company size override only. Kept for one release; read fallback_customer_cents.' }
        fallback_customer_cents:
          type: [integer, 'null']
          description: >
            A22: the customer price that applies when this entry's own size override is removed: the OWNER's default
            percent, else the company size override, else the company default percent, else SRP (a default only where
            it applies). For a company entry, the company layers.
        rep_earns_cents: { type: [integer, 'null'] }
        active: { type: boolean }
        updated_at: { type: [string, 'null'], format: date-time }

    HvacCatalogOverridesResponse:
      type: object
      additionalProperties: false
      required: [overrides, users]
      properties:
        overrides:
          type: array
          items: { $ref: '#/components/schemas/HvacCatalogOverrideEntry' }
        users:
          type: array
          items:
            type: object
            additionalProperties: false
            required: [user, company_count, personal_count, inactive_count, last_updated_at]
            properties:
              user: { $ref: '#/components/schemas/HvacCatalogPerson' }
              company_count: { type: integer }
              personal_count: { type: integer }
              inactive_count: { type: integer }
              last_updated_at: { type: [string, 'null'], format: date-time }
        defaults:
          type: array
          description: >
            A22: every stored default override percent (the company's first, then each rep's). Present only for a seat
            with pricebooks:write; a price-only seat reads its own and the company percent from GET /hvac-price-catalog.
          items: { $ref: '#/components/schemas/HvacCatalogDefaultEntry' }
        sub_account_overrides:
          type: array
          description: >
            POR-2458: the sub-account (branch) size overrides, read-only here. A seat with pricebooks:write (owner, admin)
            gets every branch's; the Sub-Account Admin gets its OWN sub-account's (from the session); any other seat does
            not get the key. No baseline or install figure.
          items: { $ref: '#/components/schemas/HvacCatalogSubAccountOverrideEntry' }

    HvacCatalogSubAccountOverrideEntry:
      type: object
      additionalProperties: false
      required: [sub_account, set_by, line, table, row, override, customer_cents, active, updated_at]
      description: >
        One open sub-account (branch) size override. active is false when it is saved but does not price a quote (no SRP,
        a price at or below $0, or below the company baseline).
      properties:
        sub_account:
          type: object
          additionalProperties: false
          required: [id, name]
          properties:
            id: { type: string, format: uuid }
            name: { type: string }
        set_by:
          type: object
          additionalProperties: false
          required: [user, at]
          properties:
            user:
              oneOf:
                - { $ref: '#/components/schemas/HvacCatalogPerson' }
                - { type: 'null' }
            at: { type: [string, 'null'], format: date-time }
        line:
          type: object
          additionalProperties: false
          required: [id, brand, install_type, zone_type, name]
          properties:
            id: { type: string, format: uuid }
            brand: { type: string }
            install_type: { type: string, enum: [ducted, ductless] }
            zone_type: { type: [string, 'null'], enum: [single, multi, single_multi, null] }
            name: { type: [string, 'null'] }
        table:
          type: object
          additionalProperties: false
          required: [id, state]
          properties:
            id: { type: string, format: uuid }
            state: { type: [string, 'null'], description: null = All states }
        row:
          type: object
          additionalProperties: false
          required: [part, btu, srp_cents]
          properties:
            part: { type: string, enum: [system, indoor, outdoor] }
            btu: { type: integer }
            srp_cents: { type: [integer, 'null'] }
        override: { $ref: '#/components/schemas/HvacCatalogBranchOverrideFields' }
        customer_cents: { type: [integer, 'null'], description: "The price this branch's reps start a quote from (no rep layer), by the quote rules at the branch percent: the company layers, then the branch value. A Company price above the company price lifts it (the floor). Null without an SRP." }
        catalog_cents: { type: [integer, 'null'], description: "The same starting price without this branch value (what a reset gives the branch). Null without an SRP." }
        active: { type: boolean, description: True when the Company price or the Customer price (or the legacy size) prices a quote right now. }
        price_inactive: { type: boolean, enum: [true], description: A typed Company price that prices nothing right now (POR-2497). }
        customer_price_inactive: { type: boolean, enum: [true], description: A typed Customer price that prices nothing right now (below the baseline or the floor). }
        updated_at: { type: [string, 'null'], format: date-time }

    HvacCatalogSubAccountOverridesResetResponse:
      type: object
      additionalProperties: false
      required: [reset]
      properties:
        reset: { type: integer, minimum: 0, description: How many of the caller's sub-account overrides were removed. }

    HvacCatalogRepOverridesPutResponse:
      type: object
      additionalProperties: false
      required: [user, overrides]
      properties:
        user: { $ref: '#/components/schemas/HvacCatalogPerson' }
        overrides:
          type: array
          items: { $ref: '#/components/schemas/HvacCatalogOverrideEntry' }

    HvacCatalogOverrideHistoryResponse:
      type: object
      additionalProperties: false
      required: [changes]
      properties:
        default_changes:
          type: array
          maxItems: 200
          description: >
            A22: changes of default override percents, newest first. A seat with pricebooks:write sees every one
            (rep defaults and the company default, and the clear done by a reset-all of a rep). Any other seat sees only
            changes of ITS OWN default, never a company default change, with no actor for a change someone else made.
          items:
            type: object
            additionalProperties: false
            required: [at, actor, scope, owner, before, after]
            properties:
              at: { type: string, format: date-time }
              actor:
                oneOf:
                  - { $ref: '#/components/schemas/HvacCatalogPerson' }
                  - { type: 'null' }
              scope: { type: string, enum: [company, rep] }
              owner:
                oneOf:
                  - { $ref: '#/components/schemas/HvacCatalogPerson' }
                  - { type: 'null' }
              before: { type: [number, 'null'] }
              after: { type: [number, 'null'] }
        sub_account_changes:
          type: array
          maxItems: 200
          description: >
            POR-2458: changes of sub-account (branch) size overrides, newest first, same split as sub_account_overrides in
            GET /hvac-price-catalog/overrides (every branch for a seat with pricebooks:write, the Sub-Account Admin's own
            otherwise). actor is the real actor, also when an owner or admin acted as the Sub-Account Admin.
          items:
            type: object
            additionalProperties: false
            required: [at, actor, sub_account, brand, line_name, state, part, btu, before, after]
            properties:
              at: { type: string, format: date-time }
              actor:
                oneOf:
                  - { $ref: '#/components/schemas/HvacCatalogPerson' }
                  - { type: 'null' }
              sub_account:
                oneOf:
                  - type: object
                    additionalProperties: false
                    required: [id, name]
                    properties:
                      id: { type: string, format: uuid }
                      name: { type: string }
                  - { type: 'null' }
              brand: { type: [string, 'null'] }
              line_name: { type: [string, 'null'] }
              state: { type: [string, 'null'] }
              part: { type: string, enum: [system, indoor, outdoor] }
              btu: { type: integer }
              before: { $ref: '#/components/schemas/HvacCatalogBranchOverrideFields' }
              after: { $ref: '#/components/schemas/HvacCatalogBranchOverrideFields' }
        changes:
          type: array
          maxItems: 200
          items:
            type: object
            additionalProperties: false
            required: [at, actor, kind, owner, brand, line_name, state, part, btu, before, after]
            properties:
              at: { type: string, format: date-time }
              actor:
                oneOf:
                  - { $ref: '#/components/schemas/HvacCatalogPerson' }
                  - { type: 'null' }
              kind: { type: string, enum: [company, personal] }
              owner:
                oneOf:
                  - { $ref: '#/components/schemas/HvacCatalogPerson' }
                  - { type: 'null' }
              brand: { type: [string, 'null'] }
              line_name: { type: [string, 'null'] }
              state: { type: [string, 'null'] }
              part: { type: string, enum: [system, indoor, outdoor] }
              btu: { type: integer }
              before: { $ref: '#/components/schemas/HvacCatalogOverrideFields' }
              after: { $ref: '#/components/schemas/HvacCatalogOverrideFields' }

    HvacCatalogTableResponse:
      type: object
      additionalProperties: false
      required: [table]
      properties:
        table: { $ref: '#/components/schemas/HvacCatalogTable' }

    HvacCatalogLineResponse:
      type: object
      additionalProperties: false
      required: [line]
      properties:
        line: { $ref: '#/components/schemas/HvacCatalogLine' }

    HvacCatalogLineCreate:
      type: object
      additionalProperties: false
      required: [brand, install_type, zone_type, name]
      properties:
        brand: { type: string, minLength: 1, maxLength: 80 }
        install_type: { type: string, enum: [ducted, ductless] }
        zone_type: { type: [string, 'null'], enum: [single, multi, single_multi, null] }
        name:
          type: [string, 'null']
          minLength: 1
          maxLength: 120
          description: May not equal (folded) a series alias of another line of the same brand and system type (400 hvac_alias_taken).

    HvacCatalogLinePatch:
      type: object
      additionalProperties: false
      properties:
        name:
          type: [string, 'null']
          minLength: 1
          maxLength: 120
          description: May not equal (folded) a series alias of another line of the same brand and system type (400 hvac_alias_taken).
        zone_type: { type: [string, 'null'], enum: [single, multi, single_multi, null] }
        series_aliases:
          type: array
          maxItems: 10
          items: { type: string, minLength: 1, maxLength: 120 }
          description: >-
            Replaces the line's aliases. Trimmed, no two equal after folding. An alias may not equal the
            name or an alias of another line of the same brand and system type (400 hvac_alias_taken).
        additional_zone_cents:
          type: [integer, 'null']
          minimum: 1
          maximum: 10000000000
          description: >-
            A20: the Additional zone price in cents; null puts the line back on the default. Setting a value on a
            ductless or multi-zone line is 400 hvac_additional_zone_ducted_only.

    HvacCatalogLineDuplicate:
      type: object
      additionalProperties: false
      required: [name]
      properties:
        name: { type: string, minLength: 1, maxLength: 120 }

    HvacCatalogBrandRename:
      type: object
      additionalProperties: false
      required: [brand]
      properties:
        brand: { type: string, minLength: 1, maxLength: 80 }

    HvacCatalogOverrideCreate:
      type: object
      additionalProperties: false
      required: [states, start_from, fees]
      properties:
        states:
          type: array
          minItems: 1
          maxItems: 51
          uniqueItems: true
          items: { type: string, minLength: 2, maxLength: 2 }
        start_from:
          oneOf:
            - { type: string, enum: [base, blank] }
            - type: object
              additionalProperties: false
              required: [table_id]
              properties:
                table_id: { type: string, format: uuid }
        fees:
          type: array
          maxItems: 8
          items: { $ref: '#/components/schemas/HvacCatalogFee' }

    HvacCatalogError:
      type: object
      required: [error]
      properties:
        error:
          type: string
          enum:
            - validation_error
            - hvac_table_version_conflict
            - hvac_price_rows_mismatch
            - hvac_line_name_taken
            - hvac_state_table_exists
            - hvac_base_table_required
            - hvac_brand_name_taken
            - hvac_alias_taken
            - hvac_additional_zone_ducted_only
            - hvac_installer_table_exists
            - hvac_installer_unknown
            - hvac_price_field_forbidden
            - hvac_copy_source_invalid
            - hvac_rep_not_found
            - hvac_rep_not_price_only
            - hvac_price_below_minimum
            - not_found
            - pricebook_write_in_progress
        message: { type: string }
        current_version: { type: integer, description: Present on hvac_table_version_conflict. }
        states:
          type: array
          items: { type: string }
          description: Present on hvac_state_table_exists and hvac_installer_table_exists.
        issues: { type: array, items: { type: object, additionalProperties: true } }

    HvacIncomeScreeningResponse:
      type: object
      required: [snapshot_id, state, bands, updated_at]
      properties:
        snapshot_id: { type: string }
        state: { type: string, minLength: 2, maxLength: 2 }
        updated_at: { type: string, format: date-time }
        bands:
          type: array
          items:
            type: object
            required: [id, label, basis, verified_pct, criteria, program_ids]
            properties:
              id: { type: string }
              label: { type: string }
              basis: { type: [string, 'null'], enum: [AMI, SMI, null] }
              verified_pct: { type: [number, 'null'] }
              criteria:
                type: array
                items:
                  type: object
                  required: [basis, min_pct, max_pct, exclusive]
                  properties:
                    basis: { type: string, enum: [AMI, SMI] }
                    min_pct: { type: [number, 'null'] }
                    max_pct: { type: [number, 'null'] }
                    exclusive:
                      type: boolean
                      description: True when the official threshold is strictly above/below.
              program_ids: { type: array, items: { type: string } }

    Error:
      type: object
      required: [error, message, request_id]
      properties:
        error:
          type: string
          description: |
            Machine-readable error code. Notable codes:
            - `idempotency_key_required` — mutating request without Idempotency-Key (including Lead/Customer collaborator DELETE)
            - `idempotency_key_invalid` — header empty or > 64 chars
            - `OFFSET_FORBIDDEN` — caller used `?offset=`; switch to cursor pagination
            - `scope_cap_exceeded` — too many scopes for the Account tier
            - `sensitive_scope_forbidden` — sensitive scope assigned to API key
            - `invalid_scope` / `invalid_grant` / `invalid_client` — OAuth errors
        message: { type: string }
        request_id: { type: string }
        documentation_url: { type: string }
        tier_caps:
          type: object
          description: Returned with scope_cap_exceeded.
          properties:
            standard: { type: integer }
            pro: { type: integer }
            enterprise: { type: integer }

    ReleaseEnvironmentStamp:
      type: object
      description: Build stamp scraped from an environment's public /auth/login page.
      required: [version, release_sha, url]
      properties:
        version: { type: string, nullable: true }
        release_sha: { type: string, nullable: true }
        url: { type: string }

    ImageUploadRequest:
      type: object
      required: [purpose, data_base64]
      additionalProperties: false
      properties:
        purpose:
          type: string
          enum: [account_logo, account_login_background, sub_account_logo, profile_avatar, pricebook_item, showroom_financing_logo]
        file_name:
          type: string
          maxLength: 240
        mime_type:
          type: string
          enum: [image/png, image/jpeg, image/webp]
        data_base64:
          type: string
          description: Base64-encoded PNG, JPG, or WebP image bytes. Maximum decoded size is 2 MB.
        sub_account_id:
          type: [string, 'null']
          format: uuid

    ImageUploadResponse:
      type: object
      required: [key, url, mime_type, size_bytes]
      properties:
        key: { type: string }
        url: { type: string, format: uri }
        mime_type: { type: string, enum: [image/png, image/jpeg, image/webp] }
        size_bytes: { type: integer, minimum: 1, maximum: 2097152 }

    PublicAccountBranding:
      type: object
      required: [matched]
      properties:
        matched: { type: boolean }
        name: { type: string }
        subdomain: { type: [string, 'null'] }
        branding:
          type: object
          additionalProperties: false
          properties:
            logo_url: { type: string }
            primary_color: { type: string, pattern: '^#[0-9A-Fa-f]{6}$' }
            login_background_url: { type: string }
            custom_login_domain: { type: string }

    PaginatedResponse:
      type: object
      required: [data, next_cursor]
      properties:
        data: { type: array, items: {} }
        next_cursor: { type: string, nullable: true }
        # Perf wave 1 (API-4): populated on first-page requests only; cursor
        # continuations return null and clients keep the total they have.
        total: { type: integer, nullable: true }

    Customer:
      type: object
      required: [id]
      additionalProperties: true
      properties:
        id: { type: string, format: uuid }
        account_id: { type: string, format: uuid }
        sub_account_id: { type: string, format: uuid, nullable: true }
        customer_type: { type: string, enum: [residential, commercial] }
        display_name: { type: string }
        service_status: { type: string, enum: [active, inactive, never], nullable: true }
        do_not_service: { type: boolean }
        lead_source: { type: string, nullable: true }
        city: { type: string, nullable: true, description: 'List only: city of the primary-first customer address, or the latest linked lead address when no customer address exists.' }
        state: { type: string, nullable: true, description: 'List only: state of the same selected address as city.' }
        lifetime_value_cents: { type: integer, nullable: true }
        outstanding_balance_cents: { type: integer, nullable: true }
        created_at: { type: string, format: date-time }

    CustomerPage:
      type: object
      required: [data, next_cursor]
      properties:
        data:
          type: array
          items: { $ref: '#/components/schemas/Customer' }
        next_cursor: { type: string, nullable: true }
        # Perf wave 1 (API-4): populated on first-page requests only; cursor
        # continuations return null and clients keep the total they have.
        total: { type: integer, nullable: true }

    AgreementRegisterRow:
      type: object
      description: |
        One agreement in the central register: a signed/in-flight contract or
        an unsigned showroom lead draft (POR-1585). Cost-safe: total_amount_cents
        is the SELL amount. signed_at is the primary attended-signature timestamp.
      required: [id, project_id, customer_id, customer_display_name, property_address, status, signed_at, total_amount_cents, created_at]
      properties:
        id: { type: string, format: uuid }
        project_id:
          type: string
          format: uuid
          nullable: true
          description: Project workspace for a contract. Null on unsigned showroom drafts.
        lead_id:
          type: string
          format: uuid
          nullable: true
          description: Originating lead ID.
        source:
          type: string
          enum: [contract, lead_draft]
          description: contract rows open /agreements/{id}; lead_draft rows open the lead desk.
        customer_id:
          type: string
          format: uuid
          nullable: true
          description: Null when the contract's customer cannot be resolved (row still rendered).
        customer_display_name: { type: string, nullable: true }
        sub_account_display_name: { type: string, nullable: true, description: 'Visible branch name, or branch ID when unavailable.' }
        sales_rep_display_name: { type: string, nullable: true, description: 'Visible user name, or abbreviated user ID when unavailable.' }
        appointment_setter_display_name: { type: string, nullable: true, description: 'Visible user name, or abbreviated user ID when unavailable.' }
        property_address: { type: string, nullable: true }
        status:
          type: string
          enum: [draft, sent, partially_signed, fully_signed, void_pending, voided, expired, unsigned]
        signed_at: { type: string, format: date-time, nullable: true }
        total_amount_cents:
          type: integer
          nullable: true
          description: SELL amount in cents. Contracts carry no cost/margin.
        created_at: { type: string, format: date-time }

    AgreementContractSigningProtocol:
      type: string
      enum: [rep_first_v1, legacy]
      description: |
        Persisted contract protocol provenance. Any signing run for the exact
        account and contract means rep_first_v1, including stopped runs or
        invalidated sources. Legacy requires a positive database result that
        no such run exists. A missing or null value from an older transport is
        unknown and must never be interpreted as legacy.

    AgreementDetail:
      type: object
      description: |
        Tenant-safe agreement (contract) detail for the agreement workspace page.
        The contract object nested in estimate agreement detail also returns the
        same authoritative signing_protocol provenance.
      required:
        [id, project_id, customer_id, customer_display_name, property_address, status, signing_mode, signing_protocol, signed_at, total_amount_cents, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        project_id: { type: string, format: uuid }
        estimate_id: { type: string, format: uuid, nullable: true }
        lead_id: { type: string, format: uuid, nullable: true }
        customer_id: { type: string, format: uuid, nullable: true }
        customer_display_name: { type: string, nullable: true }
        property_address: { type: string, nullable: true }
        estimate_number: { type: string, nullable: true }
        status:
          type: string
          enum: [draft, sent, partially_signed, fully_signed, void_pending, voided, expired]
        signing_mode: { type: string, enum: [single, split] }
        signing_protocol: { $ref: '#/components/schemas/AgreementContractSigningProtocol' }
        primary_signer_person_id: { type: string, format: uuid, nullable: true }
        signed_at: { type: string, format: date-time, nullable: true }
        total_amount_cents: { type: integer, nullable: true }
        cpm_installer_status:
          type: string
          nullable: true
          enum: [match, no_licensed_contractor]
          description: |
            POR-1897: the CPM (HVAC) installer status the server resolved when this
            agreement was frozen. `null` for non-CPM / non-HVAC agreements.
            `placeholder` and `no_offer_in_state` refuse at the lock, so they never
            appear here.
        payload:
          type: object
          additionalProperties: true
          description: Cost-safe contract payload (estimate line items, project refs).
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time, nullable: true }
        admin_label:
          type: string
          nullable: true
          description: POR-1972 tenant admin maintenance label. Never part of the legal document.
        admin_notes:
          type: string
          nullable: true
          description: POR-1972 tenant admin maintenance notes. Never part of the legal document.

    AgreementRegisterPage:
      type: object
      required: [data, next_cursor, total]
      properties:
        data:
          type: array
          items: { $ref: '#/components/schemas/AgreementRegisterRow' }
        next_cursor: { type: string, nullable: true }
        total: { type: integer, minimum: 0, description: 'Total matching agreements before cursor pagination.' }

    SubAccount:
      type: object
      additionalProperties: true
      required: [id, account_id, name, status, branding_json, pipeline_config_json, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        account_id: { type: string, format: uuid }
        name: { type: string }
        status: { type: string, enum: [active, suspended, archived] }
        branding_json: { type: object, additionalProperties: true }
        pipeline_config_json: { type: object, additionalProperties: true }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    LeadAssignmentPolicy:
      type: object
      additionalProperties: false
      required: [mode, fixed_user_id]
      properties:
        mode:
          type: string
          enum: [manual, fixed_user, round_robin]
        fixed_user_id:
          type: [string, 'null']
          format: uuid

    LeadAssignmentPolicyInput:
      type: object
      additionalProperties: false
      required: [mode]
      allOf:
        - if:
            required: [mode]
            properties:
              mode: { const: fixed_user }
          then:
            required: [fixed_user_id]
            properties:
              fixed_user_id: { type: string, format: uuid }
      properties:
        mode:
          type: string
          enum: [manual, fixed_user, round_robin]
        fixed_user_id:
          type: [string, 'null']
          format: uuid
          description: Required when mode is fixed_user; ignored and canonicalized to null otherwise.

    LeadAssignmentMemberOption:
      type: object
      additionalProperties: false
      required:
        - user_id
        - name
        - role
        - role_label
        - sub_account_id
        - membership_scope
        - status
      properties:
        user_id: { type: string, format: uuid }
        name: { type: string, minLength: 1 }
        role:
          type: string
          enum:
            - owner
            - admin
            - sub_account_admin
            - sales_manager
            - sales_rep
            - account_manager
            - project_manager
            - architect
            - general_contractor
            - field_rep
            - cfo
            - site_surveyor
            - custom
        role_label: { type: string, minLength: 1 }
        sub_account_id:
          type: [string, 'null']
          format: uuid
        membership_scope:
          type: string
          enum: [account, sub_account]
        status:
          type: string
          enum: [active, suspended]

    LeadAssignmentPolicyResponse:
      type: object
      additionalProperties: false
      required: [policy, candidates]
      properties:
        policy: { $ref: '#/components/schemas/LeadAssignmentPolicy' }
        candidates:
          type: array
          items: { $ref: '#/components/schemas/LeadAssignmentMemberOption' }

    StageProbabilityMap:
      type: object
      description: |
        Win probability per open lead stage id (new, contacted, qualified, appointment_set,
        appointment_held, proposal_sent, agreement_pending, no_show). Fraction 0..1, at most 4 decimals.
        Won and lost stages are fixed and have no entry.
      additionalProperties: { type: number, minimum: 0, maximum: 1 }

    StageProbabilityInput:
      type: object
      additionalProperties: false
      required: [stage_probability]
      properties:
        stage_probability: { $ref: '#/components/schemas/StageProbabilityMap' }

    StageProbabilityResponse:
      type: object
      additionalProperties: false
      required: [stage_probability]
      properties:
        stage_probability: { $ref: '#/components/schemas/StageProbabilityMap' }

    SubAccountLeadAssignmentPolicyResponse:
      type: object
      additionalProperties: false
      required:
        - sub_account_id
        - override_policy
        - effective_policy
        - source
        - override_state
        - override_candidates
        - effective_candidates
      properties:
        sub_account_id: { type: string, format: uuid }
        override_policy:
          oneOf:
            - $ref: '#/components/schemas/LeadAssignmentPolicy'
            - type: 'null'
        effective_policy: { $ref: '#/components/schemas/LeadAssignmentPolicy' }
        source:
          type: string
          enum: [sub_account_override, account_default, implicit_manual]
        override_state:
          type: string
          enum: [inherited, configured, invalid]
        override_candidates:
          type: array
          items: { $ref: '#/components/schemas/LeadAssignmentMemberOption' }
        effective_candidates:
          type: array
          items: { $ref: '#/components/schemas/LeadAssignmentMemberOption' }

    SubAccountSummary:
      allOf:
        - $ref: '#/components/schemas/SubAccount'
        - type: object
          additionalProperties: false
          required:
            - team_count
            - member_count
            - lead_count
            - customer_count
            - project_count
            - invoice_count
            - invoice_open_cents
            - invoice_paid_cents
          properties:
            team_count: { type: integer, minimum: 0 }
            member_count: { type: integer, minimum: 0 }
            lead_count: { type: integer, minimum: 0 }
            customer_count: { type: integer, minimum: 0 }
            project_count: { type: integer, minimum: 0 }
            invoice_count: { type: integer, minimum: 0 }
            invoice_open_cents: { type: integer, minimum: 0 }
            invoice_paid_cents: { type: integer, minimum: 0 }

    SubAccountSummaryTotals:
      type: object
      additionalProperties: false
      required:
        - sub_account_count
        - active_sub_account_count
        - team_count
        - member_count
        - lead_count
        - customer_count
        - project_count
        - invoice_count
        - invoice_open_cents
        - invoice_paid_cents
      properties:
        sub_account_count: { type: integer, minimum: 0 }
        active_sub_account_count: { type: integer, minimum: 0 }
        team_count: { type: integer, minimum: 0 }
        member_count: { type: integer, minimum: 0 }
        lead_count: { type: integer, minimum: 0 }
        customer_count: { type: integer, minimum: 0 }
        project_count: { type: integer, minimum: 0 }
        invoice_count: { type: integer, minimum: 0 }
        invoice_open_cents: { type: integer, minimum: 0 }
        invoice_paid_cents: { type: integer, minimum: 0 }

    SubAccountSummaryResponse:
      type: object
      additionalProperties: false
      required: [data, totals]
      properties:
        data:
          type: array
          items: { $ref: '#/components/schemas/SubAccountSummary' }
        totals: { $ref: '#/components/schemas/SubAccountSummaryTotals' }

    CustomerChildList:
      type: object
      required: [data]
      properties:
        data:
          type: array
          items:
            type: object
            additionalProperties: true
        next_cursor:
          type: string
          nullable: true
          description: Present on high-volume child resources; omitted on bounded people/address lists.

    CustomerPortalInvitation:
      type: object
      required: [invitation_id, customer_person_id, customer_id, expires_at, redemption_window_expires_at, accept_url]
      properties:
        invitation_id: { type: string, format: uuid }
        customer_person_id: { type: string, format: uuid }
        customer_id: { type: string, format: uuid }
        expires_at: { type: string, format: date-time }
        redemption_window_expires_at:
          type: string
          format: date-time
          description: LD-19 consumable redemption window, capped at 15 minutes.
        accept_url:
          type: string
          format: uri
          description: Web-app path-token URL for `/portal/accept/{token}`. Raw token is returned once and never persisted.

    CustomerPortalInvitationResponse:
      type: object
      required: [data]
      properties:
        data: { $ref: '#/components/schemas/CustomerPortalInvitation' }

    # Tenant BYO financing credential lifecycle (palmetto | goodleap | ghl).
    # Safe metadata only — never plaintext secrets or envelope ciphertext.
    IntegrationCredentialField:
      type: object
      additionalProperties: false
      required: [name, label, inputType, required]
      properties:
        name: { type: string }
        label: { type: string }
        help: { type: string }
        inputType: { type: string, enum: [text, password] }
        required: { type: boolean }

    IntegrationCredentialRequirements:
      type: object
      additionalProperties: false
      required: [provider, environments, schemaVersion, fields]
      properties:
        provider: { type: string, enum: [palmetto, goodleap, ghl, docusign, zoho_sign] }
        environments:
          type: array
          items: { type: string, enum: [sandbox, production] }
        schemaVersion: { type: integer, minimum: 1 }
        fields:
          type: array
          items: { $ref: '#/components/schemas/IntegrationCredentialField' }

    IntegrationCredentialGeneration:
      type: object
      additionalProperties: false
      required: [id, generationNumber, status, validatedAt, activatedAt, revokedAt, lastErrorCode, createdAt]
      properties:
        id: { type: string, format: uuid }
        generationNumber: { type: integer, minimum: 1 }
        status: { type: string }
        validatedAt: { type: string, format: date-time, nullable: true }
        activatedAt: { type: string, format: date-time, nullable: true }
        revokedAt: { type: string, format: date-time, nullable: true }
        lastErrorCode: { type: string, nullable: true }
        createdAt: { type: string, format: date-time }

    IntegrationCredentialSet:
      type: object
      additionalProperties: false
      required: [id, provider, environment, label, status, adapterSchemaVersion, subAccountId, latestGeneration, createdAt, updatedAt]
      properties:
        id: { type: string, format: uuid }
        provider: { type: string, enum: [palmetto, goodleap, ghl, docusign, zoho_sign] }
        environment: { type: string, enum: [sandbox, production] }
        label: { type: string }
        status: { type: string }
        adapterSchemaVersion: { type: integer, minimum: 1 }
        subAccountId:
          type: string
          format: uuid
          nullable: true
          description: Exact Palmetto branch override scope. NULL is the account default. Always NULL for GoodLeap.
        latestGeneration:
          description: Operational generation — the active generation when one exists, otherwise the newest.
          allOf:
            - { $ref: '#/components/schemas/IntegrationCredentialGeneration' }
          nullable: true
        createdAt: { type: string, format: date-time }
        updatedAt: { type: string, format: date-time }

    IntegrationCredentialRevealResult:
      type: object
      additionalProperties: false
      required: [fields]
      description: >
        Explicit GHL Show response. Never included in list/status. Cache-Control
        no-store. Owner/Admin + step-up. Do not log these values.
      properties:
        fields:
          type: object
          additionalProperties: false
          required: [client_id, client_secret]
          properties:
            client_id: { type: string }
            client_secret: { type: string }

    IntegrationCredentialSetList:
      type: object
      additionalProperties: false
      required:
        - connectionId
        - bindingMode
        - runtimeFlagEnabled
        - runtimeSourceForReads
        - runtimeSourceForWrites
        - hasActiveGeneration
        - hasActiveGenerationByEnv
        - scopeBindings
        - items
      properties:
        connectionId:
          type: string
          format: uuid
          nullable: true
          description: Account-owned integration_connections.id for this provider, if present.
        bindingMode:
          type: string
          enum: [tenant_byo, legacy_platform]
          nullable: true
          description: >
            Safe binding projection. Palmetto reports tenant_byo or NULL only;
            legacy database rows are normalized to NULL and require a tenant-owned
            credential. GoodLeap may report legacy_platform for compatibility.
        runtimeFlagEnabled:
          type: boolean
          description: PORTREX_TENANT_BYO_CREDENTIALS_RUNTIME / flag.tenant_byo_credentials_runtime.
        runtimeSourceForReads:
          type: string
          enum: [tenant_byo, legacy_platform, fail_closed]
          description: >
            Status-only projection of what outbound resolution would use for reads
            (no secrets). Palmetto reports tenant_byo only for a runtime-enabled
            active tenant credential; otherwise fail_closed. legacy_platform is
            a GoodLeap compatibility state only.
        runtimeSourceForWrites:
          type: string
          enum: [tenant_byo, legacy_platform, fail_closed]
          description: >
            Status-only projection of what outbound resolution would use for writes
            (no secrets). Palmetto reports tenant_byo only for a runtime-enabled
            active tenant credential; otherwise fail_closed. legacy_platform is
            a GoodLeap compatibility state only.
        hasActiveGeneration:
          type: boolean
          description: >
            Coarse OR — true when any environment has an active generation.
            Do not use alone for tenant_byo cutover; require hasActiveGenerationByEnv
            for each environment the pilot will exercise.
        hasActiveGenerationByEnv:
          type: object
          additionalProperties: false
          required: [sandbox, production]
          description: >
            Per-environment active generation readiness. Worker outbound resolve
            is env-scoped; sandbox-only active must not green-light production cutover.
          properties:
            sandbox: { type: boolean }
            production: { type: boolean }
        scopeBindings:
          type: array
          description: >
            Explicit Palmetto branch decisions only. A missing exact branch and
            sandbox decision fails closed; inheritance is never inferred.
          items: { $ref: '#/components/schemas/PalmettoCredentialScopeBinding' }
        items:
          type: array
          items: { $ref: '#/components/schemas/IntegrationCredentialSet' }

    PalmettoCredentialScopeBinding:
      type: object
      additionalProperties: false
      required: [subAccountId, environment, mode, credentialSetId, credentialReady]
      properties:
        subAccountId: { type: string, format: uuid }
        environment: { type: string, enum: [sandbox] }
        mode: { type: string, enum: [branch_override, account_inheritance, fail_closed] }
        credentialSetId:
          type: string
          format: uuid
          nullable: true
        credentialReady:
          type: boolean
          description: Credential material is valid; runtime and mapping readiness are separate gates.

    IntegrationCredentialAcceptBody:
      type: object
      additionalProperties: false
      required: [environment, credentials]
      properties:
        environment: { type: string, enum: [sandbox, production] }
        subAccountId:
          type: string
          format: uuid
          nullable: true
          description: >
            Exact Palmetto branch override. Omit or NULL for the account default.
            Unsupported for GoodLeap. Palmetto currently accepts sandbox only.
        label: { type: string, minLength: 1, maxLength: 200 }
        schemaVersion: { type: integer, minimum: 1, maximum: 100 }
        credentials:
          type: object
          additionalProperties: true
          description: Provider-specific secret fields. Never echoed in responses.

    IntegrationCredentialAcceptResult:
      type: object
      additionalProperties: false
      required: [commandId, credentialSetId, generationId, status, commandType]
      properties:
        commandId: { type: string, format: uuid }
        credentialSetId: { type: string, format: uuid }
        generationId: { type: string, format: uuid }
        status: { type: string, enum: [queued] }
        commandType: { type: string, enum: [validate, rotate, revoke] }

    IntegrationCredentialCommand:
      type: object
      additionalProperties: false
      required: [id, credentialSetId, generationId, commandType, status, lastErrorCode, createdAt, updatedAt, completedAt]
      properties:
        id: { type: string, format: uuid }
        credentialSetId: { type: string, format: uuid }
        generationId: { type: string, format: uuid }
        commandType: { type: string }
        status: { type: string }
        lastErrorCode: { type: string, nullable: true }
        createdAt: { type: string, format: date-time }
        updatedAt: { type: string, format: date-time }
        completedAt: { type: string, format: date-time, nullable: true }

    IntegrationCredentialBindingBody:
      type: object
      additionalProperties: false
      required: [mode]
      properties:
        mode:
          type: string
          enum: [tenant_byo, legacy_platform]
          description: >
            Outbound credential binding for this connection. tenant_byo requires
            an active sandbox generation before the mode can be set. Palmetto
            accepts tenant_byo only; legacy_platform is supported for GoodLeap
            compatibility only.

    GoodLeapCredentialBindingBody:
      type: object
      additionalProperties: false
      required: [mode, targetEnvironment]
      properties:
        mode:
          type: string
          enum: [tenant_byo, legacy_platform]
        targetEnvironment:
          type: string
          enum: [sandbox, production]
          description: Exact credential namespace selected in GoodLeap Settings.

    IntegrationCredentialBindingResult:
      type: object
      additionalProperties: false
      required: [connectionId, bindingMode, updatedAt]
      properties:
        connectionId: { type: string, format: uuid }
        bindingMode:
          type: string
          enum: [tenant_byo, legacy_platform]
          description: >
            Applied binding mode. Palmetto responses always return tenant_byo;
            GoodLeap may return legacy_platform for compatibility.
        updatedAt: { type: string, format: date-time }

    PalmettoCredentialScopeBody:
      type: object
      additionalProperties: false
      required: [subAccountId, environment, mode]
      properties:
        subAccountId: { type: string, format: uuid }
        environment: { type: string, enum: [sandbox] }
        mode:
          type: string
          enum: [inherit_account, fail_closed]
          description: >
            Explicitly inherit the active account-default credential or fail
            closed. Missing decisions never inherit automatically.

    IntegrationConnection:
      type: object
      required:
        - id
        - provider
        - name
        - category
        - description
        - glyph
        - color
        - enabled
        - can_toggle
        - status
        - status_label
        - auth_type
        - oauth_configured
        - connect_path
        - management_href
        - detail
        - last_error
        - last_checked_at
        - connected_at
        - disconnected_at
        - oauth_token_expires_at
        - connected_scopes
        - updated_at
      properties:
        id: { type: string, format: uuid, nullable: true }
        provider:
          type: string
          enum: [lead_sources, webhooks, stripe, square, twilio, email, documenso, docusign, zoho_sign, ghl, palmetto, goodleap, google_calendar, microsoft_365, quickbooks, hubspot, zapier_make, eagleview_hover, jobnimbus, acculynx, sunbase, mattermost]
        name: { type: string }
        category: { type: string }
        description: { type: string }
        glyph: { type: string }
        color: { type: string }
        enabled: { type: boolean }
        can_toggle:
          type: boolean
          description: Whether the generic account enable/disable endpoints apply to this provider.
        status:
          type: string
          enum: [available, connected, not_connected, disabled, error, planned]
        status_label: { type: string }
        auth_type:
          type: string
          enum: [built_in, webhook, oauth, api_key, manual]
        oauth_configured: { type: boolean }
        connect_path: { type: string, nullable: true }
        management_href: { type: string, nullable: true }
        detail: { type: string }
        last_error:
          type: object
          nullable: true
          required: [code, message]
          properties:
            code: { type: string, nullable: true }
            message: { type: string }
        last_checked_at: { type: string, format: date-time, nullable: true }
        connected_at: { type: string, format: date-time, nullable: true }
        disconnected_at: { type: string, format: date-time, nullable: true }
        oauth_token_expires_at: { type: string, format: date-time, nullable: true }
        connected_scopes:
          type: array
          items: { type: string }
        updated_at: { type: string, format: date-time, nullable: true }

    IntegrationOAuthStart:
      type: object
      required: [provider, authorization_url, redirect_uri, expires_at]
      properties:
        provider:
          type: string
          enum: [lead_sources, webhooks, stripe, square, twilio, documenso, ghl, google_calendar, microsoft_365, quickbooks, hubspot, zapier_make, eagleview_hover, jobnimbus, acculynx, sunbase, mattermost]
        authorization_url: { type: string, format: uri }
        redirect_uri: { type: string, format: uri }
        expires_at: { type: string, format: date-time }

    IntegrationConnectionPage:
      type: object
      required: [data, next_cursor]
      properties:
        data:
          type: array
          items: { $ref: '#/components/schemas/IntegrationConnection' }
        next_cursor: { type: string, nullable: true }

    WebhookSubscription:
      type: object
      required: [id, url, events, description, active, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        url: { type: string, format: uri }
        events:
          type: array
          items: { type: string }
        description: { type: string, nullable: true }
        active: { type: boolean }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    WebhookSubscriptionPage:
      type: object
      required: [data, next_cursor]
      properties:
        data:
          type: array
          items: { $ref: '#/components/schemas/WebhookSubscription' }
        next_cursor: { type: string, nullable: true }

    WebhookSubscriptionCreateResponse:
      type: object
      required: [id, account_id, url, events, description, active, secret, created_at]
      properties:
        id: { type: string, format: uuid }
        account_id: { type: string, format: uuid }
        url: { type: string, format: uri }
        events:
          type: array
          items: { type: string }
        description: { type: string, nullable: true }
        active: { type: boolean }
        secret:
          type: string
          description: HMAC signing secret returned exactly once.
        created_at: { type: string, format: date-time }

    WebhookSecretRotationResponse:
      type: object
      required: [id, secret, previous_secret_expires_at, rotated_at]
      properties:
        id: { type: string, format: uuid }
        secret:
          type: string
          description: New HMAC signing secret returned exactly once.
        previous_secret_expires_at:
          type: string
          format: date-time
          description: Previous secret remains valid until this timestamp.
        rotated_at: { type: string, format: date-time }

    LeadImportConflictPage:
      type: object
      required: [data, next_cursor]
      properties:
        data:
          type: array
          items: { $ref: '#/components/schemas/LeadImportConflict' }
        next_cursor: { type: string, nullable: true }

    LeadImportConflictResolution:
      type: object
      required: [id, action]
      properties:
        id: { type: string, format: uuid }
        action:
          type: string
          enum: [skip, create_new, merge]
        resolved_lead_id: { type: string, format: uuid, nullable: true }

    PricebookImportParseResult:
      type: object
      required: [id, status, headers, row_count]
      properties:
        id: { type: string, format: uuid }
        status:
          type: string
          enum: [mapping]
        headers:
          type: array
          items: { type: string }
        row_count: { type: integer, minimum: 0 }

    PricebookImportStartRequest:
      type: object
      required: [filename]
      properties:
        filename: { type: string }
        upload_url: { type: string, nullable: true }
        csv_text:
          type: string
          description: Inline RFC 4180 CSV text for local/admin paste flows. Production uploads may pass upload_url and parse asynchronously. Stored with the import so dry-run and commit work on any API instance.
        scope: { $ref: '#/components/schemas/PricebookImportScope' }
      additionalProperties: false

    PricebookImportScope:
      type: object
      description: Import & Export hub scope, applied fill-blank-only to every imported row (a value the row or the item it updates already has wins).
      properties:
        industry: { type: string, minLength: 1, maxLength: 80 }
        renovation_type: { type: string, enum: [kitchen, bathroom, basement, general, decks, patio, gutters] }
        showroom_trade: { type: string, enum: [adu, hvac, renovation, generac, roofing, water-filtration, solar] }
        manufacturer: { type: string, minLength: 1, maxLength: 120 }
      additionalProperties: false

    ImportUndoResult:
      type: object
      required: [id, status, replayed, archived, restored, kept_edited]
      properties:
        id: { type: string, format: uuid }
        status: { type: string, enum: [rolled_back] }
        replayed: { type: boolean }
        archived: { type: integer }
        restored: { type: integer }
        kept_edited:
          type: array
          items:
            type: object
            required: [item_id, name]
            properties:
              item_id: { type: [string, 'null'], format: uuid, description: 'Null when the row no longer exists (a rate row deleted since the import)' }
              name: { type: string }

    ImportUndoPreview:
      type: object
      required: [id, changed_since_commit, will_create, will_update, will_archive, kept_edited]
      properties:
        id: { type: string, format: uuid }
        changed_since_commit: { type: boolean }
        will_create: { type: integer }
        will_update: { type: integer }
        will_archive: { type: integer }
        kept_edited:
          type: array
          items:
            type: object
            required: [item_id, name]
            properties:
              item_id: { type: [string, 'null'], format: uuid, description: 'Null when the row no longer exists (a rate row deleted since the import)' }
              name: { type: string }

    ImportHistoryPage:
      type: object
      required: [data, next_cursor]
      properties:
        data:
          type: array
          items:
            type: object
            required: [id, source, status, filename, scope, initiated_by, created_at, committed_at, counts, undo_available, undo_unavailable_reason]
            properties:
              id: { type: string, format: uuid }
              source: { type: string, enum: [csv, jobnimbus, json, xlsx, showroom_workbook, rate_card] }
              status: { type: string }
              filename: { type: string, nullable: true }
              scope:
                allOf: [{ $ref: '#/components/schemas/PricebookImportScope' }]
                nullable: true
              initiated_by:
                type: object
                nullable: true
                properties:
                  id: { type: string, format: uuid }
                  name: { type: string }
              created_at: { type: string, format: date-time }
              committed_at: { type: string, format: date-time, nullable: true }
              counts:
                type: object
                properties:
                  inserted: { type: integer, nullable: true }
                  updated: { type: integer, nullable: true }
                  skipped: { type: integer, nullable: true }
                  errors: { type: integer, nullable: true }
              undo_available: { type: boolean }
              undo_unavailable_reason: { type: string, nullable: true }
        next_cursor: { type: string, nullable: true }

    PricebookImportMappingsRequest:
      type: object
      required: [mappings]
      properties:
        mappings:
          type: array
          items:
            type: object
            required: [source_column, target_field]
            properties:
              source_column: { type: string }
              target_field: { type: string, nullable: true }
            additionalProperties: false
      additionalProperties: false

    PricebookImportMappingsResponse:
      type: object
      required: [id, status, mappings]
      properties:
        id: { type: string, format: uuid }
        status:
          type: string
          enum: [confirmed]
        mappings:
          type: array
          items: { $ref: '#/components/schemas/PricebookImportMapping' }

    PricebookImportDryRunRequest:
      type: object
      properties:
        parsed_rows:
          type: array
          items:
            type: object
            additionalProperties: { type: string }
      additionalProperties: false

    PricebookImportDryRunResponse:
      type: object
      required: [id, status, summary]
      properties:
        id: { type: string, format: uuid }
        status:
          type: string
          enum: [dry_run]
        summary: { $ref: '#/components/schemas/PricebookImportDryRunSummary' }
        preview_rows:
          type: array
          maxItems: 500
          description: The first 500 resulting rows in file order, scope applied (also stored in summary.preview_rows). Cost fields are omitted for seats without pricebook:cost:read.
          items: { $ref: '#/components/schemas/PricebookImportPreviewRow' }

    PricebookImportPreviewRow:
      type: object
      required: [row, action, item_id, name, sku, fields, changed]
      properties:
        row: { type: integer, nullable: true, description: CSV line (1 = header); null for workbook rows }
        action: { type: string, enum: [insert, update, unchanged, skip, error] }
        item_id: { type: string, format: uuid, nullable: true }
        name: { type: string, nullable: true }
        sku: { type: string, nullable: true }
        fields: { type: object, additionalProperties: true, description: Resulting item values }
        changed:
          type: array
          items: { type: string }
          description: Fields that differ from the stored item; every written field for an insert

    PricebookImportCommitRequest:
      type: object
      properties:
        parsed_rows:
          type: array
          items:
            type: object
            additionalProperties: { type: string }
      additionalProperties: false

    PricebookImportCommitResponse:
      type: object
      required: [id, status, replayed, rows_committed, committed_at]
      properties:
        id: { type: string, format: uuid }
        status:
          type: string
          enum: [committed]
        replayed: { type: boolean }
        rows_committed: { type: integer, minimum: 0 }
        committed_at: { type: string, format: date-time, nullable: true }

    PricebookExpireGrantsResponse:
      type: object
      required: [ok, setExpiry, revoked]
      properties:
        ok: { type: boolean }
        setExpiry: { type: integer, minimum: 0 }
        revoked: { type: integer, minimum: 0 }

    ContractVoidInitiation:
      type: object
      required: [void_event_id, status, expires_at, fcra_review_required, diff_total]
      properties:
        void_event_id: { type: string, format: uuid }
        status:
          type: string
          enum: [pending_rep_signature, pending_homeowner_signature, countersigned, expired, cancelled]
        expires_at: { type: string, format: date-time }
        fcra_review_required: { type: boolean }
        diff_total: { type: integer, minimum: 1 }

    OAuthAuthorizeResponse:
      type: object
      required: [code, redirect_uri, expires_in]
      properties:
        code: { type: string }
        state: { type: string }
        redirect_uri: { type: string, format: uri }
        expires_in: { type: integer, minimum: 1 }

    BillingBannerState:
      type: object
      required: [state, message, days_remaining]
      properties:
        state: { type: string, enum: [ok, past_due, suspended] }
        message: { type: string }
        days_remaining: { type: integer, minimum: 0 }

    LeadPipelineStageSummary:
      type: object
      required: [count, value_cents]
      properties:
        count: { type: integer, minimum: 0 }
        value_cents: { type: integer, minimum: 0 }

    LeadPipelineSummary:
      type: object
      required: [by_status, open_pipeline]
      properties:
        by_status:
          type: object
          additionalProperties: { $ref: '#/components/schemas/LeadPipelineStageSummary' }
        open_pipeline: { $ref: '#/components/schemas/LeadPipelineStageSummary' }

    LeadStageDefinition:
      type: object
      required: [id, label, category, funnel_order, default_probability_bp, probability_bp]
      properties:
        id: { type: string }
        label: { type: string }
        category: { type: string, enum: [open, won, lost] }
        funnel_order: { type: integer, nullable: true, minimum: 0, maximum: 7 }
        default_probability_bp: { type: integer, minimum: 0, maximum: 10000 }
        probability_bp: { type: integer, minimum: 0, maximum: 10000 }

    LeadPage:
      type: object
      required: [data, next_cursor]
      properties:
        data:
          type: array
          items: { $ref: '#/components/schemas/Lead' }
        next_cursor: { type: string, nullable: true }
        total: { type: integer }

    LeadServiceInterests:
      type: array
      maxItems: 32
      uniqueItems: true
      default: []
      description: >
        Canonical service interests, independent of quotes, projects, and catalog
        availability. The renovation key means general renovation. An empty
        array clears the interests; omission from PATCH preserves them.
      items:
        type: string
        enum: [adu, hvac, renovation, generac, roofing, water-filtration, solar, 'renovation:basement', 'renovation:kitchen', 'renovation:bathroom', 'renovation:decks', 'renovation:patio', 'renovation:gutters', 'renovation:windows', 'renovation:doors', 'renovation:siding', 'renovation:plumbing', 'renovation:electrician']
      example: [hvac, 'renovation:kitchen']

    Lead:
      type: object
      required: [id, account_id, source, status, created_at]
      properties:
        id: { type: string, format: uuid }
        account_id: { type: string, format: uuid }
        sub_account_id: { type: string, format: uuid, nullable: true }
        customer_id: { type: string, format: uuid, nullable: true }
        associated_customer_id:
          type: string
          format: uuid
          nullable: true
          description: >
            Single-lead GET and mutation responses. Showroom-minted or
            person-attached customer while leads.customer_id stays null until a
            fully signed agreement (POR-1111 / POR-1583). Omitted from list
            responses.
        source:
          type: string
          enum: [web_form, csv_import, lead_buy, canvassing_knock, manual, api, ghl]
        status:
          type: string
          enum: [new, contacted, qualified, appointment_set, appointment_held, proposal_sent, closed_won, closed_lost, no_show]
        assigned_user_id: { type: string, format: uuid, nullable: true }
        appointment_setter_user_id: { type: string, format: uuid, nullable: true }
        sales_manager_user_id:
          type: [string, 'null']
          format: uuid
          description: >
            Lead sales manager. Assignment does not change membership roles or
            grant lead access. Null means no manager.
        service_interests: { $ref: '#/components/schemas/LeadServiceInterests' }
        do_not_call: { type: boolean, default: false, description: 'Lead-local call restriction. False does not grant consent.' }
        do_not_text: { type: boolean, default: false, description: 'Lead-local text restriction. False does not grant consent.' }
        do_not_email: { type: boolean, default: false, description: 'Lead-local email restriction. False does not grant consent.' }
        description: { type: string, nullable: true }
        value_cents: { type: integer, nullable: true }
        raw_address_json: { type: object, nullable: true }
        lead_source_id: { type: string, format: uuid, nullable: true }
        source_external_id: { type: string, nullable: true }
        source_created_at: { type: string, format: date-time, nullable: true }
        source_updated_at: { type: string, format: date-time, nullable: true }
        custom_fields_json:
          type: object
          additionalProperties: true
        data_quality_status:
          type: string
          enum: [ok, needs_review, conflict, rejected]
        converted_project_id: { type: string, format: uuid, nullable: true }
        converted_at: { type: string, format: date-time, nullable: true }
        expected_close_date: { type: string, format: date, nullable: true, description: 'Optional expected close date (yyyy-mm-dd); read by the pipeline forecast report.' }
        archived_at: { type: string, format: date-time, nullable: true }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }
        customer_records_available:
          type: boolean
          description: >
            Detail GET only. False when the viewer can read the lead but nested
            customer records are branch-fenced (POR-1542).
        same_person_kept:
          $ref: '#/components/schemas/SamePersonKept'

    SamePersonKept:
      type: object
      additionalProperties: false
      required: [person_id, customer_id, display_name, fields]
      description: >
        POST /v1/leads only (POR-2744). Present when the rep answered "same
        person" and at least one typed email, phone or address differs from
        what the existing person or customer keeps. The typed values are not
        written (no overwrite of the existing person); the lead keeps its own
        raw_address_json. Values are compared normalized (digits-only phone,
        trimmed lowercase email, street/city/state/ZIP5 address).
      properties:
        person_id: { type: string, format: uuid }
        customer_id:
          type: string
          format: uuid
          nullable: true
          description: The person's live customer, for the edit-contact link.
        display_name: { type: string, nullable: true }
        fields:
          type: array
          minItems: 1
          items:
            type: object
            additionalProperties: false
            required: [field, typed, kept]
            properties:
              field: { type: string, enum: [email, phone, address] }
              typed: { type: string, description: The value the rep typed; not applied. }
              kept: { type: string, nullable: true, description: The stored value that stays; null when none is on file. }

    LeadConversionResult:
      type: object
      required: [lead_id, project_id, status, already_converted, lead_source_id, source_external_id, data_quality_status, converted_project_id, converted_at, project]
      properties:
        lead_id: { type: string, format: uuid }
        customer_id: { type: string, format: uuid, nullable: true }
        project_id: { type: string, format: uuid }
        status: { type: string, enum: [closed_won] }
        already_converted: { type: boolean }
        lead_source_id: { type: string, format: uuid, nullable: true }
        source_external_id: { type: string, nullable: true }
        data_quality_status:
          type: string
          enum: [ok, needs_review, conflict, rejected]
        converted_project_id: { type: string, format: uuid, nullable: true }
        converted_at: { type: string, format: date-time, nullable: true }
        project:
          type: object
          additionalProperties: true

    Project:
      type: object
      additionalProperties: false
      required: [id, account_id, property_id, status, pipeline_stage, stage_entered_at, stage_deadline_at, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        account_id: { type: string, format: uuid }
        sub_account_id: { type: string, format: uuid, nullable: true }
        customer_id: { type: string, format: uuid, nullable: true }
        property_id: { type: string, format: uuid }
        lead_id: { type: string, format: uuid, nullable: true }
        primary_contact_id: { type: string, format: uuid, nullable: true }
        owner_user_id: { type: string, format: uuid, nullable: true }
        status:
          type: string
          enum: [active, closed_won, closed_lost, on_hold, archived]
        pipeline_stage:
          type: string
          enum: [sales, account_management, site_survey, final_approval, project_setup, permitting_build, won, lost, on_hold]
        stage_entered_at: { type: string, format: date-time }
        stage_deadline_at: { type: string, format: date-time, nullable: true }
        total_contracted_amount_cents: { type: integer, nullable: true }
        opened_at: { type: string, format: date-time }
        closed_at: { type: string, format: date-time, nullable: true }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    ProjectPage:
      type: object
      required: [data, next_cursor]
      properties:
        data:
          type: array
          items: { $ref: '#/components/schemas/Project' }
        next_cursor: { type: string, nullable: true }
        total: { type: integer, description: Number of matching visible projects before pagination. }
        filter_options:
          type: object
          properties:
            accounts: { type: array, items: { type: string } }
            owners: { type: array, items: { type: string } }
            services: { type: array, items: { type: string } }
            cities: { type: array, items: { type: string } }
        scope_counts:
          type: object
          properties:
            all: { type: integer }
            company: { type: integer }
            mine: { type: integer }

    ProjectSnapshotEstimateLine:
      type: object
      additionalProperties: false
      required: [line_id, parent_line_id, is_optional, name, quantity, unit_price_cents, line_total_cents, commission_treatment, pass_through_kind]
      properties:
        line_id: { type: string, nullable: true }
        parent_line_id: { type: string, nullable: true }
        is_optional: { type: boolean, nullable: true }
        name: { type: string, nullable: true }
        quantity: { type: number, nullable: true }
        unit_price_cents: { type: integer, nullable: true }
        line_total_cents: { type: integer, nullable: true }
        commission_treatment: { type: string, enum: [commissionable, adder, pass_through], nullable: true }
        pass_through_kind: { type: string, enum: [financing_fee, agent_collection, other], nullable: true }

    ProjectSnapshotEstimate:
      type: object
      additionalProperties: false
      required: [id, estimate_number, status, accepted_at, lines]
      properties:
        id: { type: string }
        estimate_number: { type: string, nullable: true }
        status: { type: string }
        accepted_at: { type: string, format: date-time, nullable: true }
        lines:
          type: array
          items: { $ref: '#/components/schemas/ProjectSnapshotEstimateLine' }

    ProjectSnapshotInvoice:
      type: object
      additionalProperties: false
      required: [id, billing_type, status, amount_cents, paid_cents, due_date, paid_at]
      properties:
        id: { type: string }
        billing_type: { type: string, nullable: true }
        status: { type: string }
        amount_cents: { type: integer }
        paid_cents: { type: integer }
        due_date: { type: string, format: date-time, nullable: true }
        paid_at: { type: string, format: date-time, nullable: true }

    ProjectSnapshotContract:
      type: object
      additionalProperties: false
      required: [id, status, contract_kind, total_amount_cents, primary_signed_at, cosigner_signed_at]
      properties:
        id: { type: string }
        status: { type: string }
        contract_kind: { type: string }
        total_amount_cents: { type: integer, nullable: true }
        primary_signed_at: { type: string, format: date-time, nullable: true }
        cosigner_signed_at: { type: string, format: date-time, nullable: true }

    ProjectSnapshotTask:
      type: object
      additionalProperties: false
      required: [id, title, status, due_date, completed_at]
      properties:
        id: { type: string }
        title: { type: string }
        status: { type: string }
        due_date: { type: string, format: date-time, nullable: true }
        completed_at: { type: string, format: date-time, nullable: true }

    ProjectSnapshotStageHistory:
      type: object
      additionalProperties: false
      required: [id, from_state, to_state, created_at]
      properties:
        id: { type: string }
        from_state: { type: string, nullable: true }
        to_state: { type: string }
        created_at: { type: string, format: date-time }

    ProjectSnapshot:
      type: object
      additionalProperties: false
      required: [id, status, pipeline_stage, stage_entered_at, opened_at, closed_at, created_at, updated_at, customer, property, lead, estimates, invoices, contracts, tasks, stage_history, unavailable]
      properties:
        id: { type: string }
        status: { type: string }
        pipeline_stage: { type: string }
        stage_entered_at: { type: string, format: date-time, nullable: true }
        opened_at: { type: string, format: date-time, nullable: true }
        closed_at: { type: string, format: date-time, nullable: true }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }
        customer:
          type: object
          nullable: true
          additionalProperties: false
          required: [id, display_name]
          properties:
            id: { type: string }
            display_name: { type: string, nullable: true }
        property:
          type: object
          nullable: true
          additionalProperties: false
          required: [id, street, city, state, zip, home_size_sqft]
          properties:
            id: { type: string }
            street: { type: string, nullable: true }
            city: { type: string, nullable: true }
            state: { type: string, nullable: true }
            zip: { type: string, nullable: true }
            home_size_sqft: { type: integer, nullable: true }
        lead:
          type: object
          nullable: true
          additionalProperties: false
          required: [id, source_raw, lead_source_name]
          properties:
            id: { type: string }
            source_raw: { type: string, nullable: true }
            lead_source_name: { type: string, nullable: true }
        estimates:
          type: array
          nullable: true
          items: { $ref: '#/components/schemas/ProjectSnapshotEstimate' }
        invoices:
          type: array
          nullable: true
          items: { $ref: '#/components/schemas/ProjectSnapshotInvoice' }
        contracts:
          type: array
          nullable: true
          items: { $ref: '#/components/schemas/ProjectSnapshotContract' }
        tasks:
          type: array
          nullable: true
          items: { $ref: '#/components/schemas/ProjectSnapshotTask' }
        stage_history:
          type: array
          items: { $ref: '#/components/schemas/ProjectSnapshotStageHistory' }
        unavailable:
          type: object
          additionalProperties: { type: string }

    ProjectSnapshotPage:
      type: object
      additionalProperties: false
      required: [data, next_cursor]
      properties:
        data:
          type: array
          items: { $ref: '#/components/schemas/ProjectSnapshot' }
        next_cursor: { type: string, nullable: true }

    ProjectEstimate:
      type: object
      required: [id, customer_id, project_id, estimate_number, showroom_key, line_item_descriptions, status, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        customer_id: { type: string, format: uuid }
        project_id: { type: string, format: uuid }
        design_id: { type: string, format: uuid, nullable: true }
        address_id: { type: string, format: uuid, nullable: true }
        estimate_number: { type: string }
        description: { type: string, nullable: true }
        showroom_key: { type: string, enum: [adu, hvac, renovation, roofing, generac, water-filtration, solar], nullable: true }
        lifecycle_mode: { type: string, enum: [versioned_draft_v1], nullable: true }
        line_item_descriptions:
          type: array
          items: { type: string }
        total_cents: { type: integer, nullable: true }
        lead_source: { type: string, nullable: true }
        status:
          type: string
          enum: [draft, sent, viewed, accepted, declined, expired]
        sent_at: { type: string, format: date-time, nullable: true }
        viewed_at: { type: string, format: date-time, nullable: true }
        accepted_at: { type: string, format: date-time, nullable: true }
        declined_at: { type: string, format: date-time, nullable: true }
        expires_at: { type: string, format: date-time, nullable: true }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    ProjectEstimatePage:
      type: object
      required: [data, next_cursor]
      properties:
        data:
          type: array
          items: { $ref: '#/components/schemas/ProjectEstimate' }
        next_cursor: { type: string, nullable: true }

    ProjectInvoice:
      type: object
      required: [id, customer_id, project_id, invoice_number, billing_type, status, amount_cents, paid_cents, payment_collection_active, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        customer_id: { type: string, format: uuid }
        project_id: { type: string, format: uuid }
        estimate_id: { type: string, format: uuid, nullable: true }
        invoice_number: { type: string }
        billing_type:
          type: string
          enum: [deposit, progress, final, one_time, service_plan_recurring]
        status:
          type: string
          enum: [draft, sent, viewed, partial, paid, void, overdue]
        amount_cents: { type: integer, minimum: 0 }
        paid_cents: { type: integer, minimum: 0 }
        due_date: { type: string, format: date-time, nullable: true }
        sent_at: { type: string, format: date-time, nullable: true }
        viewed_at: { type: string, format: date-time, nullable: true }
        paid_at: { type: string, format: date-time, nullable: true }
        payment_collection_active: { type: boolean }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    ProjectInvoicePage:
      type: object
      required: [data, next_cursor]
      properties:
        data:
          type: array
          items: { $ref: '#/components/schemas/ProjectInvoice' }
        next_cursor: { type: string, nullable: true }

    ProjectContract:
      type: object
      additionalProperties: false
      required: [id, project_id, status, contract_kind, cfo_approved_at, cfo_approved_by_user_id, signing_mode, agreement_delivery, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        project_id: { type: string, format: uuid }
        estimate_id: { type: string, format: uuid, nullable: true }
        estimate_number: { type: string, nullable: true }
        estimate_status: { type: string, nullable: true }
        status:
          type: string
          enum: [draft, sent, partially_signed, fully_signed, void_pending, voided, expired]
        contract_kind:
          type: string
          enum: [signed_agreement, final_agreement]
        cfo_approved_at: { type: string, format: date-time, nullable: true }
        cfo_approved_by_user_id: { type: string, format: uuid, nullable: true }
        signing_mode:
          type: string
          enum: [single, split]
        total_amount_cents: { type: integer, nullable: true }
        customer_person_id: { type: string, format: uuid, nullable: true }
        primary_signer_person_id: { type: string, format: uuid, nullable: true }
        cosigner_person_id: { type: string, format: uuid, nullable: true }
        customer_contact_id: { type: string, format: uuid, nullable: true }
        primary_signer_contact_id: { type: string, format: uuid, nullable: true }
        cosigner_contact_id: { type: string, format: uuid, nullable: true }
        superseded_by_contract_id: { type: string, format: uuid, nullable: true }
        primary_signed_at: { type: string, format: date-time, nullable: true }
        cosigner_signed_at: { type: string, format: date-time, nullable: true }
        created_by_user_id: { type: string, format: uuid, nullable: true }
        agreement_delivery: { $ref: '#/components/schemas/ProjectContractAgreementDelivery' }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    ProjectContractAgreementDelivery:
      type: object
      required:
        - state
        - send_job_status
        - send_requested_at
        - send_locked_at
        - send_completed_at
        - send_attempts
        - send_last_error_code
        - mapping_status
        - mapped_signer_roles
        - mapped_signer_count
        - required_signer_count
      additionalProperties: false
      properties:
        state:
          type: string
          enum: [not_requested, queued, processing, completed, failed, mapped, mapping_incomplete]
        send_job_status:
          type: string
          enum: [not_requested, pending, processing, completed, failed]
        send_requested_at: { type: string, format: date-time, nullable: true }
        send_locked_at: { type: string, format: date-time, nullable: true }
        send_completed_at: { type: string, format: date-time, nullable: true }
        send_attempts: { type: integer, minimum: 0 }
        send_last_error_code: { type: string, nullable: true }
        mapping_status:
          type: string
          enum: [none, partial, ready]
        mapped_signer_roles:
          type: array
          items:
            type: string
            enum: [primary, cosigner]
        mapped_signer_count: { type: integer, minimum: 0 }
        required_signer_count: { type: integer, enum: [1, 2] }

    ProjectContractPage:
      type: object
      required: [data, next_cursor]
      properties:
        data:
          type: array
          items: { $ref: '#/components/schemas/ProjectContract' }
        next_cursor: { type: string, nullable: true }

    ProjectNote:
      type: object
      required: [id, project_id, body, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        customer_id: { type: string, format: uuid, nullable: true }
        project_id: { type: string, format: uuid }
        body: { type: string }
        author_user_id: { type: string, format: uuid, nullable: true }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    ProjectNotePage:
      type: object
      required: [data, next_cursor]
      properties:
        data:
          type: array
          items: { $ref: '#/components/schemas/ProjectNote' }
        next_cursor: { type: string, nullable: true }

    ProjectTask:
      type: object
      required: [id, project_id, title, status, priority, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        customer_id: { type: string, format: uuid, nullable: true }
        project_id: { type: string, format: uuid }
        title: { type: string }
        description: { type: string, nullable: true }
        assigned_user_id: { type: string, format: uuid, nullable: true }
        due_date: { type: string, format: date-time, nullable: true }
        status:
          type: string
          enum: [open, in_progress, done, cancelled]
        priority:
          type: string
          enum: [low, normal, high]
        completed_at: { type: string, format: date-time, nullable: true }
        created_by_user_id: { type: string, format: uuid, nullable: true }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    ProjectTaskPage:
      type: object
      required: [data, next_cursor]
      properties:
        data:
          type: array
          items: { $ref: '#/components/schemas/ProjectTask' }
        next_cursor: { type: string, nullable: true }

    ProjectAppointment:
      type: object
      required: [id, project_id, title, type, starts_at, ends_at, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        sub_account_id: { type: string, format: uuid, nullable: true }
        customer_id: { type: string, format: uuid, nullable: true }
        project_id: { type: string, format: uuid }
        lead_id: { type: string, format: uuid, nullable: true }
        owner_user_id: { type: string, format: uuid, nullable: true }
        type:
          type: string
          enum: [in_home, phone, virtual]
        title: { type: string }
        starts_at: { type: string, format: date-time }
        ends_at: { type: string, format: date-time }
        location_address: { type: string, nullable: true }
        notes: { type: string, nullable: true }
        outcome:
          type: string
          enum: [no_show, rescheduled, completed, cancelled]
          nullable: true
        outcome_notes: { type: string, nullable: true }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    ProjectAppointmentPage:
      type: object
      required: [data, next_cursor]
      properties:
        data:
          type: array
          items: { $ref: '#/components/schemas/ProjectAppointment' }
        next_cursor: { type: string, nullable: true }

    ProjectWorkspaceCustomer:
      type: object
      additionalProperties: false
      required: [id, sub_account_id, customer_type, display_name, do_not_service, service_status, lifetime_value_cents, outstanding_balance_cents, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        sub_account_id: { type: string, format: uuid, nullable: true }
        customer_type: { type: string }
        display_name: { type: string }
        do_not_service: { type: boolean }
        service_status: { type: string, nullable: true }
        lifetime_value_cents: { type: integer, nullable: true }
        outstanding_balance_cents: { type: integer, nullable: true }
        created_at: { type: string, format: date-time, nullable: true }
        updated_at: { type: string, format: date-time, nullable: true }

    ProjectWorkspaceProperty:
      type: object
      additionalProperties: false
      required: [id, sub_account_id, street, city, state, zip, country, parcel_id, primary_aerial_image_url, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        sub_account_id: { type: string, format: uuid, nullable: true }
        street: { type: string }
        city: { type: string }
        state: { type: string }
        zip: { type: string }
        country: { type: string }
        parcel_id: { type: string, nullable: true }
        primary_aerial_image_url: { type: string, nullable: true }
        created_at: { type: string, format: date-time, nullable: true }
        updated_at: { type: string, format: date-time, nullable: true }

    ProjectWorkspacePrimaryContact:
      type: object
      additionalProperties: false
      required: [id, customer_id, given_name, family_name, display_name, role, can_sign, email_count, phone_count, email, phone, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        customer_id: { type: string, format: uuid }
        given_name: { type: string }
        family_name: { type: string }
        display_name: { type: string }
        role: { type: string }
        can_sign: { type: boolean }
        email_count: { type: integer, minimum: 0 }
        phone_count: { type: integer, minimum: 0 }
        email: { type: string, nullable: true }
        phone: { type: string, nullable: true }
        created_at: { type: string, format: date-time, nullable: true }
        updated_at: { type: string, format: date-time, nullable: true }

    ProjectWorkspaceLead:
      type: object
      additionalProperties: false
      required: [id, sub_account_id, customer_id, status, source, assigned_user_id, description, value_cents, lead_source_id, source_external_id, data_quality_status, converted_project_id, converted_at, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        sub_account_id: { type: string, format: uuid, nullable: true }
        customer_id: { type: string, format: uuid, nullable: true }
        status: { type: string }
        source: { type: string }
        assigned_user_id: { type: string, format: uuid, nullable: true }
        description: { type: string, nullable: true }
        value_cents: { type: integer, nullable: true }
        lead_source_id: { type: string, format: uuid, nullable: true }
        source_external_id: { type: string, nullable: true }
        data_quality_status: { type: string, nullable: true }
        converted_project_id: { type: string, format: uuid, nullable: true }
        converted_at: { type: string, format: date-time, nullable: true }
        created_at: { type: string, format: date-time, nullable: true }
        updated_at: { type: string, format: date-time, nullable: true }

    ProjectWorkspaceOwner:
      type: object
      additionalProperties: false
      required: [user_id, full_name, email, avatar_url, role, sub_account_id, team_id, is_active]
      properties:
        user_id: { type: string, format: uuid }
        full_name: { type: string }
        email: { type: string }
        avatar_url: { type: string, nullable: true }
        role: { type: string }
        sub_account_id: { type: string, format: uuid, nullable: true }
        team_id: { type: string, format: uuid, nullable: true }
        is_active: { type: boolean }

    ProjectDesignSummary:
      type: object
      additionalProperties: false
      required: [id, project_id, service_type, version_number, status, parent_design_id, created_by_user_id, presented_at, accepted_at, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        project_id: { type: string, format: uuid }
        service_type: { type: string }
        version_number: { type: integer }
        status: { type: string }
        parent_design_id: { type: string, format: uuid, nullable: true }
        created_by_user_id: { type: string, format: uuid, nullable: true }
        presented_at: { type: string, format: date-time, nullable: true }
        accepted_at: { type: string, format: date-time, nullable: true }
        created_at: { type: string, format: date-time, nullable: true }
        updated_at: { type: string, format: date-time, nullable: true }

    ProjectActivitySummary:
      type: object
      additionalProperties: false
      required: [id, sub_account_id, owner_type, owner_id, type, direction, author_user_id, body_text, note_id, attachments, occurred_at]
      properties:
        id: { type: string, format: uuid }
        sub_account_id: { type: string, format: uuid, nullable: true }
        owner_type: { type: string }
        owner_id: { type: string, format: uuid }
        type: { type: string }
        direction: { type: string }
        author_user_id: { type: string, format: uuid, nullable: true }
        body_text: { type: string, nullable: true }
        note_id: { type: string, format: uuid, nullable: true }
        attachments:
          type: array
          items: {}
        occurred_at: { type: string, format: date-time, nullable: true }

    ProjectAttachmentSummary:
      type: object
      additionalProperties: false
      required: [id, customer_id, project_id, r2_key, mime_type, size_bytes, original_filename, uploaded_by_user_id, created_at]
      properties:
        id: { type: string, format: uuid }
        customer_id: { type: string, format: uuid, nullable: true }
        project_id: { type: string, format: uuid, nullable: true }
        r2_key: { type: string }
        mime_type: { type: string }
        size_bytes: { type: integer, minimum: 0 }
        original_filename: { type: string, nullable: true }
        uploaded_by_user_id: { type: string, format: uuid, nullable: true }
        created_at: { type: string, format: date-time, nullable: true }

    ProjectTagSummary:
      type: object
      additionalProperties: false
      required: [id, name, color, assignment_id, created_at]
      properties:
        id: { type: string, format: uuid }
        name: { type: string }
        color: { type: string, nullable: true }
        assignment_id: { type: string, format: uuid }
        created_at: { type: string, format: date-time, nullable: true }

    ProjectServicePlanSummary:
      type: object
      additionalProperties: false
      required: [id, customer_id, property_id, name, description, status, cadence, cadence_custom_days, next_service_date, pricing_cents_per_period, auto_invoice, started_at, ends_at, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        customer_id: { type: string, format: uuid }
        property_id: { type: string, format: uuid, nullable: true }
        name: { type: string }
        description: { type: string, nullable: true }
        status:
          type: string
          enum: [active, paused, cancelled, expired]
        cadence:
          type: string
          enum: [monthly, quarterly, semiannual, annual, custom]
        cadence_custom_days: { type: integer, nullable: true }
        next_service_date: { type: string, format: date-time, nullable: true }
        pricing_cents_per_period: { type: integer, nullable: true }
        auto_invoice: { type: boolean }
        started_at: { type: string, format: date-time, nullable: true }
        ends_at: { type: string, format: date-time, nullable: true }
        created_at: { type: string, format: date-time, nullable: true }
        updated_at: { type: string, format: date-time, nullable: true }

    ProjectStageHistoryEntry:
      type: object
      additionalProperties: false
      required: [id, entity_type, entity_id, from_state, to_state, actor_kind, actor_role, actor_user_id, reason, created_at]
      properties:
        id: { type: string, format: uuid }
        entity_type: { type: string }
        entity_id: { type: string, format: uuid }
        from_state: { type: string, nullable: true }
        to_state: { type: string }
        actor_kind: { type: string }
        actor_role: { type: string, nullable: true }
        actor_user_id: { type: string, format: uuid, nullable: true }
        reason: { type: string, nullable: true }
        created_at: { type: string, format: date-time, nullable: true }

    ProjectSiteSurveySummary:
      type: object
      additionalProperties: false
      required: [id, sub_account_id, customer_id, project_id, property_id, appointment_id, surveyor_user_id, status, scheduled_for, completed_at, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        sub_account_id: { type: string, format: uuid, nullable: true }
        customer_id: { type: string, format: uuid }
        project_id: { type: string, format: uuid }
        property_id: { type: string, format: uuid, nullable: true }
        appointment_id: { type: string, format: uuid, nullable: true }
        surveyor_user_id: { type: string, format: uuid, nullable: true }
        status: { type: string }
        scheduled_for: { type: string, format: date-time, nullable: true }
        completed_at: { type: string, format: date-time, nullable: true }
        created_at: { type: string, format: date-time, nullable: true }
        updated_at: { type: string, format: date-time, nullable: true }

    ProjectSurveyReportSummary:
      type: object
      additionalProperties: false
      required: [id, site_survey_id, customer_id, project_id, outcome, findings, conditions, submitted_by_user_id, submitted_at, created_at]
      properties:
        id: { type: string, format: uuid }
        site_survey_id: { type: string, format: uuid }
        customer_id: { type: string, format: uuid }
        project_id: { type: string, format: uuid }
        outcome: { type: string }
        findings:
          type: object
          additionalProperties: true
        conditions: { type: string, nullable: true }
        submitted_by_user_id: { type: string, format: uuid, nullable: true }
        submitted_at: { type: string, format: date-time, nullable: true }
        created_at: { type: string, format: date-time, nullable: true }

    ProjectFeasibilitySummary:
      type: object
      additionalProperties: false
      required: [id, sub_account_id, customer_id, project_id, status, findings, prepared_by_user_id, approved_at, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        sub_account_id: { type: string, format: uuid, nullable: true }
        customer_id: { type: string, format: uuid }
        project_id: { type: string, format: uuid }
        status: { type: string }
        findings:
          type: object
          additionalProperties: true
        prepared_by_user_id: { type: string, format: uuid, nullable: true }
        approved_at: { type: string, format: date-time, nullable: true }
        created_at: { type: string, format: date-time, nullable: true }
        updated_at: { type: string, format: date-time, nullable: true }

    ProjectArchitecturalStampSummary:
      type: object
      additionalProperties: false
      required: [id, sub_account_id, project_id, design_id, architect_user_id, status, stamp_document_id, license_number, stamped_at, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        sub_account_id: { type: string, format: uuid, nullable: true }
        project_id: { type: string, format: uuid }
        design_id: { type: string, format: uuid, nullable: true }
        architect_user_id: { type: string, format: uuid, nullable: true }
        status: { type: string }
        stamp_document_id: { type: string, format: uuid, nullable: true }
        license_number: { type: string, nullable: true }
        stamped_at: { type: string, format: date-time, nullable: true }
        created_at: { type: string, format: date-time, nullable: true }
        updated_at: { type: string, format: date-time, nullable: true }

    ProjectPermitApplicationSummary:
      type: object
      additionalProperties: false
      required: [id, sub_account_id, customer_id, project_id, jurisdiction_id, permit_type, status, external_reference, submitted_at, window_started_at, window_days, decision_due_at, decided_at, signed_at, signed_by_user_id, signed_document_id, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        sub_account_id: { type: string, format: uuid, nullable: true }
        customer_id: { type: string, format: uuid }
        project_id: { type: string, format: uuid }
        jurisdiction_id: { type: string, format: uuid, nullable: true }
        permit_type: { type: string }
        status: { type: string }
        external_reference: { type: string, nullable: true }
        submitted_at: { type: string, format: date-time, nullable: true }
        window_started_at: { type: string, format: date-time, nullable: true }
        window_days: { type: integer }
        decision_due_at: { type: string, format: date-time, nullable: true }
        decided_at: { type: string, format: date-time, nullable: true }
        signed_at: { type: string, format: date-time, nullable: true }
        signed_by_user_id: { type: string, format: uuid, nullable: true }
        signed_document_id: { type: string, format: uuid, nullable: true }
        created_at: { type: string, format: date-time, nullable: true }
        updated_at: { type: string, format: date-time, nullable: true }

    ProjectPermitSummary:
      type: object
      additionalProperties: false
      required: [id, project_id, permit_application_id, permit_number, issued_at, expires_at, created_at]
      properties:
        id: { type: string, format: uuid }
        project_id: { type: string, format: uuid }
        permit_application_id: { type: string, format: uuid }
        permit_number: { type: string, nullable: true }
        issued_at: { type: string, format: date-time, nullable: true }
        expires_at: { type: string, format: date-time, nullable: true }
        created_at: { type: string, format: date-time, nullable: true }

    ProjectPermitDocumentSummary:
      type: object
      additionalProperties: false
      required: [id, permit_application_id, attachment_id, doc_type, created_at]
      properties:
        id: { type: string, format: uuid }
        permit_application_id: { type: string, format: uuid }
        attachment_id: { type: string, format: uuid }
        doc_type: { type: string }
        created_at: { type: string, format: date-time, nullable: true }

    ProjectDisbursementSummary:
      type: object
      additionalProperties: false
      required: [id, sub_account_id, customer_id, project_id, vendor_id, vendor_name, permit_application_id, status, description, amount_cents, approved_by_user_id, approved_at, paid_at, voided_at, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        sub_account_id: { type: string, format: uuid, nullable: true }
        customer_id: { type: string, format: uuid, nullable: true }
        project_id: { type: string, format: uuid, nullable: true }
        vendor_id: { type: string, format: uuid, nullable: true }
        vendor_name: { type: string, nullable: true }
        permit_application_id: { type: string, format: uuid, nullable: true }
        status: { type: string }
        description: { type: string }
        amount_cents: { type: integer, nullable: true }
        approved_by_user_id: { type: string, format: uuid, nullable: true }
        approved_at: { type: string, format: date-time, nullable: true }
        paid_at: { type: string, format: date-time, nullable: true }
        voided_at: { type: string, format: date-time, nullable: true }
        created_at: { type: string, format: date-time, nullable: true }
        updated_at: { type: string, format: date-time, nullable: true }

    ProjectWorkspacePermissions:
      type: object
      additionalProperties: false
      required:
        - can_read_project
        - can_update_project
        - collaborator_access
        - can_manage_collaborators
        - can_write_project_files
      properties:
        can_read_project: { type: boolean }
        can_update_project: { type: boolean }
        collaborator_access:
          type: string
          enum: [none, view, edit, primary]
        can_manage_collaborators: { type: boolean }
        can_write_project_files: { type: boolean }

    ProjectCollaborator:
      type: object
      additionalProperties: false
      required: [user_id, access, is_primary, assigned_at]
      properties:
        user_id: { type: string, format: uuid }
        access: { type: string, enum: [view, edit] }
        is_primary: { type: boolean }
        role: { type: string, nullable: true }
        full_name: { type: string, nullable: true }
        email: { type: string, nullable: true }
        assigned_at: { type: string, format: date-time }

    ProjectWorkspaceCapabilityState:
      type: string
      enum: [available, read_only, unavailable]

    ProjectWorkspaceCapabilities:
      type: object
      additionalProperties: false
      required:
        - project_summary
        - project_child_reads
        - project_child_mutations
        - project_collaboration_mutations
        - project_note_mutations
        - project_task_mutations
        - project_appointment_mutations
        - project_estimate_mutations
        - project_invoice_mutations
        - project_contract_reads
        - project_contract_mutations
        - project_contracts
        - customer_context
        - property_context
        - lead_context
        - estimates
        - invoices
        - designs
        - tasks
        - activities
        - owner_profile
        - contracts
        - payments
        - service_plans
        - lead_to_build_workflow
        - pipeline_stage_history
        - site_surveys
        - feasibility_studies
        - architectural_stamps
        - permits
        - disbursements
        - deal_economics
        - revenue_allocations
      properties:
        project_summary: { $ref: '#/components/schemas/ProjectWorkspaceCapabilityState' }
        project_child_reads: { $ref: '#/components/schemas/ProjectWorkspaceCapabilityState' }
        project_child_mutations: { $ref: '#/components/schemas/ProjectWorkspaceCapabilityState' }
        project_collaboration_mutations: { $ref: '#/components/schemas/ProjectWorkspaceCapabilityState' }
        project_note_mutations: { $ref: '#/components/schemas/ProjectWorkspaceCapabilityState' }
        project_task_mutations: { $ref: '#/components/schemas/ProjectWorkspaceCapabilityState' }
        project_appointment_mutations: { $ref: '#/components/schemas/ProjectWorkspaceCapabilityState' }
        project_estimate_mutations: { $ref: '#/components/schemas/ProjectWorkspaceCapabilityState' }
        project_invoice_mutations: { $ref: '#/components/schemas/ProjectWorkspaceCapabilityState' }
        project_contract_reads: { $ref: '#/components/schemas/ProjectWorkspaceCapabilityState' }
        project_contract_mutations: { $ref: '#/components/schemas/ProjectWorkspaceCapabilityState' }
        project_contracts: { $ref: '#/components/schemas/ProjectWorkspaceCapabilityState' }
        customer_context: { $ref: '#/components/schemas/ProjectWorkspaceCapabilityState' }
        property_context: { $ref: '#/components/schemas/ProjectWorkspaceCapabilityState' }
        lead_context: { $ref: '#/components/schemas/ProjectWorkspaceCapabilityState' }
        estimates: { $ref: '#/components/schemas/ProjectWorkspaceCapabilityState' }
        invoices: { $ref: '#/components/schemas/ProjectWorkspaceCapabilityState' }
        designs: { $ref: '#/components/schemas/ProjectWorkspaceCapabilityState' }
        tasks: { $ref: '#/components/schemas/ProjectWorkspaceCapabilityState' }
        activities: { $ref: '#/components/schemas/ProjectWorkspaceCapabilityState' }
        owner_profile: { $ref: '#/components/schemas/ProjectWorkspaceCapabilityState' }
        contracts: { $ref: '#/components/schemas/ProjectWorkspaceCapabilityState' }
        payments: { $ref: '#/components/schemas/ProjectWorkspaceCapabilityState' }
        service_plans: { $ref: '#/components/schemas/ProjectWorkspaceCapabilityState' }
        lead_to_build_workflow: { $ref: '#/components/schemas/ProjectWorkspaceCapabilityState' }
        pipeline_stage_history: { $ref: '#/components/schemas/ProjectWorkspaceCapabilityState' }
        site_surveys: { $ref: '#/components/schemas/ProjectWorkspaceCapabilityState' }
        feasibility_studies: { $ref: '#/components/schemas/ProjectWorkspaceCapabilityState' }
        architectural_stamps: { $ref: '#/components/schemas/ProjectWorkspaceCapabilityState' }
        permits: { $ref: '#/components/schemas/ProjectWorkspaceCapabilityState' }
        disbursements: { $ref: '#/components/schemas/ProjectWorkspaceCapabilityState' }
        deal_economics: { $ref: '#/components/schemas/ProjectWorkspaceCapabilityState' }
        revenue_allocations: { $ref: '#/components/schemas/ProjectWorkspaceCapabilityState' }

    ProjectWorkspace:
      type: object
      required: [project, customer, property, primary_contact, lead, owner, estimates, invoices, contracts, designs, tasks, notes, activities, appointments, attachments, tags, service_plans, stage_history, site_surveys, survey_reports, feasibility_studies, architectural_stamps, permit_applications, permits, permit_documents, disbursements, permissions, capabilities, unavailable]
      additionalProperties: false
      properties:
        project: { $ref: '#/components/schemas/Project' }
        customer:
          oneOf:
            - $ref: '#/components/schemas/ProjectWorkspaceCustomer'
            - type: 'null'
        property:
          oneOf:
            - $ref: '#/components/schemas/ProjectWorkspaceProperty'
            - type: 'null'
        primary_contact:
          oneOf:
            - $ref: '#/components/schemas/ProjectWorkspacePrimaryContact'
            - type: 'null'
        lead:
          oneOf:
            - $ref: '#/components/schemas/ProjectWorkspaceLead'
            - type: 'null'
        owner:
          oneOf:
            - $ref: '#/components/schemas/ProjectWorkspaceOwner'
            - type: 'null'
        estimates:
          type: array
          items: { $ref: '#/components/schemas/ProjectEstimate' }
        invoices:
          type: array
          items: { $ref: '#/components/schemas/ProjectInvoice' }
        contracts:
          type: array
          items: { $ref: '#/components/schemas/ProjectContract' }
        designs:
          type: array
          items: { $ref: '#/components/schemas/ProjectDesignSummary' }
        tasks:
          type: array
          items: { $ref: '#/components/schemas/ProjectTask' }
        notes:
          type: array
          items: { $ref: '#/components/schemas/ProjectNote' }
        activities:
          type: array
          items: { $ref: '#/components/schemas/ProjectActivitySummary' }
        appointments:
          type: array
          items: { $ref: '#/components/schemas/ProjectAppointment' }
        attachments:
          type: array
          items: { $ref: '#/components/schemas/ProjectAttachmentSummary' }
        tags:
          type: array
          items: { $ref: '#/components/schemas/ProjectTagSummary' }
        service_plans:
          type: array
          items: { $ref: '#/components/schemas/ProjectServicePlanSummary' }
        stage_history:
          type: array
          items: { $ref: '#/components/schemas/ProjectStageHistoryEntry' }
        site_surveys:
          type: array
          items: { $ref: '#/components/schemas/ProjectSiteSurveySummary' }
        survey_reports:
          type: array
          items: { $ref: '#/components/schemas/ProjectSurveyReportSummary' }
        feasibility_studies:
          type: array
          items: { $ref: '#/components/schemas/ProjectFeasibilitySummary' }
        architectural_stamps:
          type: array
          items: { $ref: '#/components/schemas/ProjectArchitecturalStampSummary' }
        permit_applications:
          type: array
          items: { $ref: '#/components/schemas/ProjectPermitApplicationSummary' }
        permits:
          type: array
          items: { $ref: '#/components/schemas/ProjectPermitSummary' }
        permit_documents:
          type: array
          items: { $ref: '#/components/schemas/ProjectPermitDocumentSummary' }
        disbursements:
          type: array
          items: { $ref: '#/components/schemas/ProjectDisbursementSummary' }
        permissions: { $ref: '#/components/schemas/ProjectWorkspacePermissions' }
        capabilities: { $ref: '#/components/schemas/ProjectWorkspaceCapabilities' }
        unavailable:
          type: object
          additionalProperties: { type: string }

    Design:
      type: object
      required: [id, account_id, project_id, service_type, version_number, status]
      properties:
        id: { type: string, pattern: '^des_' }
        account_id: { type: string, format: uuid }
        project_id: { type: string, format: uuid }
        service_type:
          type: string
          enum: [solar, hvac, roofing, remodeling]
        version_number: { type: integer }
        status:
          type: string
          enum: [draft, presented, accepted, superseded, archived]
        configuration_json: { type: object }
        derived_outputs_json: { type: object }
        created_at: { type: string, format: date-time }

    PricebookImport:
      type: object
      required: [id, account_id, status, started_at]
      properties:
        id: { type: string, format: uuid }
        account_id: { type: string, format: uuid }
        source:
          type: string
          enum: [jobnimbus, csv, json, xlsx]
        filename: { type: string, nullable: true }
        status:
          type: string
          enum: [uploaded, mapping, confirmed, dry_run, committed, failed]
        started_at: { type: string, format: date-time }
        committed_at: { type: string, format: date-time, nullable: true }
        dry_run_summary:
          allOf:
            - $ref: '#/components/schemas/PricebookImportDryRunSummary'
          nullable: true
        upload:
          type: object
          description: Presigned workbook upload (xlsx start response only).
          nullable: true
          properties:
            url: { type: string }
            expires_at: { type: string, format: date-time }
        units:
          type: array
          description: Detected table regions (xlsx imports only).
          items: { $ref: '#/components/schemas/PricebookImportUnit' }
        workbook_meta:
          type: object
          nullable: true
          additionalProperties: true
        mappings:
          type: array
          items: { $ref: '#/components/schemas/PricebookImportMapping' }

    PricebookImportUnit:
      type: object
      required: [id, sheet_index, sheet_name, region, detected_shape, status]
      properties:
        id: { type: string, format: uuid }
        sheet_index: { type: integer, minimum: 0 }
        sheet_name: { type: string }
        region:
          type: object
          required: [first_row, last_row, first_col, last_col]
          properties:
            first_row: { type: integer, minimum: 1 }
            last_row: { type: integer, minimum: 1 }
            first_col: { type: integer, minimum: 1 }
            last_col: { type: integer, minimum: 1 }
        detected_shape:
          type: string
          enum: [flat_items, pricing_matrix, sections_list, ignore]
        ai_confidence: { type: number, nullable: true }
        ai_reasoning: { type: string, nullable: true }
        interpretation:
          type: object
          additionalProperties: true
          description: Versioned interpretation doc (zod-validated server-side).
        status:
          type: string
          enum: [detected, confirmed, ignored, failed]
        human_confirmed_by: { type: string, format: uuid, nullable: true }
        human_confirmed_at: { type: string, format: date-time, nullable: true }
        row_count: { type: integer, minimum: 0 }

    PricebookImportDryRunSummary:
      type: object
      required: [rowsAnalyzed, willInsert, willUpdate, willSkip, warnings]
      properties:
        rowsAnalyzed: { type: integer, minimum: 0 }
        willInsert: { type: integer, minimum: 0 }
        willUpdate: { type: integer, minimum: 0 }
        willSkip: { type: integer, minimum: 0 }
        warnings:
          type: array
          items: { type: string }

    PricebookImportMapping:
      type: object
      properties:
        source_column: { type: string }
        target_field: { type: string, nullable: true }
        ai_suggested_field: { type: string, nullable: true }
        ai_confidence: { type: number, nullable: true }
        ai_reasoning: { type: string, nullable: true }
        human_confirmed_by: { type: string, format: uuid, nullable: true }
        human_confirmed_at: { type: string, format: date-time, nullable: true }

    Contract:
      type: object
      required: [id, project_id, status, version_number]
      properties:
        id: { type: string, pattern: '^ctr_' }
        project_id: { type: string, format: uuid }
        status:
          type: string
          enum: [draft, sent, partially_signed, fully_signed, voided, superseded]
        version_number: { type: integer }
        total_amount_cents: { type: integer, nullable: true }
        created_at: { type: string, format: date-time }

    DataExport:
      type: object
      required:
        - id
        - account_id
        - lane
        - status
        - schema_version
        - account_state_at_request
        - created_at
      properties:
        id: { type: string, format: uuid }
        account_id: { type: string, format: uuid }
        lane:
          type: string
          enum: [priority, standard, free]
          description: |
            Derived from the requesting account's billing tier.
            enterprise → priority; pro/standard → standard; free → free.
        status:
          type: string
          enum: [queued, running, succeeded, failed]
        schema_version:
          type: string
          description: Bundle layout version. Bumped on layout changes.
        account_state_at_request:
          type: string
          enum: [in_life, terminated]
          description: |
            Captured at request time. Drives signed-URL TTL (L-37):
            in_life → 24h, terminated → 7d. Mid-job state changes do NOT shift
            the URL window.
        signed_url:
          type: string
          format: uri
          nullable: true
          description: GCS v4 signed URL. Only present once status=succeeded.
        signed_url_expires_at:
          type: string
          format: date-time
          nullable: true
        created_at: { type: string, format: date-time }

    # POR-44 (E11 Lead Inbox) — CSV cold-lead import
    LeadImportBatch:
      type: object
      required: [id, status, row_count, inserted_count, conflict_count, noop_count, failed_count, created_at]
      properties:
        id: { type: string, format: uuid }
        status:
          type: string
          enum: [pending, processing, completed, failed]
        row_count: { type: integer, minimum: 0 }
        inserted_count: { type: integer, minimum: 0 }
        conflict_count: { type: integer, minimum: 0 }
        noop_count: { type: integer, minimum: 0 }
        failed_count: { type: integer, minimum: 0 }
        created_at: { type: string, format: date-time }
        started_at: { type: string, format: date-time, nullable: true }
        completed_at: { type: string, format: date-time, nullable: true }

    LeadImportConflict:
      type: object
      required: [id, row_number, reason, candidate_lead_ids, raw_row, created_at]
      properties:
        id: { type: string, format: uuid }
        row_number: { type: integer, minimum: 1 }
        reason:
          type: string
          enum: [exact_match_existing, multi_match, pii_detected]
        candidate_lead_ids:
          type: array
          items: { type: string, format: uuid }
        raw_row: { type: object, additionalProperties: true }
        pii_report:
          type: object
          nullable: true
          additionalProperties: true
          description: Structured PII-discovery scan metadata. Contains field names and categories, never raw matched values.
        resolved_action:
          type: string
          nullable: true
          enum: [skip, create_new, merge, no_op]
        created_at: { type: string, format: date-time }

    IdempotencyKeyConflict:
      type: object
      required: [code, error, original_batch_id]
      properties:
        code: { type: string, enum: [idempotency_key_conflict] }
        error: { type: string }
        original_batch_id: { type: string, format: uuid }

    LeadIntakePayload:
      type: object
      properties:
        contact_name: { type: string }
        contact_email: { type: string, format: email }
        contact_phone: { type: string }
        raw_address: { type: object, additionalProperties: true }
        sub_account_id: { type: [string, 'null'], format: uuid }
        assigned_user_id: { type: [string, 'null'], format: uuid }
        source_external_id: { type: [string, 'null'] }
        status:
          type: string
          enum: [new, contacted, qualified, appointment_set, appointment_held, proposal_sent, closed_lost, no_show]
        description: { type: [string, 'null'] }
        value_cents: { type: [integer, 'null'] }
        source_payload: {}
      additionalProperties: true

    LeadSource:
      type: object
      required:
        - id
        - account_id
        - name
        - source_type
        - status
        - source_key
        - default_status
        - delivery_summary
        - inbound_path
        - created_at
        - updated_at
      properties:
        id: { type: string, format: uuid }
        account_id: { type: string, format: uuid }
        sub_account_id: { type: [string, 'null'], format: uuid }
        name: { type: string }
        source_type:
          type: string
          enum: [manual, web_form, csv_import, api, lead_buy, partner_webhook]
        status:
          type: string
          enum: [active, paused, revoked]
        source_key: { type: string }
        default_assigned_user_id: { type: [string, 'null'], format: uuid }
        default_team_id: { type: [string, 'null'], format: uuid }
        default_status:
          type: string
          enum: [new, contacted, qualified, appointment_set, appointment_held, proposal_sent, closed_lost, no_show]
        dedupe_policy_json: { type: object, additionalProperties: true }
        field_mapping_json: { type: object, additionalProperties: true }
        created_by_user_id: { type: [string, 'null'], format: uuid }
        last_seen_at: { type: [string, 'null'], format: date-time }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }
        delivery_summary:
          type: object
          required: [total, accepted, duplicate, rejected, conflict, failed]
          properties:
            total: { type: integer }
            accepted: { type: integer }
            duplicate: { type: integer }
            rejected: { type: integer }
            conflict: { type: integer }
            failed: { type: integer }
            last_delivery_at: { type: [string, 'null'], format: date-time }
        inbound_path: { type: string }
        inbound_url: { type: string, format: uri }
        secret:
          type: string
          description: Returned only on source creation or secret rotation.

    LeadSourceDedupePolicy:
      type: object
      description: |
        Duplicate matching for leads this source delivers. A missing key means `off`. `flag` records other
        open leads in the same account that share the value as possible duplicates for staff to review; it
        never links people and never changes who a lead belongs to. Email matching is not configurable.
        Unknown keys are accepted and kept.
      properties:
        version: { type: integer, enum: [1] }
        phone: { type: string, enum: [flag, 'off'] }
        company_domain: { type: string, enum: [flag, 'off'] }
      additionalProperties: true

    LeadDuplicateCandidate:
      type: object
      required: [id, reason, status, created_at, other_lead]
      properties:
        id: { type: string, format: uuid }
        reason: { type: string, enum: [phone, company_domain] }
        status: { type: string, enum: [open, dismissed] }
        created_at: { type: string, format: date-time }
        other_lead:
          type: object
          required: [id, status]
          properties:
            id: { type: string, format: uuid }
            status: { type: string }
            given_name: { type: [string, 'null'] }
            family_name: { type: [string, 'null'] }
            display_name: { type: [string, 'null'] }
            company_name: { type: [string, 'null'] }

    LeadIntakeResult:
      type: object
      required: [outcome, deliveryId]
      properties:
        outcome:
          type: string
          enum: [accepted, duplicate, dry_run, rejected, failed]
        leadId: { type: [string, 'null'], format: uuid }
        customerId: { type: [string, 'null'], format: uuid }
        deliveryId: { type: [string, 'null'], format: uuid }
        idempotentReplay: { type: boolean }
        code: { type: string }
        message: { type: string }

    BulkLeadJob:
      type: object
      required: [id, account_id, status, total_count, accepted_count, duplicate_count, rejected_count, failed_count, created_at]
      properties:
        id: { type: string, format: uuid }
        account_id: { type: string, format: uuid }
        idempotency_key: { type: [string, 'null'] }
        request_fingerprint: { type: string }
        status:
          type: string
          enum: [pending, processing, completed, failed]
        total_count: { type: integer }
        accepted_count: { type: integer }
        duplicate_count: { type: integer }
        rejected_count: { type: integer }
        failed_count: { type: integer }
        created_by_user_id: { type: [string, 'null'], format: uuid }
        created_at: { type: string, format: date-time }
        completed_at: { type: [string, 'null'], format: date-time }

    BulkLeadJobItem:
      type: object
      required: [id, job_id, row_number, status, created_at]
      properties:
        id: { type: string, format: uuid }
        job_id: { type: string, format: uuid }
        row_number: { type: integer }
        lead_source_id: { type: [string, 'null'], format: uuid }
        source_external_id: { type: [string, 'null'] }
        status:
          type: string
          enum: [accepted, duplicate, rejected, failed]
        lead_id: { type: [string, 'null'], format: uuid }
        error_code: { type: [string, 'null'] }
        error_message: { type: [string, 'null'] }
        raw_payload_json: {}
        result_json: {}
        created_at: { type: string, format: date-time }

    ImpersonationElevationGrant:
      type: object
      additionalProperties: false
      required: [method, routeId, scopes]
      properties:
        method: { type: string, enum: [POST, PUT, PATCH, DELETE] }
        routeId:
          type: string
          minLength: 5
          maxLength: 512
          pattern: '^/v1/(?:[a-z0-9]+(?:[._-][a-z0-9]+)*|:[A-Za-z_][A-Za-z0-9_]*)(?:/(?:[a-z0-9]+(?:[._-][a-z0-9]+)*|:[A-Za-z_][A-Za-z0-9_]*))*$'
        scopes:
          type: array
          minItems: 1
          maxItems: 64
          uniqueItems: true
          x-portrex-lexicographically-sorted: true
          items:
            type: string
            minLength: 3
            maxLength: 128
            pattern: '^[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)+$'
    ImpersonationElevationFactor:
      type: object
      additionalProperties: false
      required: [factor]
      properties:
        factor: { type: string, enum: [webauthn, totp] }
    ImpersonationElevationRequest:
      type: object
      additionalProperties: false
      required: [impersonationSessionId, reason, ticketId, grants, factor]
      properties:
        impersonationSessionId: { type: string, format: uuid }
        reason:
          type: string
          minLength: 10
          maxLength: 500
          pattern: '^\S(?:[\s\S]*\S)?$'
          x-portrex-trim-before-validation: true
        ticketId:
          type: string
          minLength: 1
          maxLength: 64
          pattern: '^[A-Za-z0-9][A-Za-z0-9._:/-]*$'
        grants:
          type: array
          minItems: 1
          maxItems: 32
          items: { $ref: '#/components/schemas/ImpersonationElevationGrant' }
        factor: { type: string, enum: [webauthn, totp] }
    ImpersonationElevationStatus:
      oneOf:
        - type: object
          additionalProperties: false
          required: [id, status, requestedAt, requestExpiresAt]
          properties:
            id: { type: string, format: uuid }
            status: { const: pending }
            requestedAt: { type: string, format: date-time }
            requestExpiresAt: { type: string, format: date-time }
        - type: object
          additionalProperties: false
          required: [id, status, requestedAt, approvedAt, requestExpiresAt]
          properties:
            id: { type: string, format: uuid }
            status: { const: approved }
            requestedAt: { type: string, format: date-time }
            approvedAt: { type: string, format: date-time }
            requestExpiresAt: { type: string, format: date-time }
        - type: object
          additionalProperties: false
          required: [id, status, requestedAt, approvedAt, activatedAt, expiresAt]
          properties:
            id: { type: string, format: uuid }
            status: { const: active }
            requestedAt: { type: string, format: date-time }
            approvedAt: { type: string, format: date-time }
            activatedAt: { type: string, format: date-time }
            expiresAt: { type: string, format: date-time }
        - type: object
          additionalProperties: false
          required: [id, status, requestedAt, revokedAt]
          properties:
            id: { type: string, format: uuid }
            status: { const: revoked }
            requestedAt: { type: string, format: date-time }
            revokedAt: { type: string, format: date-time }
        - type: object
          additionalProperties: false
          required: [id, status, requestedAt, expiredAt]
          properties:
            id: { type: string, format: uuid }
            status: { const: expired }
            requestedAt: { type: string, format: date-time }
            expiredAt: { type: string, format: date-time }
        - type: object
          additionalProperties: false
          required: [id, status, requestedAt, deniedAt]
          properties:
            id: { type: string, format: uuid }
            status: { const: denied }
            requestedAt: { type: string, format: date-time }
            deniedAt: { type: string, format: date-time }
    ImpersonationElevationStatusEnvelope:
      type: object
      additionalProperties: false
      required: [data]
      properties:
        data: { $ref: '#/components/schemas/ImpersonationElevationStatus' }
    ImpersonationElevationTenantDetail:
      oneOf:
        - type: object
          additionalProperties: false
          required: [id, status, requestedAt, requestExpiresAt, requestingStaffName, reason, ticketId, grants]
          properties:
            requestingStaffName: { type: string, minLength: 1, maxLength: 120 }
            reason: { type: string, minLength: 10, maxLength: 500 }
            ticketId: { type: string, minLength: 1, maxLength: 64 }
            grants: { type: array, minItems: 1, maxItems: 32, items: { $ref: '#/components/schemas/ImpersonationElevationGrant' } }
            id: { type: string, format: uuid }
            status: { const: pending }
            requestedAt: { type: string, format: date-time }
            requestExpiresAt: { type: string, format: date-time }
        - type: object
          additionalProperties: false
          required: [id, status, requestedAt, approvedAt, requestExpiresAt, requestingStaffName, reason, ticketId, grants]
          properties:
            requestingStaffName: { type: string, minLength: 1, maxLength: 120 }
            reason: { type: string, minLength: 10, maxLength: 500 }
            ticketId: { type: string, minLength: 1, maxLength: 64 }
            grants: { type: array, minItems: 1, maxItems: 32, items: { $ref: '#/components/schemas/ImpersonationElevationGrant' } }
            id: { type: string, format: uuid }
            status: { const: approved }
            requestedAt: { type: string, format: date-time }
            requestExpiresAt: { type: string, format: date-time }
            approvedAt: { type: string, format: date-time }
        - type: object
          additionalProperties: false
          required: [id, status, requestedAt, approvedAt, activatedAt, expiresAt, requestingStaffName, reason, ticketId, grants]
          properties:
            requestingStaffName: { type: string, minLength: 1, maxLength: 120 }
            reason: { type: string, minLength: 10, maxLength: 500 }
            ticketId: { type: string, minLength: 1, maxLength: 64 }
            grants: { type: array, minItems: 1, maxItems: 32, items: { $ref: '#/components/schemas/ImpersonationElevationGrant' } }
            id: { type: string, format: uuid }
            status: { const: active }
            requestedAt: { type: string, format: date-time }
            approvedAt: { type: string, format: date-time }
            activatedAt: { type: string, format: date-time }
            expiresAt: { type: string, format: date-time }
        - type: object
          additionalProperties: false
          required: [id, status, requestedAt, revokedAt, requestingStaffName, reason, ticketId, grants]
          properties:
            requestingStaffName: { type: string, minLength: 1, maxLength: 120 }
            reason: { type: string, minLength: 10, maxLength: 500 }
            ticketId: { type: string, minLength: 1, maxLength: 64 }
            grants: { type: array, minItems: 1, maxItems: 32, items: { $ref: '#/components/schemas/ImpersonationElevationGrant' } }
            id: { type: string, format: uuid }
            status: { const: revoked }
            requestedAt: { type: string, format: date-time }
            revokedAt: { type: string, format: date-time }
        - type: object
          additionalProperties: false
          required: [id, status, requestedAt, expiredAt, requestingStaffName, reason, ticketId, grants]
          properties:
            requestingStaffName: { type: string, minLength: 1, maxLength: 120 }
            reason: { type: string, minLength: 10, maxLength: 500 }
            ticketId: { type: string, minLength: 1, maxLength: 64 }
            grants: { type: array, minItems: 1, maxItems: 32, items: { $ref: '#/components/schemas/ImpersonationElevationGrant' } }
            id: { type: string, format: uuid }
            status: { const: expired }
            requestedAt: { type: string, format: date-time }
            expiredAt: { type: string, format: date-time }
        - type: object
          additionalProperties: false
          required: [id, status, requestedAt, deniedAt, requestingStaffName, reason, ticketId, grants]
          properties:
            requestingStaffName: { type: string, minLength: 1, maxLength: 120 }
            reason: { type: string, minLength: 10, maxLength: 500 }
            ticketId: { type: string, minLength: 1, maxLength: 64 }
            grants: { type: array, minItems: 1, maxItems: 32, items: { $ref: '#/components/schemas/ImpersonationElevationGrant' } }
            id: { type: string, format: uuid }
            status: { const: denied }
            requestedAt: { type: string, format: date-time }
            deniedAt: { type: string, format: date-time }

    MarketingContactRequest:
      type: object
      additionalProperties: false
      required:
        - topic
        - message
        - name
        - email
        - preferredContact
        - sourcePath
        - website
        - turnstileToken
      properties:
        topic:
          type: string
          enum: [sales_representative, general_inquiry, account_issue, billing, technical_support, feedback]
        message: { type: string, minLength: 10, maxLength: 4000 }
        name: { type: string, minLength: 1, maxLength: 120 }
        email: { type: string, format: email, maxLength: 254 }
        company: { type: string, maxLength: 160 }
        phone: { type: string, maxLength: 32 }
        preferredContact: { type: string, enum: [email, phone, either] }
        preferredTime: { type: string, maxLength: 120 }
        sourcePath: { type: string, minLength: 1, maxLength: 512 }
        utmSource: { type: string, maxLength: 100 }
        utmMedium: { type: string, maxLength: 100 }
        utmCampaign: { type: string, maxLength: 100 }
        locale: { type: string, maxLength: 64 }
        timeZone: { type: string, maxLength: 64 }
        website:
          type: string
          maxLength: 512
          description: Honeypot field. Human clients must leave it empty.
        turnstileToken: { type: string, maxLength: 4096 }

    MarketingContactAcceptedResponse:
      type: object
      additionalProperties: false
      required: [data]
      properties:
        data:
          type: object
          additionalProperties: false
          required: [contactRequestId, reference, status, receivedAt]
          properties:
            contactRequestId: { type: string, format: uuid }
            reference: { type: string, minLength: 1 }
            status: { type: string, const: received }
            receivedAt: { type: string, format: date-time }

    PartnerApplicationRequest:
      type: object
      additionalProperties: false
      required:
        - kind
        - fullName
        - email
        - role
        - contractorCount
        - agreeTerms
        - sourcePath
        - website
        - turnstileToken
      properties:
        kind: { type: string, const: apply }
        fullName: { type: string, minLength: 1, maxLength: 120 }
        email: { type: string, format: email, maxLength: 320 }
        phone: { type: string, maxLength: 32 }
        company: { type: string, maxLength: 160 }
        role:
          type: string
          enum:
            - manufacturer_distributor_rep
            - consultant_coach
            - association_buying_group
            - software_marketing_vendor
            - accountant_bookkeeper
            - other
        contractorCount: { type: string, enum: ['1-5', '6-20', '21-100', '100+'] }
        howDidYouHear: { type: string, maxLength: 200 }
        notes: { type: string, maxLength: 2000 }
        agreeTerms: { type: boolean, const: true }
        termsVersion:
          type: string
          enum: [affiliate-apply-v1, affiliate-apply-v2, affiliate-apply-v3]
          description: Version of the application acknowledgment shown in the rendered form. Omitted legacy forms retain the affiliate-apply-v1 database default. This is not an agreement signature.
        sourcePath: { type: string, minLength: 1, maxLength: 512 }
        utmSource: { type: string, maxLength: 100 }
        utmMedium: { type: string, maxLength: 100 }
        utmCampaign: { type: string, maxLength: 100 }
        src: { type: string, maxLength: 100 }
        pageUrl: { type: string, maxLength: 512 }
        website:
          type: string
          maxLength: 512
          description: Honeypot field. Human clients must leave it empty.
        turnstileToken: { type: string, maxLength: 4096 }

    PartnerReferralRequest:
      type: object
      additionalProperties: false
      required:
        - kind
        - partnerName
        - partnerEmail
        - prospectCompany
        - prospectContactName
        - prospectContactEmail
        - trades
        - approxUsers
        - relationship
        - consent
        - nextStep
        - sourcePath
        - website
        - turnstileToken
      properties:
        kind: { type: string, const: refer }
        partnerName: { type: string, minLength: 1, maxLength: 120 }
        partnerEmail: { type: string, format: email, maxLength: 320 }
        partnerCode: { type: string, maxLength: 40 }
        prospectCompany: { type: string, minLength: 1, maxLength: 160 }
        prospectWebsite: { type: string, maxLength: 200 }
        prospectAddress:
          type: string
          maxLength: 300
          description: Optional prospect address as free text. Trimmed and normalized to NFC; blank values are omitted. No autocomplete selection is required.
        prospectContactName:
          type: string
          minLength: 1
          maxLength: 121
          description: Full contact name. When first and last names are supplied, must match their normalized values joined by one space after collapsing whitespace.
        prospectContactFirstName:
          type: string
          maxLength: 60
          description: Optional first name, trimmed and normalized to NFC with internal whitespace collapsed. Must be supplied with last name; blank values are omitted.
        prospectContactLastName:
          type: string
          maxLength: 60
          description: Optional last name, trimmed and normalized to NFC with internal whitespace collapsed. Must be supplied with first name; blank values are omitted.
        prospectContactEmail: { type: string, format: email, maxLength: 320 }
        prospectContactPhone: { type: string, maxLength: 32 }
        trades:
          type: array
          minItems: 1
          maxItems: 5
          items:
            type: string
            enum: [hvac, plumbing, electrical, roofing, other]
        approxUsers: { type: string, enum: ['<10', '10-19', '20-49', '50+'] }
        relationship: { type: string, minLength: 1, maxLength: 2000 }
        consent: { type: boolean, const: true }
        nextStep: { type: string, enum: [intro_email, joint_call, portrex_outreach] }
        sourcePath: { type: string, minLength: 1, maxLength: 512 }
        utmSource: { type: string, maxLength: 100 }
        utmMedium: { type: string, maxLength: 100 }
        utmCampaign: { type: string, maxLength: 100 }
        src: { type: string, maxLength: 100 }
        pageUrl: { type: string, maxLength: 512 }
        website:
          type: string
          maxLength: 512
          description: Honeypot field. Human clients must leave it empty.
        turnstileToken: { type: string, maxLength: 4096 }

    PartnerRequest:
      oneOf:
        - $ref: '#/components/schemas/PartnerApplicationRequest'
        - $ref: '#/components/schemas/PartnerReferralRequest'
      discriminator:
        propertyName: kind
        mapping:
          apply: '#/components/schemas/PartnerApplicationRequest'
          refer: '#/components/schemas/PartnerReferralRequest'

    PartnerRequestAcceptedResponse:
      type: object
      additionalProperties: false
      required: [data]
      properties:
        data:
          type: object
          additionalProperties: false
          required: [partnerRequestId, kind, status, receivedAt]
          properties:
            partnerRequestId: { type: string, format: uuid }
            kind: { type: string, enum: [apply, refer] }
            status: { type: string, const: received }
            receivedAt: { type: string, format: date-time }

    StaffMarketingContactTask:
      type: object
      additionalProperties: false
      required:
        - id
        - reference
        - topic
        - title
        - status
        - priority
        - dueAt
        - receivedAt
        - contact
        - preferences
        - message
        - source
        - clientContext
      properties:
        id: { type: string, format: uuid }
        reference: { type: string, minLength: 1 }
        topic:
          type: string
          enum: [sales_representative, general_inquiry, account_issue, billing, technical_support, feedback]
        title: { type: string, minLength: 1 }
        status: { type: string, enum: [todo, doing, done] }
        priority: { type: string, enum: [normal, high] }
        dueAt: { type: string, format: date-time }
        receivedAt: { type: string, format: date-time }
        contact:
          type: object
          additionalProperties: false
          required: [name, email, company, phone]
          properties:
            name: { type: string }
            email: { type: string, format: email }
            company: { type: [string, 'null'] }
            phone: { type: [string, 'null'] }
        preferences:
          type: object
          additionalProperties: false
          required: [method, time]
          properties:
            method: { type: string, enum: [email, phone, either] }
            time: { type: [string, 'null'] }
        message: { type: string }
        source:
          type: object
          additionalProperties: false
          required: [path, utmSource, utmMedium, utmCampaign]
          properties:
            path: { type: string }
            utmSource: { type: [string, 'null'] }
            utmMedium: { type: [string, 'null'] }
            utmCampaign: { type: [string, 'null'] }
        clientContext:
          type: object
          additionalProperties: false
          required: [locale, timeZone]
          properties:
            locale: { type: [string, 'null'] }
            timeZone: { type: [string, 'null'] }

    Contractor:
      type: object
      description: |
        Third-party trade partner (not a Portrex tenant). `sub_account_ids`
        empty means the contractor serves the main company (visible to every
        branch); one or more ids means the contractor serves exactly those
        branches. Always sorted.
      required: [id, account_id, sub_account_ids, company_name, contact_name, address, phone, email, archived_at, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        account_id: { type: string, format: uuid }
        sub_account_ids:
          type: array
          items: { type: string, format: uuid }
        company_name: { type: string }
        contact_name: { type: [string, 'null'] }
        address: { type: [string, 'null'] }
        phone: { type: [string, 'null'] }
        email: { type: [string, 'null'] }
        archived_at: { type: [string, 'null'], format: date-time }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    ContractorEffectiveContact:
      type: object
      description: License contact fields with NULL overrides falling back to the parent contractor's fields.
      required: [company_name, address, phone, email]
      properties:
        company_name: { type: string }
        address: { type: [string, 'null'] }
        phone: { type: [string, 'null'] }
        email: { type: [string, 'null'] }

    ContractorLicense:
      type: object
      required: [id, contractor_id, service_line, state, license_number, is_valid, expires_on, company_name, address, phone, email, status, effective, created_at, updated_at]
      properties:
        id: { type: string, format: uuid }
        contractor_id: { type: string, format: uuid }
        service_line: { type: string, enum: [ADU, HVAC, Roofing, Renovation, Generac] }
        state: { type: string, description: Two-letter US state code. }
        license_number: { type: string }
        is_valid: { type: boolean }
        expires_on: { type: string, format: date }
        company_name: { type: [string, 'null'], description: 'Override; NULL inherits the contractor value.' }
        address: { type: [string, 'null'] }
        phone: { type: [string, 'null'] }
        email: { type: [string, 'null'] }
        status:
          type: string
          enum: [valid, expiring_soon, expired, invalid]
          description: |
            Derived: `invalid` if not is_valid; `expired` if past expires_on;
            `expiring_soon` within 30 days; else `valid`.
        effective: { $ref: '#/components/schemas/ContractorEffectiveContact' }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    ContractorDetail:
      allOf:
        - $ref: '#/components/schemas/Contractor'
        - type: object
          required: [licenses]
          properties:
            licenses:
              type: array
              items: { $ref: '#/components/schemas/ContractorLicense' }

    ContractorPage:
      type: object
      required: [data, next_cursor]
      properties:
        data:
          type: array
          items: { $ref: '#/components/schemas/ContractorDetail' }
        next_cursor: { type: [string, 'null'] }
        total: { type: [integer, 'null'] }

    ContractorCreateBody:
      type: object
      required: [company_name]
      additionalProperties: false
      properties:
        company_name: { type: string, minLength: 1, maxLength: 200 }
        sub_account_ids:
          type: array
          items: { type: string, format: uuid }
          maxItems: 50
          description: 'Absent/[] = main company; otherwise serves exactly these branches (deduped).'
        contact_name: { type: [string, 'null'], maxLength: 200 }
        address: { type: [string, 'null'], maxLength: 500 }
        phone: { type: [string, 'null'] }
        email: { type: [string, 'null'] }

    ContractorPatchBody:
      type: object
      description: Partial update; at least one field required. A present `sub_account_ids` replaces the whole set.
      additionalProperties: false
      minProperties: 1
      properties:
        company_name: { type: string, minLength: 1, maxLength: 200 }
        sub_account_ids:
          type: array
          items: { type: string, format: uuid }
          maxItems: 50
        contact_name: { type: [string, 'null'], maxLength: 200 }
        address: { type: [string, 'null'], maxLength: 500 }
        phone: { type: [string, 'null'] }
        email: { type: [string, 'null'] }

    ContractorLicenseCreateBody:
      type: object
      required: [service_line, state, license_number, is_valid, expires_on]
      additionalProperties: false
      properties:
        service_line: { type: string, enum: [ADU, HVAC, Roofing, Renovation, Generac] }
        state: { type: string, description: Two-letter US state code. }
        license_number: { type: string, minLength: 1, maxLength: 120 }
        is_valid: { type: boolean }
        expires_on: { type: string, format: date }
        company_name: { type: [string, 'null'], maxLength: 200 }
        address: { type: [string, 'null'], maxLength: 500 }
        phone: { type: [string, 'null'] }
        email: { type: [string, 'null'] }

    ContractorLicensePatchBody:
      type: object
      description: Partial update; at least one field required.
      additionalProperties: false
      minProperties: 1
      properties:
        service_line: { type: string, enum: [ADU, HVAC, Roofing, Renovation, Generac] }
        state: { type: string, description: Two-letter US state code. }
        license_number: { type: string, minLength: 1, maxLength: 120 }
        is_valid: { type: boolean }
        expires_on: { type: string, format: date }
        company_name: { type: [string, 'null'], maxLength: 200 }
        address: { type: [string, 'null'], maxLength: 500 }
        phone: { type: [string, 'null'] }
        email: { type: [string, 'null'] }

    ContractorError:
      type: object
      required: [error, message, request_id]
      properties:
        error:
          type: string
          description: |
            Machine-readable error code, e.g. `not_found`, `branch_scope`
            (403 — target sub-account outside the caller's seat),
            `contractor_archived` / `already_archived` / `not_archived` (409),
            `invalid_sub_account` (400 — sub_account_id not in this tenant).
        message: { type: string }
        request_id: { type: string }
        details: {}

    ShowroomQuoteHistoryEditorLabel:
      description: Who changed a copy or left unsaved changes. Full name only, never an email; `unknown` when no name is on file.
      oneOf:
        - type: object
          additionalProperties: false
          required: [kind]
          properties:
            kind: { type: string, enum: [you] }
        - type: object
          additionalProperties: false
          required: [kind, name]
          properties:
            kind: { type: string, enum: [person] }
            name: { type: string, minLength: 1 }
        - type: object
          additionalProperties: false
          required: [kind]
          properties:
            kind: { type: string, enum: [unknown] }

    ShowroomQuoteHistoryCopy:
      type: object
      additionalProperties: false
      required: [id, estimate_number, version_number, status, total_cents, created_at, updated_at, is_current, changed_by]
      properties:
        id: { type: string, format: uuid }
        estimate_number: { type: string }
        version_number: { type: [integer, 'null'] }
        status: { type: string, enum: [draft, sent, viewed, accepted, declined, expired] }
        total_cents: { type: [integer, 'null'] }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }
        is_current: { type: boolean }
        changed_by:
          description: Null when no editor was recorded for this copy.
          oneOf:
            - $ref: '#/components/schemas/ShowroomQuoteHistoryEditorLabel'
            - type: 'null'

    ShowroomQuoteHistoryUnsaved:
      type: object
      additionalProperties: false
      required: [recovery_id, base_estimate_id, created_at, expires_at, total_cents, line_count, by, can_put_back]
      properties:
        recovery_id: { type: string, format: uuid }
        base_estimate_id: { type: string, format: uuid }
        created_at: { type: string, format: date-time }
        expires_at: { type: string, format: date-time }
        total_cents: { type: [integer, 'null'] }
        line_count: { type: integer, minimum: 0 }
        by: { $ref: '#/components/schemas/ShowroomQuoteHistoryEditorLabel' }
        can_put_back: { type: boolean }

    ShowroomQuoteHistory:
      type: object
      additionalProperties: false
      required: [estimate_id, root_estimate_id, current_head_id, head_changed_by, copies, unsaved]
      properties:
        estimate_id: { type: string, format: uuid }
        root_estimate_id: { type: string, format: uuid }
        current_head_id: { type: string, format: uuid }
        head_changed_by:
          oneOf:
            - $ref: '#/components/schemas/ShowroomQuoteHistoryEditorLabel'
            - type: 'null'
        copies:
          type: array
          items: { $ref: '#/components/schemas/ShowroomQuoteHistoryCopy' }
        unsaved:
          type: array
          items: { $ref: '#/components/schemas/ShowroomQuoteHistoryUnsaved' }

    ShowroomQuoteHistoryRestoreResponse:
      type: object
      additionalProperties: false
      required: [estimate_id]
      properties:
        estimate_id: { type: string, format: uuid }

    # --- Tenant document vault (2026-10-23) ------------------------------------
    DocumentType:
      type: string
      enum: [legal, contract, form, warranty, license, insurance, picture, other]
    DocumentUserRef:
      type: object
      required: [id, name]
      properties:
        id: { type: string, format: uuid }
        name: { type: string }
    TenantDocumentVersion:
      type: object
      required: [id, versionNumber, originalFilename, mimeType, sizeBytes, textStatus, uploadedAt, uploadedBy]
      properties:
        id: { type: string, format: uuid }
        versionNumber: { type: integer, minimum: 1 }
        originalFilename: { type: string }
        mimeType: { type: string }
        sizeBytes: { type: integer, minimum: 1, maximum: 104857600 }
        textStatus:
          type: string
          enum: [pending, indexed, skipped_format, skipped_size, failed]
          description: Whether the file text is searchable. Pictures and other formats are `skipped_format`; files over 25 MB are `skipped_size`.
        uploadedAt: { type: [string, 'null'], format: date-time }
        uploadedBy: { $ref: '#/components/schemas/DocumentUserRef' }
    EmailTemplate:
      type: object
      required: [id, subAccountId, name, subject, body, version, archivedAt, createdBy, createdAt, updatedAt]
      properties:
        id: { type: string, format: uuid }
        subAccountId: { type: [string, 'null'], format: uuid, description: 'The owning branch; null for a company-wide template.' }
        name: { type: string, maxLength: 120 }
        subject: { type: string, maxLength: 200 }
        body: { type: string, maxLength: 20000, description: 'Plain text with `{{field}}` or `{{field|fallback}}` merge fields.' }
        version: { type: integer, minimum: 1 }
        archivedAt: { type: [string, 'null'], format: date-time }
        createdBy: { type: string, format: uuid }
        createdAt: { type: string, format: date-time }
        updatedAt: { type: string, format: date-time }
    EmailTemplateList:
      type: object
      required: [items]
      properties:
        items:
          type: array
          items: { $ref: '#/components/schemas/EmailTemplate' }
    EmailTemplateCreateBody:
      type: object
      additionalProperties: false
      required: [name, subject, body]
      properties:
        name: { type: string, minLength: 1, maxLength: 120 }
        subject: { type: string, minLength: 1, maxLength: 200 }
        body: { type: string, minLength: 1, maxLength: 20000 }
        subAccountId: { type: [string, 'null'], format: uuid, description: 'Omit or null for a company-wide template.' }
    EmailTemplatePatchBody:
      type: object
      additionalProperties: false
      minProperties: 1
      properties:
        name: { type: string, minLength: 1, maxLength: 120 }
        subject: { type: string, minLength: 1, maxLength: 200 }
        body: { type: string, minLength: 1, maxLength: 20000 }
    EmailTemplatePreviewBody:
      type: object
      additionalProperties: false
      description: At most one of `leadId` and `customerId`; neither means sample values.
      properties:
        leadId: { type: string, format: uuid }
        customerId: { type: string, format: uuid }
    EmailTemplatePreview:
      type: object
      required: [subject, text, html, missingFields]
      properties:
        subject: { type: string }
        text: { type: string }
        html: { type: string, description: 'Escaped HTML; only `https://` URLs written in the template are linked.' }
        missingFields:
          type: array
          items: { type: string }
          description: Merge fields with no value and no fallback on the previewed record.
    EmailTemplateError:
      type: object
      required: [error]
      properties:
        error:
          type: string
          description: |
            Machine-readable code: `unknown_merge_field` (with `fields`), `invalid_merge_syntax`,
            `invalid_subject`, `invalid_body`, `invalid_query`, `invalid_sub_account` (400);
            `company_template_read_only`, `company_template_owner_admin_only`, `sub_account_forbidden`,
            `template_not_yours`, `leads_read_required`, `customers_read_required` (403);
            `template_not_found`, `lead_not_found`, `customer_not_found` (404);
            `template_name_taken`, `template_archived` (409).
        fields:
          type: array
          items: { type: string }
          description: Present with `unknown_merge_field`.
    TenantDocument:
      type: object
      required: [id, title, documentType, tags, description, expiresOn, expiry, subAccount, trashedAt, createdAt, updatedAt, createdBy, currentVersion, previewKind]
      properties:
        id: { type: string, format: uuid }
        title: { type: string, maxLength: 200 }
        documentType: { $ref: '#/components/schemas/DocumentType' }
        tags:
          type: array
          maxItems: 20
          items: { type: string, maxLength: 40 }
          description: Stored lower-case and trimmed, without a leading `#` (the UI shows `#tag`).
        description: { type: [string, 'null'], maxLength: 500 }
        expiresOn: { type: [string, 'null'], format: date }
        expiry:
          type: object
          required: [status, daysLeft]
          description: Computed from `expiresOn` and today's date in the branch timezone (company timezone for company-wide documents). Expiring = today up to 30 days ahead.
          properties:
            status: { type: string, enum: [none, valid, expiring, expired] }
            daysLeft: { type: [integer, 'null'] }
        subAccount:
          description: The owning branch; null for a company-wide document.
          oneOf:
            - type: 'null'
            - type: object
              required: [id, name]
              properties:
                id: { type: string, format: uuid }
                name: { type: string }
        trashedAt: { type: [string, 'null'], format: date-time }
        createdAt: { type: string, format: date-time }
        updatedAt: { type: string, format: date-time }
        createdBy: { $ref: '#/components/schemas/DocumentUserRef' }
        currentVersion:
          oneOf:
            - type: 'null'
            - $ref: '#/components/schemas/TenantDocumentVersion'
        previewKind:
          type: string
          enum: [image, pdf, none]
          description: Only png, jpeg, gif, webp and pdf preview inline; everything else is download-only.
    TenantDocumentDetail:
      allOf:
        - $ref: '#/components/schemas/TenantDocument'
        - type: object
          required: [versions, versionsNextCursor]
          properties:
            versions:
              type: array
              maxItems: 20
              description: The newest 20 uploaded versions, newest first.
              items: { $ref: '#/components/schemas/TenantDocumentVersion' }
            versionsNextCursor:
              type: [string, 'null']
              description: Cursor for `GET /documents/{id}/versions` when older uploaded versions exist; null otherwise.
    TenantDocumentVersionPage:
      type: object
      required: [items, nextCursor]
      properties:
        items:
          type: array
          maxItems: 20
          description: Uploaded versions, newest first.
          items: { $ref: '#/components/schemas/TenantDocumentVersion' }
        nextCursor: { type: [string, 'null'] }
    TenantDocumentPage:
      type: object
      required: [items, nextCursor]
      properties:
        items:
          type: array
          items: { $ref: '#/components/schemas/TenantDocument' }
        nextCursor: { type: [string, 'null'] }
    DocumentFileInput:
      type: object
      required: [name, mimeType, sizeBytes]
      properties:
        name: { type: string, minLength: 1, maxLength: 255 }
        mimeType:
          type: string
          maxLength: 160
          description: As declared by the browser. Any type is accepted; empty is stored as application/octet-stream.
        sizeBytes:
          type: integer
          minimum: 0
          description: 0 is refused with `empty_file` (400); more than 104857600 (100 MB) with `file_too_large` (413).
    DocumentUploadIntentBody:
      type: object
      required: [documentType, subAccountId, file]
      properties:
        title: { type: string, minLength: 1, maxLength: 200, description: Defaults to the file name without its extension. }
        documentType: { $ref: '#/components/schemas/DocumentType' }
        subAccountId:
          type: [string, 'null']
          format: uuid
          description: The branch, or null for company-wide. A branch-seated caller may only name its own branch.
        tags:
          type: array
          maxItems: 20
          items: { type: string, maxLength: 200 }
          description: A leading `#` is stripped, then each tag is trimmed and lower-cased; at most 40 characters after that.
        description: { type: string, maxLength: 500 }
        expiresOn: { type: string, format: date }
        file: { $ref: '#/components/schemas/DocumentFileInput' }
    DocumentVersionUploadIntentBody:
      type: object
      required: [file]
      properties:
        file: { $ref: '#/components/schemas/DocumentFileInput' }
    DocumentUploadIntent:
      type: object
      required: [document, versionId, uploadUrl, uploadHeaders]
      properties:
        document: { $ref: '#/components/schemas/TenantDocument' }
        versionId: { type: string, format: uuid }
        uploadUrl: { type: string, description: Presigned PUT URL (5 minutes). }
        uploadHeaders:
          type: object
          additionalProperties: { type: string }
    DocumentUploadUrl:
      type: object
      required: [versionId, uploadUrl, uploadHeaders]
      properties:
        versionId: { type: string, format: uuid }
        uploadUrl: { type: string, description: Presigned PUT URL (5 minutes) for the same pending version. }
        uploadHeaders:
          type: object
          additionalProperties: { type: string }
    DocumentPatchBody:
      type: object
      additionalProperties: false
      properties:
        title: { type: string, minLength: 1, maxLength: 200 }
        documentType: { $ref: '#/components/schemas/DocumentType' }
        tags:
          type: array
          maxItems: 20
          items: { type: string, maxLength: 200 }
          description: A leading `#` is stripped, then each tag is trimmed and lower-cased; at most 40 characters after that.
        description: { type: [string, 'null'], maxLength: 500 }
        expiresOn: { type: [string, 'null'], format: date }
        subAccountId:
          type: [string, 'null']
          format: uuid
          description: Account-level owner and admin only; null moves the document to company-wide.
    DocumentFileUrl:
      type: object
      required: [url, expiresAt]
      properties:
        url: { type: string }
        expiresAt: { type: [string, 'null'], format: date-time }
    DocumentTagSuggestions:
      type: object
      required: [items]
      properties:
        items:
          type: array
          maxItems: 50
          items:
            type: object
            required: [tag, count]
            properties:
              tag: { type: string, maxLength: 40 }
              count: { type: integer, minimum: 1 }
    DocumentsSummary:
      type: object
      required: [total, expiringSoon, expired, companyWide, trash]
      properties:
        total: { type: integer, minimum: 0 }
        expiringSoon: { type: integer, minimum: 0 }
        expired: { type: integer, minimum: 0 }
        companyWide: { type: integer, minimum: 0 }
        trash:
          type: integer
          minimum: 0
          description: Visible uploaded documents in Trash; the other counts exclude Trash.
    DocumentError:
      type: object
      required: [error]
      properties:
        error:
          type: string
          description: |
            Machine-readable code: `document_not_found`, `version_not_found`,
            `document_version_not_found`, `thumbnail_unavailable`, `document_object_missing` (404);
            `company_document_read_only`, `sub_account_forbidden`,
            `document_branch_change_forbidden`, `document_delete_forbidden` (403);
            `document_trashed`, `document_not_trashed`, `document_version_not_pending`,
            `preview_unsupported` (409);
            `empty_file`, `object_missing`, `size_mismatch`, `invalid_sub_account`,
            `invalid_body`, `invalid_query`, `invalid_cursor`, `idempotency_key_required`,
            `idempotency_key_invalid` (400); `file_too_large` (413).
    IdempotencySecretResponseUnavailableError:
      type: object
      required: [error, code, message, request_id]
      properties:
        error: { type: string, enum: [idempotency_secret_response_unavailable] }
        code: { type: string, enum: [idempotency_secret_response_unavailable] }
        message: { type: string }
        request_id: { type: string }
    SecretOperationConflictError:
      oneOf:
        - $ref: '#/components/schemas/IdempotencySecretResponseUnavailableError'
        - type: object
          required: [error]
          properties:
            error: { type: string, enum: [idempotency_in_progress] }
    IdempotencyKeyConflictError:
      type: object
      required: [error, code]
      properties:
        error: { type: string, enum: [idempotency_key_conflict] }
        code: { type: string, enum: [idempotency_key_conflict] }
        message: { type: string }
        original_request_hash: { type: string }
        current_request_hash: { type: string }
        request_id: { type: string }

paths:
  /project-discovery:
    get:
      operationId: listVisibleProjectDiscovery
      summary: Discover visible project IDs
      description: |
        Requires projects:read and a tenant-user principal, including the tenant
        service principal used by API keys. A distinct integration_user is not
        admitted. This adds a narrow read under the existing scope; that scope can
        also authorize other broader project reads. Results are currently visible,
        nondeleted projects and include only native ID, nullable authored name and
        current status. IDs are opaque, not project numbers. GET and implicit HEAD
        responses, including errors, use Cache-Control: private, no-store.

        Only limit and cursor are accepted. Limit is a canonical decimal integer
        from 1 through 100, default 50. Results are ordered by UUID ascending. The
        unsigned cursor contains the last returned authorized ID and is a position,
        not authority. Each page reauthorizes the current context; replaying a
        cursor under another context can skip rows but cannot grant visibility.
        Keep credentials and context unchanged throughout traversal; restart after
        a change. Concurrent data or permission changes can alter traversal.

        A visible invalid name, including a lookahead name, fails the page closed.
        Names must be null or 1-255 characters and no more than 1020 UTF-8 bytes.
        The limit bounds response rows, not database work. A bounded query timeout
        returns a sanitized 503; no partial page is returned.
      tags: [Projects]
      parameters:
        - name: limit
          in: query
          schema: { type: integer, minimum: 1, maximum: 100, default: 50 }
        - name: cursor
          in: query
          schema: { type: string, minLength: 1, maxLength: 160 }
          description: Unsigned continuation position from the prior page.
      responses:
        '200':
          description: Page of currently visible projects
          headers:
            Cache-Control: { schema: { type: string, example: 'private, no-store' } }
          content:
            application/json:
              schema:
                type: object
                additionalProperties: false
                required: [data, next_cursor]
                properties:
                  data:
                    type: array
                    maxItems: 100
                    items:
                      type: object
                      additionalProperties: false
                      required: [id, name, status]
                      properties:
                        id: { type: string, format: uuid }
                        name: { type: [string, 'null'], minLength: 1, maxLength: 255 }
                        status: { type: string, enum: [active, closed_won, closed_lost, on_hold, archived] }
                  next_cursor: { type: [string, 'null'], maxLength: 160 }
        '400':
          description: Unsupported query parameter or invalid pagination
          headers:
            Cache-Control: { schema: { type: string, example: 'private, no-store' } }
        '401':
          description: Authentication required
          headers:
            Cache-Control: { schema: { type: string, example: 'private, no-store' } }
        '403':
          description: Missing scope or forbidden principal
          headers:
            Cache-Control: { schema: { type: string, example: 'private, no-store' } }
        '500':
          description: Internal server error
          headers:
            Cache-Control: { schema: { type: string, example: 'private, no-store' } }
  /projects/{id}/identity:
    get:
      operationId: getProjectIdentity
      summary: Read one project identity/site projection (C5-C20)
      description: |
        Current stored values only; no signed-revision provenance is claimed.
        Requires `projects:read`. Accepts tenant sessions, scoped API keys, and
        OAuth 2.1 tokens (`oauth_user` and `integration_user`) with tenant and
        branch checks. Machine callers receive coarsened relationship links
        (`resolved` / `unresolved`). Returns live current values: project
        id/name/status, linked customer/lead, primary-person availability flags
        (never decrypted contact values), canonical site address and computable
        home size. Fields with no stored source (C17 owner/renter, C18 home
        type, C20 organization) are explicit nulls with a capture gap.
      tags: [Projects]
      security: [{ bearerToken: [] }, { sessionCookie: [] }]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Identity/site projection
          headers:
            Cache-Control: { schema: { type: string, example: 'private, no-store' } }
        '401': { description: Authentication required }
        '403': { description: Missing scope or forbidden principal }
        '404': { description: Project not found or not visible }
  /projects/{id}/agreement:
    get:
      operationId: getProjectAgreement
      summary: Read one project agreement/people projection (C21-C34, C75-C76)
      description: |
        Current stored values only; no signed-revision provenance is claimed.
        Requires `projects:read`. Accepts tenant sessions, scoped API keys, and
        OAuth 2.1 tokens (`oauth_user` and `integration_user`) with tenant and
        branch checks. Compensation percentages (C27/C29/C31) remain null with
        a compensation_sensitive gap; contact details for assigned users
        (C33/C34) remain redacted. C25 signed-artifact identity is separate and
        file_delivered=false until project-file delivery serves verified bytes.
      tags: [Projects]
      security: [{ bearerToken: [] }, { sessionCookie: [] }]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Agreement/people projection
          headers:
            Cache-Control: { schema: { type: string, example: 'private, no-store' } }
        '401': { description: Authentication required }
        '403': { description: Missing scope or forbidden principal }
        '404': { description: Project not found or not visible }
  /projects/{id}/finance:
    get:
      operationId: getProjectFinance
      summary: Read one project finance projection (C35-C47)
      description: |
        Current stored values only. Requires `projects:read` and
        `finance_records:read`. Accepts tenant sessions, scoped API keys, and
        OAuth 2.1 tokens (`oauth_user` and `integration_user`) with tenant and
        branch checks. All money is integer cents; currency is null
        (currency_not_stored) because stored rows carry no currency column.
        Totals/line consistency is a CHECK that never invents a missing total.
      tags: [Projects]
      security: [{ bearerToken: [] }, { sessionCookie: [] }]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Finance projection
          headers:
            Cache-Control: { schema: { type: string, example: 'private, no-store' } }
        '401': { description: Authentication required }
        '403': { description: Missing scope or forbidden principal }
        '404': { description: Project not found or not visible }
  /projects/{projectId}/estimates/{estimateId}/lines:
    get:
      operationId: listProjectEstimateLines
      summary: Read selected-estimate pricing lines (C41-C44)
      description: |
        Requires `projects:read` and `estimates:read`. Accepts tenant sessions,
        scoped API keys, and OAuth 2.1 tokens (`oauth_user` and
        `integration_user`). Reads the current stored lines for an explicitly
        selected estimate; discovery grants no estimate access. Each line
        carries the stored name (C41 candidate), quantity decimal text (C42),
        raw native cents (C43) and commission/pass-through treatment (C44).
        Cost, vendor data and calculated totals are not included. Cursor
        pagination (limit default 50, max 100).
      tags: [Projects]
      security: [{ bearerToken: [] }, { sessionCookie: [] }]
      parameters:
        - name: projectId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: estimateId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: limit
          in: query
          schema: { type: integer, minimum: 1, maximum: 100, default: 50 }
        - name: cursor
          in: query
          schema: { type: string, minLength: 1, maxLength: 1024 }
      responses:
        '200':
          description: Selected-estimate pricing lines page
          headers:
            Cache-Control: { schema: { type: string, example: 'private, no-store' } }
        '400': { description: Invalid pagination }
        '401': { description: Authentication required }
        '403': { description: Missing scope or forbidden principal }
        '404': { description: Project or estimate not found or not visible }
        '500': { description: Stored estimate data failed integrity checks }
  /project-files:
    get:
      operationId: listProjectFiles
      summary: Discover project files by HW365 kind (C25/C84/C87/C89/C92)
      description: |
        Requires project_files:read (non-sensitive; API keys may hold it only
        with an explicit file-read permission) plus a per-object entitlement
        re-check against the parent project; a revoked entitlement is 403.
        Five kinds only: signed_agreement (C25), electric_bill (C84), gas_bill
        (C87), panel_photo (C89), meter_photo (C92), classified from stored
        attachment metadata — unclassifiable files are not returned under a
        kind. Cursor pagination; limit default 50, max 100.
      tags: [Projects]
      security: [{ bearerToken: [] }]
      parameters:
        - name: project_id
          in: query
          required: true
          schema: { type: string, format: uuid }
        - name: kind
          in: query
          schema: { type: string, enum: [signed_agreement, electric_bill, gas_bill, panel_photo, meter_photo] }
        - name: limit
          in: query
          schema: { type: integer, minimum: 1, maximum: 100, default: 50 }
        - name: cursor
          in: query
          schema: { type: string }
      responses:
        '200':
          description: Project file page
          headers:
            Cache-Control: { schema: { type: string, example: 'private, no-store' } }
        '400': { description: 'Invalid project id, kind, or cursor' }
        '401': { description: Authentication required }
        '403': { description: Missing file scope or revoked project entitlement }
        '404': { description: Project not found }
  /project-files/signed-agreement:
    get:
      operationId: getProjectFileSignedAgreement
      summary: Select the signed agreement file for a project (C25)
      description: |
        Same project_files:read + per-object fence as the list. Selects the
        authoritative signed artifact identity (contract/revision/stage/sha256)
        for one project; bytes (if any) are served by the download operation,
        never by this metadata read. Used for C25.
      tags: [Projects]
      security: [{ bearerToken: [] }]
      parameters:
        - name: project_id
          in: query
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Signed agreement file selection
          headers:
            Cache-Control: { schema: { type: string, example: 'private, no-store' } }
        '400': { description: Invalid project id }
        '401': { description: Authentication required }
        '403': { description: Missing file scope or revoked project entitlement }
        '404': { description: Project or signed agreement not found }
  /project-files/{fileId}/download:
    get:
      operationId: downloadProjectFile
      summary: Download one project file by id (C25/C84/C87/C89/C92)
      description: |
        Same project_files:read + per-object fence as the list. The signed
        storage URL is minted only after both gates pass; the response is the
        file bytes (or a short redirect to them), never a public URL. Bytes are
        checksum-verified against stored metadata before delivery.
      tags: [Projects]
      security: [{ bearerToken: [] }]
      parameters:
        - name: fileId
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: File bytes
          headers:
            Cache-Control: { schema: { type: string, example: 'private, no-store' } }
        '400': { description: Invalid file id }
        '401': { description: Authentication required }
        '403': { description: Missing file scope or revoked project entitlement }
        '404': { description: File or parent project not found }
  /marketing/contact-requests:
    post:
      operationId: submitMarketingContactRequest
      summary: Submit a public marketing contact request
      description: |
        Accepts an anonymous contact request after endpoint-owned UUID idempotency,
        durable rate limiting, and bot verification. The response never exposes
        staff assignment or email-delivery details.
      tags: [Marketing]
      security: []
      parameters:
        - name: Idempotency-Key
          in: header
          required: true
          schema: { type: string, format: uuid }
          description: Stable UUID for one logical submission; preserve it across retries.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/MarketingContactRequest' }
      responses:
        '202':
          description: Request accepted after durable request/task/delivery commit, or safely replayed.
          headers:
            Cache-Control:
              required: true
              schema: { type: string, enum: [no-store] }
            Idempotency-Replayed:
              required: false
              schema: { type: string, enum: ['true'] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/MarketingContactAcceptedResponse' }
        '400': { description: 'Missing or invalid UUID Idempotency-Key, or an ambiguous/invalid proxy chain.' }
        '403': { description: Bot verification rejected the request. }
        '413': { description: Request body exceeds 16 KiB. }
        '422': { description: Request validation failed or the idempotency key conflicts with another fingerprint. }
        '429':
          description: Durable public intake rate limit exceeded.
          headers:
            Retry-After:
              required: true
              schema: { type: integer, minimum: 1 }
        '500': { description: The accepted-request transaction returned an invalid or failed outcome. }
        '503': { description: 'Database, hashing configuration, or bot verification is unavailable.' }

  /marketing/affiliate-requests:
    post:
      operationId: submitMarketingPartnerRequest
      summary: Submit a public referral-partner application or referral registration
      description: |
        Accepts an anonymous partner application or referral after endpoint-owned
        UUID idempotency, durable rate limiting, honeypot handling, and Turnstile
        verification. Sends a staff notification to partners@portrex.io (CC
        sales@portrex.io) and a Portrex-branded acknowledgment to the submitter
        only on the first accepted create or a pending/failed mail retry. The
        response never exposes email-delivery details or submitter PII.
      tags: [Marketing]
      security: []
      parameters:
        - name: Idempotency-Key
          in: header
          required: true
          schema: { type: string, format: uuid }
          description: Stable UUID for one logical submission; preserve it across retries.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/PartnerRequest' }
      responses:
        '202':
          description: Request accepted after both staff and acknowledgment emails were accepted by the mailer, safely replayed, or a honeypot was silently accepted.
          headers:
            Cache-Control:
              required: true
              schema: { type: string, enum: [no-store] }
            Idempotency-Replayed:
              required: false
              schema: { type: string, enum: ['true'] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PartnerRequestAcceptedResponse' }
        '400': { description: 'Missing or invalid UUID Idempotency-Key, or an ambiguous/invalid proxy chain.' }
        '403': { description: Bot verification rejected the request. }
        '413': { description: Request body exceeds 16 KiB. }
        '422': { description: Request validation failed or the idempotency key conflicts with another fingerprint. }
        '429':
          description: Durable public intake rate limit exceeded.
          headers:
            Retry-After:
              required: true
              schema: { type: integer, minimum: 1 }
        '500': { description: The accepted-request transaction returned an invalid or failed outcome. }
        '503': { description: 'Database, hashing configuration, bot verification, or the mailer is unavailable.' }

  /staff/work/tasks:
    get:
      operationId: listStaffMarketingContactTasks
      summary: List marketing contact tasks assigned to the current staff admin
      description: Requires `staff:operations:read`; the database enforces the exact live assignee identity.
      tags: [Staff]
      security:
        - staffBetterAuthCookie: []
        - staffHmacSessionCookie: []
      x-portrex-scopes: [staff:operations:read]
      parameters:
        - name: status
          in: query
          required: false
          schema: { type: string, enum: [todo, doing, done] }
      responses:
        '200':
          description: Canonical contact-request details for the caller's assigned tasks.
          content:
            application/json:
              schema:
                type: object
                additionalProperties: false
                required: [data]
                properties:
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/StaffMarketingContactTask' }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '403': { description: Staff role or live database identity is not an active platform admin. }
        '422': { description: Invalid list filter. }
        '500': { description: Task query failed. }
        '503': { description: Database unavailable. }

  /staff/work/tasks/{id}:
    get:
      operationId: getStaffMarketingContactTask
      summary: Get one marketing contact task assigned to the current staff admin
      description: Requires `staff:operations:read`; missing and inaccessible IDs share one response.
      tags: [Staff]
      security:
        - staffBetterAuthCookie: []
        - staffHmacSessionCookie: []
      x-portrex-scopes: [staff:operations:read]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Canonical detail for the caller's assigned task.
          content:
            application/json:
              schema:
                type: object
                additionalProperties: false
                required: [data]
                properties:
                  data: { $ref: '#/components/schemas/StaffMarketingContactTask' }
        '400': { description: Invalid task UUID. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '403': { description: Staff role or live database identity is not an active platform admin. }
        '404': { description: 'No assigned task exists for this caller and ID.' }
        '500': { description: Task query failed. }
        '503': { description: Database unavailable. }

  /staff/work/tasks/{id}/status:
    patch:
      operationId: updateStaffMarketingContactTaskStatus
      summary: Update one assigned marketing contact task status
      description: Requires `staff:operations:write`; the database enforces the exact live assignee identity.
      tags: [Staff]
      security:
        - staffBetterAuthCookie: []
        - staffHmacSessionCookie: []
      x-portrex-scopes: [staff:operations:write]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [status]
              properties:
                status: { type: string, enum: [todo, doing, done] }
      responses:
        '200':
          description: Assigned task status updated; returns the canonical task detail.
          content:
            application/json:
              schema:
                type: object
                additionalProperties: false
                required: [data]
                properties:
                  data: { $ref: '#/components/schemas/StaffMarketingContactTask' }
        '400': { description: Invalid task UUID. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '403': { description: Staff role or live database identity is not an active platform admin. }
        '404': { description: No assigned task exists for this caller and ID. }
        '422': { description: 'Status is not todo, doing, or done, or the body contains caller-controlled assignment/source fields.' }
        '500': { description: Task update failed. }
        '503': { description: Database unavailable. }

  /staff/impersonation/elevations:
    post:
      operationId: requestImpersonationElevation
      summary: Request a dual-approved impersonation elevation (assigned Account Manager only)
      security: [{ sessionCookie: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ImpersonationElevationRequest' }
      responses:
        '201':
          description: Pending elevation status; never contains an activation token.
          content: { application/json: { schema: { $ref: '#/components/schemas/ImpersonationElevationStatusEnvelope' } } }
        '403': { $ref: '#/components/responses/Forbidden' }
        '409': { description: A live pending elevation already exists; no capability cookie is issued. }
        '503': { description: Authoritative Better Auth elevation step-up is unavailable or proof storage is not ready. }
  /staff/impersonation/elevations/reissue:
    post:
      operationId: reissueImpersonationElevation
      summary: Perform the single proof-bound recovery rotation for a matching pending elevation
      security: [{ sessionCookie: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ImpersonationElevationRequest' }
      responses:
        '200':
          description: Pending elevation status; the fresh capability is delivered only by HttpOnly cookie.
          content: { application/json: { schema: { $ref: '#/components/schemas/ImpersonationElevationStatusEnvelope' } } }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { description: No matching live pending elevation exists. }
        '503': { description: Authoritative Better Auth elevation step-up is unavailable or proof storage is not ready. }
  /staff/impersonation/elevations/{id}/activate:
    post:
      operationId: activateImpersonationElevation
      summary: Activate an approved elevation using the server-bound HttpOnly capability
      security: [{ sessionCookie: [] }]
      parameters: [{ name: id, in: path, required: true, schema: { type: string, format: uuid } }]
      requestBody:
        required: true
        content: { application/json: { schema: { $ref: '#/components/schemas/ImpersonationElevationFactor' } } }
      responses:
        '200':
          description: Active or expired elevation status.
          content: { application/json: { schema: { $ref: '#/components/schemas/ImpersonationElevationStatusEnvelope' } } }
        '403': { $ref: '#/components/responses/Forbidden' }
        '503': { description: Authoritative Better Auth elevation step-up is unavailable or proof storage is not ready. }
  /staff/impersonation/elevations/{id}/revoke:
    post:
      operationId: revokeStaffImpersonationElevation
      summary: Revoke an approved or active elevation as its requesting Account Manager
      security: [{ sessionCookie: [] }]
      parameters: [{ name: id, in: path, required: true, schema: { type: string, format: uuid } }]
      requestBody: { required: true, content: { application/json: { schema: { type: object, additionalProperties: false } } } }
      responses:
        '200':
          description: Revoked elevation status.
          content: { application/json: { schema: { $ref: '#/components/schemas/ImpersonationElevationStatusEnvelope' } } }
        '403': { $ref: '#/components/responses/Forbidden' }
        '503': { description: Authoritative Better Auth elevation step-up is unavailable or proof storage is not ready. }
  /staff/impersonation/login-as-owner:
    post:
      operationId: staffLoginAsOwner
      summary: Sign in to a tenant as its owner (platform_admin only; no tenant consent, no step-up)
      description: >-
        Creates a 4-hour owner_login impersonation session with write access and returns a one-time
        handoff URL. The code is in the URL fragment and expires after 60 seconds. This response never
        sets a tenant cookie. Only a staff audit row is written.
      security: [{ sessionCookie: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [account_id]
              additionalProperties: false
              properties:
                account_id: { type: string, format: uuid }
                reason: { type: string, maxLength: 486 }
      responses:
        '201':
          description: One-time handoff URL and the owner the session acts as.
          content:
            application/json:
              schema:
                type: object
                required: [handoff_url, code_expires_at, session_expires_at, owner]
                additionalProperties: false
                properties:
                  handoff_url: { type: string, format: uri }
                  code_expires_at: { type: string, format: date-time }
                  session_expires_at: { type: string, format: date-time }
                  owner:
                    type: object
                    required: [user_id, email, full_name]
                    additionalProperties: false
                    properties:
                      user_id: { type: string, format: uuid }
                      email: { type: string, format: email }
                      full_name: { type: string, nullable: true }
        '400': { description: 'Invalid body, or the reason is longer than 486 characters.' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { description: 'account_not_found or owner_not_found.' }
        '409': { description: 'account_inactive or owner_inactive.' }
  /staff/impersonation/handoff/redeem:
    post:
      operationId: redeemStaffOwnerLoginHandoff
      summary: Redeem a one-time owner-login handoff code on the tenant web origin
      description: >-
        Unauthenticated; the one-time code is the credential. On success the response clears competing
        Better Auth tenant and demo cookies, sets the tenant session cookie, and returns the redirect path.
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [code]
              additionalProperties: false
              properties:
                code: { type: string, minLength: 32, maxLength: 128 }
      responses:
        '200':
          description: Tenant session cookie set.
          content:
            application/json:
              schema:
                type: object
                required: [redirect_to]
                additionalProperties: false
                properties: { redirect_to: { type: string } }
        '400': { description: 'handoff_invalid — the body is not a valid code.' }
        '410': { description: 'handoff_invalid — the code is unknown, expired, or already used.' }
  /staff/house/handoff:
    post:
      operationId: staffHouseCrmIssueHandoff
      summary: Get a one-time handoff URL into the Portrex house account CRM (platform_admin and account_manager)
      description: >-
        Issues a one-time code that expires after 60 seconds and returns the web handoff URL with the code in
        the URL fragment. The staff member's own user gets an admin membership in the house account when the
        code is redeemed. `next_path` is confined to the house CRM paths; any other value becomes `/pipeline`.
        This response never sets a tenant cookie. Only a staff audit row is written.
      security: [{ sessionCookie: [] }]
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                next_path: { type: string, maxLength: 512 }
      responses:
        '200':
          description: One-time handoff URL.
          content:
            application/json:
              schema:
                type: object
                required: [handoff_url, expires_at]
                additionalProperties: false
                properties:
                  handoff_url: { type: string, format: uri }
                  expires_at: { type: string, format: date-time }
        '400': { description: 'Invalid body.' }
        '401': { description: Authentication required }
        '403': { $ref: '#/components/responses/Forbidden' }
        '503': { description: 'house_account_missing — the house account has not been provisioned.' }
  /auth/house-handoff/redeem:
    post:
      operationId: redeemHouseCrmHandoff
      summary: Redeem a one-time house CRM handoff code on the tenant web origin
      description: >-
        Unauthenticated; the one-time code is the credential. On success the response clears competing
        Better Auth tenant and demo cookies, sets the tenant session cookie and the house CRM embed marker
        cookie, and returns the confined redirect path. A refusal sets and clears no cookie.
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [code]
              additionalProperties: false
              properties:
                code: { type: string, minLength: 1, maxLength: 128 }
      responses:
        '200':
          description: Tenant session cookie and embed marker cookie set.
          content:
            application/json:
              schema:
                type: object
                required: [redirect_to]
                additionalProperties: false
                properties: { redirect_to: { type: string } }
        '400': { description: 'invalid_request — the body is not a valid code.' }
        '403': { description: 'house_crm_not_allowed — the staff member no longer has house CRM access.' }
        '410': { description: 'handoff_code_invalid — the code is unknown, expired, or already used.' }
        '503': { description: 'house_account_missing — the house account has not been provisioned.' }
  /impersonation/end:
    post:
      operationId: endCurrentImpersonationSession
      summary: End the exact authenticated staff impersonation session
      security: [{ sessionCookie: [] }]
      requestBody:
        required: true
        content: { application/json: { schema: { type: object, additionalProperties: false } } }
      responses:
        '200':
          description: Current impersonation session ended and tenant cookie cleared.
          content:
            application/json:
              schema:
                type: object
                required: [ended]
                additionalProperties: false
                properties: { ended: { type: boolean, const: true } }
        '403': { $ref: '#/components/responses/Forbidden' }
  /impersonation/elevations/pending:
    get:
      operationId: listPendingImpersonationElevations
      summary: List pending elevation approvals for the authenticated tenant Owner or Admin
      security: [{ sessionCookie: [] }]
      responses:
        '200':
          description: Tenant-audience approval details with no capability material.
          content:
            application/json:
              schema:
                type: object
                required: [data]
                additionalProperties: false
                properties:
                  data: { type: array, items: { $ref: '#/components/schemas/ImpersonationElevationTenantDetail' } }
        '403': { $ref: '#/components/responses/Forbidden' }
  /impersonation/elevations/{id}/approve:
    post:
      operationId: approveImpersonationElevation
      summary: Approve an elevation as a tenant Owner or Admin
      security: [{ sessionCookie: [] }]
      parameters: [{ name: id, in: path, required: true, schema: { type: string, format: uuid } }]
      requestBody:
        required: true
        content: { application/json: { schema: { $ref: '#/components/schemas/ImpersonationElevationFactor' } } }
      responses:
        '200':
          description: Approved elevation status.
          content: { application/json: { schema: { $ref: '#/components/schemas/ImpersonationElevationStatusEnvelope' } } }
        '403': { $ref: '#/components/responses/Forbidden' }
        '503': { description: Authoritative Better Auth elevation step-up is unavailable or proof storage is not ready. }
  /impersonation/elevations/{id}/deny:
    post:
      operationId: denyImpersonationElevation
      summary: Deny an elevation as a tenant Owner or Admin
      security: [{ sessionCookie: [] }]
      parameters: [{ name: id, in: path, required: true, schema: { type: string, format: uuid } }]
      requestBody:
        required: true
        content: { application/json: { schema: { $ref: '#/components/schemas/ImpersonationElevationFactor' } } }
      responses:
        '200':
          description: Denied elevation status.
          content: { application/json: { schema: { $ref: '#/components/schemas/ImpersonationElevationStatusEnvelope' } } }
        '403': { $ref: '#/components/responses/Forbidden' }
        '503': { description: Authoritative Better Auth elevation step-up is unavailable or proof storage is not ready. }
  /impersonation/elevations/{id}/revoke:
    post:
      operationId: revokeTenantImpersonationElevation
      summary: Revoke an approved or active elevation as a tenant Owner or Admin
      security: [{ sessionCookie: [] }]
      parameters: [{ name: id, in: path, required: true, schema: { type: string, format: uuid } }]
      requestBody:
        required: true
        content: { application/json: { schema: { $ref: '#/components/schemas/ImpersonationElevationFactor' } } }
      responses:
        '200':
          description: Revoked elevation status.
          content: { application/json: { schema: { $ref: '#/components/schemas/ImpersonationElevationStatusEnvelope' } } }
        '403': { $ref: '#/components/responses/Forbidden' }
        '503': { description: Authoritative Better Auth elevation step-up is unavailable or proof storage is not ready. }
  /accounts/public-branding:
    get:
      operationId: getPublicAccountBranding
      summary: Resolve safe public account branding by host
      description: |
        Returns only non-sensitive branding fields needed by public login
        surfaces. The route resolves active accounts by `{subdomain}.portrex.io`
        or a configured custom login domain.
      tags: [Accounts]
      security: []
      parameters:
        - name: host
          in: query
          required: false
          schema: { type: string, maxLength: 253 }
      responses:
        '200':
          description: Public branding envelope
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PublicAccountBranding' }

  /accounts/{accountId}/lead-assignment-policy:
    get:
      operationId: getLeadAssignmentPolicy
      summary: Get account lead-assignment fallback policy
      tags: [Accounts]
      parameters:
        - name: accountId
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Lead assignment policy
          content:
            application/json:
              schema: { $ref: '#/components/schemas/LeadAssignmentPolicyResponse' }
        '401': { description: Unauthorized }
        '403': { description: Account mismatch or missing account read permission }
        '404': { description: Account not found }
    patch:
      operationId: updateLeadAssignmentPolicy
      summary: Update account lead-assignment fallback policy
      tags: [Accounts]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
        - name: accountId
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/LeadAssignmentPolicy' }
      responses:
        '200':
          description: Updated lead assignment policy
          content:
            application/json:
              schema: { $ref: '#/components/schemas/LeadAssignmentPolicyResponse' }
        '400': { description: Invalid policy or inactive fixed assignee }
        '401': { description: Unauthorized }
        '403': { description: Account mismatch or missing account write permission }
        '404': { description: Account not found }

  /accounts/{accountId}/stage-probability:
    patch:
      operationId: updateAccountStageProbability
      summary: Replace the account's per-stage win probabilities
      description: |
        Replaces the whole stage_probability map of the account (account owner or admin only).
        An empty object removes the override so every stage returns to its default.
        The result shows in GET /leads/stage-definitions.
      tags: [Accounts]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
        - name: accountId
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/StageProbabilityInput' }
      responses:
        '200':
          description: Stored per-stage win probabilities
          content:
            application/json:
              schema: { $ref: '#/components/schemas/StageProbabilityResponse' }
        '400': { description: 'Unknown or won/lost stage id, or a probability outside 0..1 or with more than 4 decimals' }
        '401': { description: Unauthorized }
        '403': { description: 'Account mismatch, branch seat, or a role other than account owner or admin' }
        '404': { description: Account not found }

  /sub-accounts/{id}/lead-assignment-policy:
    get:
      operationId: getSubAccountLeadAssignmentPolicy
      summary: Get a branch lead-assignment override and effective policy
      description: |
        Returns the configured branch override, or the inherited account
        fallback. Malformed stored overrides fail closed to a terminal manual
        policy and are reported with override_state `invalid`.
      tags: [Accounts]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Branch override and effective lead-assignment policy
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SubAccountLeadAssignmentPolicyResponse' }
        '401': { description: Unauthorized }
        '403': { description: Role denied or branch scope mismatch }
        '404': { description: Branch not found in the authenticated account }
    put:
      operationId: replaceSubAccountLeadAssignmentPolicy
      summary: Completely replace a branch lead-assignment override
      description: |
        Replaces the branch override atomically. fixed_user requires an active,
        eligible member of this exact branch. manual and round_robin are stored
        canonically with fixed_user_id null.
      tags: [Accounts]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/LeadAssignmentPolicyInput' }
      responses:
        '200':
          description: Replaced branch override and effective lead-assignment policy
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SubAccountLeadAssignmentPolicyResponse' }
        '400': { description: Invalid policy or inactive exact-branch fixed assignee }
        '401': { description: Unauthorized }
        '403': { description: Role denied or branch scope mismatch }
        '404': { description: Branch not found in the authenticated account }
        '422': { description: Idempotency key was previously used with a different request }
    delete:
      operationId: deleteSubAccountLeadAssignmentPolicy
      summary: Delete a branch lead-assignment override
      description: |
        Idempotently removes the branch override key and returns the inherited
        effective account policy (or implicit manual fallback).
      tags: [Accounts]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Inherited effective lead-assignment policy
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SubAccountLeadAssignmentPolicyResponse' }
        '401': { description: Unauthorized }
        '403': { description: Role denied or branch scope mismatch }
        '404': { description: Branch not found in the authenticated account }

  /uploads/images:
    post:
      operationId: uploadTenantImage
      summary: Upload a tenant image asset
      description: |
        Uploads PNG, JPG, or WebP images for account logos, login backgrounds,
        sub-account logos, pricebook item images, and user profile avatars. The
        response URL is the hosted image URL that should be stored by the
        calling profile/settings/pricebook mutation.
      tags: [Uploads]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ImageUploadRequest' }
      responses:
        '201':
          description: Uploaded image asset
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ImageUploadResponse' }
        '400': { description: Invalid request or MIME mismatch }
        '401': { description: Unauthorized }
        '403': { description: Missing account write permission or sub-account mismatch }
        '413': { description: Image is larger than 2 MB }
        '415': { description: Unsupported image type }

  /uploads/images/{assetKey}:
    get:
      operationId: getUploadedTenantImage
      summary: Serve an uploaded tenant image asset
      tags: [Uploads]
      security: []
      parameters:
        - name: assetKey
          in: path
          required: true
          schema: { type: string }
          description: Path-style asset key returned by uploadTenantImage.
      responses:
        '200':
          description: Image bytes
          content:
            image/png: { schema: { type: string, format: binary } }
            image/jpeg: { schema: { type: string, format: binary } }
            image/webp: { schema: { type: string, format: binary } }
        '404': { description: Asset not found }

  /sub-accounts/summary:
    get:
      operationId: listSubAccountSummaries
      summary: List sub-account roll-up summaries
      description: |
        Parent account owner/admin users receive summaries for all visible
        child sub-accounts. Child-scoped users are clamped to their own
        sub-account by the API authorization layer.
      tags: [Accounts]
      parameters:
        - $ref: '#/components/parameters/activeSubAccountId'
        - name: status
          in: query
          schema: { type: string, enum: [active, suspended, archived] }
        - name: include_archived
          in: query
          schema: { type: boolean }
      responses:
        '200':
          description: Sub-account roll-up summaries
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SubAccountSummaryResponse' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '503': { description: DB unavailable in production }

  /contractors:
    get:
      operationId: listContractors
      summary: List contractors (cursor paginated)
      description: |
        Requires `account:read`. Company-wide contractors (no
        `sub_account_ids`) plus contractors serving the caller's own branch,
        if branch-seated; account-wide roles see every contractor. A
        contractor can serve many branches at once.
      tags: [Contractors]
      parameters:
        - $ref: '#/components/parameters/cursor'
        - $ref: '#/components/parameters/limit'
        - name: q
          in: query
          schema: { type: string, maxLength: 200 }
          description: Matches company name, contact name, email, phone digits, or license number.
        - name: service_line
          in: query
          schema: { type: string, enum: [ADU, HVAC, Roofing, Renovation, Generac] }
        - name: state
          in: query
          schema: { type: string, description: Two-letter US state code. }
        - name: license_status
          in: query
          schema: { type: string, enum: [valid, expiring_soon, expired, invalid] }
        - name: sub_account_id
          in: query
          schema: { type: string, format: uuid, nullable: true }
          description: '`null` filters to company-wide contractors only.'
        - name: include_archived
          in: query
          schema: { type: boolean }
      responses:
        '200':
          description: Paginated contractors
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ContractorPage' }
        '400': { description: Invalid query parameters or OFFSET pagination requested }
        '401': { description: Unauthorized }
        '403':
          description: sub_account_id filter outside the caller's branch scope
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ContractorError' }
    post:
      operationId: createContractor
      summary: Create a contractor
      description: |
        Requires `account:write`. Branch-seated callers may only target their
        own branch or the company-wide scope they are permitted to write to.
      tags: [Contractors]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ContractorCreateBody' }
      responses:
        '201':
          description: Created contractor
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ContractorDetail' }
        '400':
          description: Invalid payload, or sub_account_id not in this tenant
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ContractorError' }
        '401': { description: Unauthorized }
        '403':
          description: Target sub-account outside the caller's branch scope
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ContractorError' }

  /contractors/{id}:
    get:
      operationId: getContractor
      summary: Get a contractor
      description: Requires `account:read`. Visibility follows the same branch rule as the list.
      tags: [Contractors]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Contractor detail
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ContractorDetail' }
        '401': { description: Unauthorized }
        '404':
          description: Not found, or not visible to the caller's branch
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ContractorError' }
    patch:
      operationId: patchContractor
      summary: Update a contractor
      description: |
        Requires `account:write`. Rejects a change to an archived contractor,
        and rejects moving the contractor outside the caller's branch scope.
      tags: [Contractors]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ContractorPatchBody' }
      responses:
        '200':
          description: Updated contractor
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ContractorDetail' }
        '400':
          description: Invalid payload, or sub_account_id not in this tenant
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ContractorError' }
        '401': { description: Unauthorized }
        '403':
          description: Target sub-account outside the caller's branch scope
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ContractorError' }
        '404':
          description: Not found, or not visible to the caller's branch
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ContractorError' }
        '409':
          description: Contractor is archived
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ContractorError' }

  /contractors/{id}/archive:
    post:
      operationId: archiveContractor
      summary: Archive a contractor
      description: Requires `account:write`.
      tags: [Contractors]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      responses:
        '200':
          description: Archived contractor
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ContractorDetail' }
        '401': { description: Unauthorized }
        '403':
          description: Target sub-account outside the caller's branch scope
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ContractorError' }
        '404':
          description: Not found, or not visible to the caller's branch
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ContractorError' }
        '409':
          description: Already archived
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ContractorError' }

  /contractors/{id}/unarchive:
    post:
      operationId: unarchiveContractor
      summary: Unarchive a contractor
      description: Requires `account:write`.
      tags: [Contractors]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      responses:
        '200':
          description: Unarchived contractor
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ContractorDetail' }
        '401': { description: Unauthorized }
        '403':
          description: Target sub-account outside the caller's branch scope
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ContractorError' }
        '404':
          description: Not found, or not visible to the caller's branch
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ContractorError' }
        '409':
          description: Not archived
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ContractorError' }

  /contractors/{id}/licenses:
    post:
      operationId: createContractorLicense
      summary: Add a license to a contractor
      description: |
        Requires `account:write`. Rejects adding a license to an archived
        contractor, or one outside the caller's branch scope.
      tags: [Contractors]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ContractorLicenseCreateBody' }
      responses:
        '201':
          description: Created license
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ContractorLicense' }
        '400':
          description: Invalid payload
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ContractorError' }
        '401': { description: Unauthorized }
        '403':
          description: Target contractor outside the caller's branch scope
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ContractorError' }
        '404':
          description: Contractor not found, or not visible to the caller's branch
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ContractorError' }
        '409':
          description: Contractor is archived
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ContractorError' }

  /contractors/{id}/licenses/{licenseId}:
    patch:
      operationId: patchContractorLicense
      summary: Update a contractor license
      description: |
        Requires `account:write`. Rejects a change on an archived contractor,
        or one outside the caller's branch scope.
      tags: [Contractors]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: licenseId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ContractorLicensePatchBody' }
      responses:
        '200':
          description: Updated license
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ContractorLicense' }
        '400':
          description: Invalid payload
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ContractorError' }
        '401': { description: Unauthorized }
        '403':
          description: Target contractor outside the caller's branch scope
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ContractorError' }
        '404':
          description: Contractor or license not found, or not visible to the caller's branch
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ContractorError' }
        '409':
          description: Contractor is archived
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ContractorError' }
    delete:
      operationId: deleteContractorLicense
      summary: Soft-delete a contractor license
      description: |
        Requires `account:write`. Rejects a delete on an archived contractor,
        or one outside the caller's branch scope.
      tags: [Contractors]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: licenseId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      responses:
        '200':
          description: Deleted license id and timestamp
          content:
            application/json:
              schema:
                type: object
                required: [id, deleted_at]
                properties:
                  id: { type: string, format: uuid }
                  deleted_at: { type: string, format: date-time }
        '401': { description: Unauthorized }
        '403':
          description: Target contractor outside the caller's branch scope
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ContractorError' }
        '404':
          description: Contractor or license not found, or not visible to the caller's branch
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ContractorError' }
        '409':
          description: Contractor is archived
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ContractorError' }

  /documents:
    get:
      operationId: listDocuments
      summary: List and search vault documents (cursor paginated)
      description: |
        Requires `documents:read` (owner, admin, sub-account admin). Tenant user
        sessions only. Account-level owners and admins see every branch and the
        company-wide documents; with `X-Portrex-Sub-Account-Id` set, that branch
        plus company-wide. The header narrows this list only: the routes that
        address one document by id ignore it for head office. A branch-seated
        caller sees its own branch plus company-wide. Documents whose first
        upload never completed are not listed.
        Order: `sort` when given (every page, keyset cursor); otherwise
        `expiry=expiring` soonest first; with `q` best match first; else
        newest change first.
      tags: [Documents]
      parameters:
        - $ref: '#/components/parameters/activeSubAccountId'
        - $ref: '#/components/parameters/cursor'
        - name: limit
          in: query
          schema: { type: integer, minimum: 1, maximum: 100, default: 50 }
        - name: q
          in: query
          schema: { type: string, maxLength: 200 }
          description: Full-text search over title, type, tags, description and extracted file text, plus a partial-title match.
        - name: type
          in: query
          schema: { $ref: '#/components/schemas/DocumentType' }
        - name: branch
          in: query
          schema: { type: string }
          description: '`all` (default), `company` (company-wide only), or a branch id.'
        - name: expiry
          in: query
          schema: { type: string, enum: [expiring] }
          description: Documents that expire within 30 days or have already expired.
        - name: view
          in: query
          schema: { type: string, enum: [active, trash], default: active }
        - name: tags
          in: query
          schema: { type: string, maxLength: 1000 }
          description: |
            Comma-separated tags (`tags=forms,tax`); only documents that carry every
            one are listed. Normalised like stored tags (leading `#` stripped,
            trimmed, lower-case); at most 20 tags of 40 characters. The cursor is
            bound to this filter.
        - name: sort
          in: query
          schema: { type: string, enum: [updated, title, type, branch, expires] }
          description: |
            Column sort applied on the server across every page. Titles and branch
            names sort case-insensitively; company-wide sorts first by `branch`
            ascending; documents without an expiry date sort last by `expires` in
            both directions. The cursor is bound to the sort and direction.
        - name: direction
          in: query
          schema: { type: string, enum: [asc, desc] }
          description: Default `desc` for `sort=updated`, else `asc`.
      responses:
        '200':
          description: One page of documents
          content:
            application/json:
              schema: { $ref: '#/components/schemas/TenantDocumentPage' }
        '400':
          description: Invalid query or cursor
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }
        '401': { description: Unauthorized }
        '403': { $ref: '#/components/responses/Forbidden' }

  /documents/tags:
    get:
      operationId: listDocumentTags
      summary: Suggest the company's existing document tags
      description: |
        Requires `documents:read`. Tenant user sessions only. Distinct tags of the
        uploaded documents not in Trash that the caller can see, fenced exactly like
        `GET /documents` (including `X-Portrex-Sub-Account-Id` for head office), each
        with the number of such documents. Prefix match on `q`; a leading `#` is
        optional. Most used first, then by tag; at most 50.
      tags: [Documents]
      parameters:
        - $ref: '#/components/parameters/activeSubAccountId'
        - name: q
          in: query
          schema: { type: string, maxLength: 200 }
          description: Start of the tag, with or without a leading `#`. Empty lists the most used tags.
      responses:
        '200':
          description: Tag suggestions
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentTagSuggestions' }
        '400':
          description: Invalid query
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }
        '401': { description: Unauthorized }
        '403': { $ref: '#/components/responses/Forbidden' }

  /documents/summary:
    get:
      operationId: getDocumentsSummary
      summary: Counts for the Documents stat tiles
      description: |
        Requires `documents:read`. Tenant user sessions only. Counts over the uploaded
        documents not in Trash that the caller can see, fenced exactly like
        `GET /documents` (including `X-Portrex-Sub-Account-Id` for head office).
        `expiringSoon`: expires today up to 30 days ahead; `expired`: the expiry date
        is before today. "Today" is the calendar date in the document's branch
        timezone, or the company's for company-wide documents.
      tags: [Documents]
      parameters:
        - $ref: '#/components/parameters/activeSubAccountId'
      responses:
        '200':
          description: Document counts
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentsSummary' }
        '401': { description: Unauthorized }
        '403': { $ref: '#/components/responses/Forbidden' }

  /documents/upload-intents:
    post:
      operationId: createDocumentUploadIntent
      summary: Start a document upload
      description: |
        Requires `documents:write`. Creates the document and version 1 in
        `pending_upload` and returns a presigned PUT URL. Send the bytes with
        `uploadHeaders`, then call the complete route. Any file type is accepted,
        up to 100 MB. A branch-seated caller may only upload into its own branch.
        Requires an `Idempotency-Key`; a retry with the same key and request returns the first response.
      tags: [Documents]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/DocumentUploadIntentBody' }
      responses:
        '201':
          description: Upload intent
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentUploadIntent' }
        '400':
          description: Invalid body, empty file, or unknown branch; or a missing or invalid `Idempotency-Key` (`idempotency_key_required`, `idempotency_key_invalid`)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }
        '401': { description: Unauthorized }
        '403':
          description: Company-wide or another branch for a branch-seated caller
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }
        '413':
          description: File larger than 100 MB
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }
        '422': { $ref: '#/components/responses/IdempotencyConflict' }

  /documents/{id}:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    get:
      operationId: getDocument
      summary: Get a document with its newest uploaded versions
      description: |
        Requires `documents:read`. The branch view header
        (`X-Portrex-Sub-Account-Id`) narrows only the list: account-level owners
        and admins open any branch's document by id, whatever view is selected.
        A branch-seated caller opens its own branch's and company-wide documents;
        another branch's document is 404. Holds the newest 20 uploaded versions;
        `versionsNextCursor` pages older ones through `GET /documents/{id}/versions`.
      tags: [Documents]
      responses:
        '200':
          description: Document detail
          content:
            application/json:
              schema: { $ref: '#/components/schemas/TenantDocumentDetail' }
        '401': { description: Unauthorized }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404':
          description: Not found, or not visible to the caller's branch
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }
    patch:
      operationId: updateDocument
      summary: Edit a document's title, type, tags, notes, expiry or branch
      description: |
        Requires `documents:write`. Company-wide documents are read-only for a
        branch-seated caller. Changing `subAccountId` is for account-level owners
        and admins only. A trashed document cannot be edited.
        Requires an `Idempotency-Key`; a retry with the same key and request returns the first response.
      tags: [Documents]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/DocumentPatchBody' }
      responses:
        '200':
          description: Updated document
          content:
            application/json:
              schema: { $ref: '#/components/schemas/TenantDocument' }
        '400':
          description: Invalid body or unknown branch; or a missing or invalid `Idempotency-Key` (`idempotency_key_required`, `idempotency_key_invalid`)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }
        '401': { description: Unauthorized }
        '403':
          description: Company-wide document for a branch-seated caller, or a branch change without head-office rights
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }
        '404':
          description: Not found, or not visible to the caller's branch
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }
        '409':
          description: Document is in Trash
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }
        '422': { $ref: '#/components/responses/IdempotencyConflict' }
    delete:
      operationId: deleteDocument
      summary: Delete a trashed document forever
      description: |
        Requires `documents:write` and an account-level owner or admin. Only a
        document in Trash can be deleted. The rows go at once; the stored files of
        every version (and their thumbnails) are queued and deleted by a
        background job, which retries a failed delete. No Idempotency-Key is used.
      tags: [Documents]
      responses:
        '204': { description: Deleted }
        '401': { description: Unauthorized }
        '403':
          description: Not an account-level owner or admin
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }
        '404':
          description: Not found, or not visible to the caller's branch
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }
        '409':
          description: Document is not in Trash
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }

  /documents/{id}/versions:
    get:
      operationId: listDocumentVersions
      summary: Page through a document's older uploaded versions
      description: |
        Requires `documents:read`. Uploaded versions, newest first, 20 per page.
        Pass the detail's `versionsNextCursor` (or a page's `nextCursor`) as
        `cursor`. The cursor is bound to this document. Visibility is the detail rule.
      tags: [Documents]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/cursor'
      responses:
        '200':
          description: One page of uploaded versions
          content:
            application/json:
              schema: { $ref: '#/components/schemas/TenantDocumentVersionPage' }
        '400':
          description: Invalid query or cursor
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }
        '401': { description: Unauthorized }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404':
          description: Not found, or not visible to the caller's branch
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }

  /documents/{id}/versions/upload-intents:
    post:
      operationId: createDocumentVersionUploadIntent
      summary: Start uploading a new version of a document
      description: |
        Requires `documents:write`. Creates the next version in `pending_upload`
        and returns a presigned PUT URL. Older versions stay downloadable.
        Requires an `Idempotency-Key`; a retry with the same key and request returns the first response.
      tags: [Documents]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/DocumentVersionUploadIntentBody' }
      responses:
        '201':
          description: Upload intent
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentUploadIntent' }
        '400':
          description: Invalid body or empty file; or a missing or invalid `Idempotency-Key` (`idempotency_key_required`, `idempotency_key_invalid`)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }
        '401': { description: Unauthorized }
        '403':
          description: Company-wide document for a branch-seated caller
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }
        '404':
          description: Not found, or not visible to the caller's branch
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }
        '409':
          description: Document is in Trash
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }
        '413':
          description: File larger than 100 MB
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }
        '422': { $ref: '#/components/responses/IdempotencyConflict' }

  /documents/{id}/versions/{versionId}/upload-url:
    post:
      operationId: renewDocumentUploadUrl
      summary: Re-sign the upload URL of a pending version
      description: |
        Requires `documents:write`. Returns a fresh presigned PUT URL for the same
        version while it is still `pending_upload`, so a retried upload reuses its
        intent. Requires an `Idempotency-Key`; a retry with the same key and request returns the first response.
        A replayed response carries the first, possibly expired, URL, so send a fresh
        `Idempotency-Key` on every renewal; reuse a key only to retry a request whose response was lost.
      tags: [Documents]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: versionId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      responses:
        '200':
          description: Upload URL
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentUploadUrl' }
        '400':
          description: A missing or invalid `Idempotency-Key` (`idempotency_key_required`, `idempotency_key_invalid`)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }
        '401': { description: Unauthorized }
        '403':
          description: Company-wide document for a branch-seated caller
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }
        '404':
          description: Document (`document_not_found`) or version (`document_version_not_found`) not found, or not visible to the caller's branch
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }
        '409':
          description: The version is no longer pending (`document_version_not_pending`), or the document is in Trash (`document_trashed`)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }
        '422': { $ref: '#/components/responses/IdempotencyConflict' }

  /documents/{id}/versions/{versionId}/complete:
    post:
      operationId: completeDocumentVersion
      summary: Finish an upload
      description: |
        Requires `documents:write`. Checks the stored object and its size, marks the
        version uploaded, makes it current (unless a later version already is) and
        clears the old extracted text. Calling it again for an uploaded version
        changes nothing. A document in Trash is refused before the object is
        checked. Emits `documents/version.uploaded` for text extraction.
        Requires an `Idempotency-Key`; a retry with the same key and request returns the first response.
      tags: [Documents]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: versionId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      responses:
        '200':
          description: Document detail
          content:
            application/json:
              schema: { $ref: '#/components/schemas/TenantDocumentDetail' }
        '400':
          description: Object missing or size mismatch (the version is marked failed); or a missing or invalid `Idempotency-Key` (`idempotency_key_required`, `idempotency_key_invalid`)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }
        '401': { description: Unauthorized }
        '403':
          description: Company-wide document for a branch-seated caller
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }
        '404':
          description: Document or version not found, or not visible to the caller's branch
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }
        '409':
          description: Document is in Trash (`document_trashed`)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }
        '422': { $ref: '#/components/responses/IdempotencyConflict' }

  /documents/{id}/versions/{versionId}/download:
    get:
      operationId: getDocumentDownload
      summary: Signed download URL for one version
      description: Requires `documents:read`. The URL always downloads as an attachment (10 minutes).
      tags: [Documents]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: versionId
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Download URL
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentFileUrl' }
        '401': { description: Unauthorized }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404':
          description: Document or uploaded version not found, or not visible to the caller's branch
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }

  /documents/{id}/preview:
    get:
      operationId: getDocumentPreview
      summary: Preview URL for the current version
      description: Requires `documents:read`. Images (png, jpeg, gif, webp) and PDF only.
      tags: [Documents]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: URL of the API-served preview content
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentFileUrl' }
        '401': { description: Unauthorized }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404':
          description: Not found, or not visible to the caller's branch
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }
        '409':
          description: This format does not preview (download it instead)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }

  /documents/{id}/preview/content:
    get:
      operationId: getDocumentPreviewContent
      summary: Stream the current version inline (images and PDF only)
      description: |
        Requires `documents:read`. Sent with `Cache-Control: private, no-store`,
        `Content-Security-Policy: default-src 'none'; frame-ancestors 'self'`,
        `X-Frame-Options: SAMEORIGIN` and `X-Content-Type-Options: nosniff`.
      tags: [Documents]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: File bytes
          content:
            image/*:
              schema: { type: string, format: binary }
            application/pdf:
              schema: { type: string, format: binary }
        '401': { description: Unauthorized }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404':
          description: Not found, not visible, or the stored object is missing
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }
        '409':
          description: This format does not preview
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }

  /documents/{id}/thumbnail:
    get:
      operationId: getDocumentThumbnail
      summary: List thumbnail of the current version (images only)
      description: |
        Requires `documents:read`; the branch fence is the same as for detail. For a
        png, jpeg, gif or webp current version of at most 25 MB, returns a WebP that
        fits in 160 × 160 pixels. It is made on the first request and stored beside the
        original. Sent with `Cache-Control: private, max-age=86400`,
        `Content-Security-Policy: default-src 'none'` and `X-Content-Type-Options: nosniff`.
        Other formats, larger originals and images that do not decode return 404
        `thumbnail_unavailable`. A missing stored file returns 404 `document_object_missing`.
        On either code the list shows the type icon.
      tags: [Documents]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: v
          in: query
          required: false
          description: The current version id. Only changes the URL so a new version is not served from the browser cache.
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: WebP thumbnail
          content:
            image/webp:
              schema: { type: string, format: binary }
        '401': { description: Unauthorized }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404':
          description: Not found or not visible (`document_not_found`), no thumbnail for this type or size (`thumbnail_unavailable`), or the stored file is missing (`document_object_missing`)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }

  /documents/{id}/trash:
    post:
      operationId: trashDocument
      summary: Move a document to Trash
      description: |
        Requires `documents:write`. Company-wide documents are read-only for a
        branch-seated caller. A document already in Trash is returned as is
        (200) and no Activity log entry is written. Requires an `Idempotency-Key`; a retry with the same key and request returns the first response.
      tags: [Documents]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      responses:
        '200':
          description: Trashed document
          content:
            application/json:
              schema: { $ref: '#/components/schemas/TenantDocument' }
        '400':
          description: A missing or invalid `Idempotency-Key` (`idempotency_key_required`, `idempotency_key_invalid`)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }
        '401': { description: Unauthorized }
        '403':
          description: Company-wide document for a branch-seated caller
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }
        '404':
          description: Not found, or not visible to the caller's branch
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }
        '422': { $ref: '#/components/responses/IdempotencyConflict' }

  /documents/{id}/restore:
    post:
      operationId: restoreDocument
      summary: Restore a document from Trash
      description: |
        Requires `documents:write`. Company-wide documents are read-only for a
        branch-seated caller. A document already not in Trash is returned as is
        (200) and no Activity log entry is written. Requires an `Idempotency-Key`; a retry with the same key and request returns the first response.
      tags: [Documents]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      responses:
        '200':
          description: Restored document
          content:
            application/json:
              schema: { $ref: '#/components/schemas/TenantDocument' }
        '400':
          description: A missing or invalid `Idempotency-Key` (`idempotency_key_required`, `idempotency_key_invalid`)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }
        '401': { description: Unauthorized }
        '403':
          description: Company-wide document for a branch-seated caller
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }
        '404':
          description: Not found, or not visible to the caller's branch
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DocumentError' }
        '422': { $ref: '#/components/responses/IdempotencyConflict' }

  /email-templates:
    get:
      operationId: listEmailTemplates
      summary: List CRM email templates
      description: |
        Requires `email_templates:read` (owner, admin, sales manager, sales rep). Tenant user
        sessions only. An account-level membership sees every branch's templates plus the
        company-wide ones. A branch-seated membership sees its own branch plus company-wide.
        Archived templates are listed only with `includeArchived=true`. Newest change first.
      tags: [EmailTemplates]
      parameters:
        - name: includeArchived
          in: query
          schema: { type: string, enum: ['true', 'false'], default: 'false' }
        - name: q
          in: query
          description: Case-insensitive match on the name or subject.
          schema: { type: string, maxLength: 120 }
        - name: limit
          in: query
          schema: { type: integer, minimum: 1, maximum: 200, default: 100 }
      responses:
        '200':
          description: Templates
          content:
            application/json:
              schema: { $ref: '#/components/schemas/EmailTemplateList' }
        '400':
          description: Invalid query
          content:
            application/json:
              schema: { $ref: '#/components/schemas/EmailTemplateError' }
        '401': { description: Unauthorized }
        '403': { $ref: '#/components/responses/Forbidden' }
    post:
      operationId: createEmailTemplate
      summary: Create an email template
      description: |
        Requires `email_templates:write`. Subject and body hold `{{field}}` or `{{field|fallback}}`
        merge fields from a fixed list; an unknown field or bad syntax is a 400 that names the field.
        Owner and admin may create a company-wide template (omit `subAccountId`). Every other
        caller creates only a branch template. A branch-seated caller creates only inside its own branch.
        Names are unique per scope (company-wide, or one branch) among non-archived templates,
        ignoring case. Sends no email.
        Requires an `Idempotency-Key`; a retry with the same key and request returns the first response.
      tags: [EmailTemplates]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/EmailTemplateCreateBody' }
      responses:
        '201':
          description: Created template (version 1)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/EmailTemplate' }
        '400':
          description: Invalid body, unknown merge field, bad merge syntax, or unknown branch; or a missing or invalid `Idempotency-Key` (`idempotency_key_required`, `idempotency_key_invalid`)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/EmailTemplateError' }
        '401': { description: Unauthorized }
        '403':
          description: Company-wide template for a caller who is not owner or admin, or a branch-seated caller outside its branch
          content:
            application/json:
              schema: { $ref: '#/components/schemas/EmailTemplateError' }
        '409':
          description: Another non-archived template in the same scope has this name
          content:
            application/json:
              schema: { $ref: '#/components/schemas/EmailTemplateError' }
        '422': { $ref: '#/components/responses/IdempotencyConflict' }

  /email-templates/{id}:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    get:
      operationId: getEmailTemplate
      summary: Get an email template
      description: |
        Requires `email_templates:read`. Another branch's template is 404 for a branch-seated caller.
      tags: [EmailTemplates]
      responses:
        '200':
          description: Template
          content:
            application/json:
              schema: { $ref: '#/components/schemas/EmailTemplate' }
        '401': { description: Unauthorized }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404':
          description: Not found, or not visible to the caller's branch
          content:
            application/json:
              schema: { $ref: '#/components/schemas/EmailTemplateError' }
    patch:
      operationId: updateEmailTemplate
      summary: Edit an email template
      description: |
        Requires `email_templates:write`. Bumps `version`. The last write wins; there is no version
        precondition. Owner and admin edit any visible template. Every other caller edits only
        templates it created, and never a company-wide one. Company-wide templates are read-only for a
        branch-seated caller. An archived template cannot be edited.
        Requires an `Idempotency-Key`; a retry with the same key and request returns the first response.
      tags: [EmailTemplates]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/EmailTemplatePatchBody' }
      responses:
        '200':
          description: Updated template
          content:
            application/json:
              schema: { $ref: '#/components/schemas/EmailTemplate' }
        '400':
          description: Invalid body, unknown merge field, or bad merge syntax; or a missing or invalid `Idempotency-Key` (`idempotency_key_required`, `idempotency_key_invalid`)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/EmailTemplateError' }
        '401': { description: Unauthorized }
        '403':
          description: Another person's template, a company-wide template for a caller who is not owner or admin, or a company-wide template for a branch-seated caller
          content:
            application/json:
              schema: { $ref: '#/components/schemas/EmailTemplateError' }
        '404':
          description: Not found, or not visible to the caller's branch
          content:
            application/json:
              schema: { $ref: '#/components/schemas/EmailTemplateError' }
        '409':
          description: Template is archived, or the name is taken in this scope
          content:
            application/json:
              schema: { $ref: '#/components/schemas/EmailTemplateError' }
        '422': { $ref: '#/components/responses/IdempotencyConflict' }
    delete:
      operationId: archiveEmailTemplate
      summary: Archive an email template
      description: |
        Requires `email_templates:write`. Sets `archivedAt`; nothing is hard-deleted and there is no
        restore route. Archiving an archived template is a no-op that returns the template. The same
        write rule as edit applies. No Idempotency-Key is used.
      tags: [EmailTemplates]
      responses:
        '200':
          description: Archived template
          content:
            application/json:
              schema: { $ref: '#/components/schemas/EmailTemplate' }
        '401': { description: Unauthorized }
        '403':
          description: Another person's template, a company-wide template for a caller who is not owner or admin, or a company-wide template for a branch-seated caller
          content:
            application/json:
              schema: { $ref: '#/components/schemas/EmailTemplateError' }
        '404':
          description: Not found, or not visible to the caller's branch
          content:
            application/json:
              schema: { $ref: '#/components/schemas/EmailTemplateError' }

  /email-templates/{id}/preview:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    post:
      operationId: previewEmailTemplate
      summary: Render a template for a lead, a customer or sample values
      description: |
        Requires `email_templates:read`. With `leadId` the caller also needs `leads:read` and the lead
        must be visible to them. With `customerId` the caller also needs `customers:read` and the
        customer must be visible. With neither id, sample values are used. A field with no value
        and no fallback is listed in `missingFields` and shown as `[field]` in the text; the route
        does not fail. Writes nothing and sends nothing.
        Requires an `Idempotency-Key`; a retry with the same key and request returns the first response.
      tags: [EmailTemplates]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/EmailTemplatePreviewBody' }
      responses:
        '200':
          description: Rendered preview
          content:
            application/json:
              schema: { $ref: '#/components/schemas/EmailTemplatePreview' }
        '400':
          description: Invalid body (both ids sent), or a stored template that no longer validates; or a missing or invalid `Idempotency-Key` (`idempotency_key_required`, `idempotency_key_invalid`)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/EmailTemplateError' }
        '401': { description: Unauthorized }
        '403':
          description: Missing `leads:read` for a lead preview, or missing `customers:read` for a customer preview
          content:
            application/json:
              schema: { $ref: '#/components/schemas/EmailTemplateError' }
        '404':
          description: Template, lead or customer not found or not visible
          content:
            application/json:
              schema: { $ref: '#/components/schemas/EmailTemplateError' }
        '422': { $ref: '#/components/responses/IdempotencyConflict' }

  /customers:
    get:
      operationId: listCustomers
      summary: List customers (cursor paginated)
      tags: [Customers]
      parameters:
        - $ref: '#/components/parameters/cursor'
        - $ref: '#/components/parameters/limit'
        - name: lead_source
          in: query
          schema: { type: string }
        - name: do_not_service
          in: query
          schema: { type: boolean }
        - name: service_status
          in: query
          schema: { type: string, enum: [active, inactive, never] }
        - name: customer_type
          in: query
          schema: { type: string, enum: [residential, commercial] }
        - name: sub_account_id
          in: query
          schema: { type: string, format: uuid, nullable: true }
        - name: lifetime_value_min_cents
          in: query
          schema: { type: integer, minimum: 0 }
        - name: lifetime_value_max_cents
          in: query
          schema: { type: integer, minimum: 0 }
      responses:
        '200':
          description: Paginated customers
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CustomerPage' }
        '400': { description: Invalid cursor or offset pagination requested }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '410': { description: Cursor filter mismatch; refetch from the first page }

  /customers/{id}:
    get:
      operationId: getCustomer
      summary: Retrieve a customer by ID
      tags: [Customers]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Customer retrieved
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Customer' }
        '400': { description: Invalid ID format }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }

    patch:
      operationId: updateCustomer
      summary: Update a customer
      tags: [Customers]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                display_name: { type: string }
                given_name: { type: string, nullable: true }
                family_name: { type: string, nullable: true }
                company_name: { type: string, nullable: true }
                role: { type: string, nullable: true }
                customer_type: { type: string, enum: [residential, commercial] }
                is_contractor: { type: boolean }
                do_not_service: { type: boolean }
                notifications_enabled: { type: boolean }
                service_status: { type: string, enum: [active, inactive, never], nullable: true }
                lead_source: { type: string, nullable: true }
                sub_account_id: { type: string, format: uuid, nullable: true }
      responses:
        '200':
          description: Customer updated
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Customer' }
        '400': { description: Invalid request (malformed customer ID or request body) }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }

    delete:
      operationId: deleteCustomer
      summary: Soft-delete a customer
      tags: [Customers]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '204': { description: Customer deleted }
        '400': { description: Invalid ID format }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }
        '409': { description: Operational customer has dependencies }

  /customers/{id}/collaborators/{userId}:
    delete:
      operationId: removeCustomerCollaborator
      summary: Remove a customer collaborator (`customers:write`; manager rights rechecked on idempotent replay)
      tags: [Customers]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: userId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [revision]
              additionalProperties: false
              properties:
                revision: { type: string }
      responses:
        '200': { description: Updated customer people roster }
        '400': { description: Invalid request or missing Idempotency-Key (`idempotency_key_required`) }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }

  /customers/{customerId}/{childResource}:
    get:
      operationId: listCustomerChildResource
      summary: List a customer child resource
      description: |
        High-volume child resources use cursor pagination and return `next_cursor`.
        People and addresses are intentionally bounded simple lists with `limit`
        clamped to 100 and no cursor support.

        For `estimates`, `lead_id` optionally narrows the customer list to one
        lead. Estimate rows include `lead_id`, `root_estimate_id`,
        `parent_estimate_id`, `version_number`, and `content_revision` when
        populated by the versioned showroom lifecycle.
      tags: [Customers]
      parameters:
        - name: customerId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: childResource
          in: path
          required: true
          schema:
            type: string
            enum:
              - people
              - addresses
              - notes
              - estimates
              - invoices
              - tasks
              - service-plans
              - leads
              - projects
              - activities
              - agreements
        - $ref: '#/components/parameters/limit'
        - $ref: '#/components/parameters/cursor'
        - name: lead_id
          in: query
          required: false
          description: Optional lead filter, supported when childResource is estimates.
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Customer child rows
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CustomerChildList' }
        '400': { description: 'Invalid customerId format, invalid cursor, unsupported cursor, or offset pagination requested' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Customer not found }
        '410': { description: Cursor filter mismatch; refetch from the first page }

  /customers/{customerId}/invoices/{id}:
    parameters:
      - name: customerId
        in: path
        required: true
        schema: { type: string, format: uuid }
      - name: id
        in: path
        required: true
        schema: { type: string, format: uuid }
    patch:
      operationId: updateCustomerInvoice
      summary: Update a customer invoice
      description: |
        Requires customer_invoices:write and customer visibility. Active payment
        collection prevents manual changes. Lead editors additionally send the
        optional invoice status/unpaid precondition; its validation and the write
        share one row-locked tenant transaction. Due dates are timestamps; the
        lead calendar editor sends a changed date at UTC midnight and omits an
        unchanged due_date to preserve its exact stored timestamp.
      tags: [Customers]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
        - $ref: '#/components/parameters/invoiceExpectedStatus'
        - $ref: '#/components/parameters/activeSubAccountId'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                invoice_number: { type: string, minLength: 1 }
                billing_type: { type: string, enum: [deposit, progress, final, one_time, service_plan_recurring] }
                status: { type: string, enum: [draft, sent, viewed, partial, paid, void, overdue] }
                amount_cents: { type: integer, minimum: 0 }
                paid_cents: { type: integer, minimum: 0 }
                project_id: { type: [string, 'null'], format: uuid }
                estimate_id: { type: [string, 'null'], format: uuid }
                due_date: { type: [string, 'null'], format: date-time }
      responses:
        '200': { description: Updated customer invoice }
        '400': { description: 'Invalid body, invoice precondition, or path parameters' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Customer or invoice not found }
        '409': { description: 'invoice_changed, payment_collection_active, project_not_found, or estimate_not_found' }
    delete:
      operationId: deleteCustomerInvoice
      summary: Delete a customer invoice
      description: |
        Requires customer_invoices:write and customer visibility. Soft-deletes
        the invoice and recomputes customer totals. The optional lead mutation
        precondition checks exact current status and zero paid cents under the
        same invoice row lock as deletion. Active payment collection also blocks
        deletion. Existing callers may omit the optimistic precondition.
      tags: [Customers]
      parameters:
        - $ref: '#/components/parameters/invoiceExpectedStatus'
        - $ref: '#/components/parameters/activeSubAccountId'
      responses:
        '204': { description: Invoice soft-deleted }
        '400': { description: Invalid invoice precondition or path parameters }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Customer or invoice not found }
        '409': { description: 'invoice_changed or payment_collection_active' }

  /customers/{customerId}/estimates/{estimateId}/take-over:
    post:
      operationId: takeOverCustomerEstimate
      summary: Take over an estimate (POR-2281)
      description: |
        Makes the caller the owner of the estimate and of every live version
        of it: each version's `assigned_user_ids` gets the caller first and
        drops the previous owner. `created_by_user_id`, the lead's assignee,
        the estimate content and `content_revision` are unchanged.

        Requires the `estimates:write` scope and a tenant user. The caller
        must be able to edit the estimate and must be an owner, admin,
        sub_account_admin or sales_manager of the estimate's customer branch.
        Writes one `estimate.taken_over` account event on success and none on
        a refusal.

        `GET /customers/{customerId}/estimates/{estimateId}` returns
        `owner_user_id` and `viewer_can_take_over` as hints; `signed` and
        `lead_closed` are refused only here.
      tags: [Customers]
      parameters:
        - name: customerId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: estimateId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      responses:
        '200':
          description: The estimate after the take-over, with `owner_user_id` set to the caller
          content:
            application/json:
              schema:
                type: object
                required: [id, owner_user_id, assigned_user_ids]
                additionalProperties: true
                properties:
                  id: { type: string, format: uuid }
                  owner_user_id: { type: string, format: uuid }
                  assigned_user_ids:
                    type: array
                    items: { type: string, format: uuid }
        '401': { description: Unauthorized }
        '403': { description: 'Forbidden: `reason: assignment_management_required` when the caller cannot reassign in the customer branch' }
        '404': { description: 'Not found, or the caller cannot edit the estimate' }
        '409': { description: '`error: take_over_refused` with `reason` one of `accepted`, `signed`, `lead_closed`, `already_owner`' }

  # ============================================================
  # POR-549 (Agreements Epic) — central Agreements register
  # ============================================================
  # An "agreement" is a row in the existing `contracts` table; there is no
  # new agreement table. The per-customer view is the `agreements` value of
  # the `/customers/{customerId}/{childResource}` enum above. This endpoint
  # is the READ-ONLY, account-wide, searchable register. It is flag-independent.
  /agreements:
    get:
      operationId: listAgreements
      summary: List agreements (central register, cursor paginated)
      description: |
        Account-wide, read-only register of every contract ("agreement"),
        one row per contract joined to its customer + property for display.
        Contracts carry no cost/margin columns; `total_amount_cents` is the
        SELL amount. Cursor v2 with `filter_hash`: a cursor minted under one
        filter set cannot be replayed under another (returns `410`). Keyset
        defaults to `(created_at, source, id) DESC` and sort changes invalidate the cursor. A contract whose customer cannot be
        resolved is rendered with a blank customer (it is NOT dropped).
        `q` is a plaintext ILIKE search over customer
        display_name/company_name/given_name/family_name and property
        street/city/zip. Requires `contracts:read` + `customers:read`.
      tags: [Contracts]
      parameters:
        - $ref: '#/components/parameters/cursor'
        - $ref: '#/components/parameters/limit'
        - name: sort_by
          in: query
          schema: { type: string, enum: [customer, subaccount, salesRep, appointmentSetter, address, status, date, total] }
          description: Sort all matching agreements. Omit for newest created first.
        - name: sort_direction
          in: query
          schema: { type: string, enum: [asc, desc] }
          description: Direction for sort_by; defaults to desc when sort_by is present.
        - name: q
          in: query
          schema: { type: string, maxLength: 100 }
          description: Plaintext ILIKE search over customer name + property address.
        - name: customer_id
          in: query
          schema: { type: string, format: uuid }
        - name: status
          in: query
          schema:
            type: string
            enum: [draft, sent, partially_signed, fully_signed, void_pending, voided, expired, unsigned, working]
          description: Legacy single-status filter. When combined with statuses, both filters apply.
        - name: statuses
          in: query
          schema: { type: string, maxLength: 1024 }
          description: JSON array of agreement statuses. An empty array applies no status filter.
        - name: date_from
          in: query
          schema: { type: string, format: date-time }
          description: Lower bound (inclusive) on contract created_at.
        - name: date_to
          in: query
          schema: { type: string, format: date-time }
          description: Upper bound (inclusive) on contract created_at.
        - name: sub_account_id
          in: query
          schema: { type: string, format: uuid, nullable: true }
      responses:
        '200':
          description: Paginated agreements register
          content:
            application/json:
              schema: { $ref: '#/components/schemas/AgreementRegisterPage' }
        '400': { description: Invalid cursor or offset pagination requested }
        '401': { description: Unauthorized }
        '403': { description: Forbidden (sub-account scope mismatch) }
        '410': { description: Cursor filter mismatch; refetch from the first page }
        '503': { description: Agreements data service temporarily unavailable }

  /contracts/{id}/pdf-preview:
    get:
      operationId: previewContractAgreementPdf
      summary: Live PDF preview of a contract agreement (POR-2456)
      description: |
        Renders the agreement PDF from the contract's stored executed document with the
        same code that writes archived versions, and streams it inline for the cockpit's
        same-origin frame. Nothing is persisted. Same visibility fence as the contract
        detail. A rep_first_v1 contract requires immutable stored agreement artifacts:
        after contract and original-source visibility checks it returns `409` with
        `stored_agreement_artifact_required`, including stopped or source-invalidated
        runs. Hidden sources remain an opaque `404`. Only positively identified legacy
        contracts can render here; unknown protocol state returns `503`. A legacy
        contract with no stored document returns `404` with a JSON body, never a PDF.
        Requires `contracts:read`. Audit event `showroom.agreement.pdf.previewed`.
      tags: [Contracts]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: The agreement PDF, inline; `Cache-Control` is `private, no-store` and the response may be framed by the same origin only
          content:
            application/pdf:
              schema: { type: string, format: binary }
        '401': { description: Unauthorized }
        '404': { description: "Agreement not found, or it has no stored document (JSON)" }
        '409':
          description: The visible rep-first agreement requires immutable stored artifacts
          content:
            application/json:
              schema:
                type: object
                required: [error]
                properties:
                  error: { type: string, enum: [stored_agreement_artifact_required] }
        '503': { description: Agreements data service or authoritative signing protocol temporarily unavailable }
    head:
      operationId: headContractAgreementPdfPreview
      summary: Check legacy PDF preview availability without rendering
      description: |
        Applies the same contract and original-source visibility checks and protocol
        refusal as GET. A visible rep-first contract returns 409; an inaccessible
        contract or source returns 404. Unknown protocol state returns 503. No PDF
        is rendered and no body is returned.
      tags: [Contracts]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200': { description: Legacy PDF preview is available }
        '401': { description: Unauthorized }
        '404': { description: Agreement or original source is unavailable }
        '409': { description: Immutable stored agreement artifacts are required }
        '503': { description: Agreements data service or authoritative signing protocol temporarily unavailable }

  /agreements/{id}/pdf:
    get:
      operationId: previewEstimateAgreementPdf
      summary: Live PDF preview of a saved estimate agreement (POR-2456)
      description: |
        `id` is a source-qualified `estimate:<uuid>`. Renders the frozen, signature-free
        saved draft document as stored (company block included) and streams it inline for
        the cockpit's same-origin frame. Working estimates and packets without a document
        return `404` with a JSON body, never a PDF. HVAC agreements go through the same
        CPM installer check as the PDF download. Same row fences and scopes as the estimate
        agreement detail. Requires `contracts:read` and `customers:read`. Audit event
        `showroom.agreement.pdf.previewed`.
      tags: [Contracts]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, pattern: '^estimate:[0-9a-fA-F-]{36}$' }
      responses:
        '200':
          description: The agreement PDF, inline; `Cache-Control` is `private, no-store` and the response may be framed by the same origin only
          content:
            application/pdf:
              schema: { type: string, format: binary }
        '401': { description: Unauthorized }
        '404': { description: "Not found, not saved, or no frozen document (JSON)" }
        '409': { description: "HVAC installer resolution refused (JSON with the CPM refusal code)" }
        '422': { description: HVAC agreement is missing its estimate or lead binding (JSON) }
        '503': { description: Agreements data service temporarily unavailable }

  /agreements/contracts/{contractId}/cockpit:
    get:
      operationId: getContractAgreementCockpit
      summary: Get a contract agreement in the Deal Cockpit shape (POR-2437)
      description: |
        The cockpit view of one contract agreement: the same field names as the
        estimate-version agreement detail, built from the contract-page fenced
        query. Frozen lines, template, payment type and a signature-free
        `document` (null once fully signed) come from the stored executed
        document; a contract without one returns its materialized line items.
        Cost-safe. Requires `contracts:read` only.
        A contract in the caller's own account that the caller may not open
        returns `403` with `contract_restricted`; anything else unknown,
        including every other account's contract, returns `404`.
      tags: [Contracts]
      parameters:
        - name: contractId
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Contract agreement cockpit detail
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized }
        '403': { description: Contract exists in the caller's account but is outside the caller's visibility (contract_restricted) }
        '404': { description: Agreement not found }
        '503': { description: Agreements data service temporarily unavailable }

  # ============================================================
  # POR-51 (E16) — Two-Signer Split sequenced signing endpoints
  # ============================================================
  /contracts/{id}:
    get:
      operationId: getAgreementDetail
      summary: Get agreement (contract) detail (POR-595)
      description: |
        Returns one tenant-scoped agreement row joined to customer and property
        for the agreement workspace page. Cost-safe: total_amount_cents is SELL only.
      tags: [Contracts]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Agreement detail
          content:
            application/json:
              schema: { $ref: '#/components/schemas/AgreementDetail' }
        '404': { description: Agreement not found }
    patch:
      operationId: patchContractAdminFields
      summary: Update agreement admin label/notes (POR-1972)
      description: |
        Tenant admin maintenance only. Writes admin_label / admin_notes
        (migration 0587). Never touches status, signatures, or the frozen
        legal payload. Requires the `contracts:write` scope, the same posture
        as POST /contracts/{id}/cancel-draft.
      tags: [Contracts]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                admin_label: { type: string, nullable: true, maxLength: 200 }
                admin_notes: { type: string, nullable: true, maxLength: 4000 }
      responses:
        '200':
          description: Updated admin fields
          content:
            application/json:
              schema:
                type: object
                required: [id, admin_label, admin_notes]
                properties:
                  id: { type: string, format: uuid }
                  admin_label: { type: string, nullable: true }
                  admin_notes: { type: string, nullable: true }
        '400': { description: Neither admin_label nor admin_notes was provided }
        '404': { description: Agreement not found }
  /contracts/{id}/signed-documents:
    get:
      operationId: listContractSignedDocuments
      summary: Provider-signed agreement, completion certificate and envelope id
      description: |
        The copy the homeowner actually signed in Zoho Sign or DocuSign and the
        provider's completion certificate, newest first per kind (signed agreement
        before certificate), plus the provider, its envelope or request id and the
        time each signer signed. Empty `data` until the provider reports the signature.
        `signers` lists the primary signer and, for a split agreement, the co-signer.
        Each `preview_url` / `download_url` is served by
        `/contracts/pdf-versions/{attachmentId}/preview|download`. Read-only; same
        visibility fence as the contract detail. Requires `contracts:read`.
      tags: [Contracts]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Signed documents for the agreement
          content:
            application/json:
              schema:
                type: object
                required: [provider, provider_document_id, signers, data]
                properties:
                  provider: { type: string, nullable: true, enum: [docusign, zoho_sign, documenso] }
                  provider_document_id: { type: string, nullable: true }
                  signers:
                    type: array
                    items:
                      type: object
                      required: [role, signed_at]
                      properties:
                        role: { type: string, enum: [primary, cosigner] }
                        signed_at: { type: string, format: date-time, nullable: true }
                  data:
                    type: array
                    items:
                      type: object
                      required: [id, kind, version, filename, size_bytes, created_at, preview_url, download_url]
                      properties:
                        id: { type: string, format: uuid }
                        kind: { type: string, enum: [signed_agreement, completion_certificate] }
                        version: { type: integer }
                        filename: { type: string }
                        size_bytes: { type: integer, nullable: true }
                        created_at: { type: string, format: date-time, nullable: true }
                        preview_url: { type: string }
                        download_url: { type: string }
        '401': { description: Unauthorized }
        '404': { description: Agreement not found }
        '503': { description: Agreements data service temporarily unavailable }
  /contracts/{id}/prepare-agreement:
    get:
      operationId: getContractPrepareAgreementPreflight
      summary: Preflight for preparing a Project-page contract draft for signing (POR-2479)
      description: |
        Read-only. Reports every reason the draft cannot be prepared yet, the
        people who can sign (a picker is needed when more than one can), the
        suggested start and substantial completion dates, and the licence
        warning. Requires the `contracts:read` scope. Tenant users only.
      tags: [Contracts]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Preflight result
          content:
            application/json:
              schema:
                type: object
                required: [contract_id, contract_status, prepared, blockers, warnings, trade, state, template_pack, signer_candidates, current_signer_person_id, signer_pick_required, suggested_schedule, financing, total_cents, deposit_cap_cents]
                properties:
                  contract_id: { type: string, format: uuid }
                  contract_status: { type: string }
                  prepared: { type: boolean }
                  blockers:
                    type: array
                    items: { type: string, enum: [contract_not_draft, remote_send_in_progress, split_signing, versioned_showroom_estimate, another_contract_exists, estimate_missing, not_project_draft, no_signer, signer_not_confirmed, missing_customer_name, missing_customer_email, missing_customer_phone, address_missing, legal_state_missing, legal_pack_missing, trade_unclassified, roofing_pricing_not_ready, account_name_missing, sub_account_identity_missing, actor_name_missing, estimate_totals_invalid, estimate_changed_since_draft, financing_changed_since_draft, project_schedule_missing, project_schedule_invalid, deposit_exceeds_cap, document_invalid, cpm_resolution_mismatch, placeholder_contractor_license, no_offer_in_state, sales_adjustment_below_baseline] }
                  warnings:
                    type: array
                    items: { type: string, enum: [missing_contractor_license] }
                  trade: { type: string, nullable: true, enum: [hvac, adu, remodeling, generator, roofing] }
                  state: { type: string, nullable: true }
                  template_pack:
                    type: object
                    nullable: true
                    properties:
                      id: { type: string }
                      version: { type: string }
                      checksum: { type: string }
                      trade: { type: string }
                      state: { type: string }
                      requires_start_completion_dates: { type: boolean }
                  signer_candidates:
                    type: array
                    items:
                      type: object
                      properties:
                        person_id: { type: string, format: uuid }
                        display_name: { type: string }
                        can_sign: { type: boolean }
                        has_email: { type: boolean }
                        has_phone: { type: boolean }
                        missing:
                          type: array
                          items: { type: string, enum: [name, email, phone] }
                  current_signer_person_id: { type: string, format: uuid, nullable: true }
                  signer_pick_required: { type: boolean }
                  suggested_schedule:
                    type: object
                    properties:
                      start_date: { type: string }
                      substantial_completion_date: { type: string }
                  financing: { type: boolean }
                  total_cents: { type: integer, nullable: true }
                  deposit_cap_cents: { type: integer, nullable: true }
        '404': { description: 'Agreement not found, not visible to the caller, or not writable by the caller (the owner, team and lead assignment write rules)' }
    post:
      operationId: prepareContractAgreement
      summary: Prepare a Project-page contract draft for signing (POR-2479)
      description: |
        Freezes the agreement document on the draft from the contract's own
        estimate snapshot, with the signer, dates, optional deposit and
        optional scope text the rep confirmed. Allowed again while the
        agreement is a draft; once it is sent its document never changes.
        Requires the `contracts:write` scope. Tenant users only. No step-up:
        nothing is signed or sent here. Writes one audit row in the same
        transaction.
      tags: [Contracts]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [signer_person_id, project_schedule]
              properties:
                signer_person_id: { type: string, format: uuid }
                project_schedule:
                  type: object
                  additionalProperties: false
                  required: [start_date, substantial_completion_date]
                  properties:
                    start_date: { type: string, pattern: '^\d{4}-\d{2}-\d{2}$' }
                    substantial_completion_date: { type: string, pattern: '^\d{4}-\d{2}-\d{2}$' }
                deposit_cents: { type: integer, minimum: 0 }
                scope_text: { type: string, maxLength: 4000 }
      responses:
        '200':
          description: Document frozen on the draft
          content:
            application/json:
              schema:
                type: object
                required: [contract_id, status, document_sha256, inputs_sha256, frozen_at, warnings]
                properties:
                  contract_id: { type: string, format: uuid }
                  status: { type: string, enum: [draft] }
                  document_sha256: { type: string }
                  inputs_sha256: { type: string }
                  frozen_at: { type: string, format: date-time }
                  warnings:
                    type: array
                    items: { type: string, enum: [missing_contractor_license] }
        '400': { description: The request body failed validation }
        '404': { description: 'Agreement not found, not visible to the caller, or not writable by the caller (the owner, team and lead assignment write rules)' }
        '409':
          description: |
            `project_agreement_not_ready` (with `reasons`), `contract_not_draft`,
            or `remote_send_in_progress`.
          content:
            application/json:
              schema:
                type: object
                required: [error, code, message]
                properties:
                  error: { type: string }
                  code: { type: string }
                  message: { type: string }
                  reasons:
                    type: array
                    items: { type: string, enum: [contract_not_draft, remote_send_in_progress, split_signing, versioned_showroom_estimate, another_contract_exists, estimate_missing, not_project_draft, no_signer, signer_not_confirmed, missing_customer_name, missing_customer_email, missing_customer_phone, address_missing, legal_state_missing, legal_pack_missing, trade_unclassified, roofing_pricing_not_ready, account_name_missing, sub_account_identity_missing, actor_name_missing, estimate_totals_invalid, estimate_changed_since_draft, financing_changed_since_draft, project_schedule_missing, project_schedule_invalid, deposit_exceeds_cap, document_invalid, cpm_resolution_mismatch, placeholder_contractor_license, no_offer_in_state, sales_adjustment_below_baseline] }
                  warnings:
                    type: array
                    items: { type: string, enum: [missing_contractor_license] }
                  request_id: { type: string }
  /contracts/{id}/cancel-draft:
    post:
      operationId: cancelDraftAgreement
      summary: Cancel a draft or sent (unsigned) agreement (POR-595)
      description: |
        Transitions a draft or sent (unsigned) agreement to `voided` without the
        void-and-reissue flow. Partially signed and fully signed agreements must
        use void-and-reissue. Writes audit log and customer/project/lead activity rows.
      tags: [Contracts]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Agreement cancelled
          content:
            application/json:
              schema:
                type: object
                required: [id, status]
                properties:
                  id: { type: string, format: uuid }
                  status: { type: string, enum: [voided] }
        '409': { description: Agreement is not in a cancellable status (draft or sent) }
  /contracts/{id}/send:
    post:
      operationId: sendContract
      summary: Send contract for signing (POR-51)
      description: |
        Remote delivery requires a connected e-sign provider and queues a
        durable provider job while the contract remains in `draft`. The worker
        provisions the provider document, persists signer mappings, dispatches
        the signing request, and then transitions the contract to `sent`.
        In-person delivery prepares a single-signer contract for attended
        capture by transitioning it to `sent`. Requires `contracts:sign` scope
        and tenant step-up freshness.
      tags: [Contracts]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                provider: { type: string, enum: [docusign, zoho_sign, documenso] }
                delivery_method: { type: string, enum: [remote, in_person] }
                cosigner_link_ttl_ms: { type: integer, minimum: 60000, description: Optional override; clamped to 7d max. }
              additionalProperties: false
      responses:
        '202':
          description: Remote provider send job accepted; contract remains draft
          content:
            application/json:
              schema:
                type: object
                required: [contract_id, status, signing_mode]
                properties:
                  contract_id: { type: string, format: uuid }
                  status: { type: string, enum: [pending_documenso_send, pending_provider_send] }
                  signing_mode: { type: string, enum: [single, split] }
                  provider: { type: string, enum: [docusign, zoho_sign, documenso] }
                  send_job_id: { type: string, format: uuid }
                  send_idempotency_key: { type: string }
                  documenso_send_job_id: { type: string, format: uuid }
                  documenso_send_idempotency_key: { type: string }
        '200':
          description: Single-signer contract sent
          content:
            application/json:
              schema:
                required: [contract_id, status, signing_mode]
                type: object
                properties:
                  contract_id: { type: string, format: uuid }
                  status: { type: string, enum: [sent] }
                  signing_mode: { type: string, enum: [single] }
        '401': { description: Unauthorized — step-up required }
        '403': { description: Forbidden — missing contracts:sign scope }
        '404': { description: Contract not found }
        '409': { description: 'Conflict — contract not in draft, split-mode without required signers, CPM freeze refusal, or `quote_expired` (the saved HVAC quote is older than 720 hours, or its Save time is unknown)' }

  /contracts/{id}/cosigner-resend:
    post:
      operationId: resendCosignerLink
      summary: Re-issue cosigner delivery (disabled)
      description: |
        Disabled while Documenso-backed resend delivery is not implemented.
        The legacy raw cosigner magic-link token path remains disabled.
        Requires `contracts:sign` scope and tenant step-up freshness.
      tags: [Contracts]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      responses:
        '501':
          description: Resend delivery is disabled
          content:
            application/json:
              schema:
                type: object
                properties:
                  error: { type: string, enum: [NotImplemented] }
                  code: { type: string, enum: [secure_cosigner_delivery_required] }
                  message: { type: string }
        '401': { description: Unauthorized — step-up required }
        '404': { description: Contract not found }
        '409': { description: Conflict — invalid status or non-split mode }

  /contracts/provider-launch/{token}:
    get:
      operationId: showAgreementProviderLaunch
      summary: Open the agreement signer's intentional continuation page
      description: |
        Public signed capability for the frozen homeowner invitation. The page
        shows a generic Continue form and creates a short-lived HttpOnly,
        SameSite=Strict nonce cookie. It does not create a provider signing URL.
        The cookie is Secure over HTTPS, lasts 600 seconds, and is scoped to
        /v1/contracts/provider-launch/. Responses are private, no-store, and
        use Referrer-Policy no-referrer, except this page (the 200 response),
        which uses same-origin so the browser sends the real Origin on the form
        POST; same-origin still sends no Referer cross-origin. Unavailable
        capabilities fail closed.
        This page's Content-Security-Policy sets form-action to 'self' plus the
        trusted Zoho Sign origins, so browsers allow the redirect that follows
        the Continue form. No other response widens form-action.
      tags: [Contracts]
      security: []
      parameters:
        - name: token
          in: path
          required: true
          schema: { type: string, pattern: '^[A-Za-z0-9_-]{43}$' }
      responses:
        '200':
          description: Generic continuation form
          content:
            text/html:
              schema: { type: string }
        '404':
          description: Unknown, expired, revoked, or completed invitation
          content:
            text/plain:
              schema: { type: string, const: 'This signing link is unavailable.' }
  /contracts/provider-launch/{token}/open:
    post:
      operationId: openAgreementProviderSigning
      summary: Continue from an active invitation to a fresh provider signing page
      description: |
        Requires the signed capability, its one-use form nonce, its matching
        HttpOnly nonce cookie, and same-origin proof. No Idempotency-Key is
        required; the one-use nonce prevents replay. The handler checks the
        active invitation, frozen source, rep signature, and saved rep artifact
        before creating a fresh provider signing URL. Successful continuation
        redirects to the validated Zoho destination. No provider URL is returned
        in JSON or stored in the notification outbox. Responses are private,
        no-store, with Referrer-Policy no-referrer.
      tags: [Contracts]
      security: []
      parameters:
        - name: token
          in: path
          required: true
          schema: { type: string, pattern: '^[A-Za-z0-9_-]{43}$' }
      requestBody:
        required: true
        content:
          application/x-www-form-urlencoded:
            schema:
              type: object
              required: [nonce]
              properties:
                nonce: { type: string, pattern: '^[A-Za-z0-9_-]{43}$' }
              additionalProperties: false
      responses:
        '303':
          description: Redirect to a fresh validated Zoho signing URL; empty body
          headers:
            Location:
              required: true
              schema: { type: string, format: uri }
        '403':
          description: |
            Invalid origin or nonce proof, for example a continue page left open
            past the 600 second nonce cookie lifetime. The HTML body asks the
            signer to open the link from their email again and links back to the
            GET page only when the path token is well formed. The response is
            private, no-store, Referrer-Policy no-referrer, with the strict
            form-action 'self' Content-Security-Policy.
          content:
            text/html:
              schema: { type: string }
        '404':
          description: |
            Invitation, source, or provider continuation unavailable, or the
            one-use nonce was already consumed. The HTML body asks the signer to
            open the link from their email again and links back to the GET page.
          content:
            text/html:
              schema: { type: string }

  /contracts/cosigner/{token}/sign:
    post:
      operationId: cosignerSign
      summary: Legacy co-signer magic-link countersign (disabled)
      description: |
        PUBLIC route kept fail-closed so old raw-token links cannot redeem.
        Documenso document/signer mappings, not body-claimed or path-token
        identifiers, are the authority for future cosigner completion.
      tags: [Contracts]
      parameters:
        - name: token
          in: path
          required: true
          schema: { type: string, minLength: 32, maxLength: 256 }
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                client_timestamp: { type: string, description: Informational only; server stamps signed_at. }
              additionalProperties: false
      responses:
        '501':
          description: Legacy cosigner token signing is disabled
          content:
            application/json:
              schema:
                type: object
                properties:
                  error: { type: string, enum: [NotImplemented] }
                  code: { type: string, enum: [secure_cosigner_delivery_required] }
                  message: { type: string }
        '401': { description: 'Unauthorized — customer step-up required, or token hash mismatch' }
        '403': { description: Forbidden — customer principal contact does not match cosigner }
        '404': { description: Invalid or unknown link }
        '409': { description: Conflict — contract not in partially_signed }
        '410': { description: Link expired }

  /leads:
    get:
      operationId: listLeads
      summary: List leads (cursor paginated)
      tags: [Leads]
      parameters:
        - $ref: '#/components/parameters/cursor'
        - $ref: '#/components/parameters/limit'
        - name: status
          in: query
          description: Filter by one or more lead statuses. Repeat the parameter or pass a comma-separated list.
          schema:
            oneOf:
              - type: string
              - type: array
                items: { type: string }
          style: form
          explode: true
        - name: source
          in: query
          description: Filter by one or more lead sources. Repeat the parameter or pass a comma-separated list.
          schema:
            oneOf:
              - type: string
              - type: array
                items: { type: string }
          style: form
          explode: true
        - name: lead_category
          in: query
          description: Filter by derived buyer segment (residential or commercial). Repeat the parameter or pass a comma-separated list.
          schema:
            oneOf:
              - type: string
                enum: [residential, commercial]
              - type: array
                items:
                  type: string
                  enum: [residential, commercial]
          style: form
          explode: true
        - name: q
          in: query
          schema: { type: string }
          description: Case-insensitive search across lead and linked customer identity fields.
        - name: sub_account_id
          in: query
          schema: { type: string, format: uuid, nullable: true }
        - name: customer_id
          in: query
          schema: { type: string, format: uuid, nullable: true }
        - name: assigned_user_id
          in: query
          schema: { type: string, format: uuid, nullable: true }
        - name: appointment_setter_user_id
          in: query
          schema: { type: string, format: uuid, nullable: true }
        - name: include_archived
          in: query
          schema: { type: boolean }
          description: When true, returns both active and archived leads. Default excludes archived.
        - name: archived_only
          in: query
          schema: { type: boolean }
          description: When true, returns only archived leads.
        - name: exclude_converted
          in: query
          schema: { type: boolean }
          description: When true, omits leads that have already been converted (converted_at set). Used by customer-capture prefill.
      responses:
        '200':
          description: Paginated leads
          content:
            application/json:
              schema: { $ref: '#/components/schemas/LeadPage' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
    post:
      operationId: createLead
      summary: Create a lead (person-first; customer_id rejected until fully signed)
      tags: [Leads]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [source]
              properties:
                source: { type: string }
                raw_address: { type: object }
                contact_name: { type: string }
                given_name: { type: string }
                family_name: { type: string }
                display_name: { type: string }
                company_name: { type: string }
                contact_email: { type: string, format: email }
                contact_phone: { type: string }
                sub_account_id: { type: string, format: uuid, nullable: true }
                customer_id:
                  type: string
                  format: uuid
                  nullable: true
                  description: Rejected with 409 agreement_required (POR-1111). Use for_customer_id to pin a person without linking.
                for_customer_id:
                  type: string
                  format: uuid
                  description: Pin leads.primary_person_id to this customer's primary person without setting leads.customer_id.
                assigned_user_id: { type: string, format: uuid, nullable: true }
                appointment_setter_user_id: { type: string, format: uuid, nullable: true }
                duplicate_action: { type: string, enum: [create, replace, merge] }
                replace_lead_id: { type: string, format: uuid }
                merge_lead_id: { type: string, format: uuid }
                created_via: { type: string, enum: [leads_page, quick_add, showroom_quote] }
                email_match:
                  type: object
                  additionalProperties: false
                  required: [decision]
                  description: The rep's answer to "same person?" (POR-2715). person_id is required with same_person and not allowed with different_person.
                  properties:
                    decision: { type: string, enum: [same_person, different_person] }
                    person_id: { type: string, format: uuid }
              additionalProperties: false
      responses:
        '201':
          description: |
            Lead created. After a "same person" answer the lead anchors on the
            existing person and the typed email, phone and address are not
            written onto it; `same_person_kept` lists the typed values that
            differ from the stored ones (POR-2744).
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Lead' }
        '409':
          description: |
            One of:
            - agreement_required — body.customer_id was supplied (pre-sign link rejected)
            - lead_duplicate — matching person-scoped lead exists; supply duplicate_action
            - email_match_confirmation_required — the email belongs, or belonged, to another person; resend with email_match (body.matches)
            - email_match_invalid — the chosen person no longer matches the email
            - contact_already_used — the email or phone is on file for another customer or person
            - Idempotency key conflict — previous response returned

  /leads/pipeline-summary:
    get:
      operationId: getLeadPipelineSummary
      summary: Lead pipeline aggregates by status (dashboard KPIs)
      description: |
        Returns per-status lead counts and value totals plus an open-pipeline rollup
        (excludes closed_won, closed_lost, no_show). Uses the same tenancy and ABAC
        visibility as GET /v1/leads without loading row payloads.
      tags: [Leads]
      responses:
        '200':
          description: Pipeline summary
          content:
            application/json:
              schema: { $ref: '#/components/schemas/LeadPipelineSummary' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }

  /leads/stage-definitions:
    get:
      operationId: getLeadStageDefinitions
      summary: Lead stage definitions with win probability
      description: |
        Returns the ten lead stages in funnel order with the account's effective win
        probability in basis points (10000 = 100%). Requires the leads:read scope.
      tags: [Leads]
      responses:
        '200':
          description: Stage definitions
          content:
            application/json:
              schema:
                type: object
                required: [stages]
                properties:
                  stages:
                    type: array
                    items: { $ref: '#/components/schemas/LeadStageDefinition' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }

  /leads/{id}:
    get:
      operationId: getLead
      summary: Get a lead by ID
      tags: [Leads]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Lead retrieved
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Lead' }
        '400': { description: Invalid ID format }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }
    patch:
      operationId: updateLead
      summary: Update a lead
      description: >
        Sparse update under the existing lead write scope and record access.
        Service interests follow the existing lead edit permissions. Only a
        tenant owner or admin can set or clear the sales manager; API keys and
        other roles cannot change that field. Omitted fields stay unchanged.
      tags: [Leads]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                status:
                  type: string
                  enum: [new, contacted, qualified, appointment_set, appointment_held, proposal_sent, closed_lost, no_show]
                  description: closed_won is only set by POST /leads/{id}/convert.
                assigned_user_id: { type: [string, 'null'], format: uuid }
                appointment_setter_user_id: { type: [string, 'null'], format: uuid }
                expected_close_date:
                  type: [string, 'null']
                  format: date
                  description: >
                    Expected close date as a plain yyyy-mm-dd calendar date
                    (no time zone). null clears it. An impossible date such as
                    2026-02-30 is a 400. Read by the pipeline forecast report.
                sales_manager_user_id:
                  type: [string, 'null']
                  format: uuid
                  description: >
                    Owner or admin only, including clearing with null. The
                    target must be an active human user with an active
                    membership in this account, either account-wide or matching
                    the lead branch. A branch move rechecks the retained
                    manager. Omission preserves the current manager.
                service_interests: { $ref: '#/components/schemas/LeadServiceInterests' }
                do_not_call: { type: boolean, description: 'Restrict calls on this lead. Omission preserves the saved value; false does not grant consent.' }
                do_not_text: { type: boolean, description: 'Restrict texts on this lead. Omission preserves the saved value; false does not grant consent.' }
                do_not_email: { type: boolean, description: 'Restrict email on this lead. Omission preserves the saved value; false does not grant consent.' }
                sub_account_id: { type: [string, 'null'], format: uuid }
                customer_id: { type: [string, 'null'], format: uuid }
                custom_fields_json:
                  type: object
                  additionalProperties: true
                archived: { type: boolean, description: 'Set true to archive, false to restore.' }
              additionalProperties: false
      responses:
        '200':
          description: Lead updated
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Lead' }
        '400': { description: Invalid request (malformed lead ID or request body) }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '409': { description: 'Conflict, including sales_manager_not_available for an inactive, foreign-account, service, or branch-mismatched manager; closed_won requires conversion.' }
        '404': { description: Not Found }
    delete:
      operationId: deleteLead
      summary: Soft-delete a lead
      tags: [Leads]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '204': { description: Lead deleted }
        '400': { description: Invalid ID format }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }

  /leads/{id}/collaborators/{userId}:
    delete:
      operationId: removeLeadCollaborator
      summary: Remove a lead collaborator (`leads:write`; manager rights rechecked on idempotent replay)
      tags: [Leads]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: userId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [revision]
              additionalProperties: false
              properties:
                revision: { type: string }
      responses:
        '200': { description: Updated lead people roster }
        '400': { description: Invalid request or missing Idempotency-Key (`idempotency_key_required`) }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }

  /leads/{id}/link-customer:
    post:
      operationId: linkLeadCustomer
      summary: Link a lead to a customer or create a customer from reviewed lead data
      tags: [Leads]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              oneOf:
                - type: object
                  required: [customer_id]
                  properties:
                    customer_id: { type: string, format: uuid }
                  additionalProperties: false
                - type: object
                  required: [create_customer]
                  properties:
                    create_customer:
                      type: object
                      required: [display_name]
                      properties:
                        display_name: { type: string }
                        given_name: { type: string }
                        family_name: { type: string }
                        company_name: { type: string }
                        customer_type: { type: string, enum: [residential, commercial] }
                        contact_email: { type: string, format: email, maxLength: 320 }
                        contact_phone: { type: string, maxLength: 32 }
                      additionalProperties: false
                  additionalProperties: false
      responses:
        '200':
          description: Lead linked to customer
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Lead' }
        '400': { description: Invalid request }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }

  /leads/{id}/unlink-customer:
    post:
      operationId: unlinkLeadCustomer
      summary: Remove a customer link from a lead
      tags: [Leads]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      responses:
        '200':
          description: Lead unlinked from customer
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Lead' }
        '400': { description: Invalid ID format }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }

  /leads/{id}/convert:
    post:
      operationId: convertLead
      summary: Convert a lead into a project
      tags: [Leads]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [property_id]
              properties:
                property_id: { type: string, format: uuid }
                customer_id: { type: [string, 'null'], format: uuid }
                owner_user_id: { type: [string, 'null'], format: uuid }
                total_contracted_amount_cents: { type: [integer, 'null'] }
              additionalProperties: false
      responses:
        '200':
          description: Existing converted project returned
          content:
            application/json:
              schema: { $ref: '#/components/schemas/LeadConversionResult' }
        '201':
          description: Lead converted to project
          content:
            application/json:
              schema: { $ref: '#/components/schemas/LeadConversionResult' }
        '400': { description: Invalid request (malformed lead ID or request body) }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }
        '409': { description: Customer required }

  /lead-sources:
    get:
      operationId: listLeadSources
      summary: List lead-source definitions and delivery health
      tags: [Lead Sources]
      parameters:
        - name: status
          in: query
          schema: { type: string, enum: [active, paused, revoked] }
        - name: source_type
          in: query
          schema: { type: string, enum: [manual, web_form, csv_import, api, lead_buy, partner_webhook] }
      responses:
        '200':
          description: Lead sources
          content:
            application/json:
              schema:
                type: object
                required: [data, next_cursor]
                properties:
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/LeadSource' }
                  next_cursor: { type: [string, 'null'] }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
    post:
      operationId: createLeadSource
      summary: Create a lead source and reveal its secret once
      description: |
        All responses, including errors, use `Cache-Control: no-store`.
        The secret response is never retained or replayed by idempotency storage.
        A completed key returns `409 idempotency_secret_response_unavailable`.
        The original operation may already have committed. Do not automatically
        retry with a fresh key; inspect the resource before recovery or an
        intentional new creation or rotation.
      tags: [Lead Sources]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name]
              properties:
                name: { type: string, minLength: 1, maxLength: 200 }
                source_type:
                  type: string
                  enum: [manual, web_form, csv_import, api, lead_buy, partner_webhook]
                sub_account_id: { type: [string, 'null'], format: uuid }
                default_assigned_user_id: { type: [string, 'null'], format: uuid }
                default_team_id: { type: [string, 'null'], format: uuid }
                default_status:
                  type: string
                  enum: [new, contacted, qualified, appointment_set, appointment_held, proposal_sent, closed_lost, no_show]
                dedupe_policy_json:
                  $ref: '#/components/schemas/LeadSourceDedupePolicy'
                field_mapping_json: { type: object, additionalProperties: true }
              additionalProperties: false
      responses:
        '201':
          description: Source created; secret is shown once.
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/LeadSource' }
        '400': { description: Invalid source configuration }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden }
        '409': { $ref: '#/components/responses/SecretOperationConflict' }

  /lead-sources/{id}:
    patch:
      operationId: updateLeadSource
      summary: Update lead-source routing defaults or status
      description: |
        `dedupe_policy_json` is merged into the stored policy: keys that are not sent, and keys this API
        does not know, are kept. An empty object changes nothing. To turn a match key off, send it as `off`.
      tags: [Lead Sources]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                name: { type: string, minLength: 1, maxLength: 200 }
                source_type:
                  type: string
                  enum: [manual, web_form, csv_import, api, lead_buy, partner_webhook]
                status: { type: string, enum: [active, paused, revoked] }
                sub_account_id: { type: [string, 'null'], format: uuid }
                default_assigned_user_id: { type: [string, 'null'], format: uuid }
                default_team_id: { type: [string, 'null'], format: uuid }
                default_status:
                  type: string
                  enum: [new, contacted, qualified, appointment_set, appointment_held, proposal_sent, closed_lost, no_show]
                dedupe_policy_json:
                  $ref: '#/components/schemas/LeadSourceDedupePolicy'
                field_mapping_json: { type: object, additionalProperties: true }
              additionalProperties: false
      responses:
        '200':
          description: Source updated
          content:
            application/json:
              schema: { $ref: '#/components/schemas/LeadSource' }
        '400': { description: 'Invalid source configuration, or `invalid_dedupe_policy` when `phone`, `company_domain` or `version` has an unsupported value' }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden }
        '404': { description: Not Found }
    delete:
      operationId: revokeLeadSource
      summary: Revoke a lead source credential
      tags: [Lead Sources]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '204': { description: Source revoked }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden }
        '404': { description: Not Found }

  /lead-sources/{id}/rotate-secret:
    post:
      operationId: rotateLeadSourceSecret
      summary: Rotate a lead-source secret and reveal the new secret once
      description: |
        All responses, including errors, use `Cache-Control: no-store`.
        The secret response is never retained or replayed by idempotency storage.
        A completed key returns `409 idempotency_secret_response_unavailable`.
        The original operation may already have committed. Do not automatically
        retry with a fresh key; inspect the resource before recovery or an
        intentional new creation or rotation.
      tags: [Lead Sources]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      responses:
        '200':
          description: Secret rotated; new secret is shown once.
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/LeadSource' }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden }
        '404': { description: Not Found }
        '409': { $ref: '#/components/responses/SecretOperationConflict' }

  /lead-sources/{id}/test:
    post:
      operationId: testLeadSource
      summary: Dry-run or commit-test a lead intake payload
      tags: [Lead Sources]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [payload]
              properties:
                commit:
                  type: boolean
                  description: When true, creates a real lead and requires fresh step-up.
                payload: { $ref: '#/components/schemas/LeadIntakePayload' }
              additionalProperties: false
      responses:
        '200':
          description: Intake test result
          content:
            application/json:
              schema:
                type: object
                required: [ok, committed, result]
                properties:
                  ok: { type: boolean }
                  committed: { type: boolean }
                  result: { $ref: '#/components/schemas/LeadIntakeResult' }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden }
        '404': { description: Not Found }
        '409': { description: Source is not active }

  /inbound/leads/{sourceKey}:
    post:
      operationId: receiveInboundLead
      summary: Receive a signed public lead-source delivery
      tags: [Lead Sources]
      security: []
      parameters:
        - name: sourceKey
          in: path
          required: true
          schema: { type: string }
        - name: X-Portrex-Source-Secret
          in: header
          required: false
          schema: { type: string }
        - name: Authorization
          in: header
          required: false
          schema: { type: string }
          description: Bearer form of the source secret. Either this header or X-Portrex-Source-Secret is required.
        - name: Idempotency-Key
          in: header
          required: true
          schema: { type: string, minLength: 1, maxLength: 128 }
          description: Required for every accepted source delivery. Reusing the same key with a different payload returns an idempotency conflict.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/LeadIntakePayload' }
      responses:
        '202': { description: Lead delivery accepted }
        '200': { description: Duplicate delivery replayed }
        '400': { description: Missing Idempotency-Key }
        '401': { description: Invalid source secret }
        '404': { description: Source not found }
        '409': { description: Source paused or inactive }
        '410': { description: Source revoked }
        '422': { description: Payload rejected }

  /bulk/leads:
    post:
      operationId: createBulkLeadJob
      summary: Import up to 1,000 leads in one authenticated request with per-account backpressure
      tags: [Bulk Leads]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [leads]
              properties:
                leads:
                  type: array
                  minItems: 1
                  maxItems: 1000
                  items:
                    allOf:
                      - $ref: '#/components/schemas/LeadIntakePayload'
                      - type: object
                        properties:
                          lead_source_id: { type: [string, 'null'], format: uuid }
                          source: { type: [string, 'null'] }
              additionalProperties: false
      responses:
        '202':
          description: Bulk job created and processed
          content:
            application/json:
              schema:
                type: object
                required: [job, items]
                properties:
                  job: { $ref: '#/components/schemas/BulkLeadJob' }
                  items:
                    type: array
                    items: { $ref: '#/components/schemas/BulkLeadJobItem' }
        '200': { description: Idempotent bulk job replay }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '422': { description: Idempotency-Key reused with different payload }
        '429': { description: Account already has five active bulk lead jobs }

  /bulk/jobs/{jobId}:
    get:
      operationId: getBulkLeadJob
      summary: Get a bulk lead job and row results
      tags: [Bulk Leads]
      parameters:
        - name: jobId
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Bulk job and items
          content:
            application/json:
              schema:
                type: object
                required: [job, items]
                properties:
                  job: { $ref: '#/components/schemas/BulkLeadJob' }
                  items:
                    type: array
                    items: { $ref: '#/components/schemas/BulkLeadJobItem' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }

  /projects/{projectId}/hvac-design:
    get:
      operationId: listProjectHvacDesigns
      summary: List HVAC final-design revisions for a project
      tags: [Projects]
      parameters:
        - name: projectId
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Design revisions (Project HVAC owning surface)
          content:
            application/json:
              schema:
                type: object
                required: [projectId, designs, owningSurface]
                properties:
                  projectId: { type: string, format: uuid }
                  owningSurface: { type: string, enum: [project_hvac] }
                  designs:
                    type: array
                    items:
                      type: object
                      required: [id, estimateId, revision, status, totalConditionedAreaSqft]
                      properties:
                        id: { type: string, format: uuid }
                        estimateId: { type: string, format: uuid }
                        revision: { type: integer, minimum: 1 }
                        status: { type: string, enum: [draft, final, superseded] }
                        totalConditionedAreaSqft: { type: number }
                        finalizedAt: { type: string, format: date-time, nullable: true }
        '401': { description: Unauthorized }
    put:
      operationId: upsertProjectHvacDesign
      summary: Create a draft HVAC final-design revision
      tags: [Projects]
      parameters:
        - name: projectId
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/HvacFinalDesignUpsert'
      responses:
        '201':
          description: Draft revision created
        '400': { description: Invalid design }
        '401': { description: Unauthorized }
    post:
      operationId: createProjectHvacDesign
      summary: Create a draft HVAC final-design revision
      tags: [Projects]
      parameters:
        - name: projectId
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/HvacFinalDesignUpsert'
      responses:
        '201':
          description: Draft revision created
        '400': { description: Invalid design }
        '401': { description: Unauthorized }
  /projects/{projectId}/hvac-design/revisions:
    get:
      operationId: listProjectHvacDesignRevisions
      summary: Cursor-paginated HVAC design revisions for a project
      tags: [Projects]
      parameters:
        - name: projectId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: limit
          in: query
          schema: { type: integer, minimum: 1, maximum: 100 }
        - name: cursor
          in: query
          schema: { type: string }
      responses:
        '200':
          description: HVAC design revisions page
          content:
            application/json:
              schema:
                type: object
                required: [projectId, designs, nextCursor]
                properties:
                  projectId: { type: string, format: uuid }
                  designs: { type: array, items: { type: object, additionalProperties: true } }
                  nextCursor: { type: string, nullable: true }
        '400': { description: Invalid pagination }
        '401': { description: Unauthorized }
        '404': { description: Project not found }
  /projects/{projectId}/hvac-design/{designId}/systems:
    get:
      operationId: listProjectHvacDesignSystems
      summary: Cursor-paginated HVAC systems for a design revision (non-cost fields)
      tags: [Projects]
      parameters:
        - name: projectId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: designId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: limit
          in: query
          schema: { type: integer, minimum: 1, maximum: 100 }
        - name: cursor
          in: query
          schema: { type: string }
      responses:
        '200':
          description: HVAC design systems page
          content:
            application/json:
              schema:
                type: object
                required: [projectId, design, systems, nextCursor]
                properties:
                  projectId: { type: string, format: uuid }
                  design: { type: object, additionalProperties: true }
                  systems: { type: array, items: { type: object, additionalProperties: true } }
                  nextCursor: { type: string, nullable: true }
        '400': { description: Invalid pagination }
        '401': { description: Unauthorized }
        '404': { description: Design not found }
  /projects/{projectId}/hvac-design/{designId}/components:
    get:
      operationId: listProjectHvacDesignComponents
      summary: Cursor-paginated HVAC components for a design revision (non-cost fields)
      tags: [Projects]
      parameters:
        - name: projectId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: designId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: limit
          in: query
          schema: { type: integer, minimum: 1, maximum: 100 }
        - name: cursor
          in: query
          schema: { type: string }
      responses:
        '200':
          description: HVAC design components page
          content:
            application/json:
              schema:
                type: object
                required: [projectId, design, components, nextCursor]
                properties:
                  projectId: { type: string, format: uuid }
                  design: { type: object, additionalProperties: true }
                  components: { type: array, items: { type: object, additionalProperties: true } }
                  nextCursor: { type: string, nullable: true }
        '400': { description: Invalid pagination }
        '401': { description: Unauthorized }
        '404': { description: Design not found }
  /projects/{projectId}/hvac-design/finalize:
    post:
      operationId: finalizeProjectHvacDesign
      summary: Finalize a draft HVAC design revision (immutable thereafter)
      tags: [Projects]
      parameters:
        - name: projectId
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [designId]
              properties:
                designId: { type: string, format: uuid }
      responses:
        '200':
          description: Design finalized
        '400': { description: Finalize failed }
        '401': { description: Unauthorized }
        '404': { description: Design not found }
        '409': { description: Design not draft }
  /projects:
    get:
      operationId: listProjects
      summary: List projects visible to the caller
      tags: [Projects]
      parameters:
        - $ref: '#/components/parameters/cursor'
        - $ref: '#/components/parameters/limit'
        - name: status
          in: query
          schema:
            type: string
            enum: [active, closed_won, closed_lost, on_hold, archived]
        - name: sub_account_id
          in: query
          schema: { type: string, format: uuid, nullable: true }
        - name: customer_id
          in: query
          schema: { type: string, format: uuid }
        - name: property_id
          in: query
          schema: { type: string, format: uuid }
        - name: owner_user_id
          in: query
          schema: { type: string, format: uuid, nullable: true }
        - name: q
          in: query
          schema: { type: string, maxLength: 500 }
        - name: scope
          in: query
          schema: { type: string, enum: [all, company, mine] }
        - name: accounts
          in: query
          description: JSON array of account labels.
          schema: { type: string }
        - name: owners
          in: query
          description: JSON array of owner labels.
          schema: { type: string }
        - name: services
          in: query
          description: JSON array of service labels.
          schema: { type: string }
        - name: cities
          in: query
          description: JSON array of city labels.
          schema: { type: string }
        - name: statuses
          in: query
          description: JSON array of portfolio status values.
          schema: { type: string }
        - name: phases
          in: query
          description: JSON array of portfolio phase values.
          schema: { type: string }
        - name: value_band
          in: query
          schema: { type: string, enum: [all, lt15, 15to30, 30to60, gt60] }
        - name: show_closed
          in: query
          schema: { type: string, enum: ['true', 'false'] }
        - name: sort
          in: query
          schema:
            type: string
            enum: [updated_desc, updated_asc, value_desc, value_asc, name_asc, name_desc, created_desc, created_asc, target_close_asc, target_close_desc, phase_progress, phase_progress_desc]
      responses:
        '200':
          description: Project page
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ProjectPage' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
    post:
      operationId: createProject
      summary: Create a project
      tags: [Projects]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [customer_id, property_id]
              properties:
                customer_id: { type: string, format: uuid }
                property_id: { type: string, format: uuid }
                sub_account_id: { type: string, format: uuid, nullable: true }
                lead_id: { type: string, format: uuid, nullable: true }
                primary_contact_id: { type: string, format: uuid, nullable: true }
                owner_user_id: { type: string, format: uuid, nullable: true }
                status:
                  type: string
                  enum: [active, closed_won, closed_lost, on_hold, archived]
                total_contracted_amount_cents: { type: integer, nullable: true }
              additionalProperties: false
      responses:
        '201':
          description: Project created
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Project' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '409':
          description: Idempotency key conflict — previous response returned

  /project-snapshots:
    get:
      operationId: listProjectSnapshots
      summary: List read-only project snapshots (cursor paginated)
      description: |
        Integrator read model: one object per project with its customer,
        property, lead, estimates, invoices, contracts, tasks and stage history.
        Requires projects:read. Each section is gated by its own scope and is
        null, with a reason in `unavailable`, when the caller lacks it:
        customers:read (customer), properties:read (property), leads:read
        (lead), estimates:read, customer_invoices:read, contracts:read and
        tasks:read. `lead.lead_source_name` additionally needs lead_sources:read
        and is never returned to API keys or integration users. Money appears
        only on invoices and contracts, never on the project itself, and no cost,
        margin, markup or vendor data is ever returned. `lead.source_raw` is the
        raw lead source enum, not a lead type.

        Each child section returns at most 50 rows per project (stage history
        100). When more exist the first rows are returned and
        `unavailable.<section>_truncated` says so; the payload is partial, not
        complete. Estimate totals sum only lines that are neither child lines nor
        optional; a null `commission_treatment` means commissionable.

        Pagination uses an opaque, filter-bound cursor with microsecond
        precision. A cursor replayed under a different `status` returns 410.
        Every call is written to the account audit log.
      tags: [Projects]
      parameters:
        - $ref: '#/components/parameters/cursor'
        - name: limit
          in: query
          schema: { type: integer, minimum: 1, maximum: 50, default: 25 }
        - name: status
          in: query
          schema:
            type: string
            enum: [active, closed_won, closed_lost, on_hold, archived]
      responses:
        '200':
          description: Project snapshot page
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ProjectSnapshotPage' }
        '400': { description: Invalid query or malformed cursor }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '410': { description: Cursor filter mismatch; refetch from the first page }

  /project-snapshots/{id}:
    get:
      operationId: getProjectSnapshot
      summary: Get one read-only project snapshot
      description: |
        Same payload and per-section scope gating as the list route
        (projects:read plus customers:read, properties:read, leads:read,
        lead_sources:read, estimates:read, contracts:read,
        customer_invoices:read and tasks:read for their sections). Returns 404
        when the project is not visible to the caller.
      tags: [Projects]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Project snapshot
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ProjectSnapshot' }
        '400': { description: Invalid id }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }

  /estimates:
    get:
      operationId: listAccountEstimates
      summary: List account-wide estimates (cursor paginated)
      description: |
        Account-wide estimates register joined to the parent customer for
        display fields. Added in perf wave 3 (POR-870) to replace the web
        Estimates page per-customer request fan-out. Cost/margin fields are
        redacted unless the caller holds pricebook:cost:read.
      tags: [Estimates]
      parameters:
        - name: cursor
          in: query
          required: false
          schema: { type: string }
        - name: limit
          in: query
          required: false
          schema: { type: string }
        - name: status
          in: query
          required: false
          schema: { type: string }
        - name: q
          in: query
          schema: { type: string, maxLength: 500 }
        - name: statuses
          in: query
          description: JSON array of estimate statuses.
          schema: { type: string }
        - name: sources
          in: query
          description: JSON array of displayed source labels.
          schema: { type: string }
        - name: link
          in: query
          schema: { type: string, enum: [all, project_linked, unlinked] }
        - name: value_band
          in: query
          schema: { type: string, enum: [all, lt5, 5to15, 15to40, gt40] }
        - name: date_window
          in: query
          schema: { type: string, enum: [all, last7, last30, last90, no_date] }
        - name: sort
          in: query
          schema: { type: string, enum: [lifecycle_desc, lifecycle_asc, total_desc, total_asc, estimate_asc, estimate_desc, customer_asc, customer_desc, status_asc, status_desc, created_desc, created_asc] }
      responses:
        '200':
          description: One page of estimates with customer display fields, filtered total, and source_options from all visible estimates
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PaginatedResponse' }
        '400': { description: Invalid cursor or pagination params }
        '401': { description: Unauthorized }
        '403': { description: Missing customers:read + estimates:read scopes }

  /projects/{id}/estimates:
    get:
      operationId: listProjectEstimates
      summary: List project-scoped estimates
      tags: [Projects]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/cursor'
        - $ref: '#/components/parameters/limit'
      responses:
        '200':
          description: Project estimate page
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ProjectEstimatePage' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }
    post:
      operationId: createProjectEstimate
      summary: Create a project-scoped estimate
      tags: [Projects]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [estimate_number]
              additionalProperties: false
              properties:
                estimate_number: { type: string, minLength: 1 }
                description: { type: string, nullable: true }
                notes: { type: string, nullable: true }
                total_cents: { type: integer, minimum: 0, nullable: true }
                lead_source: { type: string, nullable: true }
                line_items:
                  type: array
                  items: {}
                design_id: { type: string, format: uuid, nullable: true }
                address_id: { type: string, format: uuid, nullable: true }
                expires_at: { type: string, format: date-time, nullable: true }
      responses:
        '201':
          description: Project estimate created
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ProjectEstimate' }
        '400': { description: Invalid request }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }
        '409': { description: Project customer or reference boundary conflict }

  /projects/{id}/estimates/{estimateId}:
    patch:
      operationId: updateProjectEstimate
      summary: Update a project-scoped estimate
      tags: [Projects]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: estimateId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                estimate_number: { type: string, minLength: 1 }
                description: { type: string, nullable: true }
                notes: { type: string, nullable: true }
                total_cents: { type: integer, minimum: 0, nullable: true }
                lead_source: { type: string, nullable: true }
                status:
                  type: string
                  enum: [draft, sent, viewed, declined, expired]
                line_items:
                  type: array
                  items: {}
                design_id: { type: string, format: uuid, nullable: true }
                address_id: { type: string, format: uuid, nullable: true }
                expires_at: { type: string, format: date-time, nullable: true }
      responses:
        '200':
          description: Project estimate
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ProjectEstimate' }
        '400': { description: Invalid request }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }
        '409': { description: Project customer or reference boundary conflict }

  /projects/{id}/estimates/{estimateId}/accept:
    post:
      operationId: acceptProjectEstimate
      summary: Accept a project-scoped estimate
      tags: [Projects]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: estimateId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      responses:
        '200':
          description: Project estimate accepted
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ProjectEstimate' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }
        '409': { description: 'Project customer conflict, company floor breached, or showroom_agreement_required (a versioned showroom estimate is accepted only by signing its agreement)' }

  /projects/{id}/invoices:
    get:
      operationId: listProjectInvoices
      summary: List project-scoped invoices
      tags: [Projects]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/cursor'
        - $ref: '#/components/parameters/limit'
      responses:
        '200':
          description: Project invoice page
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ProjectInvoicePage' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }
    post:
      operationId: createProjectInvoice
      summary: Create a project-scoped invoice
      tags: [Projects]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [invoice_number, amount_cents]
              additionalProperties: false
              properties:
                invoice_number: { type: string, minLength: 1 }
                amount_cents: { type: integer, minimum: 0 }
                billing_type:
                  type: string
                  enum: [deposit, progress, final, one_time, service_plan_recurring]
                estimate_id: { type: string, format: uuid, nullable: true }
                due_date: { type: string, format: date-time, nullable: true }
      responses:
        '201':
          description: Project invoice created
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ProjectInvoice' }
        '400': { description: Invalid request }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }
        '409': { description: Project customer or estimate boundary conflict }

  /projects/{id}/invoices/{invoiceId}:
    patch:
      operationId: updateProjectInvoice
      summary: Update a project-scoped invoice
      tags: [Projects]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: invoiceId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                invoice_number: { type: string, minLength: 1 }
                billing_type:
                  type: string
                  enum: [deposit, progress, final, one_time, service_plan_recurring]
                status:
                  type: string
                  enum: [draft, sent, viewed, partial, paid, void, overdue]
                amount_cents: { type: integer, minimum: 0 }
                paid_cents: { type: integer, minimum: 0 }
                estimate_id: { type: string, format: uuid, nullable: true }
                due_date: { type: string, format: date-time, nullable: true }
      responses:
        '200':
          description: Project invoice
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ProjectInvoice' }
        '400': { description: Invalid request }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }
        '409': { description: Project boundary conflict or active payment collection }

  /projects/{id}/invoices/{invoiceId}/mark_paid:
    post:
      operationId: markProjectInvoicePaid
      summary: Mark a project-scoped invoice paid
      tags: [Projects]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: invoiceId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      responses:
        '200':
          description: Project invoice marked paid
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ProjectInvoice' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }
        '409': { description: Project customer conflict or active payment collection }

  /projects/{id}/contracts:
    get:
      operationId: listProjectContracts
      summary: List project-scoped contract drafts
      tags: [Projects]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/cursor'
        - $ref: '#/components/parameters/limit'
      responses:
        '200':
          description: Project contract page
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ProjectContractPage' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }
    post:
      operationId: createProjectContractDraft
      summary: Create a project-scoped contract draft from an accepted estimate
      description: Creates the native contract draft/handoff record. Provider delivery, countersign, and native signing use their dedicated authenticated routes.
      tags: [Projects]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [estimate_id]
              additionalProperties: false
              properties:
                estimate_id: { type: string, format: uuid }
                signing_mode:
                  type: string
                  enum: [single, split]
                customer_person_id: { type: string, format: uuid, nullable: true }
                primary_signer_person_id: { type: string, format: uuid, nullable: true }
                cosigner_person_id: { type: string, format: uuid, nullable: true }
                customer_contact_id: { type: string, format: uuid, nullable: true }
                primary_signer_contact_id: { type: string, format: uuid, nullable: true }
                cosigner_contact_id: { type: string, format: uuid, nullable: true }
      responses:
        '201':
          description: Project contract draft created
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ProjectContract' }
        '400': { description: Invalid request }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }
        '409': { description: 'Project, estimate, or signer boundary conflict' }

  /projects/{id}/notes:
    get:
      operationId: listProjectNotes
      summary: List project-scoped notes
      tags: [Projects]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/cursor'
        - $ref: '#/components/parameters/limit'
      responses:
        '200':
          description: Project note page
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ProjectNotePage' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }
    post:
      operationId: createProjectNote
      summary: Create a project-scoped note and matching activity row
      tags: [Projects]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [body]
              additionalProperties: false
              properties:
                body: { type: string, minLength: 1, maxLength: 10000 }
      responses:
        '201':
          description: Project note created
          content:
            application/json:
              schema:
                type: object
                required: [note_id, activity_id]
                properties:
                  note_id: { type: string, format: uuid }
                  activity_id: { type: string, format: uuid }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }

  /projects/{id}/notes/{noteId}:
    patch:
      operationId: updateProjectNote
      summary: Update a project-scoped note
      tags: [Projects]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: noteId
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [body]
              additionalProperties: false
              properties:
                body: { type: string, minLength: 1, maxLength: 10000 }
      responses:
        '200':
          description: Project note
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ProjectNote' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }
    delete:
      operationId: deleteProjectNote
      summary: Soft-delete a project-scoped note
      tags: [Projects]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: noteId
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '204': { description: Project note deleted }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }

  /projects/{id}/tasks:
    get:
      operationId: listProjectTasks
      summary: List project-scoped tasks
      tags: [Projects]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: status
          in: query
          schema:
            type: string
            enum: [open, in_progress, done, cancelled]
        - $ref: '#/components/parameters/cursor'
        - $ref: '#/components/parameters/limit'
      responses:
        '200':
          description: Project task page
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ProjectTaskPage' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }
    post:
      operationId: createProjectTask
      summary: Create a project-scoped task
      tags: [Projects]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [title]
              additionalProperties: false
              properties:
                title: { type: string, minLength: 1, maxLength: 500 }
                description: { type: string, nullable: true }
                assigned_user_id: { type: string, format: uuid, nullable: true }
                due_date: { type: string, format: date-time, nullable: true }
                priority:
                  type: string
                  enum: [low, normal, high]
      responses:
        '201':
          description: Project task created
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ProjectTask' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }

  /projects/{id}/tasks/{taskId}:
    patch:
      operationId: updateProjectTask
      summary: Update a project-scoped task
      tags: [Projects]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: taskId
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                title: { type: string, minLength: 1, maxLength: 500 }
                description: { type: string, nullable: true }
                assigned_user_id: { type: string, format: uuid, nullable: true }
                due_date: { type: string, format: date-time, nullable: true }
                status:
                  type: string
                  enum: [open, in_progress, done, cancelled]
                priority:
                  type: string
                  enum: [low, normal, high]
      responses:
        '200':
          description: Project task
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ProjectTask' }
        '400': { description: Invalid request }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }
    delete:
      operationId: deleteProjectTask
      summary: Soft-delete a project-scoped task
      tags: [Projects]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: taskId
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '204': { description: Project task deleted }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }

  /projects/{id}/appointments:
    get:
      operationId: listProjectAppointments
      summary: List project-scoped appointments
      tags: [Projects]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: from
          in: query
          schema: { type: string, format: date-time }
        - name: to
          in: query
          schema: { type: string, format: date-time }
        - $ref: '#/components/parameters/limit'
      responses:
        '200':
          description: Project appointment page
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ProjectAppointmentPage' }
        '400': { description: Invalid time range }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }
    post:
      operationId: createProjectAppointment
      summary: Create a project-scoped appointment
      tags: [Projects]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [title, starts_at, ends_at]
              additionalProperties: false
              properties:
                title: { type: string, minLength: 1, maxLength: 500 }
                type:
                  type: string
                  enum: [in_home, phone, virtual]
                starts_at: { type: string, format: date-time }
                ends_at: { type: string, format: date-time }
                owner_user_id: { type: string, format: uuid, nullable: true }
                location_address: { type: string, nullable: true }
                notes: { type: string, nullable: true }
      responses:
        '201':
          description: Project appointment created
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ProjectAppointment' }
        '400': { description: Invalid request }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }
        '409': { description: Appointment conflict }

  /projects/{id}/appointments/{appointmentId}:
    patch:
      operationId: updateProjectAppointment
      summary: Update a project-scoped appointment
      tags: [Projects]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: appointmentId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                title: { type: string, minLength: 1, maxLength: 500 }
                type:
                  type: string
                  enum: [in_home, phone, virtual]
                starts_at: { type: string, format: date-time }
                ends_at: { type: string, format: date-time }
                owner_user_id: { type: string, format: uuid, nullable: true }
                location_address: { type: string, nullable: true }
                notes: { type: string, nullable: true }
                outcome:
                  type: string
                  enum: [no_show, rescheduled, completed, cancelled]
                  nullable: true
                outcome_notes: { type: string, nullable: true }
      responses:
        '200':
          description: Project appointment
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ProjectAppointment' }
        '400': { description: Invalid request }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }
        '409': { description: Appointment conflict }

  /projects/{id}/collaborators:
    get:
      operationId: listProjectCollaborators
      summary: List project people
      tags: [Projects]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Project people
          content:
            application/json:
              schema:
                type: object
                required: [data]
                additionalProperties: false
                properties:
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/ProjectCollaborator' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }
    post:
      operationId: addProjectCollaborator
      summary: Add a project collaborator (`projects:read` floor; manager/Primary checked in handler)
      tags: [Projects]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [user_id, access]
              additionalProperties: false
              properties:
                user_id: { type: string, format: uuid }
                access: { type: string, enum: [view, edit] }
      responses:
        '201':
          description: Updated project people
          content:
            application/json:
              schema:
                type: object
                required: [data]
                additionalProperties: false
                properties:
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/ProjectCollaborator' }
        '400': { description: Invalid request }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }
        '409': { description: Already primary }

  /projects/{id}/collaborators/{userId}:
    patch:
      operationId: updateProjectCollaborator
      summary: Update collaborator access or promote Primary (`projects:read` floor; manager/Primary checked in handler)
      tags: [Projects]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: userId
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                access: { type: string, enum: [view, edit] }
                is_primary: { type: boolean }
      responses:
        '200':
          description: Updated project people
          content:
            application/json:
              schema:
                type: object
                required: [data]
                additionalProperties: false
                properties:
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/ProjectCollaborator' }
        '400': { description: Invalid request }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }
        '409': { description: Already primary }
    delete:
      operationId: removeProjectCollaborator
      summary: Remove a project collaborator (`projects:read` floor; manager/Primary checked in handler)
      tags: [Projects]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: userId
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Updated project people
          content:
            application/json:
              schema:
                type: object
                required: [data]
                additionalProperties: false
                properties:
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/ProjectCollaborator' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }
        '409': { description: Primary required }

  /projects/{id}:
    get:
      operationId: getProject
      summary: Get a project
      tags: [Projects]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Project
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Project' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }
    patch:
      operationId: updateProject
      summary: Update a project
      tags: [Projects]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                customer_id: { type: string, format: uuid }
                property_id: { type: string, format: uuid }
                sub_account_id: { type: string, format: uuid, nullable: true }
                lead_id: { type: string, format: uuid, nullable: true }
                primary_contact_id: { type: string, format: uuid, nullable: true }
                owner_user_id: { type: string, format: uuid, nullable: true }
                status:
                  type: string
                  enum: [active, closed_won, closed_lost, on_hold, archived]
                total_contracted_amount_cents: { type: integer, nullable: true }
                closed_at: { type: string, format: date-time, nullable: true }
      responses:
        '200':
          description: Project
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Project' }
        '400': { description: Invalid request }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }

  /projects/{id}/workspace:
    get:
      operationId: getProjectWorkspace
      summary: Get the read-only project workspace aggregate
      tags: [Projects]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Project workspace aggregate
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ProjectWorkspace' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }

  /projects/{projectId}/invoices/{invoiceId}/payment-link:
    post:
      operationId: createProjectInvoicePaymentLink
      summary: Create a connected-merchant homeowner payment link
      description: |
        Creates, or returns, one hosted checkout page for the invoice on the
        tenant's payment processor (Stripe Checkout or a Square payment link).
        `provider` names the processor; exactly one provider reference is set.
      tags: [Projects]
      parameters:
        - name: projectId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: invoiceId
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Hosted payment URL
          content:
            application/json:
              schema:
                type: object
                required: [payment_url, invoice_id, provider]
                properties:
                  payment_url: { type: string, format: uri }
                  invoice_id: { type: string, format: uuid }
                  provider: { type: string, enum: [stripe, square] }
                  stripe_checkout_session_id: { type: string }
                  square_payment_link_id: { type: string }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }
        '409':
          description: |
            Payment unavailable, processing (`payment_settlement_pending`),
            already settled (`payment_already_settled`), or invoice is not
            payable. `payment_link_expiry_pending`: the current Stripe session
            is on a Stripe account that is no longer connected and can still
            take a payment until `retry_after`; after it, the answer is
            `stripe_payment_unconfirmed`. `stripe_payment_unconfirmed`: the
            invoice has a Stripe session past its expiry on a Stripe account
            that is no longer connected; Portrex cannot ask Stripe whether the
            customer paid, so the invoice stays bound. Cancel the old link
            first (`.../payment-link/cancel` with `confirm_unpaid: true`).
            `payment_link_on_ended_connection`: the invoice has a Square
            payment link on a Square account that is no longer connected;
            cancel the link (`.../payment-link/cancel`), then create a new one.
            `connected_merchant_unavailable`: no payment processor is ready for
            the project.
          content:
            application/json:
              schema:
                type: object
                required: [error]
                properties:
                  error: { type: string }
                  retry_after:
                    type: string
                    format: date-time
                    nullable: true
                    description: Only with `payment_link_expiry_pending`. The stored expiry of the Stripe session.
        '503':
          description: |
            `db_unavailable`; `payment_processor_not_configured` when neither
            processor can run a checkout on this deployment;
            `stripe_not_configured` / `square_not_configured` when the
            processor of the invoice is known and not configured;
            `payment_provider_unavailable` when the processor does not answer.
          content:
            application/json:
              schema:
                type: object
                required: [error]
                properties:
                  error:
                    type: string
                    enum: [db_unavailable, payment_processor_not_configured, stripe_not_configured, square_not_configured, payment_provider_unavailable]

  /projects/{projectId}/invoices/{invoiceId}/payment-link/cancel:
    post:
      operationId: cancelProjectInvoicePaymentLink
      summary: Revoke an unpaid connected-merchant payment link
      tags: [Projects]
      parameters:
        - name: projectId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: invoiceId
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                confirm_unpaid:
                  type: boolean
                  description: |
                    Only for a Stripe session past its expiry on a Stripe
                    account that is no longer connected. Portrex cannot ask
                    Stripe, so `true` states that the caller checked the
                    company's Stripe account and the customer did not pay.
                    Without it that cancel answers 409
                    `stripe_payment_unconfirmed`. With it the invoice is
                    released, and an audit row records the caller. Ignored
                    in every other case.
      responses:
        '200':
          description: The checkout is released
          content:
            application/json:
              schema:
                type: object
                required: [cancelled]
                properties:
                  cancelled: { type: boolean }
                  provider_confirmed:
                    type: boolean
                    description: |
                      Sent for both processors. `true`: no payable link remains
                      at the processor. The processor confirmed the
                      cancellation (or had already ended the link), or the link
                      is past its expiry time. `false`: Portrex released the
                      invoice but could not cancel the link at the processor
                      (its account is no longer connected), so the old link can
                      still accept a payment. Today only a Square link can end
                      this way; a Stripe session is released without Stripe
                      only after its expiry and with `confirm_unpaid: true`,
                      so it answers `true`. A Square
                      claim with no stored link also answers `false` when the
                      search of Square's records hit its page limit: no URL of
                      that claim was handed out, but a link nobody received can
                      remain at Square. A Square checkout whose payment was
                      partly refunded before Portrex settled the invoice is
                      released with `true` (the single-use link is spent); an
                      administrator records the money that was kept by hand
                      (`kept_cents`). A Square checkout that was `processing`
                      on an account that is no longer connected is released
                      with `false`: Square can no longer report its end. A
                      Stripe async payment whose PaymentIntent failed
                      (`requires_payment_method` or `canceled`) ends the
                      attempt with `true`.
                  kept_cents:
                    type: integer
                    minimum: 0
                    description: |
                      Present only when the cancel released a Square checkout
                      whose payment was partly refunded before Portrex settled
                      the invoice. The money Square kept, in the minor unit of
                      `kept_currency`. Nobody recorded it yet: record it on the
                      invoice by hand before a new payment link.
                  kept_currency:
                    type: string
                    description: Present only with `kept_cents`. ISO 4217 code, today always `USD`.
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }
        '409':
          description: |
            Payment is processing, already settled (`payment_already_settled`),
            or attempt changed. `payment_link_expiry_pending`: the Stripe
            session is on a Stripe account that is no longer connected and can
            still take a payment until `retry_after`; cancel again after it.
            `stripe_payment_unconfirmed`: that session is past its expiry and
            Portrex cannot ask Stripe whether the customer paid; send
            `confirm_unpaid: true` after a check in the company's Stripe account.
          content:
            application/json:
              schema:
                type: object
                required: [error]
                properties:
                  error: { type: string }
                  retry_after:
                    type: string
                    format: date-time
                    nullable: true
                    description: Only with `payment_link_expiry_pending`. The stored expiry of the Stripe session.
        '503':
          description: |
            `db_unavailable`; `stripe_not_configured` / `square_not_configured`
            when the processor of the link is not configured;
            `payment_provider_unavailable` when the processor does not answer
            or did not confirm the cancellation.
          content:
            application/json:
              schema:
                type: object
                required: [error]
                properties:
                  error:
                    type: string
                    enum: [db_unavailable, stripe_not_configured, square_not_configured, payment_provider_unavailable]

  /designs:
    post:
      operationId: createDesign
      summary: Create or update a design
      tags: [Designs]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [project_id, service_type]
              properties:
                project_id: { type: string, format: uuid }
                service_type: { type: string, enum: [solar, hvac, roofing, remodeling] }
                configuration_json: { type: object }
              additionalProperties: false
      responses:
        '201':
          description: Design created
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Design' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '409':
          description: Idempotency key conflict — previous response returned

  /contracts/{id}/sign:
    post:
      operationId: signContract
      summary: Native primary signer contract signature
      tags: [Contracts]
      description: |
        Captures a primary signer signature with server-derived IP/user-agent,
        per-account KEK encrypted signature artifact storage, and same-transaction
        audit evidence. Customer identity, signer matching, step-up, CPM
        validation, encryption, and the signing store all fail closed.
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string }
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [signature_data, signature_method]
              properties:
                signature_data: { type: string, minLength: 1, maxLength: 262144 }
                signature_method:
                  type: string
                  enum: [pencil, typed, voice_attestation, witness_countersign]
              additionalProperties: false
      responses:
        '200':
          description: Signature captured and contract state advanced
          content:
            application/json:
              schema:
                type: object
                required: [contract_id, status, signing_mode, signed_at, signature_method, signature_event_id, signature_evidence_sha256, closing_celebration]
                properties:
                  contract_id: { type: string, format: uuid }
                  status: { type: string, enum: [partially_signed, fully_signed] }
                  signing_mode: { type: string, enum: [single, split] }
                  signed_at: { type: string, format: date-time }
                  signature_method:
                    type: string
                    enum: [pencil, typed, voice_attestation, witness_countersign]
                  signature_event_id: { type: string, format: uuid }
                  signature_evidence_sha256: { type: string }
                  closing_celebration:
                    type: object
                    required: [eligible, trigger]
                    properties:
                      eligible: { type: boolean }
                      trigger:
                        type: string
                        enum: [contract.fully_signed]
                        nullable: true
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }
        '409':
          description: Conflict — contract state/signatory mismatch, idempotency conflict, CPM freeze refusal, or `quote_expired` (the saved HVAC quote is older than 720 hours, or its Save time is unknown; the rep saves the quote again)
        '503': { description: Signing store or encryption unavailable }

  /contracts/{id}/sign-in-person:
    post:
      operationId: signContractInPerson
      summary: Attended in-person contract signing (rep-witnessed)
      tags: [Contracts]
      description: |
        Captures a rep-witnessed, attended in-person primary signature. The rep
        (tenant_user) performs a step-up re-auth, then captures the client's
        signature on a `sent`, single-mode contract. The signatory_person_id
        in the request body must match the contract's primary_signer_person_id.

        Actor attribution: actor_user_id = rep; actor_customer_user_id = null.
        The contract transitions SENT → FULLY_SIGNED (single-mode only).

        Step-up required: 5-min freshness, WebAuthn or TOTP.
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [signatory_person_id, signature_data, signature_method, signer_typed_name, consent_ack]
              properties:
                signatory_person_id:
                  type: string
                  format: uuid
                  description: customer_people.id of the client being witnessed
                signature_data:
                  type: string
                  minLength: 1
                  maxLength: 262144
                signature_method:
                  type: string
                  enum: [pencil, typed, witness_countersign]
                signer_typed_name:
                  type: string
                  minLength: 1
                consent_ack:
                  type: boolean
                  enum: [true]
              additionalProperties: false
      responses:
        '200':
          description: Signature captured; status is the store's post-sign contract state
          content:
            application/json:
              schema:
                type: object
                required: [contract_id, status, signed_at, signature_method, signature_event_id, signature_evidence_sha256]
                properties:
                  contract_id: { type: string, format: uuid }
                  status: { type: string, enum: [sent, partially_signed, fully_signed] }
                  signed_at: { type: string, format: date-time }
                  signature_method:
                    type: string
                    enum: [pencil, typed, witness_countersign]
                  signature_event_id: { type: string, format: uuid }
                  signature_evidence_sha256: { type: string }
        '401': { description: Unauthorized — step-up required }
        '403': { description: Forbidden — signatory mismatch or wrong principal kind }
        '404': { description: Not Found — contract not found }
        '409': { description: 'Conflict — contract not in sent status, CPM freeze refusal, or `quote_expired` (the saved HVAC quote is older than 720 hours, or its Save time is unknown; the rep saves the quote again)' }
        '503': { description: Signing store or encryption unavailable }

  # ----------------------------------------------------------------
  # OAuth 2.1 / PKCE (E10 / POR-52)
  # ----------------------------------------------------------------
  /me:
    get:
      operationId: getCredentialMe
      summary: Introspect the authenticated credential, tenant, and granted scopes
      description: |
        Works uniformly for tenant sessions, API keys (`ptx_live_sk_*`), OAuth 2.1
        user tokens (`oat_*`), and OAuth 2.1 Integration User tokens (`oat_*`).
        Returns the resolved credential class, tenant, branch, role, and sorted
        effective scope list.
      tags: [Auth]
      security: [{ bearerToken: [] }, { sessionCookie: [] }]
      responses:
        '200':
          description: Authenticated credential summary
          headers:
            Cache-Control: { schema: { type: string, example: 'private, no-store' } }
        '401': { description: Authentication required }
        '403': { description: Forbidden principal kind }

  /oauth/clients:
    get:
      operationId: listOAuthClients
      summary: List active OAuth 2.1 clients for the current account
      description: Requires `account:read`. Secrets are never returned.
      tags: [OAuth]
      responses:
        '200': { description: Active OAuth clients }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
    post:
      operationId: registerOAuthClient
      summary: Register an OAuth 2.1 client (PKCE or client_credentials)
      tags: [OAuth]
      description: |
        Requires `account:write`. Returns the `client_secret` ONLY on creation.
        Allowed scope count is capped per Account tier (Standard=5, Pro=10, Enterprise=20).
      responses:
        '201': { description: OAuth client registered }
        '400': { description: Invalid client metadata or scope }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Bound integration user not found }

  /oauth/clients/{id}:
    delete:
      operationId: revokeOAuthClient
      summary: Revoke an OAuth 2.1 client and all of its active tokens
      description: Requires `account:write`.
      tags: [OAuth]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        '204': { description: Revoked }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Client not found }

  /oauth/authorize/decision:
    post:
      operationId: decideOAuthAuthorization
      summary: Submit explicit user consent (approve or deny) for an OAuth 2.1 request
      description: |
        Requires an interactive tenant session and `account:read`. API keys and
        OAuth access tokens are rejected with 403 `session_required`.
      tags: [OAuth]
      security: [{ sessionCookie: [] }]
      responses:
        '200': { description: Consent recorded and redirect URI returned }
        '400': { description: Invalid authorization parameters }
        '401': { description: Login required }
        '403': { description: Interactive session required or tenant mismatch }

  /oauth/introspect:
    post:
      operationId: oauthIntrospect
      summary: Introspect an OAuth 2.1 access or refresh token (RFC 7662)
      description: Confidential client authentication required (Basic auth or client_id/client_secret body).
      tags: [OAuth]
      security: []
      responses:
        '200': { description: 'Introspection result (active true or false)' }
        '401': { description: Invalid confidential client credentials }

  /integration-users:
    get:
      operationId: listIntegrationUsers
      summary: List Integration Users for the current account
      description: Requires `account:read`.
      tags: [Integration Users]
      responses:
        '200': { description: Integration Users list }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
    post:
      operationId: createIntegrationUser
      summary: Provision a dedicated Integration User for OAuth 2.1 client_credentials
      description: Requires `account:write`. Provisions a backing service user and validates scopes against the canonical Integration User scope set.
      tags: [Integration Users]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      responses:
        '201': { description: Integration User provisioned }
        '400': { description: Invalid scopes or lifetime }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '409': { description: Duplicate active Integration User name }

  /integration-users/{id}:
    get:
      operationId: getIntegrationUser
      summary: Fetch one Integration User by ID
      description: Requires `account:read`.
      tags: [Integration Users]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        '200': { description: Integration User detail }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }
    patch:
      operationId: updateIntegrationUser
      summary: Update Integration User metadata, scopes, token lifetime, or active/suspended status
      description: Requires `account:write`. Suspending an Integration User immediately revokes all active access tokens.
      tags: [Integration Users]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string, format: uuid } }
        - $ref: '#/components/parameters/idempotencyKey'
      responses:
        '200': { description: Updated Integration User }
        '400': { description: Invalid scopes or payload }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }
        '409': { description: Duplicate Integration User name }
    delete:
      operationId: revokeIntegrationUser
      summary: Permanently revoke an Integration User and all of its active tokens
      description: Requires `account:write`.
      tags: [Integration Users]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        '204': { description: Revoked }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }
  # ============================================================
  # POR-58/POR-434: Pricebook Import
  # Pipeline: uploaded → mapping → confirmed → dry_run → committed
  # Start endpoints require data_import:run and create a per-import
  # Migration-Operator grant. Follow-up endpoints require that active
  # grant, which is auto-revoked 48h after commit.
  # ============================================================

  /imports/pricebook/csv:
    post:
      operationId: createCsvPricebookImport
      summary: Start a generic CSV pricebook import (upload + AI-1 column suggestions)
      tags: [Imports]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/PricebookImportStartRequest' }
      responses:
        '201':
          description: Import created (status=uploaded or mapping if csv_text supplied)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PricebookImport' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden — missing data_import:run or step-up }

  /imports/pricebook/jobnimbus:
    post:
      operationId: createJobnimbusPricebookImport
      summary: Start a JobNimbus pricebook import (upload + AI-1 column suggestions)
      tags: [Imports]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/PricebookImportStartRequest' }
      responses:
        '201':
          description: Import created (status=uploaded or mapping if csv_text supplied)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PricebookImport' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden — missing data_import:run or step-up }

  /imports/pricebook/{id}:
    get:
      operationId: getPricebookImport
      summary: Get import status + AI suggestions + human-confirmed mappings
      tags: [Imports]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Import detail
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PricebookImport' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden — no active operator grant on this import }
        '404': { description: Import not found in this tenant }

  /imports/pricebook/xlsx:
    post:
      operationId: createXlsxPricebookImport
      summary: Start an xlsx pricebook import (returns a presigned workbook upload URL)
      description: |
        Creates the import and a presigned PUT URL for the workbook (no inline
        file body). After uploading, call `/imports/pricebook/{id}/analyze` to
        detect table regions. AI output is a suggestion only — every unit needs
        human confirmation before commit.
      tags: [Imports]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [filename, size_bytes]
              properties:
                filename: { type: string, maxLength: 256 }
                size_bytes: { type: integer, minimum: 1 }
                default_industry: { type: string, maxLength: 64 }
                scope: { $ref: '#/components/schemas/PricebookImportScope' }
              additionalProperties: false
      responses:
        '201':
          description: Import created with presigned upload
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PricebookImport' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden — missing data_import:run or step-up }

  /imports/pricebook/{id}/workbook:
    put:
      operationId: uploadXlsxPricebookWorkbook
      summary: Upload the workbook through the API (same-origin; base64 payload)
      description: |
        Same-origin alternative to the presigned PUT — immune to CSP
        connect-src, bucket CORS, and local port-mapping differences.
      tags: [Imports]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [data_base64]
              properties:
                data_base64: { type: string }
              additionalProperties: false
      responses:
        '200':
          description: Workbook staged
        '400': { description: Invalid or empty payload }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Import not found }
        '409': { description: 'Not an xlsx import, or already committed' }
        '413': { description: Workbook too large }

  /imports/pricebook/{id}/analyze:
    post:
      operationId: analyzeXlsxPricebookImport
      summary: Parse the staged workbook and detect table units (heuristic + AI-refined)
      tags: [Imports]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Detected units awaiting human confirmation
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PricebookImport' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Import not found }
        '409': { description: 'Workbook not uploaded yet, or not an xlsx import' }

  /imports/pricebook/{id}/units/{unitId}/interpretation:
    put:
      operationId: updatePricebookImportUnitInterpretation
      summary: Edit/confirm a detected unit (region, shape, mappings — the human gate)
      tags: [Imports]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: unitId
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                interpretation:
                  type: object
                  additionalProperties: true
                status:
                  type: string
                  enum: [detected, confirmed, ignored]
                region:
                  type: object
                  required: [first_row, last_row, first_col, last_col]
                  properties:
                    first_row: { type: integer, minimum: 1 }
                    last_row: { type: integer, minimum: 1 }
                    first_col: { type: integer, minimum: 1 }
                    last_col: { type: integer, minimum: 1 }
                  additionalProperties: false
              additionalProperties: false
      responses:
        '200':
          description: Updated unit
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PricebookImportUnit' }
        '400': { description: Invalid interpretation doc }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Import or unit not found }

  /imports/pricebook/{id}/units/{unitId}/preview:
    get:
      operationId: previewPricebookImportUnit
      summary: Grid slice + compiler-computed normalized output for one unit
      description: |
        The preview runs the SAME compiler dry-run/commit use, so what the
        human confirms is exactly what will be written.
      tags: [Imports]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: unitId
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Unit preview (grid slice + compiled output + warnings)
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Import or unit not found }
        '409': { description: Staged workbook unavailable }

  /imports/pricebook/{id}/parse:
    post:
      operationId: parsePricebookImport
      summary: Re-parse the upload CSV (RFC 4180) and refresh AI-1 suggestions
      tags: [Imports]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [csv_text]
              properties:
                csv_text: { type: string }
              additionalProperties: false
      responses:
        '200':
          description: Re-parsed CSV summary
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PricebookImportParseResult' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Import not found }

  /contracts/{contractId}/void:
    post:
      operationId: initiateContractVoid
      summary: Initiate a contract void & reissue (POR-60)
      description: |
        Creates a `void_event` row in `pending_rep_signature` with a 14-day TTL.
        Requires `contracts:void` scope and step-up freshness (5 min).
        Returns 422 with `no_changes_to_void` when the replacement payload
        is identical to the current contract (zero diff).
      tags: [Contracts]
      parameters:
        - name: contractId
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [reason, replacement_contract_payload]
              properties:
                reason: { type: string, minLength: 1, maxLength: 2000 }
                replacement_contract_payload:
                  type: object
                  additionalProperties: true
              additionalProperties: false
      responses:
        '201':
          description: Void event initiated
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ContractVoidInitiation' }
        '401': { description: 'Unauthorized — step-up required' }
        '403': { description: 'Forbidden — missing contracts:void scope' }
        '404': { description: Contract not found }
        '422': { description: 'no_changes_to_void — replacement is identical' }

  /oauth/authorize:
    get:
      operationId: oauthAuthorize
      summary: OAuth authorization endpoint (PKCE S256 required)
      tags: [OAuth]
      parameters:
        - { name: response_type, in: query, required: true, schema: { type: string, enum: [code] } }
        - { name: client_id, in: query, required: true, schema: { type: string } }
        - { name: redirect_uri, in: query, required: true, schema: { type: string, format: uri } }
        - { name: scope, in: query, schema: { type: string, description: 'Space-separated scopes' } }
        - { name: state, in: query, schema: { type: string } }
        - { name: code_challenge, in: query, required: true, schema: { type: string, minLength: 43, maxLength: 128 } }
        - { name: code_challenge_method, in: query, required: true, schema: { type: string, enum: [S256] } }
      responses:
        '200':
          description: Authorization code issued; redirect URI is returned for the caller to follow
          content:
            application/json:
              schema: { $ref: '#/components/schemas/OAuthAuthorizeResponse' }
        '400': { description: Invalid request }
        '401': { description: Login required }
        '403': { description: Client belongs to another account }

  /void-events/{id}/sign:
    post:
      operationId: signVoidEvent
      summary: Sign a void event (rep or homeowner countersign)
      description: |
        Two-party countersign endpoint. Accepts either a TenantPrincipal
        (signer_role='rep' — requires `contracts:sign`) or a CustomerPrincipal
        (signer_role='homeowner'). Both surfaces require step-up freshness.
        Optimistic concurrency: returns 409 `void_event_state_changed` when
        a concurrent writer (cron, webhook) changed status between read
        and write.
      tags: [VoidEvents]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [signer_role]
              properties:
                signer_role: { type: string, enum: [rep, homeowner] }
                client_timestamp: { type: string, format: date-time }
              additionalProperties: false
      responses:
        '200':
          description: Signature applied
          content:
            application/json:
              schema:
                type: object
                properties:
                  code: { type: string }
                  state: { type: string }
                  redirect_uri: { type: string }
                  expires_in: { type: integer }

  /oauth/token:
    post:
      operationId: oauthToken
      summary: Exchange authorization_code for access token (PKCE verified)
      tags: [OAuth]
      security: []
      # NOTE: pre-existing copy-paste defect (OAuth/imports interleave) —
      # operation body to be re-specified in the spec-repair follow-up.
      responses:
        '200': { description: Access token issued }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not found }

  /imports/pricebook/{id}/mappings:
    post:
      operationId: confirmPricebookMappings
      summary: Human-confirm column→field mappings (AI confidence is not consent)
      tags: [Imports]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/PricebookImportMappingsRequest' }
      responses:
        '200':
          description: Mappings confirmed
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PricebookImportMappingsResponse' }
        '400':
          description: Invalid target field
        '401': { description: Unauthorized }
        '403': { description: Forbidden — no active operator grant on this import }
        '404': { description: Import not found in this tenant }

  /oauth/revoke:
    post:
      operationId: oauthRevoke
      summary: Revoke an access token (RFC 7009)
      tags: [OAuth]
      security: []
      # NOTE: pre-existing copy-paste defect (OAuth/imports interleave).
      # Operation body to be re-specified in the spec-repair follow-up.
      responses:
        '200':
          description: Token revoked
        '400': { description: invalid_token }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not found }

  /imports/pricebook/{id}/dry-run:
    post:
      operationId: pricebookDryRun
      summary: Compute import diff without writing
      tags: [Imports]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: false
        content:
          application/json:
            schema: { $ref: '#/components/schemas/PricebookImportDryRunRequest' }
      responses:
        '200':
          description: Dry-run summary
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PricebookImportDryRunResponse' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden — no active operator grant on this import }
        '404': { description: Import not found in this tenant }
        '409': { description: Invalid import state }

  # ----------------------------------------------------------------
  # API keys (E10 / POR-52)
  # ----------------------------------------------------------------
  /api-keys:
    get:
      operationId: listApiKeys
      summary: List API keys for the current Account
      tags: [API Keys]
      responses:
        '200':
          description: API keys
          content:
            application/json:
              schema:
                type: object
                required: [data, next_cursor]
                properties:
                  data:
                    type: array
                    items:
                      type: object
                      required: [id, account_id, name, key_prefix, scopes, ip_allowlist, created_at]
                      properties:
                        id: { type: string, format: uuid }
                        account_id: { type: string, format: uuid }
                        name: { type: string }
                        key_prefix: { type: string }
                        scopes: { type: array, items: { type: string } }
                        ip_allowlist: { type: array, items: { type: string } }
                        expires_at: { type: [string, 'null'], format: date-time }
                        last_used_at: { type: [string, 'null'], format: date-time }
                        created_at: { type: string, format: date-time }
                  next_cursor: { type: [string, 'null'] }
    post:
      operationId: createApiKey
      summary: Create an API key (scope-capped per tier; sensitive scopes forbidden)
      description: |
        All responses, including errors, use `Cache-Control: no-store`.
        The secret response is never retained or replayed by idempotency storage.
        A completed key returns `409 idempotency_secret_response_unavailable`.
        The original operation may already have committed. Do not automatically
        retry with a fresh key; inspect the resource before recovery or an
        intentional new creation or rotation.
      tags: [API Keys]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name, scopes]
              additionalProperties: false
              properties:
                name: { type: string, minLength: 1, maxLength: 200 }
                scopes: { type: array, minItems: 1, items: { type: string } }
                ip_allowlist:
                  type: array
                  maxItems: 100
                  uniqueItems: true
                  items: { type: string, minLength: 1, maxLength: 64 }
                expires_at: { type: string, format: date-time }
      responses:
        '201':
          description: API key created (secret shown once)
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema:
                type: object
                required: [id, account_id, name, key_prefix, api_key, scopes, ip_allowlist, created_at]
                properties:
                  id: { type: string, format: uuid }
                  account_id: { type: string, format: uuid }
                  name: { type: string }
                  key_prefix: { type: string }
                  api_key: { type: string }
                  scopes: { type: array, items: { type: string } }
                  ip_allowlist: { type: array, items: { type: string } }
                  expires_at: { type: [string, 'null'], format: date-time }
                  last_used_at: { type: [string, 'null'], format: date-time }
                  created_at: { type: string, format: date-time }
        '400': { description: "Invalid scope, sensitive scope, scope cap exceeded, invalid IP allowlist, or expires_at not in the future" }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '409': { $ref: '#/components/responses/SecretOperationConflict' }

  /imports/pricebook/{id}/commit:
    post:
      operationId: pricebookCommit
      summary: Persist the import (idempotent; refuses without human-confirmed mappings)
      tags: [Imports]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: false
        content:
          application/json:
            schema: { $ref: '#/components/schemas/PricebookImportCommitRequest' }
      responses:
        '201':
          description: Import committed
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PricebookImportCommitResponse' }
        '200':
          description: Idempotent replay of a committed import
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PricebookImportCommitResponse' }
        '400': { description: Missing Idempotency-Key }
        '401': { description: Unauthorized }
        '403': { description: Forbidden — no active operator grant on this import }
        '404': { description: Import not found in this tenant }
        '409': { description: 'Invalid state, already committed, catalog drifted since dry-run, or pricebook_write_in_progress (another price book write for this account and trade held the lock past the statement timeout; retry)' }
        '422': { description: Idempotency body conflict or parsed rows unavailable }

  /imports/pricebook/{id}/undo:
    post:
      operationId: pricebookImportUndo
      summary: Undo a committed import (items, showroom catalog or rate card)
      description: |
        Items: archives the items the import created and restores the items it
        updated to their pre-import version; items edited since are left alone
        and listed in kept_edited. Showroom catalog: replays the pre-commit
        snapshot in replace mode with the same scope. Rate card: writes the
        prior values back as new rows effective today. Status becomes
        rolled_back. The same Idempotency-Key replays the result. Rate card
        imports need pricebooks:write and pricebook:cost:read.
      tags: [Imports]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      responses:
        '200':
          description: Import rolled back (or replay of the same undo)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ImportUndoResult' }
        '400': { description: Missing Idempotency-Key }
        '401': { description: Unauthorized }
        '403': { description: 'Forbidden — no active operator grant on this import, or a rate card import without pricebooks:write + pricebook:cost:read' }
        '404': { description: Import not found in this tenant }
        '409': { description: 'Already rolled back, not committed, a newer import on the same data exists ("Undo the newer import first"), no undo record, pricebook_write_in_progress, or (showroom, the replace commit''s own guards) CATALOG_DRIFTED / cpm_catalog_present / STRUCTURAL_REDACTION' }

  /imports/pricebook/{id}/undo-preview:
    get:
      operationId: pricebookImportUndoPreview
      summary: What undoing this import would do now, without doing it
      description: |
        Runs the undo in a transaction and rolls it back. changed_since_commit
        is true when items or rate rows the import wrote were edited since
        (they are left alone and listed in kept_edited), or when the in-scope
        showroom catalog changed since the commit (the undo reverts it; the
        counts say how much). Rate card imports need pricebooks:write and
        pricebook:cost:read. The preview takes no price book write lock and
        no FOR UPDATE row lock, so it never makes a running commit wait or
        fail; when its own writes meet a row a writer holds it answers 409
        pricebook_write_in_progress. Not audited (it changes nothing).
      tags: [Imports]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: The undo's effect
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ImportUndoPreview' }
        '401': { description: Unauthorized }
        '403': { description: 'Forbidden — no active operator grant, or a rate card import without pricebooks:write + pricebook:cost:read' }
        '404': { description: Import not found in this tenant }
        '409': { description: 'Already rolled back, not committed, a newer import on the same data exists, no undo record, pricebook_write_in_progress, or (showroom) CATALOG_DRIFTED / cpm_catalog_present / STRUCTURAL_REDACTION' }

  /imports/history:
    get:
      operationId: listImportHistory
      summary: The account's pricebook imports (Items, Showroom catalog, Rate card), newest first
      tags: [Imports]
      parameters:
        - name: cursor
          in: query
          required: false
          schema: { type: string, maxLength: 200 }
        - name: limit
          in: query
          required: false
          schema: { type: integer, minimum: 1, maximum: 100, default: 25 }
      responses:
        '200':
          description: One page of imports with counts and undo availability
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ImportHistoryPage' }
        '400': { description: Invalid cursor }
        '401': { description: Unauthorized }
        '403': { description: 'Forbidden — missing pricebooks:read, or a sub-account seat' }

  /imports/pricebook/_internal/expire-grants:
    post:
      operationId: pricebookExpireGrantsCron
      summary: Internal cron sweep — sets expires_at and revokes expired grants
      description: |
        Internal-only endpoint authenticated via the `X-Internal-Cron-Token`
        header (expects `INTERNAL_CRON_TOKEN` env var). Called by the worker
        Inngest cron `imports-migration-operator-expire`.
      tags: [Imports]
      security: []
      parameters:
        - name: X-Internal-Cron-Token
          in: header
          required: true
          schema: { type: string }
      responses:
        '200':
          description: Sweep complete
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PricebookExpireGrantsResponse' }
        '401': { description: Unauthorized internal cron token }
        '503': { description: INTERNAL_CRON_TOKEN not configured }

  /internal/esign/zoho/status:
    post:
      operationId: esignZohoStatusReport
      summary: Internal worker report of a Zoho Sign request state
      description: |
        Internal-only endpoint authenticated via the `X-Esign-Poll-Token`
        header (expects the `ESIGN_POLL_INTERNAL_TOKEN` env var). Called by the
        worker cron `esign-zoho-status-poller`, which reads the request from
        Zoho Sign with the tenant's own OAuth token. The body never names an
        account or contract: both come from the stored provider mappings.
        SIGNED actions are applied first (primary, then cosigner) through the
        e-sign event ledger; then, if Zoho ended the request (declined,
        recalled, expired), an unsigned `sent` contract returns to `draft` and
        a `partially_signed` contract stays as it is with polling stopped.
        No Idempotency-Key is required: every write is idempotent through the
        e-sign event ledger.
      tags: [Contracts]
      security: []
      parameters:
        - name: X-Esign-Poll-Token
          in: header
          required: true
          schema: { type: string }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [request_id, request_state, raw_status, actions]
              properties:
                request_id: { type: string, minLength: 1, maxLength: 128 }
                request_state:
                  type: string
                  enum: [in_progress, completed, declined, recalled, expired, other]
                raw_status: { type: string, maxLength: 64 }
                request_action_time: { type: string, nullable: true, maxLength: 64 }
                provider_expires_at: { type: string, nullable: true, maxLength: 64 }
                reason: { type: string, nullable: true, maxLength: 2000 }
                actions:
                  type: array
                  minItems: 1
                  maxItems: 10
                  items:
                    type: object
                    additionalProperties: false
                    required: [action_id, action_status]
                    properties:
                      action_id: { type: string, minLength: 1, maxLength: 128 }
                      action_status: { type: string, maxLength: 64 }
      responses:
        '200':
          description: The report was processed; per-action failures stay inside this response
          content:
            application/json:
              schema:
                type: object
                required: [contract_id, contract_status, stopped, outcomes]
                properties:
                  contract_id: { type: string, format: uuid }
                  contract_status: { type: string }
                  stopped: { type: boolean }
                  outcomes:
                    type: array
                    items:
                      type: object
                      required: [action_id, outcome]
                      properties:
                        action_id: { type: string }
                        outcome:
                          type: string
                          enum: [applied, duplicate, state_changed, not_signed, failed]
        '400': { description: Body failed validation }
        '401': { description: Unauthorized poll token }
        '404': { description: No stored mapping matches the request (mapping_missing) }
        '409': { description: The request's actions resolve to different contracts (mapping_conflict) }
        '503': { description: 'ESIGN_POLL_INTERNAL_TOKEN not configured (ESIGN_POLL_DISABLED), or another session held a lock for more than 8 seconds (record_busy, with Retry-After). The worker retries record_busy.' }

  /internal/esign/docusign/status:
    post:
      operationId: esignDocusignStatusReport
      summary: Internal worker report of a DocuSign envelope state
      description: |
        Internal-only endpoint authenticated via the `X-Esign-Poll-Token`
        header (expects the `ESIGN_POLL_INTERNAL_TOKEN` env var). Called by the
        worker function `esign-docusign-status`, which answers a DocuSign Connect
        hint by reading the envelope from DocuSign with the tenant's own OAuth
        token. The body never names an account, contract or signer role: all
        three come from the stored provider mappings. Completed recipients are
        applied first (primary, then cosigner) through the e-sign event ledger,
        with the provider's signing time. When the envelope is completed and
        the contract is fully signed, the signed-PDF archive is enqueued.
        Declined, voided and timed-out envelopes are only logged. No
        Idempotency-Key is required: every write is idempotent through the
        e-sign event ledger.
      tags: [Contracts]
      security: []
      parameters:
        - name: X-Esign-Poll-Token
          in: header
          required: true
          schema: { type: string }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [envelope_id, envelope_state, raw_status, recipients]
              properties:
                envelope_id:
                  type: string
                  pattern: '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'
                envelope_state:
                  type: string
                  enum: [in_progress, completed, declined, voided, timedout, other]
                raw_status: { type: string, maxLength: 64 }
                recipients:
                  type: array
                  minItems: 1
                  maxItems: 10
                  items:
                    type: object
                    additionalProperties: false
                    required: [recipient_id, status]
                    properties:
                      recipient_id: { type: string, minLength: 1, maxLength: 128 }
                      status: { type: string, maxLength: 64 }
                      signed_date_time: { type: string, nullable: true, maxLength: 64 }
      responses:
        '200':
          description: The report was processed; per-recipient failures stay inside this response
          content:
            application/json:
              schema:
                type: object
                required: [contract_id, contract_status, archive_enqueued, outcomes]
                properties:
                  contract_id: { type: string, format: uuid }
                  contract_status: { type: string }
                  archive_enqueued: { type: boolean }
                  outcomes:
                    type: array
                    items:
                      type: object
                      required: [recipient_id, outcome]
                      properties:
                        recipient_id: { type: string }
                        outcome:
                          type: string
                          enum: [applied, duplicate, state_changed, not_signed, failed]
        '400': { description: Body failed validation }
        '401': { description: Unauthorized poll token }
        '404': { description: No stored mapping matches the envelope (mapping_missing) }
        '409': { description: The envelope's recipients resolve to different contracts (mapping_conflict) }
        '500': { description: The signed-PDF archive could not be enqueued; the report is safe to repeat }
        '503': { description: ESIGN_POLL_INTERNAL_TOKEN not configured }

  /internal/billing/tick:
    post:
      operationId: billingRunTick
      summary: 'Internal: sweep stale attempts and list the due Square payers'
      description: |
        In one transaction with no tenant setting, runs the token-free sweep of
        stale attempts (each new finding writes one alert line) and lists one
        page of due payers by the database clock. Send `after` with the
        `next_cursor` of the answer for the next page.
        Internal-only endpoint authenticated by the `X-Billing-Run-Token`
        header (the `BILLING_RUN_INTERNAL_TOKEN` secret, compared in constant
        time). Called by the worker, which runs no SQL of this plan and holds
        no Square secret (plan 2026-11-19-002 § 7.7, K8). No
        Idempotency-Key: each write is idempotent through the engine's own
        keys (the attempt id, the period invoice).
      tags: [Billing]
      security: []
      parameters:
        - name: X-Billing-Run-Token
          in: header
          required: true
          schema: { type: string }
      requestBody:
        required: false
        content:
          application/json:
            schema: { $ref: '#/components/schemas/InternalBillingTickInput' }
      responses:
        '200':
          description: The step ran
          content:
            application/json:
              schema: { $ref: '#/components/schemas/InternalBillingTickResult' }
        '400':
          description: Body failed validation
          content:
            application/json:
              schema: { $ref: '#/components/schemas/InternalBillingError' }
        '401':
          description: No token header, or a wrong value (`unauthorized`)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/InternalBillingError' }
        '503':
          description: 'BILLING_RUN_INTERNAL_TOKEN not configured on this instance (`billing_run_not_configured`), or the database is unavailable'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/InternalBillingError' }

  /internal/billing/charge-due:
    post:
      operationId: billingRunChargeDue
      summary: 'Internal: charge, or recover the open attempt of, one due Square payer'
      description: |
        Charges one due payer, or runs only the recovery of an attempt that is
        `claimed` for more than 2 minutes (plan 2026-11-19-002 § 5.2, § 5.9).
        The account comes from `resolve_billing_payer`; a value in the body
        cannot change it.
        Internal-only endpoint authenticated by the `X-Billing-Run-Token`
        header (the `BILLING_RUN_INTERNAL_TOKEN` secret, compared in constant
        time). Called by the worker, which runs no SQL of this plan and holds
        no Square secret (plan 2026-11-19-002 § 7.7, K8). No
        Idempotency-Key: each write is idempotent through the engine's own
        keys (the attempt id, the period invoice).
      tags: [Billing]
      security: []
      parameters:
        - name: X-Billing-Run-Token
          in: header
          required: true
          schema: { type: string }
      requestBody:
        required: false
        content:
          application/json:
            schema: { $ref: '#/components/schemas/InternalBillingChargeDueInput' }
      responses:
        '200':
          description: The step ran
          content:
            application/json:
              schema: { $ref: '#/components/schemas/InternalBillingChargeDueResult' }
        '400':
          description: Body failed validation
          content:
            application/json:
              schema: { $ref: '#/components/schemas/InternalBillingError' }
        '401':
          description: No token header, or a wrong value (`unauthorized`)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/InternalBillingError' }
        '503':
          description: 'BILLING_RUN_INTERNAL_TOKEN not configured on this instance (`billing_run_not_configured`), or the database is unavailable'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/InternalBillingError' }

  /internal/billing/reconcile:
    post:
      operationId: billingRunReconcile
      summary: 'Internal: the daily reconcile of Square subscriptions'
      description: |
        Reconciles each tenant seller location with Square, runs the sweep, and
        gives the notice for each renewal of the next 3 days (plan
        2026-11-19-002 § 5.10, § 7.7). One failed step does not stop the next
        step; `failed_steps` names it.
        Internal-only endpoint authenticated by the `X-Billing-Run-Token`
        header (the `BILLING_RUN_INTERNAL_TOKEN` secret, compared in constant
        time). Called by the worker, which runs no SQL of this plan and holds
        no Square secret (plan 2026-11-19-002 § 7.7, K8). No
        Idempotency-Key: each write is idempotent through the engine's own
        keys (the attempt id, the period invoice).
      tags: [Billing]
      security: []
      parameters:
        - name: X-Billing-Run-Token
          in: header
          required: true
          schema: { type: string }
      responses:
        '200':
          description: The step ran
          content:
            application/json:
              schema: { $ref: '#/components/schemas/InternalBillingReconcileResult' }
        '400':
          description: Body failed validation
          content:
            application/json:
              schema: { $ref: '#/components/schemas/InternalBillingError' }
        '401':
          description: No token header, or a wrong value (`unauthorized`)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/InternalBillingError' }
        '503':
          description: 'BILLING_RUN_INTERNAL_TOKEN not configured on this instance (`billing_run_not_configured`), or the database is unavailable'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/InternalBillingError' }

  /api-keys/{id}:
    patch:
      operationId: updateApiKey
      summary: Update mutable API key metadata (`name`, `ip_allowlist`)
      description: Requires `account:write`. Active, non-expired keys only.
      tags: [API Keys]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string, format: uuid } }
        - $ref: '#/components/parameters/idempotencyKey'
      responses:
        '200': { description: Updated API key metadata }
        '400': { description: Invalid CIDR allowlist or payload }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }
        '409': { description: Expired API key cannot be updated }
    delete:
      operationId: revokeApiKey
      summary: Revoke an API key
      tags: [API Keys]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        '204': { description: Revoked }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }

  /api-keys/{id}/rotate:
    post:
      operationId: rotateApiKey
      summary: Rotate an API key secret
      description: |
        All responses, including errors, use `Cache-Control: no-store`.
        The secret response is never retained or replayed by idempotency storage.
        A completed key returns `409 idempotency_secret_response_unavailable`.
        The original operation may already have committed. Do not automatically
        retry with a fresh key; inspect the resource before recovery or an
        intentional new creation or rotation.
      tags: [API Keys]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string, format: uuid } }
        - $ref: '#/components/parameters/idempotencyKey'
      responses:
        '200':
          description: API key rotated (new secret shown once; old secret revoked immediately)
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema:
                type: object
                required: [id, account_id, name, key_prefix, api_key, scopes, ip_allowlist, created_at, rotated_at]
                properties:
                  id: { type: string, format: uuid }
                  account_id: { type: string, format: uuid }
                  name: { type: string }
                  key_prefix: { type: string }
                  api_key: { type: string }
                  scopes:
                    type: array
                    items: { type: string }
                  ip_allowlist:
                    type: array
                    items: { type: string }
                  expires_at: { type: [string, 'null'], format: date-time }
                  last_used_at: { type: [string, 'null'], format: date-time }
                  created_at: { type: string, format: date-time }
                  rotated_at: { type: string, format: date-time }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }
        '409':
          description: An expired key cannot be rotated (api_key_expired); or the idempotency reservation is active or its secret response cannot be replayed.
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
            Retry-After:
              description: Present only for idempotency_in_progress.
              schema: { type: string }
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: '#/components/schemas/SecretOperationConflictError'
                  - type: object
                    required: [error]
                    properties:
                      error: { type: string, enum: [api_key_expired] }

  /void-events/{id}/diff:
    get:
      operationId: getVoidEventDiff
      summary: Diff between original contract and replacement payload
      tags: [VoidEvents]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Diff payload
          content:
            application/json:
              schema:
                type: object
                properties:
                  void_event_id: { type: string, format: uuid }
                  total_diff_count: { type: integer }
                  fields:
                    type: array
                    items:
                      type: object
                      properties:
                        path: { type: string }
                        before: {}
                        after: {}
        '401': { description: Unauthorized }
        '404': { description: Not Found }

  /void-events/{id}/fcra-notice/draft:
    post:
      operationId: createFcraNoticeDraft
      summary: Draft an FCRA Adverse Action Notice (DRAFT ONLY — never auto-sends)
      description: |
        Requires `contracts:fcra:draft` scope and step-up. The void event's
        `fcra_review_required` MUST be true. Returns `auto_send: false`
        explicitly — no send job is enqueued.
      tags: [VoidEvents]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [body_markdown]
              properties:
                body_markdown: { type: string, minLength: 1, maxLength: 50000 }
              additionalProperties: false
      responses:
        '201':
          description: Draft created
          content:
            application/json:
              schema:
                type: object
                properties:
                  draft_id: { type: string, format: uuid }
                  void_event_id: { type: string, format: uuid }
                  status: { type: string, enum: [queued_for_review] }
                  auto_send: { type: boolean, enum: [false] }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '409': { description: fcra_review_required is false }

  /webhooks/documenso:
    post:
      operationId: documensoWebhook
      summary: Documenso inbound webhook (signature events)
      description: |
        HMAC-signed inbound webhook. Verifies `X-Documenso-Signature` header
        against `DOCUMENSO_WEBHOOK_SECRET` and rejects stale deliveries outside
        the replay window. On `signature.completed` for a known void_event,
        advances the matching signer via the same `signAndMaterialize` path the
        synchronous /sign route uses. Contract signing events are a POR-242
        mapping-foundation path: the body must include `documenso_document_id`
        and `documenso_signer_id`; the server resolves those IDs through
        `documenso_contract_mappings` and treats body `account_id`,
        `contract_id`, and `signer_role` only as optional cross-checks.
        The legacy void-event leg still requires `account_id`. This does not
        make Documenso self-host/send/countersign UX production-ready by itself.
      tags: [Webhooks]
      security: []
      parameters:
        - name: X-Documenso-Signature
          in: header
          required: true
          schema: { type: string }
        - name: X-Documenso-Timestamp
          in: header
          required: true
          schema: { type: string }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [event, event_id, data]
              properties:
                event: { type: string }
                event_id: { type: string }
                data:
                  type: object
                  properties:
                    account_id:
                      type: string
                      format: uuid
                      description: Required for void-event webhooks; optional cross-check for contract webhooks.
                    void_event_id: { type: string, format: uuid }
                    contract_id:
                      type: string
                      format: uuid
                      description: Optional cross-check for contract webhooks; Documenso IDs are authoritative.
                    documenso_document_id:
                      type: string
                      description: Required for contract signing webhook events.
                    documenso_signer_id:
                      type: string
                      description: Required for contract signing webhook events.
                    signer_role:
                      type: string
                      enum: [rep, homeowner, primary, cosigner]
                      description: Cross-check only; server derives or resolves signer authority.
                    signed_at: { type: string, format: date-time }
                  additionalProperties: true
              additionalProperties: false
      responses:
        '200': { description: OK (idempotent) }
        '401': { description: Invalid or missing signature }
        '400': { description: Missing required fields }
        '409':
          description: Contract mapping missing, unmapped, mismatched, or state changed

  /activities:
    get:
      operationId: listActivities
      summary: List activities for an entity
      tags: [Activities]
      parameters:
        - $ref: '#/components/parameters/cursor'
        - $ref: '#/components/parameters/limit'
        - name: owner_type
          in: query
          required: true
          schema:
            type: string
            enum: [lead, contact, project, job, customer, estimate, service_plan, task, invoice, customer_invoice]
        - name: owner_id
          in: query
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Paginated activities
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PaginatedResponse' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }

  /activities/calls/{ownerType}/{ownerId}/{callId}:
    parameters:
      - name: ownerType
        in: path
        required: true
        schema: { type: string, enum: [lead, customer] }
      - name: ownerId
        in: path
        required: true
        schema: { type: string, format: uuid }
      - name: callId
        in: path
        required: true
        schema: { type: string, format: uuid }
    put:
      operationId: updateRecordCallLog
      x-portrex-scopes: [activities:write]
      summary: Replace the editable details of a call log
      tags: [Activities]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [direction, callOutcome]
              additionalProperties: false
              properties:
                direction: { type: string, enum: [inbound, outbound] }
                callOutcome: { type: string, enum: [connected, voicemail, no_answer, busy, wrong_number, callback_requested] }
                callDurationSeconds: { type: integer, minimum: 0, maximum: 86400 }
                bodyText: { type: string, maxLength: 240 }
      responses:
        '204': { description: Call log updated }
        '400': { description: Invalid request }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Call log unavailable on this record }
    delete:
      operationId: removeRecordCallLog
      x-portrex-scopes: [activities:write]
      summary: Remove a call log from the record
      tags: [Activities]
      responses:
        '204': { description: Call log removed }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Call log unavailable on this record }

  /leads/{id}/consents:
    post:
      operationId: recordLeadConsent
      summary: Record a TCPA consent for a contact on this lead
      tags: [Consent]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [contact_id, channel, message_class, consent_type, evidence, source]
              properties:
                contact_id: { type: string, format: uuid }
                channel: { type: string, enum: [sms, email, voice] }
                message_class:
                  type: string
                  enum: [marketing, transactional, informational, all]
                consent_type:
                  type: string
                  enum: [web_form_checkbox, double_opt_in_sms, signed_paper, verbal_recorded, e_signature, imported, door_knock_photo_gps]
                destination: { type: string, nullable: true }
                evidence: { type: object, additionalProperties: true }
                source: { type: string }
              additionalProperties: false
      responses:
        '201':
          description: Consent recorded
          content:
            application/json:
              schema:
                type: object
                required: [id]
                properties:
                  id: { type: string, format: uuid }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '422':
          description: TCPA consent policy violation
          content:
            application/json:
              schema:
                type: object
                required: [error, message]
                properties:
                  error: { type: string, example: tcpa_violation }
                  message: { type: string }
        '503': { description: DB not wired }

  # ============================================================
  # POR-44 (Epic E11 Lead Inbox) — CSV cold-lead import + conflict queue
  # ============================================================
  /leads/import:
    get:
      operationId: listLeadImportBatches
      summary: List lead-import batches for the current account
      tags: [Leads]
      parameters:
        - $ref: '#/components/parameters/cursor'
        - $ref: '#/components/parameters/limit'
      responses:
        '200':
          description: Paginated import batches
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PaginatedResponse' }
        '400': { description: Invalid cursor or offset pagination requested }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
    post:
      operationId: createLeadImportBatch
      summary: Start a CSV lead-import batch (idempotent)
      description: |
        Kicks off a CSV import. Idempotency-Key is REQUIRED. Re-uploading with the
        same key + same canonical body returns the original batch_id with
        `idempotent_replay: true` (HTTP 200). Re-using the key with a DIFFERENT body
        returns HTTP 422 `idempotency_key_conflict`. Concurrent first-time POSTs
        with the same key collapse to a single batch and a single processing event.

        `csv_inline` is capped at 10 MiB; larger payloads must be uploaded via the
        signed-URL path and referenced with `csv_url`.
      tags: [Leads]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                csv_inline:
                  type: string
                  description: Raw or base64 CSV content, capped at 10 MiB.
                csv_url:
                  type: string
                  format: uri
                  description: Signed URL for larger CSV uploads.
                mapping:
                  type: object
                  additionalProperties: true
              oneOf:
                - required: [csv_inline]
                - required: [csv_url]
              additionalProperties: false
      responses:
        '200':
          description: Idempotent replay of an existing batch
          content:
            application/json:
              schema:
                type: object
                required: [batch_id, idempotent_replay]
                properties:
                  batch_id: { type: string }
                  idempotent_replay: { type: boolean }
        '202':
          description: Batch accepted for processing
          content:
            application/json:
              schema:
                type: object
                required: [batch_id, idempotent_replay]
                properties:
                  batch_id: { type: string }
                  idempotent_replay: { type: boolean }
        '400': { description: Missing CSV body or idempotency key }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '413': { description: Inline CSV exceeds the 10 MiB cap }
        '422': { description: Idempotency key reused with a different request body }
  # ----- POR-437 / E29 Account Integration Connections -----
  /integrations:
    get:
      operationId: listIntegrationConnections
      summary: List integration provider states for the current account
      tags: [Integrations]
      responses:
        '200':
          description: Account-scoped integration catalog with live enablement and status
          content:
            application/json:
              schema: { $ref: '#/components/schemas/IntegrationConnectionPage' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
  /integrations/{provider}/enable:
    post:
      operationId: enableIntegrationConnection
      summary: Enable an integration provider for the current account
      tags: [Integrations]
      parameters:
        - name: provider
          in: path
          required: true
          schema:
            type: string
            enum: [lead_sources, webhooks, stripe, square, twilio, documenso, ghl, google_calendar, microsoft_365, quickbooks, hubspot, zapier_make, eagleview_hover, jobnimbus, acculynx, sunbase, mattermost]
      responses:
        '200':
          description: Updated provider connection state
          content:
            application/json:
              schema: { $ref: '#/components/schemas/IntegrationConnection' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Unknown integration provider }
        '409': { description: Provider connection state is managed through its dedicated settings surface }
        '503': { description: GoHighLevel runtime environment is not ready }
  /integrations/{provider}/connect:
    post:
      operationId: startIntegrationOAuth
      summary: Start an OAuth connection flow for an integration provider
      tags: [Integrations]
      parameters:
        - name: provider
          in: path
          required: true
          schema:
            type: string
            enum: [lead_sources, webhooks, stripe, square, twilio, documenso, ghl, google_calendar, microsoft_365, quickbooks, hubspot, zapier_make, eagleview_hover, jobnimbus, acculynx, sunbase, mattermost]
      responses:
        '200':
          description: Provider authorization URL and callback URI
          content:
            application/json:
              schema: { $ref: '#/components/schemas/IntegrationOAuthStart' }
        '400': { description: Provider does not support OAuth }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Unknown integration provider }
        '409': { description: Provider OAuth credentials are not configured }
        '503': { description: GoHighLevel runtime environment is not ready }
    get:
      operationId: redirectIntegrationOAuth
      summary: Redirect the browser into an OAuth connection flow
      tags: [Integrations]
      parameters:
        - name: provider
          in: path
          required: true
          schema:
            type: string
            enum: [lead_sources, webhooks, stripe, square, twilio, documenso, ghl, google_calendar, microsoft_365, quickbooks, hubspot, zapier_make, eagleview_hover, jobnimbus, acculynx, sunbase, mattermost]
      responses:
        '302': { description: Redirect to provider authorization URL }
        '303': { description: Redirect back to settings when provider credentials are missing }
        '400': { description: Provider does not support OAuth }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Unknown integration provider }
        '409': { description: GoHighLevel account gate denied the OAuth start }
        '503': { description: GoHighLevel runtime environment is not ready }
  /integrations/{provider}/callback:
    get:
      operationId: completeIntegrationOAuth
      summary: Complete an OAuth connection callback for an integration provider
      tags: [Integrations]
      parameters:
        - name: provider
          in: path
          required: true
          schema:
            type: string
            enum: [lead_sources, webhooks, stripe, square, twilio, documenso, ghl, google_calendar, microsoft_365, quickbooks, hubspot, zapier_make, eagleview_hover, jobnimbus, acculynx, sunbase, mattermost]
        - name: code
          in: query
          schema: { type: string }
        - name: state
          in: query
          schema: { type: string }
        - name: error
          in: query
          schema: { type: string }
        - name: error_description
          in: query
          schema: { type: string }
        - name: realmId
          in: query
          schema: { type: string }
      responses:
        '303':
          description: |
            Redirect back to integration settings with callback result. A
            no-session arrival (e.g. a GHL-marketplace-initiated install)
            never exchanges the code and redirects to settings — for GHL with
            `oauth=finish_from_portrex` (plan 2026-07-02-002 §8.2).
      security: []
  /integrations/{provider}/disable:
    post:
      operationId: disableIntegrationConnection
      summary: Disable an integration provider for the current account
      tags: [Integrations]
      parameters:
        - name: provider
          in: path
          required: true
          schema:
            type: string
            enum: [lead_sources, webhooks, stripe, square, twilio, documenso, ghl, google_calendar, microsoft_365, quickbooks, hubspot, zapier_make, eagleview_hover, jobnimbus, acculynx, sunbase, mattermost]
      responses:
        '200':
          description: Updated provider connection state
          content:
            application/json:
              schema: { $ref: '#/components/schemas/IntegrationConnection' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Unknown integration provider }
        '409': { description: Provider connection state is managed through its dedicated settings surface }

  /integrations/{provider}/credential-requirements:
    get:
      operationId: getIntegrationCredentialRequirements
      summary: Field metadata for tenant BYO financing credentials (Owner/Admin)
      description: |
        Returns adapter field descriptors for `palmetto` or `goodleap` only.
        Never includes secret values. Requires `integrations:credentials:write`,
        Owner/Admin, verified email. Other providers return 404.
      tags: [Integrations]
      parameters:
        - name: provider
          in: path
          required: true
          schema: { type: string, enum: [palmetto, goodleap, ghl, docusign, zoho_sign] }
      responses:
        '200':
          description: Credential field requirements
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/IntegrationCredentialRequirements' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Unsupported provider }
        '503': { description: Credential lifecycle not configured }

  /integrations/goodleap/credentials:
    post:
      operationId: acceptGoodLeapIntegrationCredentials
      summary: Accept sealed GoodLeap credentials without step-up (Owner/Admin)
      description: |
        GoodLeap's exact always-on route shares the generic encrypt-only
        credential handler but has no MFA or step-up dependency. Owner/Admin,
        verified email, impersonation denial, and
        `integrations:credentials:write` remain required.
      tags: [Integrations]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/IntegrationCredentialAcceptBody' }
      responses:
        '202':
          description: Validation queued
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/IntegrationCredentialAcceptResult' }
        '400': { description: Invalid body or credentials }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Connection not found }
        '503': { description: Credential lifecycle or seal unavailable }

  /integrations/goodleap/credentials/{setId}/rotate:
    post:
      operationId: rotateGoodLeapIntegrationCredentials
      summary: Rotate GoodLeap credentials without step-up (Owner/Admin)
      description: Requires verified email and `integrations:credentials:write`; no step-up.
      tags: [Integrations]
      parameters:
        - { name: setId, in: path, required: true, schema: { type: string, format: uuid } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/IntegrationCredentialAcceptBody' }
      responses:
        '202':
          description: Rotation queued
          content:
            application/json:
              schema: { $ref: '#/components/schemas/IntegrationCredentialAcceptResult' }
        '400': { description: Invalid body or credentials }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Connection or set not found }
        '409': { description: Set revoked }
        '503': { description: Credential lifecycle or seal unavailable }

  /integrations/goodleap/credentials/{setId}/revoke:
    post:
      operationId: revokeGoodLeapIntegrationCredentials
      summary: Revoke GoodLeap credentials without step-up (Owner/Admin)
      description: Requires verified email and `integrations:credentials:write`; no step-up.
      tags: [Integrations]
      parameters:
        - { name: setId, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        '202':
          description: Revoke queued
          content:
            application/json:
              schema: { $ref: '#/components/schemas/IntegrationCredentialAcceptResult' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Connection or set not found }
        '503': { description: Credential lifecycle not configured }

  /integrations/goodleap/credentials/{setId}/reveal:
    post:
      operationId: rejectGoodLeapCredentialReveal
      summary: Reject unsupported GoodLeap credential reveal without step-up
      description: GoodLeap credentials remain encrypt-only; this exact route never opens them.
      tags: [Integrations]
      parameters:
        - { name: setId, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        '400': { description: credential_reveal_unsupported }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }

  /integrations/goodleap/credential-binding:
    patch:
      operationId: patchGoodLeapCredentialBinding
      summary: Set GoodLeap credential binding without step-up (Owner/Admin)
      description: |
        Updates the account-owned GoodLeap connection binding. Switching to
        tenant_byo requires an active generation in the explicit
        `targetEnvironment`; a production binding has no sandbox prerequisite. Requires verified
        email and `integrations:credentials:write`; no step-up.
      tags: [Integrations]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/GoodLeapCredentialBindingBody' }
      responses:
        '200':
          description: Binding mode updated
          content:
            application/json:
              schema: { $ref: '#/components/schemas/IntegrationCredentialBindingResult' }
        '400': { description: Invalid body or target environment active generation required }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Connection not found }
        '409': { description: Tenant-owned binding conflict }
        '503': { description: Credential lifecycle not configured }

  /integrations/goodleap/credential-scope:
    patch:
      operationId: rejectGoodLeapCredentialScope
      summary: Reject unsupported GoodLeap branch credential scope without step-up
      description: GoodLeap uses its exact mapping/connection binding; Palmetto-only branch scope is unsupported.
      tags: [Integrations]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/PalmettoCredentialScopeBody' }
      responses:
        '400': { description: unsupported_credential_scope }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }

  /integrations/{provider}/credentials:
    get:
      operationId: listIntegrationCredentials
      summary: List safe credential set status (Owner/Admin)
      description: |
        Safe metadata only — never plaintext secrets or envelope ciphertext.
        Requires `integrations:credentials:write`, Owner/Admin, verified email.
      tags: [Integrations]
      parameters:
        - name: provider
          in: path
          required: true
          schema: { type: string, enum: [palmetto, goodleap, ghl, docusign, zoho_sign] }
      responses:
        '200':
          description: Credential sets
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/IntegrationCredentialSetList' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Unsupported provider }
        '503': { description: Credential lifecycle not configured }
    post:
      operationId: acceptIntegrationCredentials
      summary: Accept sealed tenant BYO credentials (Owner/Admin)
      description: |
        Validates shape via adapter, seals with dedicated KEK, persists a
        generation + validate command + ID-only outbox row, returns 202.
        API never decrypts and never contacts the provider. Non-GoodLeap
        providers require step-up (300s, WebAuthn/TOTP), verified email, and
        `integrations:credentials:write`; GoodLeap uses its exact path above.
      tags: [Integrations]
      parameters:
        - name: provider
          in: path
          required: true
          schema: { type: string, enum: [palmetto, ghl, docusign, zoho_sign] }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/IntegrationCredentialAcceptBody' }
      responses:
        '202':
          description: Validation queued
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/IntegrationCredentialAcceptResult' }
        '400': { description: Invalid body or credentials }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden }
        '404': { description: 'Unsupported provider or connection not found' }
        '503': { description: Credential lifecycle or seal unavailable }

  /integrations/{provider}/credentials/{setId}/rotate:
    post:
      operationId: rotateIntegrationCredentials
      summary: Rotate a credential set (Owner/Admin)
      description: |
        Seals a new generation and queues async validate/rotate. Non-GoodLeap
        providers require step-up (300s); GoodLeap uses its exact path above.
        Secrets never appear in the response.
      tags: [Integrations]
      parameters:
        - name: provider
          in: path
          required: true
          schema: { type: string, enum: [palmetto, ghl, docusign, zoho_sign] }
        - name: setId
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/IntegrationCredentialAcceptBody' }
      responses:
        '202':
          description: Rotation queued
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/IntegrationCredentialAcceptResult' }
        '400': { description: Invalid body or credentials }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden }
        '404': { description: 'Unsupported provider, connection, or set not found' }
        '409': { description: Set revoked }
        '503': { description: Credential lifecycle or seal unavailable }

  /integrations/{provider}/credentials/{setId}/revoke:
    post:
      operationId: revokeIntegrationCredentials
      summary: Revoke a credential set (Owner/Admin)
      description: |
        Immediately halts use of the set and queues async revoke cleanup.
        Non-GoodLeap providers require step-up (300s); GoodLeap uses its exact
        path above.
      tags: [Integrations]
      parameters:
        - name: provider
          in: path
          required: true
          schema: { type: string, enum: [palmetto, ghl, docusign, zoho_sign] }
        - name: setId
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '202':
          description: Revoke queued
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/IntegrationCredentialAcceptResult' }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden }
        '404': { description: 'Unsupported provider, connection, or set not found' }
        '503': { description: Credential lifecycle not configured }

  /integrations/{provider}/credentials/{setId}/reveal:
    post:
      operationId: revealIntegrationCredentials
      summary: Show saved GHL Client ID and Client Secret (Owner/Admin)
      description: |
        Opens the active GoHighLevel credential generation and returns
        client_id / client_secret for an explicit Show action. List/status APIs
        stay encrypt-only. Other supported credential providers return
        credential_reveal_unsupported. Requires verified email, Owner/Admin
        access, and integrations:credentials:write.

        The declared step-up window is 300 seconds. Freshness is enforced when
        PORTREX_REQUIRE_STEP_UP is exactly true. This gate checks freshness,
        not the step-up factor type; authentication and principal checks always apply.

        All responses, including errors, use Cache-Control: no-store. The response
        is never retained or replayed by idempotency storage. A completed key,
        including one with legacy stored JSON, returns
        409 idempotency_secret_response_unavailable without opening the secret again.
        For a new, explicit read-only Show action, send a fresh key. Do not
        interpret this error as permission to retry a credential creation or rotation.
      tags: [Integrations]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
        - name: provider
          in: path
          required: true
          schema: { type: string, enum: [palmetto, ghl, docusign, zoho_sign] }
        - name: setId
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
      responses:
        '200':
          description: Revealed GHL credential fields
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/IntegrationCredentialRevealResult' }
        '400': { description: Provider does not support reveal }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden }
        '404': { description: 'Unsupported provider, set, or active generation missing' }
        '409':
          description: Set revoked (set_revoked) or halted (credential_set_halted); or the idempotency reservation is active or its secret response cannot be replayed.
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
            Retry-After:
              description: Present only for idempotency_in_progress.
              schema: { type: string }
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: '#/components/schemas/SecretOperationConflictError'
                  - type: object
                    required: [error]
                    properties:
                      error: { type: string, enum: [set_revoked, credential_set_halted] }
        '503': { description: Credential open failed or lifecycle not configured }

  /integrations/{provider}/credential-binding:
    patch:
      operationId: patchIntegrationCredentialBinding
      summary: Set credential binding mode (Owner/Admin)
      description: |
        Updates `integration_connections.credential_binding_mode` for the
        account-owned connection. Switching to `tenant_byo` requires an active
        sandbox credential generation. Palmetto is tenant-BYO-only: a
        `legacy_platform` request is rejected with
        `palmetto_tenant_byo_required` and never writes the connection. Generic
        providers require step-up (300s), verified email, and
        `integrations:credentials:write`; GoodLeap uses its exact path above.
      tags: [Integrations]
      parameters:
        - name: provider
          in: path
          required: true
          schema: { type: string, enum: [palmetto, ghl, docusign, zoho_sign] }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/IntegrationCredentialBindingBody' }
      responses:
        '200':
          description: Binding mode updated
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/IntegrationCredentialBindingResult' }
        '400':
          description: >
            Invalid body, palmetto_tenant_byo_required, or sandbox active
            generation required for tenant_byo
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden }
        '404': { description: Unsupported provider or connection not found }
        '409': { description: Tenant-owned binding conflict }
        '503': { description: Credential lifecycle not configured }

  /integrations/{provider}/credential-scope:
    patch:
      operationId: patchPalmettoCredentialScope
      summary: Set an explicit Palmetto branch credential decision (Owner/Admin)
      description: |
        For Palmetto only, records an immutable exact branch and Next-sandbox
        decision to inherit the active account-default credential or fail closed.
        Inheritance is never inferred from a missing decision. A later explicit
        decision wins over any credential activation that was already queued.
        Requires step-up (300s, WebAuthn/TOTP), verified email, and
        `integrations:credentials:write`. GoodLeap and production are rejected.
      tags: [Integrations]
      parameters:
        - name: provider
          in: path
          required: true
          schema: { type: string, enum: [palmetto] }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/PalmettoCredentialScopeBody' }
      responses:
        '200':
          description: Exact branch credential decision recorded
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PalmettoCredentialScopeBinding' }
        '400': { description: 'Invalid body, unsupported provider, or unsupported environment' }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden }
        '404': { description: Connection or sub-account not found }
        '409': { description: Active account-default credential required for inheritance }
        '503': { description: Credential lifecycle not configured }

  /integrations/{provider}/credential-commands/{commandId}:
    get:
      operationId: getIntegrationCredentialCommand
      summary: Poll credential command status (Owner/Admin)
      description: |
        Safe command status only. Requires `integrations:credentials:write`,
        Owner/Admin, verified email.
      tags: [Integrations]
      parameters:
        - name: provider
          in: path
          required: true
          schema: { type: string, enum: [palmetto, goodleap, ghl, docusign, zoho_sign] }
        - name: commandId
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Command status
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/IntegrationCredentialCommand' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Unsupported provider or command not found }
        '503': { description: Credential lifecycle not configured }

  # ----- HubSpot multi-branch CRM integration ---------------------------------
  /integrations/hubspot/summary:
    get:
      operationId: getHubSpotIntegrationSummary
      summary: HubSpot multi-branch connection summary (parent company + branches)
      description: |
        Returns the parent company HubSpot connection (for head office owners/admins) and each
        branch's HubSpot mode (`inherit`, `own`, or `disabled`), effective portal status, and
        configured webhook target URL. Branch admins (`sub_account_admin`) receive only their own
        branch and a boolean `parent_connected` indicator (`parent` is `null`).
        Scopes: `integrations:read` or `account:read`.
      tags: [Integrations]
      responses:
        '200':
          description: HubSpot multi-branch integration summary
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }

  /integrations/hubspot/connect/oauth:
    post:
      operationId: startHubSpotOAuthPost
      summary: Start HubSpot OAuth 2.0 authorization (JSON URL mode)
      description: |
        Starts HubSpot OAuth 2.0 for the parent company (default) or a specific branch
        (`?sub_account_id=<uuid>`). Step-up gated (1h, WebAuthn/TOTP).
        Scope: `integrations:branch:write`.
      tags: [Integrations]
      parameters:
        - name: sub_account_id
          in: query
          required: false
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Authorization URL payload
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Branch not found }
    get:
      operationId: startHubSpotOAuthRedirect
      summary: Start HubSpot OAuth 2.0 authorization (redirect mode)
      description: |
        Redirects the browser to HubSpot OAuth 2.0 authorization for the parent company or target
        branch (`?sub_account_id=<uuid>`). Step-up gated (1h, WebAuthn/TOTP).
        Scope: `integrations:branch:write`.
      tags: [Integrations]
      parameters:
        - name: sub_account_id
          in: query
          required: false
          schema: { type: string, format: uuid }
      responses:
        '302': { description: Redirect to HubSpot OAuth authorization }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }

  /integrations/hubspot/connect/private-app:
    post:
      operationId: connectHubSpotPrivateApp
      summary: Connect HubSpot using a Private App access token
      description: |
        Verifies a HubSpot Private App token against HubSpot `/account-info/v3/details` and checks
        that it can read Contacts and Deals through CRM search (Notes and Tasks are not checked).
        Nothing is saved when either check fails. Then encrypts the token and optional webhook
        client secret with the tenant KEK, and binds the portal to the parent company or a specific
        branch (`sub_account_id`). Step-up gated (1h, WebAuthn/TOTP).
        Scope: `integrations:branch:write`.
      tags: [Integrations]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [access_token]
              properties:
                access_token: { type: string, minLength: 10 }
                webhook_secret: { type: string, nullable: true }
                sub_account_id: { type: string, format: uuid, nullable: true }
      responses:
        '200':
          description: Verified and connected HubSpot connection view
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '400': { description: Validation error }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '409': { description: HubSpot portal already linked to another scope or tenant }
        '422': { description: "HubSpot rejected the token, or the token cannot read Contacts and Deals (code hubspot_missing_scopes). Nothing was saved." }
        '424': { description: HubSpot rejected the Private App token }

  /integrations/hubspot/disconnect:
    post:
      operationId: disconnectHubSpotIntegration
      summary: Disconnect a HubSpot connection (parent company or branch)
      description: |
        Clears stored HubSpot credentials, disables active sync directions for the target scope,
        and releases the portal claim. For a branch, reverts branch mode to `inherit`.
        Step-up gated (1h, WebAuthn/TOTP). Scope: `integrations:branch:write`.
      tags: [Integrations]
      parameters:
        - name: sub_account_id
          in: query
          required: false
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Disconnected acknowledgement
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Connection or branch not found }

  /integrations/hubspot/test:
    post:
      operationId: testHubSpotConnection
      summary: Verify live HubSpot connectivity for the parent or branch connection
      description: |
        Executes a live probe against HubSpot `/account-info/v3/details` using the stored OAuth or
        Private App credential, then checks read access to Contacts and Deals with one Search call
        each, and records health metadata. A credential without that access is recorded as
        `error` and answered with 424 `hubspot_missing_scopes`. Scope: `integrations:branch:write`.
      tags: [Integrations]
      parameters:
        - name: sub_account_id
          in: query
          required: false
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Live probe result
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: No active HubSpot connection }
        '424': { description: HubSpot rejected the stored credential }

  /integrations/hubspot/branches/{subAccountId}/policy:
    put:
      operationId: updateHubSpotBranchPolicy
      summary: Update a branch HubSpot inheritance policy (`inherit` or `disabled`) and branch tag
      description: |
        Sets whether a branch inherits the parent company's HubSpot portal (`inherit`) or opts out
        (`disabled`), and optionally sets its `branch_property_value` tag for parent-portal
        attribution. Returns `409` if the branch currently has its own active HubSpot connection.
        Step-up gated (1h, WebAuthn/TOTP). Scope: `integrations:branch:write`.
      tags: [Integrations]
      parameters:
        - name: subAccountId
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [mode]
              properties:
                mode: { type: string, enum: [inherit, disabled] }
                branch_property_value:
                  type: string
                  maxLength: 128
                  pattern: '^[^\u0000-\u001f\u007f]*$'
                  nullable: true
      responses:
        '200':
          description: Updated branch policy
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '400': { description: Validation error }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Branch not found }
        '409': { description: Branch has its own active HubSpot connection }

  /integrations/hubspot/sync/config:
    get:
      operationId: getHubSpotSyncConfig
      summary: Get HubSpot entity sync configuration for the parent or branch scope
      description: |
        Returns per-entity-pair sync directions, conflict policies, deal pipeline and stage
        mappings, and optional branch property name. Scopes: `integrations:read` or `account:read`.
      tags: [Integrations]
      parameters:
        - name: sub_account_id
          in: query
          required: false
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: HubSpot sync configuration
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: No active HubSpot connection }
    put:
      operationId: updateHubSpotSyncConfig
      summary: Update HubSpot entity sync directions, conflict policies, and pipeline stage mapping
      description: |
        Persists entity sync configuration for the active HubSpot connection under
        `portrex_integration_write_lock`. Step-up gated (1h, WebAuthn/TOTP).
        Scope: `integrations:branch:write`.
      tags: [Integrations]
      parameters:
        - name: sub_account_id
          in: query
          required: false
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, additionalProperties: true }
      responses:
        '200':
          description: Updated sync configuration
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '400': { description: Validation error }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: No active HubSpot connection }

  /integrations/hubspot/sync/health:
    get:
      operationId: getHubSpotSyncHealth
      summary: Get HubSpot sync health metrics (linked counts, cursor status, open errors)
      description: |
        Aggregates `sync_links`, `sync_journal`, and `sync_cursors` counts for the effective
        HubSpot connection. Scopes: `integrations:read` or `account:read`.
      tags: [Integrations]
      parameters:
        - name: sub_account_id
          in: query
          required: false
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: HubSpot sync health summary
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: No active HubSpot connection }

  /integrations/hubspot/sync/errors:
    get:
      operationId: listHubSpotSyncErrors
      summary: List unresolved HubSpot sync journal errors
      description: |
        Returns recent `failed`, `dead`, and `needs_review` journal entries for the effective
        HubSpot connection. Scopes: `integrations:read` or `account:read`.
      tags: [Integrations]
      parameters:
        - name: sub_account_id
          in: query
          required: false
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: HubSpot sync errors list
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }

  /integrations/hubspot/sync/errors/{journalId}/retry:
    post:
      operationId: retryHubSpotSyncError
      summary: Retry a failed HubSpot sync journal entry
      description: |
        Re-enqueues the Cloud Task (`hubspot-webhook-process` or `hubspot-outbound-push`) for a
        failed HubSpot sync journal item. Scope: `integrations:branch:write`.
      tags: [Integrations]
      parameters:
        - name: journalId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: sub_account_id
          in: query
          required: false
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Retry queued
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Journal entry or connection not found }

  /integrations/hubspot/sync/errors/{journalId}/resolve:
    post:
      operationId: resolveHubSpotSyncError
      summary: Mark a HubSpot sync journal error as resolved
      description: |
        Transitions a failed HubSpot sync journal row to `skipped_noop` so it clears from the
        unresolved error feed. Scope: `integrations:branch:write`.
      tags: [Integrations]
      parameters:
        - name: journalId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: sub_account_id
          in: query
          required: false
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Error resolved
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Journal entry or connection not found }

  /integrations/hubspot/sync/backfill:
    post:
      operationId: triggerHubSpotBackfill
      summary: Trigger a resumable HubSpot backfill for enabled entity pairs
      description: |
        Enqueues `hubspot-backfill` tasks for the selected (or all enabled) entity pairs on the
        active HubSpot connection. Step-up gated (1h, WebAuthn/TOTP).
        Scope: `integrations:branch:write`.
      tags: [Integrations]
      parameters:
        - name: sub_account_id
          in: query
          required: false
          schema: { type: string, format: uuid }
      requestBody:
        required: false
        content:
          application/json:
            schema: { type: object, additionalProperties: true }
      responses:
        '202':
          description: Backfill tasks enqueued
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '400': { description: Validation error }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: No active HubSpot connection }

  /integrations/hubspot/metadata/pipelines:
    get:
      operationId: listHubSpotPipelines
      summary: List live HubSpot deal pipelines and stages
      description: |
        Fetches active HubSpot Deal pipelines and stages for stage mapping configuration.
        Scopes: `integrations:read` or `account:read`.
      tags: [Integrations]
      parameters:
        - name: sub_account_id
          in: query
          required: false
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: HubSpot deal pipelines
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: No active HubSpot connection }

  /integrations/hubspot/metadata/owners:
    get:
      operationId: listHubSpotRemoteOwners
      summary: List live HubSpot CRM owners
      description: |
        Fetches HubSpot CRM owners for owner-to-team-member mapping.
        Scopes: `integrations:read` or `account:read`.
      tags: [Integrations]
      parameters:
        - name: sub_account_id
          in: query
          required: false
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: HubSpot owners list
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: No active HubSpot connection }

  /integrations/hubspot/metadata/properties:
    get:
      operationId: listHubSpotProperties
      summary: List live HubSpot CRM properties for Contacts or Deals
      description: |
        Fetches active HubSpot CRM v3 properties for Contacts or Deals to populate custom field mapping selectors.
        Scopes: `integrations:read` or `account:read`.
      tags: [Integrations]
      parameters:
        - name: object_type
          in: query
          required: false
          schema: { type: string, enum: [contacts, deals], default: deals }
        - name: sub_account_id
          in: query
          required: false
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: HubSpot CRM properties list
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '400': { description: Invalid object_type query parameter }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: No active HubSpot connection }

  /integrations/hubspot/owner-mappings:
    get:
      operationId: listHubSpotOwnerMappings
      summary: List saved HubSpot owner to Portrex user mappings
      description: |
        Lists configured HubSpot owner ↔ Portrex team member mappings for the effective HubSpot
        connection. Scopes: `integrations:read` or `account:read`.
      tags: [Integrations]
      parameters:
        - name: sub_account_id
          in: query
          required: false
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Owner mappings list
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
    put:
      operationId: upsertHubSpotOwnerMapping
      summary: Upsert a HubSpot owner to Portrex user mapping
      description: |
        Maps a HubSpot owner ID to an active Portrex team member on the target connection.
        Step-up gated (1h, WebAuthn/TOTP). Scope: `integrations:branch:write`.
      tags: [Integrations]
      parameters:
        - name: sub_account_id
          in: query
          required: false
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [hubspot_owner_id, user_id]
              properties:
                hubspot_owner_id: { type: string }
                hubspot_owner_email: { type: string, nullable: true }
                hubspot_owner_name: { type: string, nullable: true }
                user_id: { type: string, format: uuid }
      responses:
        '200':
          description: Saved owner mapping
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '400': { description: Validation error }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Connection or user not found }

  /integrations/hubspot/owner-mappings/{hubspotOwnerId}:
    delete:
      operationId: deleteHubSpotOwnerMapping
      summary: Delete a HubSpot owner mapping
      description: |
        Removes a HubSpot owner ↔ Portrex user mapping from the target connection.
        Step-up gated (1h, WebAuthn/TOTP). Scope: `integrations:branch:write`.
      tags: [Integrations]
      parameters:
        - name: hubspotOwnerId
          in: path
          required: true
          schema: { type: string }
        - name: sub_account_id
          in: query
          required: false
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Mapping deleted
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }

  /integrations/ghl/disconnect:
    post:
      operationId: disconnectGhlIntegration
      summary: Disconnect the GoHighLevel integration (remote revoke + token and sync teardown)
      description: |
        POR-734 (plan 2026-07-02-002 §8 / SEC-GHL-04; W7 plan 2026-08-13-001
        §3.3). Cancels queued sync-journal work and pauses every sync
        direction, then attempts a best-effort remote uninstall of the
        Portrex app from the bound GHL location (while the stored token is
        still usable), then nulls the stored OAuth tokens and sets the
        connection to `disabled`. The remote outcome is reported verbatim in
        `remote_revoke` — `revoked`, `failed`,
        `skipped_app_id_unconfigured` (env `GHL_APP_ID` not provisioned),
        `skipped_no_location`, or `skipped_no_token`; a failed or skipped
        revoke never blocks the local teardown. Step-up gated (1h,
        WebAuthn/TOTP). The GHL location claim is retained; releasing it is a
        staff-mediated admin-CLI procedure.
      tags: [Integrations]
      responses:
        '200':
          description: Updated provider connection state plus the remote revoke outcome
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/IntegrationConnection'
                  - type: object
                    required: [remote_revoke]
                    properties:
                      remote_revoke:
                        type: string
                        enum: [revoked, failed, skipped_app_id_unconfigured, skipped_no_location, skipped_no_token]
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: GoHighLevel is not connected for this account }

  /integrations/ghl/consent-ack:
    post:
      operationId: ackGhlConsent
      summary: Record the GoHighLevel connect-time disclosure acknowledgement
      description: |
        POR-732 (plan §8.2 / SEC-GHL-20). Records who/when acknowledged the
        connect-time disclosure of shared field categories, pinned to a
        disclosed-categories `version`. Called BEFORE the OAuth redirect. Writes
        audit `integration.ghl.consent_flow_ack` and persists the ack on the
        connection's metadata. SENSITIVE (`integrations:connection:write`) —
        the same authz as the connect flow it precedes. Not step-up gated (it
        precedes connect, which carries the step-up). Registered unconditionally.
      tags: [Integrations]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [version]
              properties:
                version: { type: string, enum: ['2026-07-01'] }
              additionalProperties: false
      responses:
        '200':
          description: Acknowledgement recorded
          content:
            application/json:
              schema:
                type: object
                properties:
                  acknowledged: { type: boolean }
                  version: { type: string, enum: ['2026-07-01'] }
                  at: { type: string, format: date-time }
        '400': { description: Validation error }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '409': { description: 'Account flag, disclosure, or connection gate denied' }
        '503': { description: GoHighLevel runtime environment is not ready }

  # ----- POR-732 GHL two-way sync API (M3a; boot-gated by GHL_SYNC_ENABLED) -----
  /integrations/ghl/sync/health:
    get:
      operationId: getGhlSyncHealth
      summary: GoHighLevel sync health (connection status, counts, timestamps)
      description: |
        POR-732 (plan 2026-07-02-002 §9). Read-only aggregate over
        sync_links / sync_journal / sync_cursors / sync_entity_config for the
        GHL connection: status, granted scopes, per-entity-pair direction,
        journal counts (linked / pending / failed / needs_review), last
        inbound/outbound/reconcile timestamps, and backfill progress. Scope:
        `account:read`. Registered only when GHL_SYNC_ENABLED=true.
      tags: [Integrations]
      responses:
        '200':
          description: Sync health aggregate
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: GoHighLevel is not connected for this account }
        '409': { description: 'Account flag, disclosure, or connection gate denied' }
        '503': { description: Sync subsystem unavailable }

  /integrations/ghl/sync/capabilities:
    get:
      operationId: getGhlSyncCapabilities
      summary: Per-capability GoHighLevel sync state, health, and needs-review rollup
      description: |
        W7 (plan 2026-08-13-001 §3.4). One entry per registered entity pair
        (the sync key registry) joining declared config (direction /
        delete propagation, defaults for pairs with no row), per-pair journal
        counts and link freshness (derived from remote_type via the registry),
        cursor phase state, the needs-review reason taxonomy
        (machine-readable codes with occurrence counts), and — for
        opportunity_lead — the 7-day owner-apply skip aggregate. Also lists
        the live location bindings; the primary binding reports the parent
        connection's status (in-row authority is structural, migration 0383).
        Reason codes and counts only — no principal identities, so the
        `account:read` floor of /health applies. Registered only when
        GHL_SYNC_ENABLED=true.
      tags: [Integrations]
      responses:
        '200':
          description: Per-capability rollup (capabilities + locations)
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: GoHighLevel is not connected for this account }
        '503': { description: Sync subsystem unavailable }

  /integrations/ghl/sync/errors:
    get:
      operationId: listGhlSyncErrors
      summary: List failed / dead / needs_review sync-journal rows (cursor-paginated)
      description: |
        POR-732 (plan §9). Per-record error feed with a human-readable cause,
        a machine-readable `reason` code (`error_json.code`, W7 §3.4),
        and the field-level diff. Cursor-based keyset pagination on
        (created_at, id). Scope: `account:read`.
      tags: [Integrations]
      parameters:
        - name: cursor
          in: query
          required: false
          schema: { type: string }
        - name: limit
          in: query
          required: false
          schema: { type: integer, minimum: 1, maximum: 100 }
        - name: status
          in: query
          required: false
          schema: { type: string, enum: [all, failed, dead, needs_review] }
        - name: direction
          in: query
          required: false
          schema: { type: string, enum: [all, inbound, outbound] }
        - name: entity_type
          in: query
          required: false
          schema: { type: string }
        - name: search
          in: query
          required: false
          schema: { type: string }
      responses:
        '200':
          description: Paginated per-record sync errors
          content:
            application/json:
              schema:
                type: object
                properties:
                  data: { type: array, items: { type: object, additionalProperties: true } }
                  next_cursor: { type: string, nullable: true }
                  total_count: { type: integer }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: GoHighLevel is not connected for this account }
        '409': { description: 'Account flag, disclosure, or connection gate denied' }
        '503': { description: Sync subsystem unavailable }

  /integrations/ghl/sync/pipelines:
    get:
      operationId: getGhlSyncPipelines
      summary: List the connected GoHighLevel location's pipelines and stages
      description: |
        POR-732 M4a (plan 2026-07-02-002 §6.2). Fetches the GHL location's
        opportunity pipelines and their ordered stages so the stage-mapping UI
        can build the GHL-stage → Portrex-status table. This is the one place
        the API reads GHL directly (via @portrex/ghl-client, no-direct-fetch);
        the connection must be connected and carry an external_location_id.
        Scope: `account:read`. Registered only when GHL_SYNC_ENABLED=true.
      tags: [Integrations]
      responses:
        '200':
          description: The location's pipelines and stages
          content:
            application/json:
              schema:
                type: object
                properties:
                  connection_id: { type: string }
                  location_id: { type: string }
                  pipelines:
                    type: array
                    items:
                      type: object
                      properties:
                        id: { type: string }
                        name: { type: string }
                        stages:
                          type: array
                          items:
                            type: object
                            properties:
                              id: { type: string }
                              name: { type: string }
                              position: { type: integer }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: GoHighLevel is not connected for this account }
        '409': { description: 'Account/connection gate denied, location unknown, or reconnect required' }
        '502': { description: GoHighLevel upstream error }
        '503': { description: Sync subsystem unavailable }

  /integrations/ghl/sync/config:
    get:
      operationId: getGhlSyncConfig
      summary: Read per-entity-pair sync configuration
      description: |
        POR-732 (plan §9 zone 2/3). Returns direction, delete propagation,
        conflict-policy overrides, and field toggles for each entity pair
        (contact_person, opportunity_lead, appointment_appointment).
        Scope: `account:read`.
      tags: [Integrations]
      responses:
        '200':
          description: Entity-pair sync configuration
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: GoHighLevel is not connected for this account }
        '409': { description: 'Account flag, disclosure, or Task 3 grant gate denied' }
        '503': { description: Sync subsystem unavailable }
    put:
      operationId: updateGhlSyncConfig
      summary: Update sync configuration for one entity pair
      description: |
        POR-732 (plan §8/§9). Sets direction / ownership overrides / field
        toggles for one entity pair. SENSITIVE (`integrations:sync`), OAuth
        user-context only — never API keys or Integration Users. Step-up is
        SESSION-START when the change WIDENS the synced field set (a direction
        or field previously off is enabled), else 1 hour. Task 2 permits only
        the legacy-core inbound lane; outbound, appointments, and advanced
        capability requests fail closed until Task 3 grant proof. A widening
        to inbound triggers a one-shot reconcile.
      tags: [Integrations]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [entity_pair, direction]
              properties:
                entity_pair:
                  type: string
                  enum: [contact_person, opportunity_lead, appointment_appointment, note_note, task_task, document_file, conversation_message]
                direction:
                  type: string
                  enum: [off, inbound, outbound, both]
                delete_propagation:
                  type: string
                  enum: [none, tombstone_pause]
                conflict_policy: { type: object, additionalProperties: true }
                field_map: { type: object, additionalProperties: { type: boolean } }
                stage_map: { type: object, additionalProperties: true }
                default_status: { type: string }
                default_pipeline_id: { type: string, nullable: true }
                reverse_stage_map: { type: object, additionalProperties: true }
                default_calendar_id: { type: string, nullable: true }
              additionalProperties: false
      responses:
        '200':
          description: Updated entity-pair configuration
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '400': { description: Validation error }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden (OAuth user-context required) }
        '404': { description: GoHighLevel is not connected for this account }
        '409': { description: Account/connection gate denied or Task 3 grant required }
        '503': { description: Sync subsystem unavailable }

  /integrations/ghl/sync/backfill:
    post:
      operationId: triggerGhlSyncBackfill
      summary: Trigger an initial backfill for one entity pair
      description: |
        POR-732 (plan §7.4/§8). Enqueues a resumable import for the entity
        pair. Task 2 accepts only inbound legacy-core contact/opportunity
        imports; outbound and appointment requests require Task 3 grant proof.
        A backfill is SENSITIVE (`integrations:sync`), Account Admin
        (owner/admin) only, OAuth user-context only, and session-start
        step-up'd. The entity pair's direction must not be `off`.

        Only `contact_person` and `opportunity_lead` are backfillable. A
        backfill enumerates the remote book from page one, which needs a
        remote list/search endpoint with a resumable cursor; GoHighLevel
        exposes none for appointments (get/create/update by id only), so
        `appointment_appointment` is CONFIGURABLE but not BACKFILLABLE and is
        rejected with 400. Appointments reach Portrex via webhooks, the
        reconcile stuck-net, the hourly outbound local sweep, and the weekly
        appointment refetch scan — see `docs/global/runbooks/ghl-sync.md` §8a.
      tags: [Integrations]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [entity_pair]
              properties:
                entity_pair:
                  type: string
                  enum: [contact_person, opportunity_lead]
              additionalProperties: false
      responses:
        '202':
          description: Backfill accepted (a ghl-backfill task is queued for the worker)
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden (Account Admin / OAuth user-context required) }
        '404': { description: GoHighLevel is not connected for this account }
        '409': { description: Connection/direction unavailable or Task 3 grant required }
        '503': { description: Sync subsystem unavailable }

  /integrations/ghl/sync/contact-address-enrichment:
    post:
      operationId: triggerGhlContactAddressEnrichment
      summary: Repair GHL contact address and source timestamp metadata
      description: |
        Enqueues the targeted repair used after legacy sparse contact backfills:
        scans active GHL contact/person links whose GHL-sourced leads are
        missing address or original-source timestamps, then full-fetches each
        contact through the normal inbound apply path. Same security posture as
        backfill: `integrations:sync`, Account Admin only, OAuth user-context
        only, and session-start step-up.
      tags: [Integrations]
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                dry_run: { type: boolean }
                batch_size: { type: integer, minimum: 1, maximum: 100 }
              additionalProperties: false
      responses:
        '202':
          description: Contact address enrichment accepted
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden (Account Admin / OAuth user-context required) }
        '404': { description: GoHighLevel is not connected for this account }
        '409': { description: Connection not connected or contact/person direction is off }
        '503': { description: Sync subsystem unavailable }

  /integrations/ghl/sync/data-inventory:
    post:
      operationId: triggerGhlDataInventory
      summary: Request a read-only GHL data coverage inventory
      description: |
        Reserved until Task 3 provides authoritative capability grant proof.
        Task 2 returns `409 ghl_task3_grant_required` before enqueue or audit.
        Requires `integrations:sync`, Account Admin, OAuth user context, and
        session-start step-up.
      tags: [Integrations]
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                sample_size: { type: integer, minimum: 1, maximum: 100 }
              additionalProperties: false
      responses:
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden (Account Admin / OAuth user-context required) }
        '404': { description: GoHighLevel is not connected for this account }
        '409': { description: Account/connection gate denied or Task 3 capability grant required }
        '503': { description: Sync subsystem unavailable }

  /integrations/ghl/sync/errors/{journalId}/retry:
    post:
      operationId: retryGhlSyncError
      summary: Re-enqueue a legacy-core inbound failed / dead / needs_review sync-journal row
      description: |
        POR-732 (plan §9). Flips the row back to `pending` and re-sends the
        legacy-core inbound processing event (contact or opportunity →
        ghl-webhook-process trigger repair). Outbound and other advanced
        capabilities remain inert until Task 3 grant proof. SENSITIVE
        (`integrations:sync`), 1h step-up, OAuth user-context only. Idempotent.
      tags: [Integrations]
      parameters:
        - name: journalId
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Row re-enqueued
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden (OAuth user-context required) }
        '404': { description: Sync-journal row not found }
        '409': { description: 'Account or connection gate denied, Task 3 grant required, or row is not actionable' }
        '503': { description: Sync subsystem unavailable }

  /integrations/ghl/sync/errors/{journalId}/resolve:
    post:
      operationId: resolveGhlSyncError
      summary: Mark a failed / dead / needs_review sync-journal row resolved
      description: |
        POR-732 (plan §9). Marks the row `skipped_noop` with the acting user.
        SENSITIVE (`integrations:sync`), 1h step-up, OAuth user-context only.
        Idempotent.
      tags: [Integrations]
      parameters:
        - name: journalId
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Row marked resolved
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden (OAuth user-context required) }
        '404': { description: Sync-journal row not found }
        '409': { description: Account/connection gate denied or row is not actionable }
        '503': { description: Sync subsystem unavailable }

  /integrations/ghl/sync/principal-mappings:
    get:
      operationId: listGhlPrincipalMappings
      summary: List remote GHL users, mappable memberships, and their mappings
      description: |
        Plan 2026-08-11-001 §5 W3 (D6). Returns the location-scoped remote-user
        catalog, its refresh health, the memberships an admin may map onto (the
        same eligibility source lead assignment uses), the existing mappings,
        and `owner_apply_skips` (actionable 7-day owner-apply skip rollup;
        always an array, empty when healthy). Read-only, but NOT weakly gated:
        the response carries a
        cross-branch personnel roster (name, role, user_id, membership_id,
        sub_account_id for every assignment-eligible member) plus third-party
        GoHighLevel staff identities. It therefore sits at the same trust level
        as the writes below. SENSITIVE (`integrations:sync`), Account Admin
        only, OAuth user-context only, branch-scoped rows, no step-up (reading
        the mapping table is not a standing authority grant).

        A remote principal is REFERENCE DATA — it is never an identity,
        membership, role, team, or grant.
      tags: [Integrations]
      responses:
        '200':
          description: Catalog, memberships, and mappings
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized }
        '403': { description: Forbidden (Account Admin / OAuth user-context) }
        '404': { description: GoHighLevel is not connected for this account }
    post:
      operationId: proposeGhlPrincipalMapping
      summary: Propose a remote GHL user → Portrex membership mapping
      description: |
        Creates the mapping in status `pending`. It grants nothing until an
        admin confirms it. The membership must already exist, be active, and be
        in this account and within the actor's branch scope; the remote user
        must already be in this connection's catalog. SENSITIVE
        (`integrations:sync`), Account Admin only, OAuth user-context only,
        session-start step-up, audited.
      tags: [Integrations]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [remote_user_id, membership_id]
              properties:
                remote_user_id: { type: string, minLength: 1, maxLength: 128 }
                membership_id: { type: string, format: uuid }
              additionalProperties: false
      responses:
        '201':
          description: Mapping proposed (status pending)
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '400': { description: Validation error }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden (Account Admin / OAuth user-context / branch scope) }
        '404': { description: 'GoHighLevel is not connected, or the remote user is not in the catalog' }
        '409': { description: 'Membership is not active, or the remote user already has a live mapping' }

  /integrations/ghl/sync/principal-mappings/{mappingId}/confirm:
    post:
      operationId: confirmGhlPrincipalMapping
      summary: Confirm a principal mapping (the admin verification step)
      description: |
        Moves the mapping to `confirmed` and records the verifying actor and
        timestamp. Only a confirmed mapping can drive an ownership write.
        Membership liveness is re-verified at confirm time. SENSITIVE
        (`integrations:sync`), Account Admin only, session-start step-up,
        audited.
      tags: [Integrations]
      parameters:
        - name: mappingId
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Mapping confirmed
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden (Account Admin / OAuth user-context / branch scope) }
        '404': { description: Mapping not found }
        '409': { description: 'Mapping is revoked, or the membership is no longer active' }

  /integrations/ghl/sync/principal-mappings/{mappingId}/revoke:
    post:
      operationId: revokeGhlPrincipalMapping
      summary: Revoke a principal mapping
      description: |
        Moves the mapping to `revoked`, recording the actor and timestamp. The
        row is kept for audit; ownership application stops immediately because
        it resolves only `confirmed` rows. SENSITIVE (`integrations:sync`),
        Account Admin only, session-start step-up, audited.
      tags: [Integrations]
      parameters:
        - name: mappingId
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Mapping revoked
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden (Account Admin / OAuth user-context / branch scope) }
        '404': { description: Mapping not found }
        '409': { description: Mapping is already revoked }

  /integrations/ghl/sync/principal-catalog/refresh:
    post:
      operationId: refreshGhlPrincipalCatalog
      summary: Refresh the remote GHL user catalog for this connection
      description: |
        Operator rung of the principal-catalog recovery ladder (the daily cron
        is rung 1 — see docs/global/runbooks/ghl-sync.md §8b). Enqueues
        `ghl/principal-catalog.requested`; the worker performs the
        `users.readonly` read. A failed refresh never deletes catalog rows.
        SENSITIVE (`integrations:sync`), Account Admin only, session-start
        step-up, audited.
      tags: [Integrations]
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
      responses:
        '202':
          description: Catalog refresh accepted
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden (Account Admin / OAuth user-context required) }
        '404': { description: GoHighLevel is not connected for this account }
        '409': { description: 'Connection not connected, or its GHL location is unknown' }

  /integrations/ghl/sync/calendar-catalog:
    get:
      operationId: getGhlCalendarCatalog
      summary: GHL calendar/group/resource catalogs + branch mappings
      description: |
        The mirrored calendar, group, and resource catalogs (migration 0387)
        with refresh health and the explicit admin-set branch mappings. Rows
        are business scheduling configuration, not personal data; a
        `service_booking` calendar_type row is the W5 "service catalog".
        Requires `account:read`; tenant-user only; no step-up; read-only.
      tags: [Integrations]
      responses:
        '200':
          description: Catalog rows + health
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized }
        '404': { description: GoHighLevel is not connected for this account }

  /integrations/ghl/sync/calendar-catalog/refresh:
    post:
      operationId: refreshGhlCalendarCatalog
      summary: Refresh the GHL calendar catalog for this connection
      description: |
        Operator rung of the calendar-catalog recovery ladder (the daily cron
        is rung 1 — see docs/global/runbooks/ghl-sync.md §8c). Enqueues
        `ghl/calendar-catalog.requested`; the worker performs the calendars /
        groups / resources reads. A failed refresh never deletes catalog rows,
        and a section denied for a pre-widening token yields a `partial`
        refresh that preserves that section. SENSITIVE (`integrations:sync`),
        Account Admin only, session-start step-up, audited.
      tags: [Integrations]
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
      responses:
        '202':
          description: Catalog refresh accepted
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden (Account Admin / OAuth user-context required) }
        '404': { description: GoHighLevel is not connected for this account }
        '409': { description: 'Connection not connected, or its GHL location is unknown' }

  /integrations/ghl/sync/calendar-catalog/calendars/{remoteCalendarId}/branch:
    put:
      operationId: setGhlCalendarBranchMapping
      summary: Set or clear a GHL calendar's Portrex branch mapping
      description: |
        The explicit branch mapping of plan W5: routes the calendar's reference
        reads to one Portrex branch. `sub_account_id: null` clears it. The
        mapping grants nothing by itself; migration 0387's composite FK pins
        the target to a real branch in this account, and the deciding actor and
        timestamp are recorded. SENSITIVE (`integrations:sync`), Account Admin
        only, session-start step-up, audited.
      tags: [Integrations]
      parameters:
        - name: remoteCalendarId
          in: path
          required: true
          schema: { type: string, minLength: 1, maxLength: 128 }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [sub_account_id]
              properties:
                sub_account_id: { type: string, format: uuid, nullable: true }
      responses:
        '200':
          description: Updated calendar row
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '400': { description: Validation error }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden (Account Admin / OAuth user-context required) }
        '404': { description: 'Calendar not in the catalog, or branch not found' }

  /integrations/ghl/sync/calendar-catalog/calendars/{remoteCalendarId}/free-slots:
    get:
      operationId: getGhlCalendarFreeSlots
      summary: Live free-slot read for a cataloged GHL calendar
      description: |
        A live `GET /calendars/{id}/free-slots` read (never persisted).
        Availability data only — no contact or personal data. The calendar must
        be in this connection's mirrored catalog; the window defaults to the
        next 14 days and is capped at 60. Requires `account:read`; tenant-user
        only; no step-up; read-only.
      tags: [Integrations]
      parameters:
        - name: remoteCalendarId
          in: path
          required: true
          schema: { type: string, minLength: 1, maxLength: 128 }
        - name: start_date
          in: query
          required: false
          schema: { type: string, pattern: '^\d{4}-\d{2}-\d{2}$' }
        - name: end_date
          in: query
          required: false
          schema: { type: string, pattern: '^\d{4}-\d{2}-\d{2}$' }
      responses:
        '200':
          description: Date-keyed free slots
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '400': { description: Invalid or oversized window }
        '401': { description: Unauthorized }
        '404': { description: 'GoHighLevel not connected, or calendar not in the catalog' }
        '409': { description: 'Connection not connected, location unknown, or re-auth required' }
        '502': { description: GoHighLevel upstream error }

  /integrations/ghl/sync/calendar-catalog/calendars/{remoteCalendarId}/blocked-slots:
    get:
      operationId: getGhlCalendarBlockedSlots
      summary: Live blocked-slot read for a cataloged GHL calendar
      description: |
        A live `GET /calendars/blocked-slots` read (never persisted). Blocked
        slots carry no contact; the response projects id/title/start/end only.
        The calendar must be in this connection's mirrored catalog; the window
        defaults to the next 14 days and is capped at 60. Requires
        `account:read`; tenant-user only; no step-up; read-only.
      tags: [Integrations]
      parameters:
        - name: remoteCalendarId
          in: path
          required: true
          schema: { type: string, minLength: 1, maxLength: 128 }
        - name: start_date
          in: query
          required: false
          schema: { type: string, pattern: '^\d{4}-\d{2}-\d{2}$' }
        - name: end_date
          in: query
          required: false
          schema: { type: string, pattern: '^\d{4}-\d{2}-\d{2}$' }
      responses:
        '200':
          description: Blocked-slot events (id/title/start/end)
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '400': { description: Invalid or oversized window }
        '401': { description: Unauthorized }
        '404': { description: 'GoHighLevel not connected, or calendar not in the catalog' }
        '409': { description: 'Connection not connected, location unknown, or re-auth required' }
        '502': { description: GoHighLevel upstream error }

  /integrations/ghl/sync/appointments/{appointmentId}/notes:
    get:
      operationId: getGhlAppointmentNotes
      summary: Live GHL notes read for a linked appointment
      description: |
        A live `GET /calendars/appointments/{id}/notes` read for a LINKED
        appointment (the path id is the Portrex appointment id; the sync link
        resolves the remote id RLS-fenced). Note bodies are unredacted CRM free
        text, so the read carries the principal-mapping-read posture: SENSITIVE
        (`integrations:sync`), Account Admin only, OAuth user-context only, no
        step-up, read-only, never persisted.
      tags: [Integrations]
      parameters:
        - name: appointmentId
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Notes for the linked appointment
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized }
        '403': { description: Forbidden (Account Admin / OAuth user-context required) }
        '404': { description: 'Appointment not linked, or gone from GoHighLevel' }
        '409': { description: Re-auth required }
        '502': { description: GoHighLevel upstream error }

  /integrations/ghl/sync/lost-reasons:
    get:
      operationId: getGhlLostReasons
      summary: Live GHL lost-reason catalog for this location
      description: |
        A live `GET /opportunities/lost-reason` read (never persisted) — the
        location's lost-reason catalog projected to id/name for pickers and for
        labelling a lost close. Requires `account:read`; tenant-user only; no
        step-up; read-only.
      tags: [Integrations]
      responses:
        '200':
          description: Lost reasons (id/name) + total
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized }
        '404': { description: GoHighLevel is not connected for this account }
        '409': { description: 'Connection not connected, location unknown, or re-auth required' }
        '502': { description: GoHighLevel upstream error }

  /integrations/ghl/sync/forecast:
    get:
      operationId: getGhlForecast
      summary: Per-stage forecast of open GHL opportunities
      description: |
        Aggregates OPEN opportunities per pipeline stage from the live GHL
        search (bounded to 20 pages of 100, with an explicit `partial` flag)
        joined with the pipeline catalog for names. Values are float dollars
        (GoHighLevel carries no currency). A stage deleted from GHL still
        aggregates with a null name — deletion never hides money. Requires
        `account:read`; tenant-user only; no step-up; read-only.
      tags: [Integrations]
      responses:
        '200':
          description: Per-pipeline, per-stage open counts and value sums
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized }
        '404': { description: GoHighLevel is not connected for this account }
        '409': { description: 'Connection not connected, location unknown, or re-auth required' }
        '502': { description: GoHighLevel upstream error }

  /integrations/ghl/sync/opportunities/{leadId}/lost-reason:
    put:
      operationId: pushGhlOpportunityLostReason
      summary: Attach a lost reason on the linked GHL opportunity
      description: |
        Pushes `PUT /opportunities/{id}/status` with `status: lost` and the
        given `lost_reason_id` for the opportunity LINKED to this Portrex
        lead/project. The local record must already be lost (409 otherwise) —
        the sync engine owns the status transition itself; this command only
        labels it, so it can never drive status drift. SENSITIVE
        (`integrations:sync`), Account Admin only, session-start step-up,
        audited.
      tags: [Integrations]
      parameters:
        - name: leadId
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [lost_reason_id]
              properties:
                lost_reason_id: { type: string, minLength: 1, maxLength: 128 }
      responses:
        '200':
          description: Lost reason pushed
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '400': { description: Validation error }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden (Account Admin / OAuth user-context required) }
        '404': { description: 'Not connected, or the lead has no live opportunity link' }
        '409': { description: 'The local record is not lost, or re-auth required' }
        '502': { description: 'GoHighLevel upstream error, or the status update was rejected' }

  /integrations/ghl/sync/opportunities/{leadId}/followers:
    post:
      operationId: addGhlOpportunityFollowers
      summary: Add followers on the linked GHL opportunity
      description: |
        Pushes `POST /opportunities/{id}/followers` for the opportunity LINKED
        to this Portrex lead/project. Every follower id must be an ACTIVE row
        in this connection's remote-principal catalog (§8b) — the tenant token
        never carries arbitrary ids to GoHighLevel. SENSITIVE
        (`integrations:sync`), Account Admin only, session-start step-up,
        audited.
      tags: [Integrations]
      parameters:
        - name: leadId
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [remote_user_ids]
              properties:
                remote_user_ids:
                  type: array
                  minItems: 1
                  maxItems: 20
                  items: { type: string, minLength: 1, maxLength: 128 }
      responses:
        '200':
          description: Followers added
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '400': { description: 'Validation error, or an id is not in the remote-principal catalog' }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden (Account Admin / OAuth user-context required) }
        '404': { description: 'Not connected, or the lead has no live opportunity link' }
        '409': { description: Re-auth required }
        '502': { description: GoHighLevel upstream error }
    delete:
      operationId: removeGhlOpportunityFollowers
      summary: Remove followers on the linked GHL opportunity
      description: |
        Pushes `DELETE /opportunities/{id}/followers` for the opportunity
        LINKED to this Portrex lead/project, with the same remote-principal
        catalog validation as the add. SENSITIVE (`integrations:sync`), Account
        Admin only, session-start step-up, audited.
      tags: [Integrations]
      parameters:
        - name: leadId
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [remote_user_ids]
              properties:
                remote_user_ids:
                  type: array
                  minItems: 1
                  maxItems: 20
                  items: { type: string, minLength: 1, maxLength: 128 }
      responses:
        '200':
          description: Followers removed
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '400': { description: 'Validation error, or an id is not in the remote-principal catalog' }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden (Account Admin / OAuth user-context required) }
        '404': { description: 'Not connected, or the lead has no live opportunity link' }
        '409': { description: Re-auth required }
        '502': { description: GoHighLevel upstream error }

  /finance/palmetto/cases:
    post:
      operationId: preparePalmettoFinanceCase
      summary: Prepare a Palmetto finance case (durable)
      description: |
        Creates the case + four chained intents + one partner_api outbox
        reference atomically and returns 202. Never calls Palmetto synchronously.
        Legacy project origination requires the existing finance command role.
        Showroom origination accepts either an assigned lead or a selected
        customer without manufacturing a lead or project. The customer origin
        additionally requires customers:read and resolves its canonical person.
        All paths require verified email and exact account/sub-account
        mapping. Legacy project origination retains fresh step-up; exact lead/customer
        showroom origination uses verified-session plus source ABAC without extra MFA.
      tags: [Finance]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [organizationMappingId, idempotencyKey]
              properties:
                projectId: { type: string, format: uuid, nullable: true }
                leadId: { type: string, format: uuid, nullable: true }
                customerId: { type: string, format: uuid, nullable: true }
                customerPersonId: { type: string, format: uuid, nullable: true }
                estimateId: { type: string, format: uuid, nullable: true }
                showroomSnapshot:
                  type: object
                  nullable: true
                  description: Safe applicant, property, HVAC system/equipment, and financed-amount snapshot. SSN, DOB, and disclosure payloads are forbidden.
                  additionalProperties: true
                keenRebateQuoteId: { type: string, format: uuid, nullable: true }
                organizationMappingId: { type: string, format: uuid }
                idempotencyKey: { type: string, format: uuid }
      responses:
        '202':
          description: Case and intents accepted
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden }
        '409': { description: Idempotency conflict }
    get:
      operationId: listPalmettoFinanceCases
      summary: List Palmetto finance cases
      description: |
        Server-backed list with non-PII URL filters and cursor pagination.
        Requires `palmetto_finance:read`. Sales Rep sees assigned cases only.
        Never returns SSN/DOB or secret versions.
      tags: [Finance]
      parameters:
        - name: bucket
          in: query
          schema: { type: string, enum: [application, contract, install, funded] }
        - name: attention
          in: query
          schema:
            type: string
            enum:
              - stipulations_required
              - confirmation_pending
              - sync_unconfirmed
              - unmapped_provider_status
              - unsupported_provider_state
              - provider_degraded
              - mapping_error
              - multiple_application_candidates
              - manual_review
        - name: syncStatus
          in: query
          schema: { type: string, enum: [current, dirty, reconciling, unconfirmed, error, needs_review] }
        - name: assignedTeamId
          in: query
          schema: { type: string, format: uuid }
        - name: createdFrom
          in: query
          schema: { type: string, format: date-time }
        - name: createdTo
          in: query
          schema: { type: string, format: date-time }
        - name: sort
          in: query
          schema: { type: string, enum: [created_at, updated_at, last_successful_sync_at], default: updated_at }
        - name: direction
          in: query
          schema: { type: string, enum: [asc, desc], default: desc }
        - name: cursor
          in: query
          schema: { type: string, nullable: true }
        - name: limit
          in: query
          schema: { type: integer, minimum: 1, maximum: 100, default: 25 }
      responses:
        '200':
          description: Case list page
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PalmettoCaseListResponse' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }

  /finance/palmetto/cases/search:
    post:
      operationId: searchPalmettoFinanceCases
      summary: Sensitive Palmetto finance case search
      description: |
        POST body search across authorized customer name/email, project id,
        case id, external reference, and remote account id. Query is never
        persisted, audited, or logged. Cache-Control: no-store.
      tags: [Finance]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [query]
              properties:
                query: { type: string, minLength: 3, maxLength: 120 }
                cursor: { type: string, nullable: true, maxLength: 500 }
                limit: { type: integer, minimum: 1, maximum: 50, default: 25 }
      responses:
        '200':
          description: Search results
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PalmettoCaseListResponse' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }

  /finance/palmetto/cases/{caseId}:
    get:
      operationId: getPalmettoFinanceCase
      summary: Get Palmetto finance case detail
      description: |
        Safe detail projection — no encrypted source snapshot, SSN/DOB, or
        secret versions. Multiple application candidates block send_application.
      tags: [Finance]
      parameters:
        - name: caseId
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Case detail
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Case not found }

  /finance/palmetto/cases/{caseId}/events:
    get:
      operationId: listPalmettoFinanceCaseEvents
      summary: List Palmetto finance case events
      description: Append-only allowlisted before/after projection events.
      tags: [Finance]
      parameters:
        - name: caseId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: cursor
          in: query
          schema: { type: string, nullable: true }
        - name: limit
          in: query
          schema: { type: integer, minimum: 1, maximum: 100, default: 25 }
      responses:
        '200':
          description: Event page
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized }
        '404': { description: Case not found }

  /finance/palmetto/showroom-existing-case:
    post:
      operationId: findExistingPalmettoShowroomCase
      summary: Find an open LightReach showroom application
      description: |
        Looks up an unarchived Portrex showroom case for the Review draft.
        The email and phone are hashed for the match and are not written to
        the audit log. Returns a null case id when none is open. Cache-Control
        is no-store. Performs no mutation.
      tags: [Finance]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [email, phone, leadId, customerId]
              properties:
                email: { type: string, maxLength: 320 }
                phone: { type: string, maxLength: 40 }
                leadId: { type: string, format: uuid, nullable: true }
                customerId: { type: string, format: uuid, nullable: true }
      responses:
        '200':
          description: Existing case id, or null when none is open
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema:
                type: object
                additionalProperties: false
                required: [caseId]
                properties:
                  caseId: { type: string, format: uuid, nullable: true }
        '400': { description: Invalid body }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Lead or customer not found }

  /finance/palmetto/preflight:
    get:
      operationId: preflightPalmettoFinanceSource
      summary: Preflight Palmetto finance source readiness
      description: |
        Returns missing source/setup codes and links to owning Portrex surfaces.
        Performs no mutation.
      tags: [Finance]
      parameters:
        - name: projectId
          in: query
          schema: { type: string, format: uuid, nullable: true }
        - name: leadId
          in: query
          schema: { type: string, format: uuid, nullable: true }
        - name: customerId
          in: query
          schema: { type: string, format: uuid, nullable: true }
        - name: source
          in: query
          schema: { type: string, enum: [showroom] }
      responses:
        '200':
          description: Preflight result
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PalmettoPreflightResponse' }
        '401': { description: Unauthorized }
        '403': { description: Customer source is outside the caller visibility or scope }
        '404': { description: 'Project, lead, or customer source not found' }

  /finance/palmetto/showroom-sources/{leadId}:
    patch:
      operationId: updatePalmettoShowroomSource
      summary: Persist LightReach showroom source corrections
      description: |
        Transactionally persists applicant contact, service address, and HVAC
        property fields to their owning Portrex lead/person/customer/property
        records before case preparation. Never accepts credit or disclosure data.
        Assigned Sales Reps and team-visible Sales Managers are allowed; legacy
        project authorization is not broadened.
      tags: [Finance]
      parameters:
        - name: leadId
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/PalmettoShowroomSourceCorrection' }
      responses:
        '200':
          description: Canonical owning-record readback
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '400': { description: Invalid owner correction }
        '401': { description: Unauthorized }
        '403': { description: Lead is outside the caller assignment scope }
        '404': { description: Lead not found }

  /finance/palmetto/showroom-sources/customers/{customerId}:
    patch:
      operationId: updatePalmettoCustomerShowroomSource
      summary: Persist selected-customer LightReach showroom corrections
      description: |
        Transactionally persists applicant contact, the primary service address,
        and HVAC property metrics to their canonical customer-owned records.
        Requires palmetto_finance:read, customers:write, verified email, and a
        customer-write ABAC decision. It does not require unrelated MFA step-up,
        never manufactures a lead, and never accepts credit data.
      tags: [Finance]
      parameters:
        - name: customerId
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/PalmettoShowroomSourceCorrection' }
      responses:
        '200':
          description: Canonical customer/person/address readback
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '400': { description: Invalid owner correction }
        '401': { description: Unauthorized }
        '403': { description: Missing customer write scope or customer visibility }
        '404': { description: Customer not found }

  /finance/palmetto/cases/{caseId}/quotes:
    post:
      operationId: createPalmettoFinanceQuote
      summary: Create a Palmetto quote intent (durable)
      description: |
        Resolves exactly one current pricing offer, persists a local quote with
        deterministic externalReference, and enqueues a partner_api outbox
        reference. Returns 202. No synchronous Palmetto HTTP. Sales roles are
        admitted only for an exact assigned/team-visible lead showroom case or
        a creator-visible customer showroom case. Legacy project cases retain
        fresh step-up; showroom cases use verified-session source authorization.
      tags: [Finance]
      parameters:
        - name: caseId
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [productId, pricingSnapshotHash, totalFinancedAmountCents, idempotencyKey]
              properties:
                productId: { type: string, minLength: 1, maxLength: 200 }
                pricingSnapshotHash: { type: string, pattern: '^[a-f0-9]{64}$' }
                totalFinancedAmountCents: { type: integer, minimum: 1, maximum: 100000000 }
                idempotencyKey: { type: string, format: uuid }
      responses:
        '202':
          description: Quote intent accepted
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden }
        '404': { description: Case not found }
        '409': { description: Idempotency conflict }

  /finance/palmetto/cases/{caseId}/account-update:
    post:
      operationId: updatePalmettoFinanceAccount
      summary: Queue an operational Palmetto account update
      description: |
        Persists a KEK-encrypted, strict operational update command and an
        IDs-only partner_api outbox reference, then returns 202. The worker
        resolves the exact tenant connection, performs one PATCH, reads the
        account back, and marks mismatches unknown/manual-review. SSN, DOB,
        disclosures, notes, billing, workflow fields, and raw provider bodies
        are forbidden.
      tags: [Finance]
      parameters:
        - name: caseId
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              minProperties: 2
              required: [idempotencyKey]
              properties:
                friendlyName: { type: string, minLength: 1, maxLength: 120 }
                language: { type: string, enum: [English, Spanish] }
                address:
                  type: object
                  additionalProperties: false
                  minProperties: 1
                  properties:
                    address1: { type: string, minLength: 1, maxLength: 200 }
                    address2: { type: [string, 'null'], maxLength: 200 }
                    city: { type: string, minLength: 1, maxLength: 120 }
                    state: { type: string, pattern: '^[A-Za-z]{2}$' }
                    zip: { type: string, pattern: '^\\d{5}(?:-\\d{4})?$' }
                coordinates:
                  type: object
                  additionalProperties: false
                  required: [lat, lon]
                  properties:
                    lat: { type: number, minimum: -90, maximum: 90 }
                    lon: { type: number, minimum: -180, maximum: 180 }
                applicants:
                  type: array
                  minItems: 1
                  maxItems: 2
                  items:
                    type: object
                    additionalProperties: false
                    required: [type]
                    minProperties: 2
                    properties:
                      type: { type: string, enum: [primary, secondary] }
                      firstName: { type: string, minLength: 1, maxLength: 100 }
                      middleName: { type: [string, 'null'], maxLength: 100 }
                      lastName: { type: string, minLength: 1, maxLength: 100 }
                      email: { type: string, format: email, maxLength: 320 }
                      phoneNumber: { type: string, minLength: 7, maxLength: 30 }
                      address:
                        type: object
                        additionalProperties: false
                        minProperties: 1
                        properties:
                          address1: { type: string, minLength: 1, maxLength: 200 }
                          address2: { type: [string, 'null'], maxLength: 200 }
                          city: { type: string, minLength: 1, maxLength: 120 }
                          state: { type: string, pattern: '^[A-Za-z]{2}$' }
                          zip: { type: string, pattern: '^\\d{5}(?:-\\d{4})?$' }
                propertyDetails:
                  type: object
                  additionalProperties: false
                  minProperties: 1
                  properties:
                    homeSize: { type: [number, 'null'], minimum: 1, maximum: 1000000 }
                    existingSystems: { type: [number, 'null'], minimum: 0, maximum: 1000 }
                    systemsBeingReplaced: { type: [number, 'null'], minimum: 1, maximum: 10 }
                salesRepresentative:
                  type: object
                  additionalProperties: false
                  minProperties: 1
                  properties:
                    name: { type: string, minLength: 1, maxLength: 200 }
                    email: { type: string, format: email, maxLength: 320 }
                    phoneNumber: { type: string, minLength: 7, maxLength: 30 }
                    licenseNumber: { type: string, minLength: 1, maxLength: 120 }
                idempotencyKey: { type: string, format: uuid }
      responses:
        '202':
          description: Durable account-update intent accepted
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { type: object, additionalProperties: false, required: [intent], properties: { intent: { type: object } } }
        '400': { description: Invalid or forbidden operational update field }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden }
        '404': { description: Case not found }
        '409': { description: Idempotency conflict }

  /finance/palmetto/cases/{caseId}/application-invitations:
    post:
      deprecated: true
      operationId: sendPalmettoApplicationInvitation
      summary: Send Palmetto hosted application invitation (durable)
      description: |
        Requires a confirmed quote, hosted handoff acknowledgement, and no
        unresolved invitation conflict. Creates send_application_invite intent
        + partner_api outbox reference. Returns 202. Sales roles are admitted
        only for an authorized showroom source. Legacy project cases retain
        fresh step-up; showroom cases use verified-session source authorization.
      tags: [Finance]
      parameters:
        - name: caseId
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [quoteId, idempotencyKey, hostedApplicationAcknowledged]
              properties:
                quoteId: { type: string, format: uuid }
                idempotencyKey: { type: string, format: uuid }
                hostedApplicationAcknowledged: { type: boolean, enum: [true] }
      responses:
        '202':
          description: Invitation intent accepted
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden }
        '404': { description: Case or quote not found }
        '409': { description: Idempotency conflict }

  /finance/palmetto/cases/{caseId}/application-session:
    post:
      operationId: startPalmettoHostedApplicationSession
      summary: Prepare a same-origin hosted-application continuation
      description: |
        Authenticated typed-client handoff for an eligible legacy synthetic or
        schema-v2 lead/customer showroom Next case. Legacy project handoff
        retains fresh step-up; showroom handoff uses verified-session source ABAC.
        Returns a short-lived HMAC-signed same-origin continuation path. The
        token contains no provider capability URL.
      tags: [Finance]
      parameters:
        - name: caseId
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Short-lived same-origin continuation prepared
          headers:
            Cache-Control:
              required: true
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema:
                type: object
                additionalProperties: false
                required: [continuationPath]
                properties:
                  continuationPath: { type: string, pattern: '^/v1/finance/palmetto/cases/' }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Hosted application unavailable }
        '404': { description: Case not found }
        '503': { description: Palmetto integration not configured }
    get:
      operationId: continuePalmettoHostedApplicationSession
      summary: Consume a signed same-origin continuation
      description: |
        Revalidates the authenticated principal, case, and feature gates before
        generating the provider capability. The capability is returned only as
        the Location of an empty, non-cacheable 303 response and is never JSON.
      tags: [Finance]
      parameters:
        - name: caseId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: continuation
          in: query
          required: true
          schema: { type: string, minLength: 32, maxLength: 2048 }
      responses:
        '303':
          description: Immediate navigation to the Palmetto-hosted application
          headers:
            Location:
              required: true
              schema: { type: string, format: uri }
            Cache-Control:
              required: true
              schema: { type: string, enum: [no-store] }
            Pragma:
              required: true
              schema: { type: string, enum: [no-cache] }
            Referrer-Policy:
              required: true
              schema: { type: string, enum: [no-referrer] }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Invalid or unavailable continuation }
        '404': { description: Case not found }
        '502': { description: Provider capability unavailable }
        '503': { description: Palmetto integration not configured }

  /finance/palmetto/cases/{caseId}/reconcile:
    post:
      operationId: reconcilePalmettoFinanceCase
      summary: Reconcile a Palmetto finance case (durable)
      description: |
        Creates or deduplicates a reconcile_case intent with the same sensitive
        command policy as mutations (scopes, verified email, and step-up).
        Provider calls are GET-only in the worker; HTTP never syncs state.
      tags: [Finance]
      parameters:
        - name: caseId
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [idempotencyKey]
              properties:
                idempotencyKey: { type: string, format: uuid }
      responses:
        '202':
          description: Reconcile intent accepted
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden }
        '404': { description: Case not found }
        '409': { description: Idempotency conflict }

  /finance/palmetto/cases/{caseId}/documents:
    get:
      operationId: listPalmettoFinanceDocuments
      summary: List safe Palmetto document metadata and durable submissions
      description: |
        Requires `palmetto_finance:read` plus `finance_records:read`, verified
        email, and 15-minute WebAuthn/TOTP step-up. Exact tenant, case, project,
        and sub-account ownership is enforced under RLS. Signed URLs and raw
        rejection free text are never returned.
      tags: [Finance]
      parameters:
        - { name: caseId, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        '200':
          description: Safe document projection and pending submissions
          headers:
            Cache-Control: { schema: { type: string, enum: [no-store] } }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PalmettoDocumentListResponse' }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden }
        '404': { description: Case not found }
    post:
      operationId: uploadPalmettoFinanceDocuments
      summary: Queue a durable Palmetto Documents v2 upload
      description: |
        Accepts 1–25 completed Portrex project attachments (PDF/JPEG/PNG) with
        an aggregate 50 MiB limit. Submission, immutable file snapshots, intent,
        audit, and reference-only outbox row are created atomically. No provider
        HTTP occurs on the request path.
      tags: [Finance]
      parameters:
        - { name: caseId, in: path, required: true, schema: { type: string, format: uuid } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [attachmentIds, type, idempotencyKey]
              properties:
                attachmentIds:
                  type: array
                  minItems: 1
                  maxItems: 25
                  uniqueItems: true
                  items: { type: string, format: uuid }
                type: { type: string, minLength: 1, maxLength: 200 }
                grouped: { type: boolean, default: false }
                idempotencyKey: { type: string, format: uuid }
      responses:
        '202':
          description: Upload submission and intent accepted
          headers:
            Cache-Control: { schema: { type: string, enum: [no-store] } }
          content:
            application/json:
              schema:
                type: object
                additionalProperties: false
                required: [submission, intent]
                properties:
                  submission: { $ref: '#/components/schemas/PalmettoDocumentSubmission' }
                  intent: { type: object, additionalProperties: true }
        '400': { description: 'Invalid attachment, type, or MIME' }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden }
        '409': { description: Idempotency conflict }
        '413': { description: Aggregate attachment size exceeds 50 MiB }
        '503': { description: Attachment storage or integration unavailable }

  /finance/palmetto/cases/{caseId}/documents/reconcile:
    post:
      operationId: reconcilePalmettoFinanceDocuments
      summary: Queue durable Palmetto document reconciliation
      tags: [Finance]
      parameters:
        - { name: caseId, in: path, required: true, schema: { type: string, format: uuid } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [idempotencyKey]
              properties:
                idempotencyKey: { type: string, format: uuid }
      responses:
        '202': { description: Reconciliation intent accepted }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden }
        '404': { description: Case not found }
        '409': { description: Idempotency conflict }

  /finance/palmetto/cases/{caseId}/documents/{documentId}:
    get:
      operationId: getPalmettoFinanceDocument
      summary: Get safe Palmetto document metadata
      tags: [Finance]
      parameters:
        - { name: caseId, in: path, required: true, schema: { type: string, format: uuid } }
        - { name: documentId, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        '200':
          description: Safe document projection
          headers:
            Cache-Control: { schema: { type: string, enum: [no-store] } }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PalmettoCaseDocument' }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden }
        '404': { description: Case or document not found }
    patch:
      operationId: updatePalmettoFinanceDocument
      summary: Queue an optimistic Palmetto document metadata update
      tags: [Finance]
      parameters:
        - { name: caseId, in: path, required: true, schema: { type: string, format: uuid } }
        - { name: documentId, in: path, required: true, schema: { type: string, format: uuid } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [expectedVersion, idempotencyKey]
              minProperties: 3
              properties:
                status: { type: string, enum: [pending, approved, rejected] }
                type: { type: string, minLength: 1, maxLength: 200 }
                rejectionNote: { type: string, minLength: 1, maxLength: 2000 }
                rejectionReasons:
                  type: array
                  minItems: 1
                  maxItems: 21
                  uniqueItems: true
                  items: { type: string, minLength: 1, maxLength: 200 }
                expectedVersion: { type: integer, minimum: 1, maximum: 2147483647 }
                idempotencyKey: { type: string, format: uuid }
      responses:
        '202': { description: Update intent accepted }
        '400': { description: Invalid or empty update }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden }
        '404': { description: Case or document not found }
        '409': { description: Idempotency or document version conflict }
    delete:
      operationId: archivePalmettoFinanceDocument
      summary: Queue an optimistic Palmetto document archive
      tags: [Finance]
      parameters:
        - { name: caseId, in: path, required: true, schema: { type: string, format: uuid } }
        - { name: documentId, in: path, required: true, schema: { type: string, format: uuid } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [expectedVersion, idempotencyKey]
              properties:
                expectedVersion: { type: integer, minimum: 1, maximum: 2147483647 }
                idempotencyKey: { type: string, format: uuid }
      responses:
        '202': { description: Archive intent accepted }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden }
        '404': { description: Case or document not found }
        '409': { description: Idempotency or document version conflict }

  /finance/palmetto/cases/{caseId}/documents/{documentId}/files/{ordinal}/content:
    get:
      operationId: getPalmettoFinanceDocumentFileContent
      summary: Relay one Palmetto document file ordinal same-origin
      description: |
        Refreshes and consumes the short-lived provider capability entirely in
        memory through the exact tenant-owned connection. The response is
        private/no-store with nosniff and a sanitized attachment disposition;
        URLs are never serialized, persisted, or logged.
      tags: [Finance]
      parameters:
        - { name: caseId, in: path, required: true, schema: { type: string, format: uuid } }
        - { name: documentId, in: path, required: true, schema: { type: string, format: uuid } }
        - { name: ordinal, in: path, required: true, schema: { type: integer, minimum: 0, maximum: 24 } }
      responses:
        '200':
          description: Document file bytes
          headers:
            Cache-Control: { schema: { type: string, enum: ['private, no-store, max-age=0'] } }
            X-Content-Type-Options: { schema: { type: string, enum: [nosniff] } }
            Content-Disposition: { schema: { type: string } }
          content:
            application/pdf: { schema: { type: string, format: binary } }
            image/jpeg: { schema: { type: string, format: binary } }
            image/png: { schema: { type: string, format: binary } }
        '400': { description: Invalid ordinal }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden }
        '404': { description: Case or document not found }
        '503': { description: Content capability unavailable }

  /integrations/palmetto:
    get:
      operationId: getPalmettoConnectionHealth
      summary: Palmetto Finance connection health (Owner/Admin)
      description: |
        Returns platform provisioning/health, webhook configuration status, and
        organization mappings. Credentials and secret versions never appear.
        Requires `integrations:sync`, Owner or Admin, and verified email.
      tags: [Integrations]
      responses:
        '200':
          description: Connection health
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PalmettoConnectionHealth' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '503': { description: Palmetto tenant settings database unavailable }

  /integrations/palmetto/host:
    get:
      operationId: getPalmettoHost
      summary: Read the tenant Palmetto host (Owner/Admin)
      description: |
        Returns the allowlisted Palmetto origin this tenant uses for login,
        lookup, and runtime HTTP. Missing config is Palmetto Next
        (`https://next.palmetto.finance`), never inferred from Portrex env.
        Requires `integrations:sync`, Owner or Admin, and verified email.
      tags: [Integrations]
      responses:
        '200':
          description: Tenant Palmetto host
          content:
            application/json:
              schema:
                type: object
                additionalProperties: false
                required: [origin, selection, saved]
                properties:
                  origin: { type: string, format: uri, maxLength: 200 }
                  selection: { type: string, enum: [next, production, custom] }
                  saved: { type: boolean }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Palmetto connection not found }
        '503': { description: Palmetto tenant settings database unavailable }
    patch:
      operationId: patchPalmettoHost
      summary: Save the tenant Palmetto host (Owner/Admin)
      description: |
        Persists an allowlisted Palmetto origin on the connection
        `config_json`. Custom URLs must still be `https://next.palmetto.finance`
        or `https://palmetto.finance`. Never stored in the sealed credential
        blob. Requires Owner/Admin, `integrations:sync` + `account:write`, and
        step-up.
      tags: [Integrations]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [selection]
              properties:
                selection: { type: string, enum: [next, production, custom] }
                origin: { type: string, maxLength: 200 }
      responses:
        '200':
          description: Saved Palmetto host
          content:
            application/json:
              schema:
                type: object
                additionalProperties: false
                required: [origin, selection, saved]
                properties:
                  origin: { type: string, format: uri, maxLength: 200 }
                  selection: { type: string, enum: [next, production, custom] }
                  saved: { type: boolean }
        '400': { description: 'Host is not allowlisted, or custom selection has no origin' }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden }
        '404': { description: Palmetto connection not found }
        '503': { description: Palmetto tenant settings database unavailable }

  /integrations/palmetto/organizations-catalog:
    get:
      operationId: getPalmettoOrganizationsCatalog
      summary: Read Palmetto organization hierarchy and licenses catalog (Owner/Admin)
      description: |
        Returns live contractor licenses, authorized states, and trade program
        types across the root organization and all child organizations discovered on
        the allowlisted Palmetto host. Requires `integrations:sync`, Owner or Admin,
        and verified email.
      tags: [Integrations]
      responses:
        '200':
          description: Palmetto organizations catalog
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Palmetto connection not found }
        '409': { description: Credentials required }
        '503': { description: Palmetto tenant settings database unavailable }

  /integrations/palmetto/remote-organizations:
    post:
      operationId: lookupPalmettoRemoteOrganization
      summary: Look up a Palmetto company by alias
      description: |
        Uses the latest sealed tenant Palmetto username and password (pending,
        active, or invalid) to log in and GET `/api/organizations/{alias}`.
        Returns Palmetto's immutable id and active HVAC license states so the
        operator never types the hex id. Does not persist a mapping.
        Requires Owner/Admin, `integrations:sync` + `account:write`, and step-up.
      tags: [Integrations]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [alias]
              additionalProperties: false
              properties:
                alias:
                  type: string
                  minLength: 1
                  maxLength: 200
                  example: portrex
      responses:
        '200':
          description: Palmetto organization as observed for this login
          content:
            application/json:
              schema:
                type: object
                additionalProperties: false
                required: [id, alias, licenseStates]
                properties:
                  id: { type: string, minLength: 1, maxLength: 200 }
                  alias: { type: string, minLength: 1, maxLength: 200 }
                  licenseStates:
                    type: array
                    items: { type: string, pattern: '^[A-Z]{2}$' }
                    maxItems: 60
        '400': { description: 'Alias invalid, Palmetto login rejected, or identity/contract mismatch' }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden }
        '404': { description: Palmetto connection not found }
        '409': { description: Tenant credentials have not been saved yet }
        '503': { description: Credential session could not be opened }

  /integrations/palmetto/preflight:
    post:
      operationId: preflightPalmettoMapping
      summary: Preflight a saved Palmetto organization mapping
      description: |
        Opens only the saved mapping's exact account or branch tenant-owned
        sandbox credential. Verifies root/acting organization id, alias, and
        every configured state observed in the live active-HVAC
        `stateLicenseNumbers` projection. The GET operation does not publish a
        response schema, so missing or malformed license data fails closed.
        Does not activate or resume writes. Requires Owner/Admin and step-up.
      tags: [Integrations]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [mappingId]
              additionalProperties: false
              properties:
                environment: { type: string, enum: [next, production], default: next }
                mappingId: { type: string, format: uuid }
      responses:
        '200':
          description: Preflight result
          content:
            application/json:
              schema:
                type: object
                additionalProperties: false
                required: [ok, remoteOrganizationId, remoteOrganizationAlias, contractorLicenseStates, errorCode]
                properties:
                  ok: { type: boolean }
                  remoteOrganizationId: { type: string, nullable: true }
                  remoteOrganizationAlias: { type: string }
                  contractorLicenseStates:
                    type: array
                    items: { type: string, pattern: '^[A-Z]{2}$' }
                  errorCode: { type: string, nullable: true }
        '400': { description: Saved mapping identity/license mismatch or uncertified license response shape }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden }
        '503': { description: Exact tenant connection credential session not available }

  /integrations/palmetto/mappings:
    post:
      operationId: createPalmettoOrganizationMapping
      summary: Save a pending Palmetto organization mapping
      description: |
        Persists account-default or exact-branch operator intent without any
        provider call. The mapping is unverified and pending validation.
        Configure the exact scoped credential next, then explicitly verify and
        activate. No global or personal credential fallback.
      tags: [Integrations]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [remoteOrganizationAlias, remoteOrganizationId, friendlyName, contractorLicenseStates]
              additionalProperties: false
              properties:
                environment: { type: string, enum: [next, production], default: next }
                remoteOrganizationAlias:
                  type: string
                  minLength: 1
                  maxLength: 63
                  pattern: '^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$'
                remoteOrganizationId: { type: string, minLength: 1, maxLength: 200 }
                friendlyName: { type: string, minLength: 1, maxLength: 200 }
                subAccountId: { type: string, format: uuid, nullable: true }
                contractorLicenseStates:
                  type: array
                  minItems: 1
                  maxItems: 60
                  items: { type: string, minLength: 2, maxLength: 2 }
      responses:
        '201':
          description: Pending, unverified mapping saved without a provider call
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PalmettoOrganizationMapping' }
        '400': { description: Invalid or non-canonical mapping identity/license input }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden }
        '409': { description: Pending or active mapping already exists for the exact account or branch scope }
        '503': { description: Palmetto tenant settings database unavailable }

  /integrations/palmetto/mapping-scope:
    patch:
      operationId: setPalmettoMappingScope
      summary: Authorize account-default mapping inheritance for one sub-account
      description: |
        Appends an immutable, mapping-only authorization decision for the exact
        sub-account. `inherit_account` resolves the current active and verified
        account-default mapping on each use. `fail_closed` revokes inheritance.
        This never creates a duplicate mapping or changes credential scope.
        Requires Owner/Admin and step-up.
      tags: [Integrations]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [subAccountId, decision]
              properties:
                subAccountId: { type: string, format: uuid }
                decision: { type: string, enum: [inherit_account, fail_closed] }
      responses:
        '200':
          description: Effective sub-account mapping authorization
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PalmettoMappingScopeBinding' }
        '400': { description: Invalid scope decision }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden }
        '404': { description: 'Connection, sub-account, or account-default mapping not found' }
        '409': { description: Concurrent mapping authorization decision }
        '503': { description: Palmetto tenant settings database unavailable }

  /integrations/palmetto/mappings/{mappingId}:
    patch:
      operationId: updatePalmettoOrganizationMapping
      summary: Rename, disable, or verify and activate a Palmetto mapping
      description: |
        `status=active` opens only the exact saved account/branch tenant-owned
        credential, performs the same identity/license preflight, and claims the
        verified remote identity atomically. An activated mapping dispatches
        immediately — there is no separate resume action. Disabled mappings may
        be verified and reactivated.
      tags: [Integrations]
      parameters:
        - name: mappingId
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                friendlyName: { type: string, minLength: 1, maxLength: 200 }
                status: { type: string, enum: [active, disabled] }
                remoteOrganizationId: { type: string, minLength: 1, maxLength: 200 }
                remoteOrganizationAlias: { type: string, minLength: 1, maxLength: 200 }
                contractorLicenseStates:
                  type: array
                  minItems: 1
                  maxItems: 60
                  items: { type: string, pattern: '^[A-Z]{2}$' }
      responses:
        '200':
          description: Mapping updated
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PalmettoOrganizationMapping' }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden }
        '404': { description: Mapping not found }
        '409': { description: Verified provider identity already claimed or concurrent activation conflict }
        '503': { description: Exact tenant connection credential session not available }

  /integrations/palmetto/webhook-registration/verify:
    post:
      operationId: verifyPalmettoWebhookRegistration
      summary: Verify Palmetto webhook registration configuration
      tags: [Integrations]
      responses:
        '200':
          description: Verification result
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden }

  /integrations/palmetto/mappings/{mappingId}/equipment-catalog/refresh:
    post:
      operationId: refreshPalmettoEquipmentCatalog
      summary: Refresh approved-vendor equipment catalog mappings
      description: |
        Owner/Admin only. Reads each supported approved-vendor category, exact-
        matches local catalog rows via palmetto-core, and atomically activates
        only a complete conflict-free set. Partial fetches activate nothing.
      tags: [Integrations]
      parameters:
        - name: mappingId
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Refresh result
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden }
        '404': { description: Mapping not found }

  # ----- POR-53 / E14 Outbound Webhooks -----
  /webhooks:
    get:
      operationId: listWebhookSubscriptions
      summary: List webhook subscriptions for the current account
      tags: [Webhooks]
      parameters:
        - $ref: '#/components/parameters/cursor'
        - $ref: '#/components/parameters/limit'
      responses:
        '200':
          description: Paginated subscriptions (secrets are NEVER returned)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/WebhookSubscriptionPage' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
    post:
      operationId: createWebhookSubscription
      summary: Create a webhook subscription
      description: |
        All responses, including errors, use `Cache-Control: no-store`.
        The secret response is never retained or replayed by idempotency storage.
        A completed key returns `409 idempotency_secret_response_unavailable`.
        The original operation may already have committed. Do not automatically
        retry with a fresh key; inspect the resource before recovery or an
        intentional new creation or rotation.
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      tags: [Webhooks]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [url, events]
              properties:
                url: { type: string, format: uri }
                events: { type: array, items: { type: string }, minItems: 1 }
                description: { type: string, nullable: true }
              additionalProperties: false
      responses:
        '201':
          description: Subscription created — secret is returned exactly once
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/WebhookSubscriptionCreateResponse' }
        '400': { description: Validation error }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '409': { $ref: '#/components/responses/SecretOperationConflict' }

  /leads/{id}/consents/{consentId}:
    delete:
      operationId: revokeLeadConsent
      summary: Revoke an active TCPA consent record
      tags: [Consent]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string }
        - name: consentId
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                reason: { type: string }
              additionalProperties: false
      responses:
        '204':
          description: Consent revoked (revoked_at set; row remains in append-only ledger)
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not found or already revoked }
        '503': { description: DB not wired }

  /leads/{id}/duplicate-candidates:
    get:
      operationId: listLeadDuplicateCandidates
      summary: List open possible duplicates of a lead
      description: |
        Other leads in the same account that share a phone or a company email domain with this lead, as
        recorded when a lead source with a dedupe policy delivered it. Only open pairs are returned. A pair
        is left out when the caller cannot read the other lead or when either lead is deleted. The list
        returns at most 20 pairs, newest first. To reach older pairs that the caller can read, a request
        examines at most 250 pairs (5 pages of 50); a caller that cannot read more than 250 newer pairs
        gets a shorter list. Requires `leads:read`.
      tags: [Leads]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Open duplicate candidates, newest first (at most 20)
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/LeadDuplicateCandidate' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Lead not found or not visible to the caller }

  /leads/{id}/duplicate-candidates/{candidateId}/dismiss:
    post:
      operationId: dismissLeadDuplicateCandidate
      summary: Mark a possible duplicate as "Not a duplicate"
      description: |
        Sets the pair to `dismissed`. A later intake does not reopen it. Repeating the call on a dismissed
        pair returns 200 and changes nothing. Requires `leads:write` and write access to the lead.
      tags: [Leads]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: candidateId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      responses:
        '200':
          description: Candidate dismissed
          content:
            application/json:
              schema: { $ref: '#/components/schemas/LeadDuplicateCandidate' }
        '400': { description: Missing Idempotency-Key }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: 'Lead or candidate not found, or not visible to the caller' }

  /exports:
    post:
      operationId: createDataExport
      summary: Enqueue a tenant data export bundle (E35 / POR-59)
      description: |
        Schedules a per-tenant ZIP export. Returns immediately (202) with the
        queued row. The signed URL appears once the worker finishes; poll
        GET /exports/{id} or wait for the export.completed webhook.
        Requires the `account:export` OAuth scope (SENSITIVE — D29).
        Browser session only; API keys receive 403 (a sensitive scope cannot
        be put on an API key).
      tags: [Exports]
      security: [{ sessionCookie: [] }]
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties: {}
              additionalProperties: false
      responses:
        '202':
          description: Export job queued
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DataExport' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '503': { description: Exports repo not wired }

  /sms/inbound:
    post:
      operationId: smsInboundWebhook
      summary: Twilio inbound SMS webhook (STOP/HELP)
      description: |
        Public webhook called by Twilio when a contact replies to an
        outbound SMS. The endpoint requires a valid `X-Twilio-Signature`
        header — the request is verified per-tenant against
        `accounts.twilio_auth_token`. Invalid or missing signatures are
        rejected with 403; no consent ledger mutation occurs.

        Idempotent: replays of the same `MessageSid` are no-ops.

        STOP: revokes ALL active SMS consent for the matched
        (contact, phone) and writes a `stop_inbound` ledger row.
        HELP: replies with a tenant-branded help message and writes a
        `help_inbound` ledger row.
      tags: [SMS]
      security: []  # public webhook — auth is signature-based
      parameters:
        - name: X-Twilio-Signature
          in: header
          required: true
          schema: { type: string }
          description: |
            HMAC-SHA1 of (URL + sorted POST params) signed with the
            tenant's Twilio auth token, base64-encoded.
      requestBody:
        required: true
        content:
          application/x-www-form-urlencoded:
            schema:
              type: object
              required: [From, Body]
              properties:
                From: { type: string, description: E.164 sender }
                To: { type: string }
                Body: { type: string }
                MessageSid: { type: string }
                AccountSid: { type: string }
              additionalProperties: true
          application/json:
            schema:
              type: object
              required: [From, Body]
              properties:
                From: { type: string }
                To: { type: string }
                Body: { type: string }
                MessageSid: { type: string }
                AccountSid: { type: string }
              additionalProperties: true
      responses:
        '200':
          description: TwiML response (STOP/HELP/empty)
          content:
            application/xml:
              schema: { type: string }
        '403':
          description: Missing or invalid X-Twilio-Signature
        '500':
          description: One or more tenants failed to process; Twilio retries

  /sms/connection:
    get:
      operationId: getSmsConnection
      summary: State of the company's own Twilio account connection
      description: |
        Returns the live Twilio connection of the company, the candidate that is waiting for the
        Twilio check (if any), and the derived gate. The auth token, its ciphertext and the full SID
        are never returned. `canSend` is exactly the dispatch gate: connected, 10DLC `approved` and a
        sender configured. `inboundWebhookUrl` and `statusCallbackUrl` are the URLs for the company's
        Twilio console; they are null when the platform public API base URL is not configured.
      tags: [SMS]
      responses:
        '200':
          description: The connection state
          content:
            application/json:
              schema: &smsConnectionView
                type: object
                required: [connected, canSend, blockers, tenDlcStatus, inboundWebhookUrl, statusCallbackUrl, live, candidate]
                properties:
                  connected:
                    type: boolean
                    description: The live columns hold an Account SID, a token and a sender.
                  canSend:
                    type: boolean
                    description: Connected and 10DLC `approved` and a sender configured. Exactly the send gate.
                  blockers:
                    type: array
                    description: >-
                      Why `canSend` is false. `credentials_incomplete`: some live column (SID, token or sender)
                      is set but `connected` is false, so the saved credentials are unusable and must be
                      entered again.
                    items:
                      type: string
                      enum: [candidate_pending, candidate_failed, credentials_incomplete, tendlc_not_approved, sender_unconfigured]
                  tenDlcStatus:
                    type: string
                    enum: [unregistered, pending, approved, rejected]
                    description: 10DLC registration status. Texting is blocked until it is `approved`. Portrex support sets it by hand for now.
                  inboundWebhookUrl:
                    type: [string, 'null']
                    description: >-
                      URL the company pastes into its own Twilio console as the inbound message
                      webhook (HTTP POST). Null when the platform public API base URL is not configured.
                  statusCallbackUrl:
                    type: [string, 'null']
                    description: >-
                      Delivery-status callback URL that Portrex sends with each outbound message.
                      Informational: it is set automatically and is not pasted anywhere.
                      Null when the platform public API base URL is not configured.
                  live:
                    description: The connection that is in use now. Null when no Account SID is stored.
                    oneOf:
                      - type: 'null'
                      - type: object
                        required: [accountSidMasked, source, verifiedAt, messagingServiceSid, fromNumber, senderKind, warnings]
                        properties:
                          accountSidMasked: { type: [string, 'null'] }
                          source:
                            type: string
                            enum: [tenant, staff]
                            description: "`tenant` when Twilio verified the SID for the company. `staff` when it was entered by hand."
                          verifiedAt: { type: [string, 'null'], format: date-time }
                          messagingServiceSid: { type: [string, 'null'] }
                          fromNumber: { type: [string, 'null'] }
                          senderKind: { type: string, enum: [messaging_service, number_only] }
                          warnings:
                            type: array
                            items:
                              type: string
                              enum: [number_only_manual_approval, subaccount_signing_unconfirmed]
                  candidate:
                    description: Credentials that wait for the Twilio check, or that failed it. Null when there is none.
                    oneOf:
                      - type: 'null'
                      - type: object
                        required: [state, errorCode, requestedAt, accountSidMasked, messagingServiceSid, fromNumber, stale, retryAfterSeconds]
                        properties:
                          state: { type: string, enum: [pending, failed] }
                          errorCode:
                            type: [string, 'null']
                            description: >-
                              Set when `state` is `failed`. One of twilio_auth_failed, twilio_account_inactive,
                              twilio_account_mismatch, twilio_account_in_use, messaging_service_not_found,
                              messaging_service_wrong_account, sender_number_not_found, sender_not_sms_capable,
                              verification_unavailable.
                          requestedAt: { type: string, format: date-time }
                          accountSidMasked: { type: [string, 'null'] }
                          messagingServiceSid: { type: [string, 'null'] }
                          fromNumber: { type: [string, 'null'] }
                          stale:
                            type: boolean
                            description: Pending for more than 15 minutes.
                          retryAfterSeconds:
                            type: integer
                            minimum: 0
                            description: Seconds until a new PUT or recheck is allowed. 0 when allowed now.
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404':
          description: The account row does not exist.
          content:
            application/json:
              schema: &smsConnectionNotFound
                type: object
                required: [error, request_id]
                properties:
                  error: { type: string, enum: [account_not_found] }
                  request_id: { type: string }
        '503':
          description: Database unavailable
          content:
            application/json:
              schema: &smsConnectionError
                type: object
                required: [error, request_id]
                properties:
                  error: { type: string }
                  message: { type: string }
                  request_id: { type: string }
    put:
      operationId: putSmsConnection
      summary: Submit the company's own Twilio account for checking (owner or admin)
      description: |
        Stores the submitted Twilio Account SID, auth token and sender (a Messaging Service SID or an
        E.164 from number) as a CANDIDATE and queues a check with Twilio. It answers 202 at once. The
        live credentials, the sender and the 10DLC columns do not change. A worker proves the token with
        Twilio and only then promotes the candidate to the live connection. A failed check keeps the
        candidate with an error code and erases the token. SIDs are stored with an upper-case prefix and
        lower-case hex, and the token in lower-case hex, so a value pasted in any letter case is
        accepted. The token is encrypted at rest and never returned.

        `enqueued` is false when the queue send failed or the queue reported a duplicate. The candidate
        stays pending and the caller can use the recheck operation.

        A PUT or recheck less than 30 seconds after the previous one is refused with 429. Requires
        step-up re-authentication. The request is audited as `integration.twilio.mutated`; the token is
        redacted. An Account SID that another company holds is not refused here: the check fails later
        with `twilio_account_in_use`.
      tags: [SMS]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [accountSid, authToken]
              properties:
                accountSid: { type: string, pattern: '^[Aa][Cc][0-9a-fA-F]{32}$' }
                authToken: { type: string, pattern: '^[0-9a-fA-F]{32}$', writeOnly: true }
                messagingServiceSid: { type: [string, 'null'], pattern: '^[Mm][Gg][0-9a-fA-F]{32}$' }
                fromNumber: { type: [string, 'null'], pattern: '^\+[1-9][0-9]{7,14}$' }
      responses:
        '202':
          description: Candidate stored; returns the connection state and whether the check was queued
          content:
            application/json:
              schema:
                allOf:
                  - *smsConnectionView
                  - type: object
                    required: [enqueued]
                    properties:
                      enqueued: { type: boolean }
        '400':
          description: >-
            Invalid body. `error` is one of invalid_body, invalid_account_sid, invalid_auth_token,
            invalid_messaging_service_sid, invalid_from_number, sender_required.
          content:
            application/json:
              schema: *smsConnectionError
        '401':
          description: >-
            No session, or no fresh step-up proof. A step-up failure is answered with
            `WWW-Authenticate: step-up-required` and `code: step-up-required`.
        '403':
          description: >-
            The role does not hold `integrations:connection:write` (owner and admin hold it).
            A branch (sub-account) seat is refused with `code: account_level_membership_required`.
        '404':
          description: The account row does not exist.
          content:
            application/json:
              schema: *smsConnectionNotFound
        '429':
          description: A PUT or recheck was accepted less than 30 seconds ago.
          headers:
            Retry-After:
              required: true
              schema: { type: integer, minimum: 1 }
          content:
            application/json:
              schema: &smsConnectionRateLimited
                type: object
                required: [error, message, retryAfterSeconds, request_id]
                properties:
                  error: { type: string, enum: [rate_limited] }
                  message: { type: string }
                  retryAfterSeconds: { type: integer, minimum: 1 }
                  request_id: { type: string }
        '503':
          description: Credential store unavailable
          content:
            application/json:
              schema: *smsConnectionError
    delete:
      operationId: deleteSmsConnection
      summary: Disconnect the company's Twilio account (owner or admin)
      description: |
        In one transaction: clears the live Twilio account (SID, token, sender, verified time and owner
        SID), resets the 10DLC status to `unregistered` and clears the campaign reference, and deletes
        the candidate. Queued conversational SMS then fail closed until a new account is connected.
        Never refused by the 30 second rule and it does not reset that timer. Requires step-up
        re-authentication. The request is audited as `integration.twilio.mutated`.
      tags: [SMS]
      responses:
        '200':
          description: Disconnected; returns the connection state
          content:
            application/json:
              schema: *smsConnectionView
        '401':
          description: >-
            No session, or no fresh step-up proof. A step-up failure is answered with
            `WWW-Authenticate: step-up-required` and `code: step-up-required`.
        '403':
          description: >-
            The role does not hold `integrations:connection:write` (owner and admin hold it).
            A branch (sub-account) seat is refused with `code: account_level_membership_required`.
        '404':
          description: The account row does not exist.
          content:
            application/json:
              schema: *smsConnectionNotFound
        '503':
          description: Database unavailable
          content:
            application/json:
              schema: *smsConnectionError

  /sms/connection/recheck:
    post:
      operationId: recheckSmsConnection
      summary: Check the pending Twilio candidate again (owner or admin)
      description: |
        Queues a new check for a PENDING candidate. It takes no body. A failed candidate cannot be
        checked again because its token was erased: submit the credentials again with PUT. With no
        pending candidate the answer is 409 `nothing_to_recheck`. The 30 second rule of PUT applies.
        Requires step-up re-authentication. The request is audited as `integration.twilio.mutated`.
        `enqueued` is false when the queue send failed or the queue reported a duplicate.
      tags: [SMS]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      responses:
        '202':
          description: Check queued (or `enqueued` false); returns the connection state
          content:
            application/json:
              schema:
                allOf:
                  - *smsConnectionView
                  - type: object
                    required: [enqueued]
                    properties:
                      enqueued: { type: boolean }
        '401':
          description: >-
            No session, or no fresh step-up proof. A step-up failure is answered with
            `WWW-Authenticate: step-up-required` and `code: step-up-required`.
        '403':
          description: >-
            The role does not hold `integrations:connection:write` (owner and admin hold it).
            A branch (sub-account) seat is refused with `code: account_level_membership_required`.
        '404':
          description: The account row does not exist.
          content:
            application/json:
              schema: *smsConnectionNotFound
        '409':
          description: There is no pending candidate to check again.
          content:
            application/json:
              schema: *smsConnectionError
        '429':
          description: A PUT or recheck was accepted less than 30 seconds ago.
          headers:
            Retry-After:
              required: true
              schema: { type: integer, minimum: 1 }
          content:
            application/json:
              schema: *smsConnectionRateLimited
        '503':
          description: Database unavailable
          content:
            application/json:
              schema: *smsConnectionError

  /sms/connection/branches:
    get:
      operationId: listSmsBranchConnections
      summary: List per-branch Twilio SMS connections
      description: |
        Returns the Twilio SMS connection state of each branch the caller may manage. Head office
        (`owner` or `admin`) receives every branch of the company; a branch seat (`sub_account_admin`)
        receives only its own active seat branch. The `x-portrex-sub-account-id` view header never
        widens a branch seat's access. Never returns an auth token or its ciphertext.
      tags: [SMS]
      responses:
        '200':
          description: Branch Twilio connection views
          content:
            application/json:
              schema:
                type: object
                required: [branches]
                properties:
                  branches:
                    type: array
                    items: &smsBranchConnectionView
                      allOf:
                        - *smsConnectionView
                        - type: object
                          required:
                            [
                              subAccountId,
                              branchName,
                              branchStatus,
                              active,
                              mode,
                              firstApprovedAt,
                              effectiveSender,
                              effectiveSenderReason,
                            ]
                          properties:
                            subAccountId: { type: string, format: uuid }
                            branchName: { type: string }
                            branchStatus: { type: string, enum: [active, suspended, archived] }
                            active: { type: boolean }
                            mode:
                              type: string
                              enum: [own, parent]
                              description: "`own` when a verified branch connection exists; `parent` when the branch has no live connection of its own."
                            firstApprovedAt: { type: [string, 'null'], format: date-time }
                            effectiveSender:
                              type: string
                              enum: [branch, company, blocked]
                              description: Which connection currently sends conversational SMS for records of this branch.
                            effectiveSenderReason:
                              type: string
                              enum:
                                [
                                  no_branch_account,
                                  branch_inactive,
                                  branch_awaiting_first_approval,
                                  branch_approved,
                                  branch_tendlc_rejected,
                                  branch_tendlc_revetting,
                                  branch_tendlc_withdrawn,
                                  branch_sender_unconfigured,
                                ]
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '503':
          description: Database unavailable
          content:
            application/json:
              schema: *smsConnectionError

  /sms/connection/branches/{subAccountId}:
    parameters:
      - name: subAccountId
        in: path
        required: true
        schema: { type: string, format: uuid }
    get:
      operationId: getSmsBranchConnection
      summary: State of one branch's Twilio SMS connection
      description: |
        Returns one branch's Twilio connection view (`mode`, `effectiveSender`, `effectiveSenderReason`,
        `live`, `candidate`, and `blockers`). A branch seat that names another branch receives the same
        404 as a branch that does not exist.
      tags: [SMS]
      responses:
        '200':
          description: Branch Twilio connection state
          content:
            application/json:
              schema: *smsBranchConnectionView
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404':
          description: The branch does not exist or is outside the caller's seat fence.
          content:
            application/json:
              schema: &smsBranchNotFound
                type: object
                required: [error, request_id]
                properties:
                  error: { type: string, enum: [sub_account_not_found] }
                  request_id: { type: string }
        '503':
          description: Database unavailable
          content:
            application/json:
              schema: *smsConnectionError
    put:
      operationId: putSmsBranchConnection
      summary: Submit a branch's own Twilio account for checking (head office or that branch's admin)
      description: |
        Stores a candidate Twilio Account SID, auth token and sender for one active branch and queues
        `twilio-connection-verify` with `subAccountId`. Live branch credentials change only after Twilio
        verifies the token. Each branch has its own 30-second cooldown independent of the company and
        other branches. Requires `integrations:branch:write` and step-up re-authentication; audited as
        `integration.twilio.branch.mutated` with `authToken` redacted.
      tags: [SMS]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [accountSid, authToken]
              properties:
                accountSid: { type: string, pattern: '^[Aa][Cc][0-9a-fA-F]{32}$' }
                authToken: { type: string, pattern: '^[0-9a-fA-F]{32}$', writeOnly: true }
                messagingServiceSid: { type: [string, 'null'], pattern: '^[Mm][Gg][0-9a-fA-F]{32}$' }
                fromNumber: { type: [string, 'null'], pattern: '^\+[1-9][0-9]{7,14}$' }
      responses:
        '202':
          description: Branch candidate stored; returns the branch connection state and whether the check was queued
          content:
            application/json:
              schema:
                allOf:
                  - *smsBranchConnectionView
                  - type: object
                    required: [enqueued]
                    properties:
                      enqueued: { type: boolean }
        '400':
          description: Invalid body
          content:
            application/json:
              schema: *smsConnectionError
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden }
        '404':
          description: The branch does not exist, is not active, or is outside the caller's seat fence.
          content:
            application/json:
              schema: *smsBranchNotFound
        '429':
          description: A PUT or recheck for this branch was accepted less than 30 seconds ago.
          headers:
            Retry-After:
              required: true
              schema: { type: integer, minimum: 1 }
          content:
            application/json:
              schema: *smsConnectionRateLimited
        '503':
          description: Credential store unavailable
          content:
            application/json:
              schema: *smsConnectionError
    delete:
      operationId: deleteSmsBranchConnection
      summary: Disconnect a branch's own Twilio account (head office or that branch's admin)
      description: |
        Deletes the branch's candidate row and live Twilio connection row in one transaction, releasing
        the normalized SID claim and returning the branch to `mode: parent` (company account). Head
        office may disconnect any branch of the company (including suspended or archived); a branch
        seat may disconnect only its own active branch. Requires `integrations:branch:write` and
        step-up re-authentication; audited as `integration.twilio.branch.mutated`.
      tags: [SMS]
      responses:
        '200':
          description: Disconnected; returns the branch connection state
          content:
            application/json:
              schema: *smsBranchConnectionView
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden }
        '404':
          description: The branch does not exist or is outside the caller's seat fence.
          content:
            application/json:
              schema: *smsBranchNotFound
        '503':
          description: Database unavailable
          content:
            application/json:
              schema: *smsConnectionError

  /sms/connection/branches/{subAccountId}/recheck:
    parameters:
      - name: subAccountId
        in: path
        required: true
        schema: { type: string, format: uuid }
    post:
      operationId: recheckSmsBranchConnection
      summary: Check a branch's pending Twilio candidate again (head office or that branch's admin)
      description: |
        Queues a new verification check for a PENDING branch candidate. Returns 409 `nothing_to_recheck`
        when the branch has no pending candidate. Subject to the per-branch 30-second cooldown. Requires
        `integrations:branch:write` and step-up re-authentication; audited as
        `integration.twilio.branch.mutated`.
      tags: [SMS]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      responses:
        '202':
          description: Check queued (or `enqueued` false); returns the branch connection state
          content:
            application/json:
              schema:
                allOf:
                  - *smsBranchConnectionView
                  - type: object
                    required: [enqueued]
                    properties:
                      enqueued: { type: boolean }
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden }
        '404':
          description: The branch does not exist, is not active, or is outside the caller's seat fence.
          content:
            application/json:
              schema: *smsBranchNotFound
        '409':
          description: There is no pending branch candidate to check again.
          content:
            application/json:
              schema: *smsConnectionError
        '429':
          description: A PUT or recheck for this branch was accepted less than 30 seconds ago.
          headers:
            Retry-After:
              required: true
              schema: { type: integer, minimum: 1 }
          content:
            application/json:
              schema: *smsConnectionRateLimited
        '503':
          description: Database unavailable
          content:
            application/json:
              schema: *smsConnectionError

  /sms/connection/10dlc:
    patch:
      operationId: patchSmsConnection10Dlc
      summary: Update the company's Twilio 10DLC status and optional campaign SID (head-office owner or admin)
      description: |
        Updates `twilio_10dlc_status` (`unregistered`, `pending`, `approved`, `rejected`) and optional
        `twilio_10dlc_campaign_sid` on the live company Twilio connection. Returns 409 `no_live_connection`
        when no verified live Twilio connection exists. Requires `integrations:connection:write` and step-up
        re-authentication; a branch seat is refused. Audited as `integration.twilio.mutated`.
      tags: [SMS]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: &smsTenDlcUpdateInput
              type: object
              required: [tenDlcStatus]
              additionalProperties: false
              properties:
                tenDlcStatus:
                  type: string
                  enum: [unregistered, pending, approved, rejected]
                campaignSid:
                  type: [string, 'null']
                  maxLength: 64
      responses:
        '200':
          description: Updated company Twilio connection state
          content:
            application/json:
              schema: *smsConnectionView
        '400':
          description: Validation error (`invalid_body`, `invalid_tendlc_status`, `invalid_campaign_sid`)
          content:
            application/json:
              schema: *smsConnectionError
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden or branch seat (`account_level_membership_required`) }
        '409':
          description: No live Twilio connection exists on the company account (`no_live_connection`).
          content:
            application/json:
              schema: *smsConnectionError
        '503':
          description: Database unavailable
          content:
            application/json:
              schema: *smsConnectionError

  /sms/connection/branches/{subAccountId}/10dlc:
    parameters:
      - name: subAccountId
        in: path
        required: true
        schema: { type: string, format: uuid }
    patch:
      operationId: patchSmsBranchConnection10Dlc
      summary: Update a branch's Twilio 10DLC status and optional campaign SID (head office or that branch's admin)
      description: |
        Updates `twilio_10dlc_status` (`unregistered`, `pending`, `approved`, `rejected`) and optional
        `twilio_10dlc_campaign_sid` on the live branch Twilio connection. Returns 409 `no_live_connection`
        when no verified live branch Twilio connection exists. Requires `integrations:branch:write` and
        step-up re-authentication; audited as `integration.twilio.branch.mutated`.
      tags: [SMS]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: *smsTenDlcUpdateInput
      responses:
        '200':
          description: Updated branch Twilio connection state
          content:
            application/json:
              schema: *smsBranchConnectionView
        '400':
          description: Validation error (`invalid_body`, `invalid_tendlc_status`, `invalid_campaign_sid`)
          content:
            application/json:
              schema: *smsConnectionError
        '401': { description: Unauthorized or step-up required }
        '403': { description: Forbidden }
        '404':
          description: The branch does not exist, is not active, or is outside the caller's seat fence.
          content:
            application/json:
              schema: *smsBranchNotFound
        '409':
          description: No live Twilio connection exists on this branch (`no_live_connection`).
          content:
            application/json:
              schema: *smsConnectionError
        '503':
          description: Database unavailable
          content:
            application/json:
              schema: *smsConnectionError

  /leads/import/{batchId}:
    get:
      operationId: getLeadImportBatch
      summary: Get a lead-import batch status + counters
      tags: [Leads]
      parameters:
        - name: batchId
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Batch retrieved
          content:
            application/json:
              schema: { $ref: '#/components/schemas/LeadImportBatch' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Batch not found (or cross-tenant) }

  /leads/import/{batchId}/conflicts:
    get:
      operationId: listLeadImportConflicts
      summary: List unresolved conflicts for a batch (cursor paginated)
      tags: [Leads]
      parameters:
        - name: batchId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/cursor'
        - $ref: '#/components/parameters/limit'
      responses:
        '200':
          description: Paginated conflicts
          content:
            application/json:
              schema: { $ref: '#/components/schemas/LeadImportConflictPage' }
        '400': { description: Invalid cursor or offset pagination requested }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Batch not found }

  /exports/{id}:
    get:
      operationId: getDataExport
      summary: Fetch a single data export's status / signed URL
      tags: [Exports]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Export row (signed_url present once status=succeeded)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/DataExport' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not found }
        '503': { description: Exports repo not wired }

  /leads/import/conflicts/{id}/resolve:
    post:
      operationId: resolveLeadImportConflict
      summary: Resolve a lead-import conflict (skip / create_new / merge_into:<leadId>)
      tags: [Leads]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [action]
              properties:
                action:
                  type: string
                  pattern: '^(skip|create_new|merge_into:.+)$'
                  description: skip, create_new, or merge_into:<leadId>
              additionalProperties: false
      responses:
        '200':
          description: Conflict resolved
          content:
            application/json:
              schema: { $ref: '#/components/schemas/LeadImportConflictResolution' }
        '400': { description: Invalid action }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Conflict not found }
        '409': { description: Conflict already resolved or merge failed }

  /webhooks/{id}:
    get:
      operationId: getWebhookSubscription
      summary: Get one webhook subscription by ID (secret never returned)
      description: Requires `webhooks:read`.
      tags: [Webhooks]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200': { description: Webhook subscription detail }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }
    patch:
      operationId: updateWebhookSubscription
      summary: Update webhook subscription URL, subscribed events, active state, or description
      description: Requires `webhooks:manage`. Destination URLs must use HTTPS and resolve to public internet hosts (SSRF-guarded).
      tags: [Webhooks]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200': { description: Updated webhook subscription }
        '400': { description: Invalid payload or unsafe webhook URL }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }
    delete:
      operationId: deleteWebhookSubscription
      summary: Soft-delete a webhook subscription
      tags: [Webhooks]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '204': { description: Deleted }
        '404': { description: Not Found }

  /webhooks/{id}/rotate-secret:
    post:
      operationId: rotateWebhookSecret
      summary: Generate a new HMAC secret for a subscription
      description: |
        All responses, including errors, use `Cache-Control: no-store`.
        The secret response is never retained or replayed by idempotency storage.
        A completed key returns `409 idempotency_secret_response_unavailable`.
        The original operation may already have committed. Do not automatically
        retry with a fresh key; inspect the resource before recovery or an
        intentional new creation or rotation.
      tags: [Webhooks]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: New secret — store immediately
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/WebhookSecretRotationResponse' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }
        '409': { $ref: '#/components/responses/SecretOperationConflict' }

  /webhooks/{id}/restore:
    post:
      operationId: restoreWebhookSubscription
      summary: Restore a soft-deleted webhook subscription within the 30-day window
      tags: [Webhooks]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Restored subscription
          content:
            application/json:
              schema: { $ref: '#/components/schemas/WebhookSubscription' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Not Found }

  /webhooks/deliveries:
    get:
      operationId: listWebhookDeliveries
      summary: List delivery attempts (history)
      tags: [Webhooks]
      parameters:
        - name: subscription_id
          in: query
          schema: { type: string, format: uuid }
        - name: status
          in: query
          schema:
            type: string
            enum: [pending, in_flight, delivered, failed, dead_lettered]
        - $ref: '#/components/parameters/cursor'
        - $ref: '#/components/parameters/limit'
      responses:
        '200':
          description: Paginated delivery history
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PaginatedResponse' }

  /webhooks/deliveries/{id}/replay:
    post:
      operationId: replayWebhookDelivery
      summary: Replay a single delivery — creates a new delivery row
      tags: [Webhooks]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '202':
          description: Replay queued
          content:
            application/json:
              schema:
                type: object
                required: [delivery_id, replay_of_id, status]
                properties:
                  delivery_id: { type: string, format: uuid }
                  replay_of_id: { type: string, format: uuid }
                  status: { type: string, enum: [pending] }
        '404': { description: Not Found }

  /webhooks/dlq:
    get:
      operationId: listWebhookDlq
      summary: List dead-lettered deliveries
      tags: [Webhooks]
      parameters:
        - name: subscription_id
          in: query
          schema: { type: string, format: uuid }
        - name: only_unreplayed
          in: query
          schema: { type: boolean, default: true }
        - $ref: '#/components/parameters/cursor'
        - $ref: '#/components/parameters/limit'
      responses:
        '200':
          description: Paginated DLQ rows
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PaginatedResponse' }

  /webhooks/dlq/replay:
    post:
      operationId: replayWebhookDlqBatch
      summary: Batch replay deliveries from the dead-letter queue
      tags: [Webhooks]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [dlq_ids]
              properties:
                dlq_ids:
                  type: array
                  minItems: 1
                  maxItems: 100
                  items: { type: string, format: uuid }
              additionalProperties: false
      responses:
        '202':
          description: DLQ replay rows queued
          content:
            application/json:
              schema:
                type: object
                required: [results]
                properties:
                  results:
                    type: array
                    items:
                      type: object
                      required: [dlq_id, replay_delivery_id, status]
                      properties:
                        dlq_id: { type: string, format: uuid }
                        replay_delivery_id: { type: string, format: uuid, nullable: true }
                        status: { type: string, enum: [queued, not_found] }
        '400': { description: Validation error }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '503': { description: Webhook delivery worker is not reachable }

  /webhooks/events:
    get:
      operationId: listWebhookEventTypes
      summary: List supported webhook event types (public)
      tags: [Webhooks]
      security: []
      responses:
        '200':
          description: Catalog of event types
          content:
            application/json:
              schema:
                type: object
                required: [events]
                properties:
                  events:
                    type: array
                    items: { type: string }

  # ----- POR-55 — Billing / Stripe self-serve --------------------------------
  /webhooks/stripe:
    post:
      operationId: stripeWebhook
      summary: Stripe inbound webhook
      description: |
        Stripe HMAC-signed inbound webhook. Verifies `Stripe-Signature` header
        against `STRIPE_WEBHOOK_SECRET` over the raw request body. Idempotent
        on Stripe `event.id`. Resolves account via the SECURITY DEFINER
        `resolve_account_by_stripe_customer` function. Handles
        `customer.subscription.created/updated/deleted`, `invoice.paid`,
        `invoice.payment_failed`.
      tags: [Webhooks]
      security: []
      parameters:
        - name: Stripe-Signature
          in: header
          required: true
          schema: { type: string }
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, additionalProperties: true }
      responses:
        '200': { description: OK (event accepted or replay) }
        '400': { description: Invalid or missing signature }

  # ----- POR-734 — GHL two-way sync (plan 2026-07-02-002) --------------------
  /webhooks/ghl:
    post:
      operationId: ghlWebhook
      summary: GoHighLevel marketplace inbound webhook
      description: |
        GHL marketplace webhook, Ed25519-signed over the raw request body
        (`x-ghl-signature`, base64; keys from `GHL_WEBHOOK_PUBLIC_KEYS`,
        try-each — the header carries no key id). No timestamp-freshness
        rejection: `webhookId` dedupe is the replay defense (plan §8.1).
        Resolves the tenant exclusively via the SECURITY DEFINER
        `resolve_account_by_ghl_location` function, then journals the event
        transactionally with the dedupe receipt. Data events for unknown or
        inactive locations are accepted and dropped (a 4xx would make GHL
        retry forever); INSTALL events for unknown locations park a claimable
        pending-install record (plan §8.2).
      tags: [Webhooks]
      security: []
      parameters:
        - name: x-ghl-signature
          in: header
          required: true
          schema: { type: string }
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, additionalProperties: true }
      responses:
        '200': { description: OK (event accepted or replayed or dropped) }
        '401': { description: Invalid or missing signature }

  /webhooks/hubspot:
    post:
      operationId: hubspotWebhook
      summary: HubSpot CRM inbound webhook (v3 HMAC-SHA256 verified)
      description: |
        Receives batched HubSpot CRM webhook notifications (Contacts, Deals, Notes, Tasks).
        Resolves the target tenant and branch connection via `resolve_hubspot_connection_by_portal`,
        verifies the HubSpot v3 HMAC-SHA256 signature (`x-hubspot-signature-v3` +
        `x-hubspot-request-timestamp`, 5-minute replay window) against the connection's secret or
        global `HUBSPOT_CLIENT_SECRET`, dedupes via `hubspot_webhook_receipts`, journals into
        `sync_journal`, and enqueues `hubspot-webhook-process` Cloud Tasks.
      tags: [Webhooks]
      security: []
      parameters:
        - name: x-hubspot-signature-v3
          in: header
          required: true
          schema: { type: string }
        - name: x-hubspot-request-timestamp
          in: header
          required: true
          schema: { type: string }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: array
              items: { type: object, additionalProperties: true }
      responses:
        '200': { description: 'OK (batch accepted, deduped, or ignored for unbound portal)' }
        '400': { description: Malformed webhook payload }
        '401': { description: Invalid or expired HubSpot v3 signature }

  /billing/checkout-session:
    post:
      operationId: createBillingCheckoutSession
      summary: Create Stripe Checkout Session for tier subscription (Owner only)
      tags: [Billing]
      parameters:
        - name: Idempotency-Key
          in: header
          required: true
          schema: { type: string }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [tier]
              properties:
                tier: { type: string, enum: [closer, operator, marketplace] }
                seats: { type: integer, minimum: 1, maximum: 10000 }
              additionalProperties: false
      responses:
        '200':
          description: Checkout URL. The server persists the exact Stripe Session before returning this short-lived URL.
          content:
            application/json:
              schema:
                type: object
                required: [checkout_url, session_id]
                properties:
                  checkout_url: { type: string, format: uri, nullable: true }
                  session_id: { type: string }
        '401': { description: Unauthorized }
        '403': { description: Forbidden (owner_required) }
        '409':
          description: "Billing is not configured (billing_not_configured), the tier is not provisioned (tier_not_provisioned), an account subscription already exists, Checkout is in progress or awaiting reconciliation, or `processor_mismatch` for a company that pays Portrex through Square (W5)."
        '500': { description: Checkout Session could not be safely persisted; no Checkout URL is returned }
        '502': { description: Stripe error }
        '503': { description: Billing database unavailable }
  # ============================================================
  # POR-54 — Pricebook with first-class CEL rules (E22)
  # ============================================================
  /pricebook/rules:
    post:
      operationId: createPricebookRule
      summary: Author a new CEL pricing rule
      tags: [Pricebook]
      parameters:
        - { name: Idempotency-Key, in: header, required: true, schema: { type: string, maxLength: 64 } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [pricebook_item_id, name, cel_source]
              properties:
                pricebook_item_id: { type: string, format: uuid }
                name: { type: string, minLength: 1, maxLength: 200 }
                cel_source: { type: string, minLength: 1, maxLength: 8192 }
                priority: { type: integer, minimum: 0, maximum: 1000 }
                enabled: { type: boolean }
      responses:
        '201': { description: Rule created }
        '422':
          description: |
            CEL_PARSE_ERROR — `diagnostics: [{position, line, column, message, severity, code}]`.
            Codes include SYNTAX_ERROR, FORBIDDEN_IDENTIFIER, MONEY_TYPE_MISMATCH.

  /pricebook/rules/{id}:
    get:
      operationId: getPricebookRule
      summary: Fetch a rule with its pending dry-run (if any)
      tags: [Pricebook]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        '200': { description: Rule + pending dry-run preview }
        '404': { description: Not Found / cross-tenant }
    patch:
      operationId: updatePricebookRule
      summary: Edit a rule (cel_source bumps version)
      tags: [Pricebook]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string, format: uuid } }
        - { name: Idempotency-Key, in: header, required: true, schema: { type: string, maxLength: 64 } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                name: { type: string }
                cel_source: { type: string }
                priority: { type: integer }
                enabled: { type: boolean }
      responses:
        '200': { description: Updated }
        '404': { description: Not Found }
        '422': { description: CEL_PARSE_ERROR or MONEY_TYPE_MISMATCH }
        '423':
          description: |
            RULE_LOCKED — the rule is locked by an active Design.
            Body: `{error, locked_by_design_id, message}`.
    delete:
      operationId: softDeletePricebookRule
      summary: Soft-delete (enabled=false). 423 if locked.
      tags: [Pricebook]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        '200': { description: Soft-deleted }
        '423': { description: RULE_LOCKED }

  /pricebook/rules/{id}/dry-run:
    post:
      operationId: pricebookRuleDryRun
      summary: Preview a proposed cel_source against synthetic context (TTL 15 min)
      tags: [Pricebook]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string, format: uuid } }
        - { name: Idempotency-Key, in: header, required: true, schema: { type: string, maxLength: 64 } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [proposed_cel_source]
              properties:
                proposed_cel_source: { type: string, maxLength: 8192 }
      responses:
        '201':
          description: 'Dry-run stored; returns {id, diff:{before, after, total_diff_count}, expires_at}'
        '422': { description: CEL_PARSE_ERROR }
        '423': { description: RULE_LOCKED }

  /pricebook/rules/{id}/commit:
    post:
      operationId: pricebookRuleCommit
      summary: Apply a previously-stored dry-run
      tags: [Pricebook]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string, format: uuid } }
        - { name: Idempotency-Key, in: header, required: true, schema: { type: string, maxLength: 64 } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [dry_run_id]
              properties:
                dry_run_id: { type: string, format: uuid }
      responses:
        '200': { description: Committed; new version returned }
        '410': { description: DRY_RUN_EXPIRED — dry_run is older than 15 min or was already burned }
        '422': { description: idempotency_key_conflict }
        '423': { description: RULE_LOCKED }

  /pricebook/rules/{id}/versions:
    get:
      operationId: listPricebookRuleVersions
      summary: Append-only version history for a rule
      tags: [Pricebook]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        '200': { description: Version history (newest first) }

  /pricebook/generac:
    get:
      operationId: getGeneracPricebook
      summary: Read the company Generac pricebook and starting prices for missing entries
      description: Requires `pricebooks:read`. Returns retail prices only, with a revision for stale-save detection.
      tags: [Pricebook]
      responses:
        '200':
          description: All 23 Generac entries, their catalog item identities, and the current revision
          content:
            application/json:
              schema: { type: object }
        '401': { description: Not signed in }
        '403': { description: Missing pricebooks:read }
        '409': { description: A reserved Generac SKU has an incompatible industry or branch assignment }
        '503': { description: Pricebook database unavailable }
    put:
      operationId: saveGeneracPricebook
      summary: Save all company Generac entries atomically and link the showroom
      description: |
        Requires `pricebooks:write`; tenant users only. Requires WebAuthn or TOTP
        step-up within 900 seconds when step-up enforcement is enabled. The
        expected revision must match all current items. Preserves costs and
        unrelated metadata. Missing rows are created with showroom roles.
      tags: [Pricebook]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [expected_revision, entries]
              properties:
                expected_revision: { type: string, pattern: '^[a-f0-9]{64}$' }
                entries:
                  type: array
                  minItems: 23
                  maxItems: 23
                  items:
                    type: object
                    additionalProperties: false
                    required: [sku, name, retail_price_cents, online_booking_enabled]
                    properties:
                      sku: { type: string }
                      name: { type: string, minLength: 1, maxLength: 256 }
                      retail_price_cents: { type: integer, minimum: 0, maximum: 100000000 }
                      online_booking_enabled: { type: boolean }
      responses:
        '200':
          description: The saved retail pricebook and new revision
          content:
            application/json:
              schema: { type: object }
        '400': { description: Invalid or incomplete book }
        '401': { description: Not signed in }
        '403': { description: Missing pricebooks:write or fresh step-up }
        '409': { description: 'Stale revision, conflicting item assignment, or another book write in progress' }
        '503': { description: Pricebook database unavailable }

  /pricebook/water:
    get:
      operationId: getWaterPricebook
      summary: Read the company Water Filtration pricebook and starting prices for missing entries
      description: Requires `pricebooks:read`. Returns retail prices only, with a revision for stale-save detection.
      tags: [Pricebook]
      responses:
        '200':
          description: All 15 Water Filtration entries, their catalog item identities, and the current revision
          content:
            application/json:
              schema: { type: object }
        '401': { description: Not signed in }
        '403': { description: Missing pricebooks:read }
        '409': { description: A reserved Water Filtration SKU has an incompatible industry or branch assignment }
        '503': { description: Pricebook database unavailable }
    put:
      operationId: saveWaterPricebook
      summary: Save all company Water Filtration entries atomically and link the showroom
      description: |
        Requires `pricebooks:write`; tenant users only. Requires WebAuthn or TOTP
        step-up within 900 seconds when step-up enforcement is enabled. The
        expected revision must match all current items. Preserves costs and
        unrelated metadata. Missing rows are created with showroom roles.
      tags: [Pricebook]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [expected_revision, entries]
              properties:
                expected_revision: { type: string, pattern: '^[a-f0-9]{64}$' }
                entries:
                  type: array
                  minItems: 15
                  maxItems: 15
                  items:
                    type: object
                    additionalProperties: false
                    required: [sku, name, retail_price_cents, online_booking_enabled]
                    properties:
                      sku: { type: string }
                      name: { type: string, minLength: 1, maxLength: 256 }
                      retail_price_cents: { type: integer, minimum: 0, maximum: 100000000 }
                      online_booking_enabled: { type: boolean }
      responses:
        '200':
          description: The saved retail pricebook and new revision
          content:
            application/json:
              schema: { type: object }
        '400': { description: Invalid or incomplete book }
        '401': { description: Not signed in }
        '403': { description: Missing pricebooks:write or fresh step-up }
        '409': { description: 'Stale revision, conflicting item assignment, or another book write in progress' }
        '503': { description: Pricebook database unavailable }

  /pricebook/solar:
    get:
      operationId: getSolarPricebook
      summary: Read the company Solar pricebook and starting prices for missing entries
      description: Requires `pricebooks:read`. Returns retail prices only, with a revision for stale-save detection.
      tags: [Pricebook]
      responses:
        '200':
          description: All 20 Solar entries, their catalog item identities, and the current revision
          content:
            application/json:
              schema: { type: object }
        '401': { description: Not signed in }
        '403': { description: Missing pricebooks:read }
        '409': { description: A reserved Solar SKU has an incompatible industry or branch assignment }
        '503': { description: Pricebook database unavailable }
    put:
      operationId: saveSolarPricebook
      summary: Save all company Solar entries atomically and link the showroom
      description: |
        Requires `pricebooks:write`; tenant users only. Requires WebAuthn or TOTP
        step-up within 900 seconds when step-up enforcement is enabled. The
        expected revision must match all current items. Preserves costs and
        unrelated metadata. Missing rows are created with showroom roles.
      tags: [Pricebook]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [expected_revision, entries]
              properties:
                expected_revision: { type: string, pattern: '^[a-f0-9]{64}$' }
                entries:
                  type: array
                  minItems: 20
                  maxItems: 20
                  items:
                    type: object
                    additionalProperties: false
                    required: [sku, name, retail_price_cents, online_booking_enabled]
                    properties:
                      sku: { type: string }
                      name: { type: string, minLength: 1, maxLength: 256 }
                      retail_price_cents: { type: integer, minimum: 0, maximum: 100000000 }
                      online_booking_enabled: { type: boolean }
      responses:
        '200':
          description: The saved retail pricebook and new revision
          content:
            application/json:
              schema: { type: object }
        '400': { description: Invalid or incomplete book }
        '401': { description: Not signed in }
        '403': { description: Missing pricebooks:write or fresh step-up }
        '409': { description: 'Stale revision, conflicting item assignment, or another book write in progress' }
        '503': { description: Pricebook database unavailable }

  /cel/parse:
    post:
      operationId: celParse
      summary: Compile CEL source for Monaco LSP (stateless; rate-limited)
      description: |
        Stateless parser — no DB write. Returns `{ok, ast, diagnostics}`.
        Token-bucket rate limit: 10 req/s per principal; 11th request → 429.
      tags: [Pricebook]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [source]
              properties:
                source: { type: string, maxLength: 8192 }
              additionalProperties: false
      responses:
        '200':
          description: Parse result
          content:
            application/json:
              schema:
                type: object
                required: [ok, ast, diagnostics]
                properties:
                  ok: { type: boolean }
                  ast: { nullable: true }
                  diagnostics:
                    type: array
                    items:
                      type: object
                      required: [position, endPosition, line, column, message, severity, code]
                      properties:
                        position: { type: integer, minimum: 0 }
                        endPosition: { type: integer, minimum: 0 }
                        line: { type: integer, minimum: 1 }
                        column: { type: integer, minimum: 1 }
                        message: { type: string }
                        severity: { type: string, enum: [error, warning, info] }
                        code: { type: string }
        '401': { description: Unauthorized }
        '429': { description: Rate limited; retry after 1 second }

  /customer-portal-invitations:
    post:
      operationId: createCustomerPortalInvitation
      summary: Mint a customer portal magic-link invitation for a tenant-scoped customer person
      description: |
        Owner/admin tenant surface for B5a. The request takes only a
        tenant-scoped `customer_person_id`; it never performs cross-tenant
        homeowner email lookup. Any person UUID not visible to the caller's
        account returns the same 404 envelope.
      tags: [Portal]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [customer_person_id]
              additionalProperties: false
              properties:
                customer_person_id: { type: string, format: uuid }
                expires_at:
                  type: string
                  format: date-time
                  description: Optional outer expiry, capped at 24 hours and must be at least 60 seconds in the future.
      responses:
        '201':
          description: Invitation minted; raw accept URL returned once.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CustomerPortalInvitationResponse' }
        '400': { description: 'Invalid request, including unsupported expiry.' }
        '401': { description: 'Unauthorized.' }
        '403': { description: 'Missing `customer_portal:manage`.' }
        '404': { description: 'Customer person is not visible to this tenant.' }
        '503': { description: 'DB unavailable.' }

  /billing/customer-portal:
    post:
      operationId: createBillingCustomerPortal
      summary: Create Stripe Customer Portal session (Owner only)
      tags: [Billing]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                intent:
                  type: string
                  enum: [change_card, change_seats]
                  description: '"Change card" opens the Stripe portal flow `payment_method_update`; "Change seats" the flow `subscription_update` of the subscription. Absent: the portal home. When Stripe refuses the flow, the portal home opens in the same request.'
      responses:
        '200':
          description: Portal URL
          content:
            application/json:
              schema:
                type: object
                required: [portal_url, flow]
                properties:
                  portal_url: { type: string, format: uri }
                  flow:
                    type: string
                    nullable: true
                    enum: [payment_method_update, subscription_update]
                    description: The Stripe portal flow the session opens; null for the portal home (no intent, or Stripe refused the flow).
        '400': { description: 'Missing or invalid Idempotency-Key; `invalid_body` for an unknown intent' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden (owner_required) }
        '409': { description: 'Billing is not configured (billing_not_configured) or the account has no Stripe customer yet; `processor_mismatch` for a company that pays Portrex through Square (W5)' }
        '502': { description: Stripe error }
        '503': { description: Billing surface unavailable }

  /billing/subscription:
    get:
      operationId: getBillingSubscription
      summary: Current account subscription + seat counts
      tags: [Billing]
      responses:
        '200':
          description: Subscription
          content:
            application/json:
              schema:
                type: object
                required: [subscription, payment_setup]
                properties:
                  payment_setup:
                    type: object
                    required: [provider, checkout_tiers]
                    description: Provider setup prerequisites; the Billing surface stays visible regardless of this state.
                    properties:
                      provider: { type: string, enum: [configured, not_configured] }
                      checkout_tiers:
                        type: array
                        items: { type: string, enum: [closer, operator, marketplace] }
                  subscription:
                    nullable: true
                    type: object
                    required: [tier, status, seats_purchased, seats_used]
                    properties:
                      tier: { type: string, enum: [closer, operator, marketplace] }
                      status:
                        type: string
                        enum: [trialing, active, past_due, canceled, suspended]
                      current_period_end: { type: string, format: date-time, nullable: true }
                      seats_purchased: { type: integer }
                      seats_used: { type: integer }
                      past_due_since: { type: string, format: date-time, nullable: true }
                      suspended_at: { type: string, format: date-time, nullable: true }
                    description: Null with no subscription, and for a Square row whose term has not started (the status `incomplete` never leaves the API).
                  processor:
                    type: string
                    enum: [stripe, square]
                    description: 'W5 (plan 2026-11-19-002 § 17.2.5): who collects the company''s Portrex subscription.'
                  plan:
                    type: object
                    nullable: true
                    additionalProperties: false
                    required: [seats, billing_cycle, amount_cents, currency, lines]
                    description: 'The plan the next charge uses. Two lines: the seats, then the card processing fee. No tax line. Square: always. Stripe: the prices of the live Stripe subscription, read from Stripe; absent when Stripe did not answer in time.'
                    properties:
                      seats: { type: integer, minimum: 1, maximum: 10000 }
                      billing_cycle: { type: string, enum: [monthly, yearly] }
                      amount_cents: { type: integer, minimum: 1, description: The amount of one period. }
                      currency: { type: string, pattern: '^[a-z]{3}$' }
                      lines:
                        type: array
                        minItems: 1
                        items:
                          type: object
                          additionalProperties: false
                          required: [kind, label, amount_cents]
                          properties:
                            kind: { type: string, enum: [seats, card_processing_fee] }
                            label: { type: string }
                            amount_cents: { type: integer, minimum: 0 }
                      custom_seat_price_dollars: { type: integer, minimum: 0, nullable: true, description: 'W7: the custom seat price of the approval, whole dollars a seat a month; null = the price table.' }
                  seat_change:
                    allOf: [{ $ref: '#/components/schemas/PlatformSeatChange' }]
                    nullable: true
                    description: 'W7 (Square): the seat count that starts at the next period; null when none waits.'
                  seat_change_starts_on:
                    type: string
                    nullable: true
                    pattern: '^[0-9]{4}-[0-9]{2}-[0-9]{2}$'
                    description: 'W7 (Square): the calendar day (the account''s time zone) that a seat change made now starts; the consent text of a higher amount names it. Null when the seats cannot change now.'
                  seat_change_blocked:
                    type: string
                    enum: [stripe_multiple_products]
                    description: 'Stripe: why `can_change_seats` is false for the owner of a live subscription. `stripe_multiple_products`: the subscription has more than one product, and the Stripe portal cannot update it. Absent otherwise, also when Stripe did not answer in time.'
                  card:
                    type: object
                    nullable: true
                    additionalProperties: false
                    description: 'The card on file: brand, last 4 and expiry only. Square: the card on the row. Stripe: the default card at Stripe; absent when Stripe did not answer in time.'
                    required: [brand, last4, exp_month, exp_year]
                    properties:
                      brand: { type: string }
                      last4: { type: string, pattern: '^[0-9]{4}$' }
                      exp_month: { type: integer, minimum: 1, maximum: 12 }
                      exp_year: { type: integer, minimum: 2000, maximum: 2100 }
                  next_charge_at: { type: string, format: date-time, nullable: true }
                  trial_ends_at: { type: string, format: date-time, nullable: true }
                  cancel_at_period_end: { type: boolean }
                  open_attempt: { type: string, enum: [none, in_progress] }
                  actions:
                    type: object
                    additionalProperties: false
                    required: [can_checkout, can_open_portal, can_subscribe, can_change_card, can_pay, can_cancel]
                    description: What the caller may do now; every value is false for a role that is not the owner. `can_checkout` and `can_open_portal` are false for a Square company.
                    properties:
                      can_checkout: { type: boolean }
                      can_open_portal: { type: boolean }
                      can_subscribe: { type: boolean }
                      can_change_card: { type: boolean }
                      can_pay: { type: boolean }
                      can_cancel: { type: boolean }
                      cancel_ends_now: { type: boolean, description: 'Square: a cancel ends the subscription now, not at the period end (a failed or unpaid state, or an open invoice). Always false for a Stripe company.' }
                      can_resume: { type: boolean, description: 'W7: "Keep subscription" (`POST /v1/billing/resume`), on both processors: a live subscription that is set to end and whose paid period has not ended.' }
                      can_change_seats: { type: boolean, description: 'W7: "Change seats". Square: `PUT /v1/billing/plan` (active or trialing, not set to end, no open invoice, no open attempt). Stripe: the Stripe portal.' }
                  not_ready_reason:
                    allOf: [{ $ref: '#/components/schemas/PlatformSellerNotReadyReason' }]
                    nullable: true
                  card_setup:
                    allOf: [{ $ref: '#/components/schemas/CardSetupState' }]
                    description: The block of the card page `/billing/card?for=platform` (seller name "Portrex"). Present only for a Square company whose seller is ready; never for a demo account or the house account.
                  card_step_up_fresh:
                    type: boolean
                    description: True when a call of the three card routes now would pass their 900 s step-up gate (the server does not enforce step-up, or the caller's last step-up is at most 900 s old). When false, the page asks the owner to re-authenticate before it opens the card page.

  /billing/invoices:
    get:
      operationId: listBillingInvoices
      summary: List account invoices (cursor-paginated)
      tags: [Billing]
      parameters:
        - name: limit
          in: query
          schema: { type: integer, minimum: 1, maximum: 100, default: 25 }
        - name: cursor
          in: query
          schema: { type: string }
      responses:
        '200':
          description: Page
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: array
                    description: 'W5: the Stripe mirror rows and the Square period invoices of the platform payer, one list by date.'
                    items:
                      type: object
                      required: [stripe_invoice_id, amount_cents, currency, status, created_at]
                      properties:
                        id: { type: string, format: uuid, description: 'W5: the Portrex id of the row; use it as the list key.' }
                        processor: { type: string, enum: [stripe, square] }
                        stripe_invoice_id: { type: string, nullable: true, description: Null for a Square period invoice. }
                        receipt_url: { type: string, format: uri, nullable: true, description: Square's receipt of the paid payment; null for a Stripe row and an unpaid Square row. }
                        amount_cents: { type: integer }
                        currency: { type: string }
                        status: { type: string, enum: [draft, open, paid, void, uncollectible] }
                        hosted_url: { type: string, nullable: true }
                        period_start: { type: string, format: date-time, nullable: true }
                        period_end: { type: string, format: date-time, nullable: true }
                        created_at: { type: string, format: date-time }
                  next_cursor: { type: string, nullable: true }

  /billing/subscribe:
    post:
      operationId: subscribePlatformBillingOnSquare
      summary: Save the company's card on Square and start its Portrex subscription (Owner only)
      description: |
        Square only (plan 2026-11-19-002 § 17.2.3, § 17.2.5). Saves the card
        with Portrex's own Square account on the company's platform row, then
        starts the term: a trial, or the first invoice opens and the answer is
        `payment_required` (the page runs the bank check and calls
        `/v1/billing/pay`). The seats and the cycle are the confirmed plan; the
        body has no seats. Requires `billing:manage`, the owner role and a
        900 s step-up. Refused for an impersonating staff member and for
        service accounts. No answer carries a token or Square's `detail` text.
      tags: [Billing]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/CardSaveRequest' }
      responses:
        '200':
          description: The card is saved (`trialing` or `payment_required`, or `payment_pending` when an attempt is open)
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardSaveResult' }
        '400': { description: 'Invalid body, or a missing Idempotency-Key' }
        '401': { description: 'Unauthorized, or `step-up-required`' }
        '403':
          description: '`owner_required`, `impersonation_forbidden` or `service_role_forbidden`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardRouteError' }
        '409':
          description: '`processor_mismatch`, `onboarding_not_complete`, `already_subscribed`, `not_ready` (with a `PlatformSellerNotReadyReason`), `consent_version_mismatch`, `demo_account` or `house_account`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardRouteError' }
        '422':
          description: '`card_refused`: Square refused the card; nothing is stored'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardRouteError' }
        '503': { description: 'Database or Square unavailable' }

  /billing/payment-method:
    put:
      operationId: replacePlatformBillingCardOnSquare
      summary: Replace the card on file of the company's Portrex subscription on Square (Owner only)
      description: |
        Square only (plan 2026-11-19-002 § 17.2.5). Saves a new card for the
        same Square customer and makes no charge. The old card stays enabled
        while an open attempt names it. With an open invoice and no open
        attempt the answer is `payment_required`. Requires `billing:manage`,
        the owner role and a 900 s step-up. Refused for an impersonating staff
        member and for service accounts.
      tags: [Billing]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/CardSaveRequest' }
      responses:
        '200':
          description: 'The card is replaced (`saved`, `payment_required` or `payment_pending`)'
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardSaveResult' }
        '400': { description: 'Invalid body, or a missing Idempotency-Key' }
        '401': { description: 'Unauthorized, or `step-up-required`' }
        '403':
          description: '`owner_required`, `impersonation_forbidden` or `service_role_forbidden`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardRouteError' }
        '409':
          description: '`processor_mismatch`, `no_subscription`, `not_ready`, `consent_version_mismatch`, `demo_account` or `house_account`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardRouteError' }
        '422':
          description: '`card_refused`: Square refused the card; nothing is stored'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardRouteError' }
        '503': { description: 'Database or Square unavailable' }

  /billing/pay:
    post:
      operationId: payPlatformBillingInvoiceOnSquare
      summary: Pay the company's open Portrex invoice with the payer present (Owner only)
      description: |
        Square only (plan 2026-11-19-002 § 3.5, § 17.2.5). Charges exactly the
        balance of the open invoice with the stored card and the token of the
        bank check that the page ran for that amount, at Portrex's own Square
        location. A different amount or currency answers `409 amount_changed`;
        a token that was used, or that Square refuses, answers `422
        verify_again`. No answer from Square answers `202 payment_pending`.
        Requires `billing:manage`, the owner role and a 900 s step-up. Refused
        for an impersonating staff member and for service accounts.
      tags: [Billing]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/CardPayRequest' }
      responses:
        '200':
          description: Paid
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardPayResult' }
        '202':
          description: '`payment_pending`: no final answer from Square yet; read `GET /v1/billing/subscription` until the attempt is finished'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardPayResult' }
        '400': { description: 'Invalid body, or a missing Idempotency-Key' }
        '401': { description: 'Unauthorized, or `step-up-required`' }
        '403':
          description: '`owner_required`, `impersonation_forbidden` or `service_role_forbidden`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardRouteError' }
        '409':
          description: '`processor_mismatch`, `amount_changed`, `charge_in_progress`, `no_open_invoice`, `not_ready`, `demo_account` or `house_account`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardRouteError' }
        '422':
          description: '`card_declined`, or `verify_again`: run the bank check again'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardRouteError' }
        '503': { description: 'Database or Square unavailable' }

  /billing/cancel:
    post:
      operationId: cancelPlatformBillingOnSquare
      summary: Cancel the company's Portrex subscription (Owner only)
      description: |
        Both processors (plan 2026-11-19-002 § 17.2.5, § 17.9; Stripe from
        W7). Square: an active or trialing subscription whose paid period
        runs gets a local stamp: it ends at the end of the period (or of the
        trial) with no charge, and no Square call is made. A failed or unpaid
        state (`past_due`, `suspended`), or an open invoice, ends NOW
        (`ended: now`): the open invoice is void and the card is disabled
        after the commit. Stripe: an active or trialing subscription is set
        to end at the period end at Stripe (`cancel_at_period_end`); a failed
        payment (`past_due`, or `suspended` = Stripe `unpaid` or `paused`)
        ends NOW at Stripe (`subscriptions.cancel`). A second call changes
        nothing (`changed: false`) and makes no provider call. Requires
        `billing:manage`, the owner role and a 900 s step-up. Refused for an
        impersonating staff member and for service accounts.
      tags: [Billing]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: false
        content:
          application/json:
            schema: { type: object, additionalProperties: false }
      responses:
        '200':
          description: The subscription is set to end, or ended now
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PlatformBillingCancelResult' }
        '400': { description: 'Invalid body, or a missing Idempotency-Key' }
        '401': { description: 'Unauthorized, or `step-up-required`' }
        '403':
          description: '`owner_required`, `impersonation_forbidden` or `service_role_forbidden`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardRouteError' }
        '409':
          description: '`no_subscription`, `charge_in_progress` (Square: an attempt is open; nothing changed), or `not_ready` with the reason `stripe_not_configured`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardRouteError' }
        '502': { description: '`stripe_error`: Stripe refused or did not answer; nothing changed in Portrex' }
        '503': { description: Database unavailable }

  /billing/resume:
    post:
      operationId: resumePlatformBilling
      summary: Keep the company's Portrex subscription — undo a cancel before the period end (Owner only)
      description: |
        "Keep subscription" (plan 2026-11-19-002 § 5.6, § 7.4; W7), both
        processors. Allowed only for a live (active or trialing)
        subscription that is set to end and whose paid period has not ended.
        Square: the stamp is cleared under the payer lock of the cancel, with
        no Square call; `409 charge_in_progress` while an attempt is open.
        Stripe: `cancel_at_period_end` is cleared at Stripe with an
        idempotency key of the request, and a fixed `cancel_at` too (a second
        update with its own key); `502 stripe_error` while Stripe still ends
        the subscription. A subscription that is not set to
        end answers `changed: false` with no provider call. Requires
        `billing:manage`, the owner role and a 900 s step-up (the row of the
        cancel). Refused for an impersonating staff member and for service
        accounts. One audit event `billing.subscription.resumed` for a change.
      tags: [Billing]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: false
        content:
          application/json:
            schema: { type: object, additionalProperties: false }
      responses:
        '200':
          description: The subscription is no longer set to end
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PlatformBillingResumeResult' }
        '400': { description: 'Invalid body, or a missing Idempotency-Key' }
        '401': { description: 'Unauthorized, or `step-up-required`' }
        '403':
          description: '`owner_required`, `impersonation_forbidden` or `service_role_forbidden`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardRouteError' }
        '409':
          description: '`no_subscription` (nothing to keep: not live, or the paid period has ended), `charge_in_progress` (Square: an attempt is open; nothing changed), or `not_ready` with the reason `stripe_not_configured`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardRouteError' }
        '502': { description: '`stripe_error`: Stripe refused, did not answer, or still ends the subscription; nothing changed in Portrex' }
        '503': { description: Database unavailable }

  /billing/plan:
    put:
      operationId: changePlatformBillingSeats
      summary: Set the seat count of the next period of the company's Portrex subscription (Owner only)
      description: |
        Square only (plan 2026-11-19-002 § 7.4, W7; the default of OD-16:
        "at the next period only"). The new count waits in `pending_seats`
        and starts at the next period: the next period invoice has its
        amount, and the row takes the count when that invoice opens. No
        charge now, no proration. The current count clears a waiting change.
        Allowed for an active or trialing subscription that is not set to
        end, with no open invoice and no open attempt. A count whose amount
        is higher than today needs a new consent for the card on file: the
        body carries `consent`, `consent_version`
        (`platform-seat-change-consent-draft-2026-11-20`), and the
        `amount_cents` and `interval` that the confirm step showed. Another
        amount or interval answers `409 amount_changed`, another version
        `409 consent_version_mismatch`; nothing is written then. A row with
        no card answers `409 not_ready` with the reason
        `payment_method_required`. The consent and the pending seats are
        written in one transaction, with the audit event
        `billing.card.consent_recorded` (amount, interval, start day, seats,
        version; no card data). A lower or equal amount needs no new consent.
        Requires `billing:manage`, the owner role and a 900 s step-up.
        Refused for an impersonating staff member and for service accounts.
        One audit event `billing.plan.changed` for a change.
      tags: [Billing]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [seats]
              properties:
                seats: { type: integer, minimum: 1, maximum: 10000 }
                consent: { type: boolean, enum: [true], description: 'A higher amount only: the owner checked the consent of the confirm step.' }
                consent_version: { type: string, pattern: '^[a-z0-9][a-z0-9-]{0,99}$' }
                amount_cents: { type: integer, minimum: 1, description: The amount of one period that the consent named. }
                interval: { type: string, enum: [month, year], description: The interval that the consent named. }
      responses:
        '200':
          description: The seat count of the next period
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PlatformBillingPlanResult' }
        '400': { description: 'Invalid body, or a missing Idempotency-Key' }
        '401': { description: 'Unauthorized, or `step-up-required`' }
        '403':
          description: '`owner_required`, `impersonation_forbidden` or `service_role_forbidden`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardRouteError' }
        '409':
          description: '`processor_mismatch` (a Stripe company changes seats in the Stripe portal), `no_subscription`, `charge_in_progress`, `billing_price_invalid`, `amount_changed`, `consent_version_mismatch`, `demo_account`, `house_account`, or `not_ready` with the reason `set_to_end`, `renewal_due` or `payment_method_required`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardRouteError' }
        '503': { description: Database unavailable }

  /onboarding/pay:
    post:
      operationId: payOnboardingFirstInvoiceOnSquare
      summary: Pay the first Portrex invoice in the onboarding wizard (Owner only)
      description: |
        Square only (plan 2026-11-19-002 § 17.2.5). The payer-present first
        charge of a company with no trial, after `POST /v1/onboarding/complete`
        answered `payment_required`. The rules of `POST /v1/billing/pay`
        apply: the exact amount, one token one time, a refused token is final,
        no `detail` text. Requires `onboarding:write` and the owner role; a
        provisional session may call it, and it has no step-up (the owner in
        the wizard often has no second factor yet). Refused for an
        impersonating staff member and for service accounts.
      tags: [Onboarding]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/CardPayRequest' }
      responses:
        '200':
          description: Paid
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardPayResult' }
        '202':
          description: '`payment_pending`: no final answer from Square yet; read `GET /v1/onboarding/wizard` until `payment.firstCharge` is final'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardPayResult' }
        '400': { description: 'Invalid body, or a missing Idempotency-Key' }
        '401': { description: Unauthorized }
        '403':
          description: '`owner_required`, `impersonation_forbidden` or `service_role_forbidden`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardRouteError' }
        '409':
          description: '`processor_mismatch`, `amount_changed`, `charge_in_progress`, `no_open_invoice`, `not_ready`, `demo_account` or `house_account`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardRouteError' }
        '422':
          description: '`card_declined`, or `verify_again`: run the bank check again'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardRouteError' }
        '503': { description: 'Database or Square unavailable' }

  /billing/banner-state:
    get:
      operationId: getBillingBannerState
      summary: Past-due / suspended banner state (used site-wide)
      tags: [Billing]
      responses:
        '200':
          description: Banner state
          content:
            application/json:
              schema: { $ref: '#/components/schemas/BillingBannerState' }
        '401': { description: Unauthorized }
        '503': { description: DB unavailable in production }

  # ============================================================
  # Phase B1 / B2 / B5 — session hydration endpoints (LD-10).
  # The web app hits these on every page load to populate auth state.
  # ============================================================
  /auth/me:
    get:
      operationId: getAuthMe
      summary: Hydrate the current Tenant User / Integration User session
      description: |
        Returns the canonical principal info for a `tenant_user` (or
        `integration_user`) session cookie. 401 when no active session.
        Single SELECT join — kept under 200ms p95 because the web app
        reads this on every page load.
      tags: [Auth]
      parameters:
        - $ref: '#/components/parameters/activeSubAccountId'
      responses:
        '200':
          description: Hydrated session
          content:
            application/json:
              schema:
                type: object
                required: [kind, userId, accountId, email, fullName, role, teamIds, accountName]
                properties:
                  kind: { type: string, enum: [tenant_user] }
                  userId: { type: string, format: uuid }
                  accountId: { type: string, format: uuid }
                  email: { type: string, format: email }
                  fullName: { type: string }
                  role: { type: string, enum: [owner, admin, sub_account_admin, sales_manager, sales_rep, account_manager, project_manager, architect, general_contractor, field_rep, cfo, site_surveyor, service_role, custom] }
                  customRoleName: { type: string, nullable: true, description: The account-defined display name when role is 'custom'; null otherwise. }
                  teamIds:
                    type: array
                    items: { type: string, format: uuid }
                  accountName: { type: string }
                  lastSignedInAt: { type: string, format: date-time, nullable: true }
                  isDemo: { type: boolean, description: True when this account is a demo/sandbox account. }
        '401':
          description: Unauthorized — no active session.
          content:
            application/json:
              schema:
                type: object
                required: [error]
                properties:
                  error: { type: string, enum: [unauthorized] }

  /staff/accounts/{id}/billing-policy:
    get:
      operationId: getStaffAccountBillingPolicy
      summary: Read a tenant's per-user billing policy and Stripe connections
      description: |
        Staff console read for one tenant: the policy Portrex staff control, the
        tenant's company-vs-branch billing choice, its connected Stripe accounts
        (ids masked), and a rollup of where its members stand — computed with the
        same decision function the enforcement layer uses. Also the company,
        branch and dues dates the tenant set (`tenant_deadlines`) and the number
        of people the engine locks now (`locked_now`). The house account answers
        404. Requires
        `staff:accounts:read`; the underlying function
        re-checks the staff role and the account's visibility to this operator.
      tags: [Staff]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        '200':
          description: Policy, connections, and member rollup
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/StaffAccountBilling' }
        '400': { description: Invalid account id }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Account not found }
        '503': { description: Database unavailable }
    put:
      operationId: setStaffAccountBillingPolicy
      summary: Set a tenant's per-user billing policy (platform admin)
      description: |
        Patch semantics — only the keys sent are changed. Sets the enforcement mode, price,
        currency, trial length, enforcement deadline, grace period and any exempt
        roles. Requires `staff:accounts:write`; the
        function additionally restricts the write to platform admins, requires a
        reason of at least 8 characters, and records both audit trails in the same
        transaction as the policy row. A change that locks one or more people at
        once (any field) is rolled back and answered 409
        `immediate_lock_not_confirmed` with the count, until it is sent again with
        `confirm_immediate_lock: true` and `confirmed_lock_count`.
      tags: [Staff]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string, format: uuid } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/StaffAccountBillingPolicyInput' }
      responses:
        '200':
          description: Updated policy
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/AccountBillingPolicy' }
        '400': { description: Invalid account id or policy }
        '401': { description: Unauthorized }
        '403': { description: Platform admin required }
        '404': { description: Account not found }
        '409':
          description: The change locks people at once and was not confirmed
          content:
            application/json:
              schema: { $ref: '#/components/schemas/StaffImmediateLockError' }
        '503': { description: Database unavailable }

  /staff/accounts/{id}/billing-deadlines/clear:
    post:
      operationId: clearStaffAccountBillingDeadline
      summary: Clear a date that the tenant set (platform admin)
      description: |
        Removes the company date, a branch date or a dues date of the tenant.
        Platform admin only, with a reason of 8 to 500 characters, a fresh
        step-up (5 minutes) and an Idempotency-Key. Requires
        `staff:accounts:write`. A clear that locks one or more people at once
        is rolled back and answered 409 `immediate_lock_not_confirmed` with the
        count, until it is sent again with `confirm_immediate_lock: true` and
        `confirmed_lock_count`. The function writes both audit trails. The house
        account answers 404.
      tags: [Staff]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string, format: uuid } }
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/StaffClearBillingDeadlineInput' }
      responses:
        '200':
          description: The date is cleared (or there was none)
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/StaffClearBillingDeadlineResult' }
        '400': { description: 'Invalid account id, body, or a missing Idempotency-Key' }
        '401': { description: Unauthorized }
        '403': { description: 'Platform admin required, or a fresh step-up required' }
        '404': { description: Account not found }
        '409':
          description: The clear locks people at once and was not confirmed
          content:
            application/json:
              schema: { $ref: '#/components/schemas/StaffImmediateLockError' }
        '503': { description: Database unavailable }

  /staff/billing/findings:
    get:
      operationId: listStaffBillingFindings
      summary: The billing findings across the accounts the staff user can see
      description: |
        One list of the billing problems a person must see (plan
        2026-11-19-002 § 5.10, § 7.6): one row for one attempt, also when the
        attempt has two findings. Open findings by default. Requires
        `staff:accounts:read`; the list keeps to the accounts the caller can
        see. No token, no provider text.
      tags: [Staff]
      parameters:
        - { name: state, in: query, required: false, schema: { type: string, enum: [open, resolved] } }
        - { name: cursor, in: query, required: false, schema: { type: string, maxLength: 500 } }
        - { name: limit, in: query, required: false, schema: { type: integer, minimum: 1, maximum: 200 } }
      responses:
        '200':
          description: One page of findings
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema:
                type: object
                additionalProperties: false
                required: [data, next_cursor]
                properties:
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/StaffBillingFindingRow' }
                  next_cursor: { type: string, nullable: true }
        '400': { description: Invalid query }
        '401': { description: Unauthorized }
        '403': { description: Missing staff scope }
        '503': { description: Database unavailable }

  /staff/billing/findings/{findingId}/resolve:
    post:
      operationId: resolveStaffBillingFinding
      summary: Settle the attempt of a billing finding (platform admin)
      description: |
        For an attempt, reads Square first: a payment is applied; no payment
        sets the attempt `failed`. When Square cannot be read, staff set the
        result only with the tenant's written statement in the reason
        (`result_without_square_read`), and the finding gets
        `set_without_square_read`. The two findings of one attempt close
        together. Platform admin only, with a reason of 8 to 500 characters, a
        fresh step-up (5 minutes) and an Idempotency-Key. Requires
        `staff:accounts:write`. The account comes from the finding row, never
        from the body; the house account answers 404. Two audit rows. A finding
        with no account, and a `seller_unavailable`, `payment_disputed` or
        `platform_subscription_unpaid` finding, closes as `closed` with the
        reason and no Square call. A platform payer's attempt is read with
        Portrex's own Square account.
      tags: [Staff]
      parameters:
        - { name: findingId, in: path, required: true, schema: { type: string, format: uuid } }
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/StaffBillingFindingResolveInput' }
      responses:
        '200':
          description: The findings are resolved
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/StaffBillingFindingResolveResult' }
        '400': { description: 'Invalid finding id, body, or a missing Idempotency-Key' }
        '401': { description: Unauthorized }
        '403': { description: 'Platform admin required, or a fresh step-up required' }
        '404':
          description: '`finding_not_found` or `account_not_found`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/StaffBillingFindingError' }
        '409':
          description: '`finding_resolved`, `square_unreadable` (send `result_without_square_read`) or `payment_not_final`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/StaffBillingFindingError' }
        '503': { description: 'Database or Square unavailable' }

  /staff/billing/findings/{findingId}/refund:
    post:
      operationId: refundStaffBillingFinding
      summary: Refund the payment of a billing finding that Portrex took by error (platform admin)
      description: |
        Refunds, on the tenant's Square seller (or on Portrex's own Square
        account for a platform payer's finding and for a finding with no
        account; only a payment at Portrex's location, and never a payment
        that Portrex took for a company), the payment of a
        `payment_without_attempt` finding, or of a `state_mismatch` finding
        whose payment paid no invoice (plan 2026-11-19-002 § 5.10, § 7.6). The
        payment is read again first; its note and location must match. Staff
        type no amount: the amount is what remains at Square, and the refund
        key is the finding id, so a second call replays. Platform admin only,
        with a reason, a fresh step-up (5 minutes) and an Idempotency-Key.
        Requires `staff:accounts:write`. Two audit rows.
      tags: [Staff]
      parameters:
        - { name: findingId, in: path, required: true, schema: { type: string, format: uuid } }
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/StaffBillingFindingRefundInput' }
      responses:
        '200':
          description: The refund Square made (a refund is `PENDING` first)
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/StaffBillingFindingRefundResult' }
        '400': { description: 'Invalid finding id, body, or a missing Idempotency-Key' }
        '401': { description: Unauthorized }
        '403': { description: 'Platform admin required, or a fresh step-up required' }
        '404':
          description: '`finding_not_found` or `account_not_found`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/StaffBillingFindingError' }
        '409':
          description: '`finding_resolved`, `refund_not_allowed`, `payment_mismatch`, `nothing_to_refund`, `refund_amount_invalid` or `square_unreadable`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/StaffBillingFindingError' }
        '503': { description: 'Database or Square unavailable' }

  /staff/platform/billing-processor:
    get:
      operationId: getStaffPlatformBillingProcessor
      summary: The processor of new company subscriptions, and whether each processor is configured
      description: |
        The platform default (plan 2026-11-19-002 § 4.2): the processor that a
        new signup approval starts with. Stripe is configured when the platform
        Stripe key is present; Square when Portrex's own Square account is
        ready. Requires `staff:financials:read`. No credential value.
      tags: [Staff]
      responses:
        '200':
          description: The default and the two processors
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/StaffPlatformBillingProcessor' }
        '401': { description: Unauthorized }
        '403': { description: Missing staff scope }
        '503': { description: Database unavailable }
    put:
      operationId: setStaffPlatformBillingProcessor
      summary: Set the processor of new company subscriptions (platform admin)
      description: |
        Only a configured processor can be selected. It changes no existing
        company. Platform admin only, with a reason of 8 to 500 characters, a
        fresh step-up (5 minutes) and an Idempotency-Key. Requires
        `staff:accounts:write`. A staff audit row and a staff activity event; the
        same processor again writes nothing.
      tags: [Staff]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/StaffPlatformBillingProcessorInput' }
      responses:
        '200':
          description: The default now
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/StaffPlatformBillingProcessor' }
        '400': { description: 'Invalid body, or a missing Idempotency-Key' }
        '401': { description: Unauthorized }
        '403': { description: 'Platform admin required, or a fresh step-up required' }
        '409':
          description: '`processor_not_configured`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/StaffPlatformBillingError' }
        '503': { description: Database unavailable }

  /staff/accounts/{id}/platform-billing-processor:
    put:
      operationId: setStaffAccountPlatformBillingProcessor
      summary: Change the processor through which one company pays Portrex (platform admin)
      description: |
        Refused while the company has a subscription on either processor that
        is live or waits for its first payment (plan 2026-11-19-002 § 7.6).
        Only a configured processor; for Square, the terms rules of the
        approval (card only, agreement standard-v2, a seat price above $0). The
        house account answers 404. Platform admin only, with a reason of 8 to
        500 characters, a fresh step-up (5 minutes) and an Idempotency-Key.
        Requires `staff:accounts:write`. A staff audit row and two account
        events; the same processor again writes nothing.
      tags: [Staff]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string, format: uuid } }
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/StaffPlatformBillingProcessorInput' }
      responses:
        '200':
          description: The processor of the company now
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/StaffAccountPlatformBillingProcessorResult' }
        '400': { description: 'Invalid account id, body, or a missing Idempotency-Key' }
        '401': { description: Unauthorized }
        '403': { description: 'Platform admin required, or a fresh step-up required' }
        '404':
          description: '`account_not_found` (also the house account)'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/StaffPlatformBillingError' }
        '409':
          description: '`subscription_exists`, `checkout_in_progress`, `onboarding_state_missing` or `processor_not_configured`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/StaffPlatformBillingError' }
        '422':
          description: '`processor_terms_not_allowed` with `problems`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/StaffPlatformBillingError' }
        '503': { description: Database unavailable }

  /staff/accounts/{id}/user-subscriptions:
    get:
      operationId: listStaffAccountUserSubscriptions
      summary: Per-member subscription rows for one tenant
      description: |
        One row for each member of the shared member set (active memberships, no
        service user, one row for each user), including members who have never
        subscribed, with the billing state the enforcement layer would compute,
        the effective deadline and its source, and the payment group. Requires
        `staff:accounts:read`; billing routes require no step-up.
      tags: [Staff]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        '200':
          description: Member subscription rows
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema:
                type: object
                required: [data, next_cursor]
                properties:
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/StaffUserSubscriptionRow' }
                  next_cursor: { type: string, nullable: true }
        '400': { description: Invalid account id }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Account not found }
        '503': { description: Database unavailable }

  /staff/releases/overview:
    get:
      operationId: getStaffReleasesOverview
      summary: Release Control Center overview (environments, toggles, live pipeline)
      description: >-
        Requires `staff:releases:read`. Environment build stamps are scraped from the public
        /auth/login pages (nulls when unreachable); toggles and pipeline state come from the
        GitHub API and degrade to defaults with `github_available: false` when the
        PORTREX_GITHUB_CONTROL_TOKEN secret is absent.
      tags: [Staff]
      security:
        - staffBetterAuthCookie: []
        - staffHmacSessionCookie: []
      x-portrex-scopes: [staff:releases:read]
      responses:
        '200':
          description: Release posture snapshot.
          content:
            application/json:
              schema:
                type: object
                required: [environments, toggles, pipeline, version_line, token, github_available]
                properties:
                  environments:
                    type: object
                    required: [staging, production, in_sync]
                    properties:
                      staging: { $ref: '#/components/schemas/ReleaseEnvironmentStamp' }
                      production: { $ref: '#/components/schemas/ReleaseEnvironmentStamp' }
                      in_sync: { type: boolean }
                  toggles:
                    type: object
                    required: [auto_promote, scheduler_enabled, batches_enabled, auto_merge_enabled, batch_active_hours_utc, batch_interval_hours]
                    properties:
                      auto_promote: { type: boolean }
                      scheduler_enabled: { type: boolean }
                      batches_enabled: { type: boolean }
                      auto_merge_enabled: { type: boolean }
                      batch_active_hours_utc: { type: string, nullable: true }
                      batch_interval_hours: { type: number }
                  pipeline:
                    type: object
                    required: [running, last_batch]
                    properties:
                      running:
                        type: object
                        nullable: true
                        properties:
                          run_id: { type: integer }
                          started_at: { type: string, format: date-time, nullable: true }
                          html_url: { type: string, nullable: true }
                      last_batch:
                        type: object
                        nullable: true
                        properties:
                          run_id: { type: integer }
                          conclusion: { type: string, nullable: true }
                          created_at: { type: string, format: date-time, nullable: true }
                          html_url: { type: string, nullable: true }
                  version_line:
                    type: object
                    required: [current, next_preview]
                    description: >-
                      Release line from the VERSION file on main (cached contents read) plus a
                      "MAJOR.MINOR.<latest batch run_number + 1>" preview of the next release stamp.
                    properties:
                      current: { type: string, nullable: true }
                      next_preview: { type: string, nullable: true }
                  token:
                    type: object
                    required: [expires_at, warn]
                    description: >-
                      GitHub control-token expiry, captured from the
                      `github-authentication-token-expiration` response header; `warn` flips when
                      less than 14 days remain.
                    properties:
                      expires_at: { type: string, nullable: true }
                      warn: { type: boolean }
                  github_available: { type: boolean }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '403': { description: Staff role lacks `staff:releases:read`. }

  /staff/releases/history:
    get:
      operationId: listStaffReleasesHistory
      summary: Staging batch and production promotion run history
      description: >-
        Requires `staff:releases:read`. Merged staging-release.yml, promote-production.yml, and
        production release.yml workflow runs, newest first. Empty with `github_available: false`
        when the control token is absent.
      tags: [Staff]
      security:
        - staffBetterAuthCookie: []
        - staffHmacSessionCookie: []
      x-portrex-scopes: [staff:releases:read]
      parameters:
        - name: limit
          in: query
          required: false
          schema: { type: integer, minimum: 1, maximum: 50, default: 20 }
      responses:
        '200':
          description: Release run history.
          content:
            application/json:
              schema:
                type: object
                required: [items]
                properties:
                  items:
                    type: array
                    items:
                      type: object
                      required: [kind, run_id]
                      properties:
                        kind: { type: string, enum: [batch, promotion] }
                        release_id: { type: string, nullable: true }
                        run_id: { type: integer }
                        run_number:
                          type: integer
                          nullable: true
                          description: Monotonic per-workflow counter; the UI derives the human version ("MAJOR.MINOR.<run_number>") from it.
                        conclusion: { type: string, nullable: true }
                        created_at: { type: string, format: date-time, nullable: true }
                        duration_seconds: { type: integer, nullable: true }
                        html_url: { type: string, nullable: true }
                  github_available: { type: boolean }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '403': { description: Staff role lacks `staff:releases:read`. }

  /staff/releases/events:
    get:
      operationId: listStaffReleasesEvents
      summary: Release event feed (merges, promotions, failures, blocked PRs, waivers)
      description: >-
        Requires `staff:releases:read`. Merged PRs, production promotions, failed workflow runs,
        open PRs blocked by the "AI review gate" check, and review:waive label activity, newest
        first. Empty with `github_available: false` when the control token is absent.
      tags: [Staff]
      security:
        - staffBetterAuthCookie: []
        - staffHmacSessionCookie: []
      x-portrex-scopes: [staff:releases:read]
      parameters:
        - name: limit
          in: query
          required: false
          schema: { type: integer, minimum: 1, maximum: 50, default: 30 }
      responses:
        '200':
          description: Release event feed.
          content:
            application/json:
              schema:
                type: object
                required: [items]
                properties:
                  items:
                    type: array
                    items:
                      type: object
                      required: [kind, title]
                      properties:
                        kind: { type: string, enum: [merge, promotion, failure, blocked_pr, waiver] }
                        title: { type: string }
                        actor: { type: string, nullable: true }
                        at: { type: string, format: date-time, nullable: true }
                        html_url: { type: string, nullable: true }
                        detail: { type: string, nullable: true }
                        pr_number:
                          type: integer
                          description: Present on blocked_pr items so the waive action never parses html_url.
                  github_available: { type: boolean }
                  degraded:
                    type: array
                    items: { type: string }
                    description: Fan-out sources that failed upstream and contributed zero items (per-source degrade — the feed itself never 500s).
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '403': { description: Staff role lacks `staff:releases:read`. }

  /staff/releases/costs:
    get:
      operationId: getStaffReleasesCosts
      summary: Release pipeline cost telemetry (GitHub Actions, OpenRouter, GCP stub)
      description: >-
        Requires `staff:releases:read`. Actions minutes/cost come from the org billing endpoints
        (projection = month-to-date / day-of-cycle × days-in-cycle); OpenRouter credits come from
        the provider credits API when OPENROUTER_API_KEY is set. GCP is a stub with a setup hint.
      tags: [Staff]
      security:
        - staffBetterAuthCookie: []
        - staffHmacSessionCookie: []
      x-portrex-scopes: [staff:releases:read]
      responses:
        '200':
          description: Cost telemetry snapshot.
          content:
            application/json:
              schema:
                type: object
                required: [actions, openrouter, gcp]
                properties:
                  actions:
                    type: object
                    required: [mtd_minutes, included_minutes, mtd_cost_usd, projected_month_cost_usd]
                    properties:
                      available: { type: boolean }
                      mtd_minutes: { type: number }
                      included_minutes: { type: number }
                      mtd_cost_usd: { type: number }
                      prev_month_cost_usd: { type: number, nullable: true }
                      projected_month_cost_usd: { type: number }
                      period_resets_at: { type: string, format: date-time, nullable: true }
                  openrouter:
                    type: object
                    properties:
                      available: { type: boolean }
                      usage_usd: { type: number, nullable: true }
                      credits_remaining_usd: { type: number, nullable: true }
                  gcp:
                    type: object
                    required: [available, setup_hint]
                    properties:
                      available: { type: boolean, enum: [false] }
                      setup_hint: { type: string }
                  github_available: { type: boolean }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '403': { description: Staff role lacks `staff:releases:read`. }

  /staff/releases/actions/flush:
    post:
      operationId: dispatchStaffReleasesFlush
      summary: Dispatch a staging batch flush now
      description: Requires `staff:releases:admin` (platform_admin, fresh step-up). Dispatches staging-release.yml on main.
      tags: [Staff]
      security:
        - staffBetterAuthCookie: []
        - staffHmacSessionCookie: []
      x-portrex-scopes: [staff:releases:admin]
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                reason: { type: string, maxLength: 500 }
      responses:
        '200':
          description: Batch flush dispatched.
          content:
            application/json:
              schema:
                type: object
                required: [ok]
                properties:
                  ok: { type: boolean }
                  workflow: { type: string }
                  run_url: { type: string }
        '400': { description: Invalid reason. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '403': { description: Staff role lacks `staff:releases:admin` or step-up is stale. }
        '502': { description: GitHub dispatch failed. }
        '503': { $ref: '#/components/responses/GithubControlTokenMissing' }

  /staff/releases/actions/promote:
    post:
      operationId: dispatchStaffReleasesPromotion
      summary: Dispatch a production promotion of a sealed staging release
      description: Requires `staff:releases:admin` (platform_admin, fresh step-up). Dispatches promote-production.yml on main.
      tags: [Staff]
      security:
        - staffBetterAuthCookie: []
        - staffHmacSessionCookie: []
      x-portrex-scopes: [staff:releases:admin]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [release_id]
              properties:
                release_id:
                  type: string
                  pattern: '^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$'
      responses:
        '200':
          description: Promotion dispatched.
          content:
            application/json:
              schema:
                type: object
                required: [ok]
                properties:
                  ok: { type: boolean }
                  workflow: { type: string }
                  release_id: { type: string }
                  run_url: { type: string }
        '400': { description: Invalid release_id. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '403': { description: Staff role lacks `staff:releases:admin` or step-up is stale. }
        '502': { description: GitHub dispatch failed. }
        '503': { $ref: '#/components/responses/GithubControlTokenMissing' }

  /staff/releases/actions/toggle:
    post:
      operationId: setStaffReleasesToggle
      summary: Flip a release pipeline repo-variable toggle
      description: >-
        Requires `staff:releases:admin` (platform_admin, fresh step-up). Patches the corresponding
        repo variable (auto_promote → PRODUCTION_AUTO_PROMOTE, scheduler →
        PRODUCTION_SCHEDULER_ENABLED, batches → STAGING_BATCH_ENABLED, auto_merge →
        AUTO_MERGE_ENABLED).
      tags: [Staff]
      security:
        - staffBetterAuthCookie: []
        - staffHmacSessionCookie: []
      x-portrex-scopes: [staff:releases:admin]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [name, value]
              properties:
                name: { type: string, enum: [auto_promote, scheduler, batches, auto_merge] }
                value: { type: boolean }
      responses:
        '200':
          description: Toggle updated.
          content:
            application/json:
              schema:
                type: object
                required: [ok]
                properties:
                  ok: { type: boolean }
                  name: { type: string }
                  variable: { type: string }
                  value: { type: boolean }
                  html_url: { type: string }
        '400': { description: Invalid toggle name or value. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '403': { description: Staff role lacks `staff:releases:admin` or step-up is stale. }
        '502': { description: GitHub variable update failed. }
        '503': { $ref: '#/components/responses/GithubControlTokenMissing' }

  /staff/releases/actions/set-batch-schedule:
    post:
      operationId: setStaffReleasesBatchSchedule
      summary: Update the staging batch schedule repo variables
      description: >-
        Requires `staff:releases:admin` (platform_admin, fresh step-up). Sets
        BATCH_ACTIVE_HOURS_UTC (empty string when null) and BATCH_INTERVAL_HOURS.
      tags: [Staff]
      security:
        - staffBetterAuthCookie: []
        - staffHmacSessionCookie: []
      x-portrex-scopes: [staff:releases:admin]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [active_hours_utc, interval_hours]
              properties:
                active_hours_utc:
                  type: string
                  nullable: true
                  pattern: '^\d{1,2}-\d{1,2}$'
                interval_hours: { type: integer, enum: [1, 2, 3, 4, 6] }
      responses:
        '200':
          description: Batch schedule updated.
          content:
            application/json:
              schema:
                type: object
                required: [ok]
                properties:
                  ok: { type: boolean }
                  active_hours_utc: { type: string, nullable: true }
                  interval_hours: { type: integer }
                  html_url: { type: string }
        '400': { description: Invalid active hours or interval. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '403': { description: Staff role lacks `staff:releases:admin` or step-up is stale. }
        '502': { description: GitHub variable update failed. }
        '503': { $ref: '#/components/responses/GithubControlTokenMissing' }

  /staff/releases/actions/waive-review:
    post:
      operationId: waiveStaffReleasesReview
      summary: Apply the review:waive label to a pull request
      description: Requires `staff:releases:admin` (platform_admin, fresh step-up).
      tags: [Staff]
      security:
        - staffBetterAuthCookie: []
        - staffHmacSessionCookie: []
      x-portrex-scopes: [staff:releases:admin]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [pr_number]
              properties:
                pr_number: { type: integer, minimum: 1 }
      responses:
        '200':
          description: Label applied.
          content:
            application/json:
              schema:
                type: object
                required: [ok]
                properties:
                  ok: { type: boolean }
                  pr_number: { type: integer }
                  label: { type: string }
                  html_url: { type: string }
        '400': { description: Invalid pr_number. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '403': { description: Staff role lacks `staff:releases:admin` or step-up is stale. }
        '502': { description: GitHub label request failed. }
        '503': { $ref: '#/components/responses/GithubControlTokenMissing' }

  /staff/releases/actions/bump-minor:
    post:
      operationId: bumpStaffReleasesMinor
      summary: Open the release-line minor bump PR with squash auto-merge
      description: >-
        Requires `staff:releases:admin` (platform_admin, fresh step-up). Reads VERSION from main,
        computes the next minor (X.Y.Z → X.(Y+1).0), pushes the change on a
        release-line/bump-&lt;version&gt; branch, opens the PR, and enables squash auto-merge.
      tags: [Staff]
      security:
        - staffBetterAuthCookie: []
        - staffHmacSessionCookie: []
      x-portrex-scopes: [staff:releases:admin]
      responses:
        '200':
          description: Bump PR opened.
          content:
            application/json:
              schema:
                type: object
                required: [ok, version, pr_url]
                properties:
                  ok: { type: boolean }
                  version: { type: string }
                  pr_number: { type: integer, nullable: true }
                  pr_url: { type: string }
                  auto_merge_enabled: { type: boolean }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '403': { description: Staff role lacks `staff:releases:admin` or step-up is stale. }
        '409': { description: The bump branch for this version already exists. }
        '502': { description: 'A GitHub step failed (read VERSION, branch, commit, or PR).' }
        '503': { $ref: '#/components/responses/GithubControlTokenMissing' }

  /staff/releases/runs/{runId}/jobs:
    get:
      operationId: getStaffReleaseRunJobs
      summary: Job and step detail for one workflow run (with child release-run chase)
      description: >-
        Requires `staff:releases:read`. Jobs come from the GitHub jobs API through the shared
        read cache. When the run is a staging batch, the dispatched release.yml child run is
        chased best-effort by release id (display title / candidate branch); `chase_resolved`
        is true only when the child run was found. Degrades to nulls with
        `github_available: false` when the control token is absent.
      tags: [Staff]
      security:
        - staffBetterAuthCookie: []
        - staffHmacSessionCookie: []
      x-portrex-scopes: [staff:releases:read]
      parameters:
        - name: runId
          in: path
          required: true
          schema: { type: string, pattern: '^\d{1,15}$' }
      responses:
        '200':
          description: Run, jobs, steps, and the chased child release run.
          content:
            application/json:
              schema:
                type: object
                required: [github_available, run, jobs, child_release_run, chase_resolved]
                properties:
                  github_available: { type: boolean }
                  run:
                    type: object
                    nullable: true
                    required: [id, status, conclusion, html_url]
                    properties:
                      id: { type: integer }
                      status: { type: string, nullable: true }
                      conclusion: { type: string, nullable: true }
                      html_url: { type: string, nullable: true }
                      workflow: { type: string, nullable: true }
                      display_title: { type: string, nullable: true }
                      created_at: { type: string, format: date-time, nullable: true }
                      run_started_at: { type: string, format: date-time, nullable: true }
                  jobs:
                    type: array
                    items:
                      type: object
                      required: [id, name, status, conclusion, started_at, completed_at, duration_seconds, html_url, steps]
                      properties:
                        id: { type: integer }
                        name: { type: string }
                        status: { type: string, nullable: true }
                        conclusion: { type: string, nullable: true }
                        created_at: { type: string, format: date-time, nullable: true }
                        started_at: { type: string, format: date-time, nullable: true }
                        completed_at: { type: string, format: date-time, nullable: true }
                        duration_seconds: { type: integer, nullable: true }
                        html_url: { type: string, nullable: true }
                        steps:
                          type: array
                          items:
                            type: object
                            required: [number, name, status, conclusion]
                            properties:
                              number: { type: integer }
                              name: { type: string }
                              status: { type: string, nullable: true }
                              conclusion: { type: string, nullable: true }
                              started_at: { type: string, format: date-time, nullable: true }
                              completed_at: { type: string, format: date-time, nullable: true }
                  child_release_run:
                    type: object
                    nullable: true
                    required: [run_id, html_url, status, conclusion]
                    properties:
                      run_id: { type: integer }
                      html_url: { type: string, nullable: true }
                      status: { type: string, nullable: true }
                      conclusion: { type: string, nullable: true }
                  chase_resolved: { type: boolean }
        '400': { description: Invalid run id. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '403': { description: Staff role lacks `staff:releases:read`. }
        '404': { description: Run not found on GitHub. }
        '502': { description: GitHub read failed. }

  /staff/releases/runs/{runId}/jobs/{jobId}/logs:
    get:
      operationId: getStaffReleaseJobLogs
      summary: Extracted log view for one job (errors, tail, or full)
      description: >-
        Requires `staff:releases:read`. Fetches the raw job log (following GitHub's signed
        redirect, 2MB tail-keeping cap) and extracts server-side — `errors` returns
        `##[error]` / `::error` lines with 3 lines of context each side, `tail` the last 500
        lines, `full` everything the cap allowed. When the per-job blob 404s upstream the
        route falls back to extracting the job's member from the run-level log archive.
        Log bodies are never put in the shared GitHub cache; a 30s per-job/mode memo bounds
        repeat extraction.
      tags: [Staff]
      security:
        - staffBetterAuthCookie: []
        - staffHmacSessionCookie: []
      x-portrex-scopes: [staff:releases:read]
      parameters:
        - name: runId
          in: path
          required: true
          schema: { type: string, pattern: '^\d{1,15}$' }
        - name: jobId
          in: path
          required: true
          schema: { type: string, pattern: '^\d{1,15}$' }
        - name: mode
          in: query
          required: false
          schema: { type: string, enum: [errors, tail, full], default: errors }
      responses:
        '200':
          description: Extracted log lines for the requested mode.
          content:
            application/json:
              schema:
                type: object
                required: [github_available, mode, truncated, total_lines]
                properties:
                  github_available: { type: boolean }
                  mode: { type: string, enum: [errors, tail, full] }
                  truncated:
                    type: boolean
                    description: True when the raw log exceeded the 2MB fetch cap (tail kept).
                  total_lines: { type: integer }
                  error_lines:
                    type: array
                    description: Present in `errors` mode only.
                    items:
                      type: object
                      required: [line_no, text, context_before, context_after]
                      properties:
                        line_no: { type: integer }
                        text: { type: string }
                        context_before: { type: array, items: { type: string } }
                        context_after: { type: array, items: { type: string } }
                  start_line_no:
                    type: integer
                    description: Present in `tail` / `full` modes — 1-based number of the first returned line.
                  lines:
                    type: array
                    description: Present in `tail` / `full` modes.
                    items: { type: string }
        '400': { description: Invalid run/job id or mode. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '403': { description: Staff role lacks `staff:releases:read`. }
        '404': { description: Job logs not found on GitHub. }
        '502': { description: GitHub log read failed. }

  /staff/releases/failures:
    get:
      operationId: listStaffReleasesFailures
      summary: Categorized Failure Center feed over recent failed workflow runs
      description: >-
        Requires `staff:releases:read`. Recent failed runs (all workflows) with their failing
        job/step, best-effort check-run annotations, and a pure-function category
        (ai_gate | billing | infra_flake | defect | unknown). Empty with
        `github_available: false` when the control token is absent.
      tags: [Staff]
      security:
        - staffBetterAuthCookie: []
        - staffHmacSessionCookie: []
      x-portrex-scopes: [staff:releases:read]
      parameters:
        - name: limit
          in: query
          required: false
          schema: { type: integer, minimum: 1, maximum: 30, default: 15 }
      responses:
        '200':
          description: Categorized failure items, newest first.
          content:
            application/json:
              schema:
                type: object
                required: [items, github_available]
                properties:
                  items:
                    type: array
                    items:
                      type: object
                      required: [run_id, workflow, category, failing_job, failing_step, error_annotations, created_at, html_url, rerunnable]
                      properties:
                        run_id: { type: integer }
                        workflow: { type: string, nullable: true }
                        category: { type: string, enum: [ai_gate, billing, infra_flake, defect, unknown] }
                        failing_job: { type: string, nullable: true }
                        failing_step: { type: string, nullable: true }
                        error_annotations: { type: array, items: { type: string } }
                        created_at: { type: string, format: date-time, nullable: true }
                        html_url: { type: string, nullable: true }
                        rerunnable: { type: boolean }
                  github_available: { type: boolean }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '403': { description: Staff role lacks `staff:releases:read`. }

  /staff/releases/actions/rerun-failed:
    post:
      operationId: rerunStaffReleasesFailedJobs
      summary: Re-run the failed jobs of one workflow run
      description: >-
        Requires `staff:releases:admin` (platform_admin, fresh step-up). Dispatches GitHub's
        rerun-failed-jobs on the run and busts the cached run-list reads.
      tags: [Staff]
      security:
        - staffBetterAuthCookie: []
        - staffHmacSessionCookie: []
      x-portrex-scopes: [staff:releases:admin]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [run_id]
              properties:
                run_id: { type: integer, minimum: 1 }
      responses:
        '200':
          description: Re-run dispatched.
          content:
            application/json:
              schema:
                type: object
                required: [ok, run_url]
                properties:
                  ok: { type: boolean }
                  run_url: { type: string }
        '400': { description: Invalid run_id. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '403': { description: Staff role lacks `staff:releases:admin` or step-up is stale. }
        '502': { description: GitHub dispatch failed. }
        '503': { $ref: '#/components/responses/GithubControlTokenMissing' }

  /staff/releases/journal:
    get:
      operationId: listStaffReleasesJournal
      summary: Sealed releases from the GCS release journal with environment truth
      description: >-
        Requires `staff:releases:read`. Sealed releases listed by object CREATION time
        (never lexicographic), each with its final state, commit SHA, migration count, UAT
        attestation, and production-promotion flag. `environment_truth` folds the live
        production WEB build-stamp SHA against the current production release's WEB
        COMPONENT source SHA (`component_sha`), not the release commit SHA: web carries
        forward when a release doesn't touch apps/web, so the stamp legitimately differs
        from the release commit. `divergent` is true only when the live stamp does not
        match the sealed release's web component source SHA. Degrades to empty items with
        `journal_available: false` when the journal bucket is unreadable — independent of
        `github_available` on the sibling reads.
      tags: [Staff]
      security:
        - staffBetterAuthCookie: []
        - staffHmacSessionCookie: []
      x-portrex-scopes: [staff:releases:read]
      parameters:
        - name: limit
          in: query
          required: false
          schema: { type: integer, minimum: 1, maximum: 50, default: 20 }
      responses:
        '200':
          description: Sealed releases, newest first, plus folded environment truth.
          content:
            application/json:
              schema:
                type: object
                required: [items, environment_truth, journal_available]
                properties:
                  items:
                    type: array
                    items:
                      type: object
                      required: [release_id, sealed_at, final_state, release_commit_sha, version, migration_count, uat_attested, promoted_to_production]
                      properties:
                        release_id: { type: string }
                        sealed_at: { type: string, format: date-time }
                        final_state: { type: string, enum: [complete, partial, rolled_back] }
                        release_commit_sha: { type: string }
                        version: { type: string, nullable: true }
                        migration_count: { type: integer }
                        uat_attested: { type: boolean }
                        promoted_to_production: { type: boolean }
                  environment_truth:
                    type: object
                    required: [component, stamp_version, stamp_sha, component_sha, journal_sha, divergent]
                    properties:
                      component: { type: string, enum: [web] }
                      stamp_version: { type: string, nullable: true }
                      stamp_sha: { type: string, nullable: true }
                      component_sha: { type: string, nullable: true }
                      journal_sha: { type: string, nullable: true }
                      divergent: { type: boolean }
                  journal_available: { type: boolean }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '403': { description: Staff role lacks `staff:releases:read`. }

  /staff/releases/journal/{releaseId}:
    get:
      operationId: getStaffReleasesJournalDetail
      summary: Full journal drill-down for one sealed release
      description: >-
        Requires `staff:releases:read`. Manifest summary, sealed state, migration plan +
        receipt, UAT attestation/evidence, the hash-linked event timeline (chain verified
        server-side; `chain_valid` reports violations), production promotion results, the
        per-component diff against the previous sealed release (with GitHub compare URLs;
        no GitHub API calls involved), and rollback eligibility.
      tags: [Staff]
      security:
        - staffBetterAuthCookie: []
        - staffHmacSessionCookie: []
      x-portrex-scopes: [staff:releases:read]
      parameters:
        - name: releaseId
          in: path
          required: true
          schema: { type: string, pattern: '^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$' }
      responses:
        '200':
          description: 'Release drill-down, or a degraded `journal_available: false` shell.'
          content:
            application/json:
              schema:
                type: object
                required: [journal_available, release_id]
                properties:
                  journal_available: { type: boolean }
                  release_id: { type: string }
                  sealed:
                    type: object
                    nullable: true
                    properties:
                      final_state: { type: string, enum: [complete, partial, rolled_back] }
                      sealed_at: { type: string, format: date-time }
                      terminal_event_hash: { type: string }
                  manifest:
                    type: object
                    nullable: true
                    properties:
                      release_commit_sha: { type: string }
                      prepared_at: { type: string, format: date-time }
                      evidence_mode: { type: string, enum: [normal, emergency_waiver] }
                      secret_version_count: { type: integer }
                      kms_key_version_count: { type: integer }
                  migrations:
                    type: object
                    properties:
                      ordered_set: { type: array, items: { type: string } }
                      receipt:
                        type: object
                        nullable: true
                        properties:
                          applied_at: { type: string, format: date-time }
                          applied_count: { type: integer }
                          receipt_uri: { type: string }
                      receipt_status: { type: string, enum: [recorded, missing] }
                  uat:
                    type: object
                    properties:
                      attested: { type: boolean }
                      attestation: { type: object, nullable: true, additionalProperties: true }
                      evidence: { type: object, nullable: true, additionalProperties: true }
                  events:
                    type: array
                    items:
                      type: object
                      required: [sequence, step, attempt, kind, state, recorded_at]
                      properties:
                        sequence: { type: integer }
                        step: { type: string }
                        attempt: { type: integer }
                        kind: { type: string, enum: [intent, discovery, result, compensation, sealed] }
                        state: { type: string }
                        recorded_at: { type: string, format: date-time }
                  chain_valid: { type: boolean }
                  chain_error: { type: string, nullable: true }
                  promotions:
                    type: array
                    items:
                      type: object
                      properties:
                        step: { type: string }
                        recovered: { type: boolean }
                        completed_at: { type: string, format: date-time }
                  promoted_to_production: { type: boolean }
                  previous_release_id: { type: string, nullable: true }
                  component_diff:
                    type: object
                    additionalProperties:
                      type: object
                      properties:
                        prev_sha: { type: string, nullable: true }
                        sha: { type: string, nullable: true }
                        changed: { type: boolean }
                        compare_url: { type: string, nullable: true }
                  rollback:
                    type: object
                    properties:
                      eligible: { type: boolean }
                      ineligible_reason: { type: string, nullable: true }
                      current_production_release_id: { type: string, nullable: true }
        '400': { description: Invalid release id. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '403': { description: Staff role lacks `staff:releases:read`. }
        '404': { description: Release not found in the journal. }

  /staff/releases/pending:
    get:
      operationId: getStaffReleasesPending
      summary: Commits on main since the last sealed release
      description: >-
        Requires `staff:releases:read`. Base is the latest sealed release from the journal;
        the GitHub compare `{base}...main` runs through the TTL/ETag cache. Changed files
        are classified with the same deterministic rules as staging-release.yml's
        "Classify changed components" step to predict the next batch's component set and
        docs-only posture.
      tags: [Staff]
      security:
        - staffBetterAuthCookie: []
        - staffHmacSessionCookie: []
      x-portrex-scopes: [staff:releases:read]
      responses:
        '200':
          description: Pending-batch preview (possibly degraded on either axis).
          content:
            application/json:
              schema:
                type: object
                required: [journal_available, github_available, base_sha, commit_count, commits, component_set, docs_only_prediction, truncated]
                properties:
                  journal_available: { type: boolean }
                  github_available: { type: boolean }
                  base_release_id: { type: string, nullable: true }
                  base_sha: { type: string, nullable: true }
                  commit_count: { type: integer }
                  commits:
                    type: array
                    items:
                      type: object
                      required: [sha, title, author, merged_pr_number]
                      properties:
                        sha: { type: string }
                        title: { type: string }
                        author: { type: string, nullable: true }
                        merged_pr_number: { type: integer, nullable: true }
                  component_set:
                    type: array
                    items: { type: string, enum: [api, worker, web, admin] }
                  docs_only_prediction: { type: boolean }
                  truncated: { type: boolean }
                  degraded:
                    type: boolean
                    description: True when the GitHub compare failed on both the manifest SHA and the release-id sha12 base — the preview is empty but the read never 502s.
                  degraded_reason:
                    type: string
                    nullable: true
                    description: Technical detail for the degraded state (surfaced as a tooltip, never as primary copy).
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '403': { description: Staff role lacks `staff:releases:read`. }

  /staff/releases/dora:
    get:
      operationId: getStaffReleasesDora
      summary: DORA metrics computed from the release journal and run history
      description: >-
        Requires `staff:releases:read`. Deploy frequency (production-promoted sealed
        releases per day), commit lead time p50/p90 (committer dates vs promotion time,
        cached per release), change failure rate, and MTTR — over a 30d or 90d window
        with a 10-minute memo. Every block carries its sample size so the UI can show
        "n=" honesty.
      tags: [Staff]
      security:
        - staffBetterAuthCookie: []
        - staffHmacSessionCookie: []
      x-portrex-scopes: [staff:releases:read]
      parameters:
        - name: window
          in: query
          required: false
          schema: { type: string, enum: ['30d', '90d'], default: '30d' }
      responses:
        '200':
          description: DORA metrics for the window.
          content:
            application/json:
              schema:
                type: object
                required: [journal_available, github_available, window_days, n_releases, deploy_frequency_per_day, lead_time_seconds, change_failure_rate, mttr_seconds, series]
                properties:
                  journal_available: { type: boolean }
                  github_available: { type: boolean }
                  window_days: { type: integer, enum: [30, 90] }
                  n_releases: { type: integer }
                  deploy_frequency_per_day: { type: number }
                  lead_time_seconds:
                    type: object
                    nullable: true
                    properties:
                      p50: { type: number, nullable: true }
                      p90: { type: number, nullable: true }
                      n_commits: { type: integer }
                  change_failure_rate:
                    type: object
                    nullable: true
                    properties:
                      rate: { type: number }
                      failures: { type: integer }
                      attempts: { type: integer }
                  mttr_seconds:
                    type: object
                    nullable: true
                    properties:
                      p50: { type: number, nullable: true }
                      worst: { type: number }
                      n: { type: integer }
                  series:
                    type: object
                    properties:
                      deploys_per_day:
                        type: array
                        items:
                          type: object
                          properties:
                            date: { type: string }
                            count: { type: integer }
        '400': { description: Invalid window. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '403': { description: Staff role lacks `staff:releases:read`. }

  /staff/releases/actions/rollback:
    post:
      operationId: rollbackStaffReleases
      summary: Dispatch a coordinated production rollback to a sealed release
      description: >-
        Requires `staff:releases:admin` (platform_admin, fresh step-up). Validates the
        target against the journal FAIL-CLOSED — it must be a sealed release with
        `final_state=complete` and must not be the currently promoted production release —
        then dispatches release.yml with `operation=rollback` (current release_id +
        rollback_to_release_id) and busts the cached run-list reads. A target sealed before the
        rollback floor is refused with 409 `below_rollback_floor`. A floor that cannot be
        evaluated from the journal is refused with 409 `rollback_floor_unreadable`.
      tags: [Staff]
      security:
        - staffBetterAuthCookie: []
        - staffHmacSessionCookie: []
      x-portrex-scopes: [staff:releases:admin]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [rollback_to_release_id]
              properties:
                rollback_to_release_id:
                  type: string
                  pattern: '^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$'
      responses:
        '200':
          description: Rollback dispatched.
          content:
            application/json:
              schema:
                type: object
                required: [ok, release_id, rollback_to_release_id, run_url]
                properties:
                  ok: { type: boolean }
                  release_id: { type: string }
                  rollback_to_release_id: { type: string }
                  run_url: { type: string }
        '400': { description: Invalid rollback_to_release_id. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '403': { description: Staff role lacks `staff:releases:admin` or step-up is stale. }
        '409': { description: 'Target not sealed complete, no promotion exists, target is current, target is below the rollback floor (`below_rollback_floor`), or the floor cannot be evaluated (`rollback_floor_unreadable`).' }
        '502': { description: GitHub dispatch failed. }
        '503': { description: GitHub control token missing or release journal unavailable. }

  /staff/releases/review-intel:
    get:
      operationId: getStaffReleasesReviewIntel
      summary: AI review gate verdicts and waiver stats for recent PRs
      description: >-
        Requires `staff:releases:read`. Recent PRs (state=all) folded with their head SHA's
        "AI review gate" check-run and the review:waive label into a per-PR verdict
        (pass / block / waived / missing). Stats treat block+waived as "flagged":
        `block_rate` = flagged / reviewed and `waive_after_block_rate` = waived / flagged
        (the false-positive proxy). Model names mirror the pinned literals in
        openrouter-review.yml / staging-release.yml. `openrouter_activity` is a degrade
        stub — the OpenRouter /activity endpoint needs a provisioning key we do not hold.
        Empty with `github_available: false` when the control token is absent.
      tags: [Staff]
      security:
        - staffBetterAuthCookie: []
        - staffHmacSessionCookie: []
      x-portrex-scopes: [staff:releases:read]
      parameters:
        - name: window
          in: query
          required: false
          schema: { type: string, enum: ['7d', '14d', '30d'], default: '14d' }
      responses:
        '200':
          description: Review intelligence snapshot.
          content:
            application/json:
              schema:
                type: object
                required: [github_available, reviews, stats, models, openrouter_activity]
                properties:
                  github_available: { type: boolean }
                  reviews:
                    type: array
                    items:
                      type: object
                      required: [pr_number, title, verdict, blocking_count]
                      properties:
                        pr_number: { type: integer }
                        title: { type: string }
                        author: { type: string, nullable: true }
                        verdict: { type: string, enum: [pass, block, waived, missing] }
                        blocking_count: { type: integer }
                        at: { type: string, format: date-time, nullable: true }
                        html_url: { type: string, nullable: true }
                  stats:
                    type: object
                    required: [total, block_rate, waive_after_block_rate]
                    properties:
                      total: { type: integer }
                      block_rate: { type: number }
                      waive_after_block_rate: { type: number }
                  models:
                    type: object
                    required: [pr, batch]
                    properties:
                      pr: { type: string }
                      batch: { type: string }
                  openrouter_activity:
                    type: object
                    required: [available]
                    properties:
                      available: { type: boolean, enum: [false] }
        '400': { description: Invalid window. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '403': { description: Staff role lacks `staff:releases:read`. }
        '502': { description: GitHub read failed. }

  /staff/releases/costs/breakdown:
    get:
      operationId: getStaffReleasesCostsBreakdown
      summary: Daily Actions net-cost series and per-workflow cost estimates
      description: >-
        Requires `staff:releases:read`. Daily net cost comes from the enhanced billing
        usage endpoint (year/month parameters cover a month boundary). Per-workflow rows
        are ESTIMATES — run wall-clock duration × $0.008/min (Linux rate), not billable
        job-minutes. `per_release_avg_usd` divides the total estimate by successful
        staging batches in the window. Empty with `github_available: false` when the
        control token is absent.
      tags: [Staff]
      security:
        - staffBetterAuthCookie: []
        - staffHmacSessionCookie: []
      x-portrex-scopes: [staff:releases:read]
      parameters:
        - name: window
          in: query
          required: false
          schema: { type: string, enum: ['30d'], default: '30d' }
      responses:
        '200':
          description: Cost breakdown snapshot.
          content:
            application/json:
              schema:
                type: object
                required: [github_available, daily, by_workflow, per_release_avg_usd]
                properties:
                  github_available: { type: boolean }
                  daily:
                    type: array
                    items:
                      type: object
                      required: [date, net_usd]
                      properties:
                        date: { type: string }
                        net_usd: { type: number }
                  by_workflow:
                    type: array
                    items:
                      type: object
                      required: [workflow, runs, minutes, est_usd]
                      properties:
                        workflow: { type: string }
                        runs: { type: integer }
                        minutes: { type: integer }
                        est_usd: { type: number }
                  per_release_avg_usd: { type: number, nullable: true }
        '400': { description: Invalid window. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '403': { description: Staff role lacks `staff:releases:read`. }

  /staff/releases/schedules:
    get:
      operationId: listStaffReleasesSchedules
      summary: Production deploy schedules from the release journal bucket
      description: >-
        Requires `staff:releases:read`. Reads the immutable schedule records under
        `releases/_schedules/production/` (definitions, cancellations, latest confirmed
        dispatch per schedule — shapes per tools/release/production-scheduler.ts).
        `recurring_supported` is false while the Production environment has no required
        reviewer (the scheduler's reviewer gate fails recurring dispatches closed).
        Empty with `journal_available: false` when the journal cannot be read.
      tags: [Staff]
      security:
        - staffBetterAuthCookie: []
        - staffHmacSessionCookie: []
      x-portrex-scopes: [staff:releases:read]
      responses:
        '200':
          description: Production deploy schedules.
          content:
            application/json:
              schema:
                type: object
                required: [journal_available, recurring_supported, items]
                properties:
                  journal_available: { type: boolean }
                  recurring_supported: { type: boolean }
                  items:
                    type: array
                    items:
                      type: object
                      required: [schedule_id, kind, deploy_at, cron, timezone, release_selector, created_by, created_at, cancelled, last_dispatch]
                      properties:
                        schedule_id: { type: string }
                        kind: { type: string, enum: [once, recurring] }
                        deploy_at: { type: string, nullable: true }
                        cron: { type: string, nullable: true }
                        timezone: { type: string }
                        release_selector:
                          type: object
                          required: [kind]
                          properties:
                            kind: { type: string, enum: [latest-green, fixed] }
                            release_id: { type: string }
                        created_by: { type: string }
                        created_at: { type: string, format: date-time }
                        cancelled: { type: boolean }
                        last_dispatch:
                          type: object
                          nullable: true
                          required: [occurrence, release_id, confirmed_at]
                          properties:
                            occurrence: { type: string, format: date-time }
                            release_id: { type: string }
                            confirmed_at: { type: string, format: date-time }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '403': { description: Staff role lacks `staff:releases:read`. }

  /staff/releases/actions/schedule:
    post:
      operationId: mutateStaffReleasesSchedule
      summary: Create or cancel a production deploy schedule
      description: >-
        Requires `staff:releases:admin` (platform_admin, fresh step-up). Validates the
        inputs (slug schedule_id; RFC3339 timing for schedule-once / five-field cron for
        schedule-recurring; IANA timezone) then dispatches production-scheduler.yml with
        its native inputs. NOTE — recurring schedules currently fail closed at dispatch
        time on the Team plan (`recurring_supported: false`): the scheduler workflow's
        reviewer gate skips recurring occurrences unless the Production environment has
        at least one required reviewer.
      tags: [Staff]
      security:
        - staffBetterAuthCookie: []
        - staffHmacSessionCookie: []
      x-portrex-scopes: [staff:releases:admin]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [action, schedule_id]
              properties:
                action: { type: string, enum: [schedule-once, schedule-recurring, cancel] }
                schedule_id:
                  type: string
                  pattern: '^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$'
                timing:
                  type: string
                  description: RFC3339 timestamp (schedule-once) or five-field cron (schedule-recurring).
                timezone: { type: string, description: 'IANA timezone; defaults to America/New_York.' }
                release_id:
                  type: string
                  pattern: '^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$'
                  description: Optional sealed release for schedule-once; forbidden for recurring.
      responses:
        '200':
          description: Schedule mutation dispatched.
          content:
            application/json:
              schema:
                type: object
                required: [ok, action, schedule_id, run_url, recurring_supported]
                properties:
                  ok: { type: boolean }
                  action: { type: string, enum: [schedule-once, schedule-recurring, cancel] }
                  schedule_id: { type: string }
                  run_url: { type: string }
                  recurring_supported: { type: boolean }
                  note: { type: string }
        '400': { description: 'Invalid action, schedule_id, timing, timezone, or release_id.' }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '403': { description: Staff role lacks `staff:releases:admin` or step-up is stale. }
        '502': { description: GitHub dispatch failed. }
        '503': { $ref: '#/components/responses/GithubControlTokenMissing' }

  /staff/releases/prs:
    get:
      operationId: listStaffReleasesPrs
      summary: Pull-request feed with Jira keys for the Release Center PR panel
      description: >-
        Requires `staff:releases:read`. Repo pull requests (GitHub `sort=updated desc`)
        with `POR-\d+` Jira keys extracted from the title and head branch name
        (uppercased, deduped). Open and draft PRs additionally carry a head-sha
        check-runs rollup (`pending | passing | failing`) and the "AI review gate"
        conclusion from the same check-runs read; merged/closed PRs skip the chase to
        protect the rate-limit budget (`checks`/`ai_gate` null). Empty with
        `github_available: false` when the control token is absent.
      tags: [Staff]
      security:
        - staffBetterAuthCookie: []
        - staffHmacSessionCookie: []
      x-portrex-scopes: [staff:releases:read]
      parameters:
        - name: state
          in: query
          required: false
          schema: { type: string, enum: [open, closed, all], default: open }
        - name: limit
          in: query
          required: false
          schema: { type: integer, minimum: 1, maximum: 100, default: 50 }
      responses:
        '200':
          description: Pull requests, most recently updated first.
          content:
            application/json:
              schema:
                type: object
                required: [items, github_available]
                properties:
                  items:
                    type: array
                    items:
                      type: object
                      required: [number, title, author, state, jira_keys, head_branch, created_at, merged_at, closed_at, html_url, checks, ai_gate]
                      properties:
                        number: { type: integer }
                        title: { type: string }
                        author: { type: string, nullable: true }
                        state: { type: string, enum: [open, draft, merged, closed] }
                        jira_keys: { type: array, items: { type: string } }
                        head_branch: { type: string, nullable: true }
                        created_at: { type: string, format: date-time, nullable: true }
                        merged_at: { type: string, format: date-time, nullable: true }
                        closed_at: { type: string, format: date-time, nullable: true }
                        html_url: { type: string, nullable: true }
                        checks: { type: string, enum: [pending, passing, failing], nullable: true }
                        ai_gate: { type: string, nullable: true }
                  github_available: { type: boolean }
        '400': { description: Invalid state parameter. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '403': { description: Staff role lacks `staff:releases:read`. }
        '502': { description: GitHub pull-request read failed. }

  /staff/me:
    get:
      operationId: getStaffMe
      summary: Hydrate the current Portrex staff session
      tags: [Staff]
      responses:
        '200':
          description: Hydrated staff session
          content:
            application/json:
              schema:
                type: object
                required: [kind, userId, email, fullName, staffRole]
                properties:
                  kind: { type: string, enum: [portrex_staff] }
                  userId: { type: string, format: uuid }
                  email: { type: string, format: email }
                  fullName: { type: string }
                  staffRole: { type: string, enum: [platform_admin, executive, security_admin, account_manager, support_agent] }
                  lastSignedInAt: { type: string, format: date-time, nullable: true }
        '401':
          description: Unauthorized — no active staff session.
          content:
            application/json:
              schema:
                type: object
                required: [error]
                properties:
                  error: { type: string, enum: [unauthorized] }

  /affiliate/me:
    get:
      operationId: getPartnerMe
      summary: Referral partner session projection
      description: >-
        Requires `affiliate_portal:read` on a referral partner session (cookie prefix
        `ptx_a`); no other identity population can reach it. Returns 403
        `affiliate_inactive` when the partner or its login is suspended or closed.
      tags: [Partners]
      security:
        - partnerBetterAuthCookie: []
      x-portrex-scopes: [affiliate_portal:read]
      responses:
        '200':
          description: The signed-in partner, its status, and whether the agreement still needs accepting.
          content:
            application/json:
              schema:
                type: object
                required:
                  [kind, partner_id, partner_user_id, email, display_name, partner_code,
                   partner_status, user_status, avatar_url, member_since, agreement_version,
                   agreement_required, scopes]
                additionalProperties: false
                properties:
                  kind: { type: string, enum: [affiliate_user] }
                  partner_id: { type: string, format: uuid }
                  partner_user_id: { type: string, format: uuid }
                  email: { type: string }
                  display_name: { type: string }
                  partner_code: { type: string }
                  partner_status: { type: string, enum: [active, suspended, closed] }
                  user_status: { type: string, enum: [invited, active, suspended] }
                  avatar_url:
                    type: string
                    nullable: true
                    description: Site-relative URL of the partner's photo, or null.
                  member_since:
                    type: string
                    description: When the partner organization was created.
                  agreement_version: { type: string, nullable: true }
                  agreement_required: { type: boolean }
                  scopes:
                    type: array
                    items: { type: string }
        '401': { description: 'Missing, invalid, or expired partner session.' }
        '403':
          description: >-
            Either the partner or its login is not active (`affiliate_inactive`, from the
            partner session middleware), or the authenticated principal belongs to another
            identity population and is refused by the scope layer's generic Forbidden shape.
          content:
            application/json:
              schema:
                oneOf:
                  - type: object
                    required: [error]
                    properties:
                      error: { type: string, enum: [affiliate_inactive] }
                      status: { type: string, enum: [suspended, closed, invited] }
                  - type: object
                    required: [error]
                    properties:
                      error: { type: string, enum: [Forbidden] }
                      message: { type: string }
        '404': { description: The partner row is no longer readable for this session. }
        '503': { description: Database unavailable. }

  /portal/accept:
    post:
      operationId: acceptCustomerPortalInvitation
      summary: Redeem a customer portal invitation token and mint a portal session
      tags: [Portal]
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [token]
              additionalProperties: false
              properties:
                token: { type: string, minLength: 16, maxLength: 256 }
      responses:
        '200':
          description: Invitation accepted; portal session cookie set.
          content:
            application/json:
              schema:
                type: object
                required: [status, redirect]
                properties:
                  status: { type: string, enum: [ok] }
                  redirect: { type: string }
        '404': { description: 'Invalid token.' }
        '410': { description: 'Expired, revoked, or already redeemed invitation.' }
        '429': { description: 'Rate limited.' }
        '503': { description: 'DB unavailable.' }

  /portal/sign-in:
    post:
      operationId: requestCustomerPortalSignIn
      summary: Request a customer portal return-visit OTP
      description: |
        Anti-enumeration endpoint. It returns the same 200 response shape
        whether or not the email exists.
      tags: [Portal]
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [email]
              additionalProperties: false
              properties:
                email: { type: string, format: email, maxLength: 320 }
      responses:
        '200':
          description: Opaque sign-in response.
          content:
            application/json:
              schema:
                type: object
                required: [status, message]
                properties:
                  status: { type: string, enum: [pending_verification] }
                  message: { type: string }

  /portal/sign-in/verify:
    post:
      operationId: verifyCustomerPortalSignIn
      summary: Verify a customer portal OTP and mint a portal session
      tags: [Portal]
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [email, code]
              additionalProperties: false
              properties:
                email: { type: string, format: email, maxLength: 320 }
                code: { type: string, minLength: 4, maxLength: 64 }
      responses:
        '200': { description: OTP verified; portal session cookie set. }
        '401': { description: Invalid credentials. }
        '429': { description: Rate limited. }
        '503': { description: DB unavailable. }

  /portal/me:
    get:
      operationId: getPortalMe
      summary: Hydrate the current Customer Portal session
      tags: [Portal]
      responses:
        '200':
          description: Hydrated portal session
          content:
            application/json:
              schema:
                type: object
                required: [kind, customerUserId, accountId]
                properties:
                  kind: { type: string, enum: [customer_user] }
                  customerUserId: { type: string, format: uuid }
                  email: { type: string, format: email, nullable: true }
                  accountId: { type: string, format: uuid }
                  accountName: { type: string, nullable: true }
                  customerPersonId: { type: string, format: uuid, nullable: true }
                  customerName: { type: string, nullable: true }
                  isDemo: { type: boolean, description: True when this account is a demo/sandbox account. }
        '401':
          description: Unauthorized — no active portal session.
          content:
            application/json:
              schema:
                type: object
                required: [error]
                properties:
                  error: { type: string, enum: [unauthorized] }

  # ── Showroom Catalog (POR-525) ────────────────────────────────────────────
  /showroom-catalog/products:
    get:
      operationId: listShowroomProducts
      summary: List showroom products for the account
      tags: [ShowroomCatalog]
      responses:
        '200':
          description: List of showroom products
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items: { type: object }
        '401': { description: Unauthorized }
        '503': { description: Database unavailable }

  /showroom-catalog/products/{id}:
    get:
      operationId: getShowroomCatalog
      summary: Get a showroom product with its full catalog
      tags: [ShowroomCatalog]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        '200':
          description: Product + catalog
          content:
            application/json:
              schema:
                type: object
                properties:
                  product: { type: object }
                  sizeTiers: { type: array, items: { type: object } }
                  packageGroups: { type: array, items: { type: object } }
                  packageOptions: { type: array, items: { type: object } }
                  addons: { type: array, items: { type: object } }
        '401': { description: Unauthorized }
        '404': { description: Product not found }
        '503': { description: Database unavailable }

  /showroom-catalog/workspace:
    get:
      operationId: getShowroomWorkspace
      summary: List all dashboard showrooms with grouped pricebook sections
      tags: [ShowroomCatalog]
      responses:
        '200':
          description: Showroom workspace (ADU, HVAC, Renovation trades)
          content:
            application/json:
              schema:
                type: object
                properties:
                  trades:
                    type: array
                    items: { type: object }
        '401': { description: Unauthorized }
        '500': { description: Workspace schema error }
        '503': { description: Database unavailable }

  /showroom-catalog/workspace/bootstrap:
    post:
      operationId: bootstrapShowroomWorkspace
      summary: Create linked showroom product shells for each trade
      tags: [ShowroomCatalog]
      responses:
        '200':
          description: Bootstrap result with created count and workspace snapshot
          content:
            application/json:
              schema:
                type: object
                properties:
                  created: { type: integer }
                  workspace: { type: object }
        '401': { description: Unauthorized }
        '503': { description: Database unavailable }

  /showroom-catalog/workspace/{key}/cpm-pricing:
    get:
      operationId: getShowroomHvacCpmPricing
      summary: HVAC Company Price Master offers, systems, defaults and installers (POR-1897)
      description: |
        Read-only (`pricebooks:read`). Company-scope: every seat of the tenant
        receives the same payload regardless of branch, because CPM resolves
        installer identity company-wide.

        `offers` and `contractors` are filtered to rows effective today
        (`effective_from <= today AND (effective_to IS NULL OR effective_to >
        today)`); `defaults` carries every non-deleted row with its own
        effectivity dates. `contractors` lists only installers holding an
        effective offer, without contact detail or licence numbers.

        `vendor_cost_cents` is present on an offer only for principals holding
        `pricebook:cost:read`; otherwise the field is absent.

        `zonePrices` (Packaged System Pricing) lists the tenant's zone price rows
        effective today: brand, state (`null` = all states), contractorId
        (`null` = any contractor), zones, retailCents, countPer and effectivity
        dates. It carries the customer retail only — the install cost, the
        floor (baseline) and the commission are never sent to any seat. A
        multi-zone system whose brand, state and installer match a row is priced
        at that retail raised by the branch price adjustment (engine v6, POR-2411).

        `catalogLines` is the HVAC price catalog as customer cents only: each row
        carries `customer_cents` (the branch price: the SRP raised by `priceAdjustmentPercent`,
        then its override; `null` when the row has no customer price or no baseline) and
        never the install cost, the rep baseline or the SRP/override split, for any seat.
        The browser matches a system to a line with the same rule the server prices with
        (exact series name or alias, same brand and system type). A matched system is
        priced from its line, ahead of the zone table and the offer rollup; its cents
        already carry the branch price adjustment (POR-2411).
        State fees are listed for information here; a quote charges them as separate fee lines
        (A17 B3), computed by the quote, not by this payload.

        Each `systems[].components[]` entry is `{ itemId, quantity }` plus three optional keys read from the
        BOM part's `account_pricebook_items` row (POR-2561; a LEFT JOIN, so an archived or missing part keeps
        its component with these keys `null`): `model` (trimmed `model_number`, `null` when blank),
        `componentType` (`pricing_metadata.cpm.component_type` verbatim, e.g. "Indoor Unit") and `maxBtu`
        (`pricing_metadata.cpm.max_btu_capacity` as a positive integer BTU, accepting a number or a string such
        as "12,000"; `null` when absent). The showroom folds them into the itemised equipment list; pricing
        ignores them.

        `systems[].metadata.ahri` is the AHRI number the quote prints: the manual number an owner or admin set
        (`PUT /v1/pricebook/items/{id}/ahri`) when there is one, else the workbook number, else `null`;
        `metadata.ahriOverride` is present only when a manual number is set. A change busts the ETag.

        `lead_id` (optional, uuid): project `catalogLines` with that lead's rep's personal overrides
        (A17 B2): the lead's assignee, else its creator, else none (account prices). The lead is bound with the
        price-quote route's fences (tenant user holding leads:read, branch and assignment visibility); a lead
        the caller cannot see, another tenant's, a deleted one or an unknown one is a 404 lead_not_found,
        never a silent fall back to account prices. Without `lead_id` the payload carries account prices only.
        `priceAdjustmentPercent` (and the branch price in `catalogLines`) is the lead's branch percent with
        `lead_id`, else the caller's seat branch percent (POR-2411); Save and Sign use the same lead branch.
        The ETag is a hash of the body, so it differs between two reps' leads.

        Conditional GET: the response carries a strong `ETag` — a hash of the
        exact bytes sent, so it differs between a cost-bearing and a
        cost-redacted seat — and `Cache-Control: private, max-age=0,
        must-revalidate`. A request whose `If-None-Match` matches gets `304`
        with no body. Unlike the sibling workspace routes this one is tagged
        because the payload is a few hundred kilobytes for a real tenant and
        the catalog moves rarely (an import, or an owner or admin editing a system's AHRI number).
      tags: [ShowroomCatalog]
      parameters:
        - name: key
          in: path
          required: true
          schema: { type: string, enum: [hvac] }
        - name: lead_id
          in: query
          required: false
          schema: { type: string, format: uuid }
        - name: If-None-Match
          in: header
          required: false
          schema: { type: string }
      responses:
        '200':
          description: CPM offers, systems, contractor defaults and installers
          headers:
            ETag:
              description: Strong validator over the exact response bytes.
              schema: { type: string }
            Cache-Control:
              schema: { type: string }
          content:
            application/json:
              schema:
                type: object
                required: [offers, systems, defaults, contractors]
                properties:
                  offers: { type: array, items: { type: object } }
                  systems: { type: array, items: { type: object } }
                  defaults: { type: array, items: { type: object } }
                  contractors: { type: array, items: { type: object } }
                  catalogLines:
                    type: array
                    items: { $ref: '#/components/schemas/HvacCatalogPricingLine' }
                  zonePrices:
                    type: array
                    items:
                      type: object
                      additionalProperties: false
                      required: [brand, state, contractorId, zones, retailCents, countPer, effectiveFrom, effectiveTo]
                      properties:
                        brand: { type: string }
                        state: { type: [string, 'null'] }
                        contractorId: { type: [string, 'null'], format: uuid }
                        zones: { type: integer, minimum: 1 }
                        retailCents: { type: integer, minimum: 1 }
                        countPer: { type: string, enum: [system, project] }
                        effectiveFrom: { type: string, format: date }
                        effectiveTo: { type: [string, 'null'], format: date }
        '304':
          description: Not modified — the client's If-None-Match matches the current ETag
          headers:
            ETag:
              schema: { type: string }
            Cache-Control:
              schema: { type: string }
        '400': { description: Invalid showroom key or lead_id }
        '401': { description: Unauthorized }
        '404': { description: lead_not_found (lead_id names a lead the caller cannot see) }
        '500': { description: CPM pricing schema drift (non-production only; validation is skipped in production) }
        '503': { description: Database unavailable }

  /showroom-catalog/workspace/hvac/price-quote:
    post:
      operationId: postShowroomHvacPriceQuote
      summary: Server price for an HVAC quote (Step 2 price engine)
      description: |
        Requires `pricebooks:read`, `leads:read` and `estimates:read` (all three):
        the quote reads the lead and its HVAC estimate. Tenant users only; an
        integration principal is refused. Read-only: a POST only because the body
        does not fit a query string. It writes nothing, so it takes no
        `Idempotency-Key` and stores no idempotency response.

        The caller names the lead, the cart lines (item id and quantity), the
        item ids to price on their own for the plan builder (`candidates`), and
        the rep's requested sales discount as a percent. The server derives the
        rest: the lead's branch prices systems, the rep's seat prices add-ons and
        sets the discount maximum, and the resolution state comes from the
        lead's HVAC estimate (its address, else its saved showroom address). A
        lead the caller cannot see, or an `estimateId` that is not that lead's
        HVAC estimate, is a `404`.

        Each line carries server cents and a `trail` of the rules that set them
        (`offer_rollup`, `zone_table`, `catalog_table`, `installer_reprice`,
        `branch_adjustment`, `additional_zone`, `addon_form`); the totals carry `sales_discount_cap`
        and, when the quote has state fees, `state_fees`.
        Every system takes the company/branch price adjustment (engine v6, POR-2411). A system the
        HVAC price catalog prices (`catalog_table`: SRP plus its override) takes it on each row's SRP
        before the override (`branch_adjustment.basis: before_override`); a zone-priced system on its
        table retail. The state
        fees of the catalog tables that priced the quote are charged once per
        quote per fee label (the largest amount when a label repeats), on top of
        the discounted subtotal: `totals.totalCents` includes them, the sales
        discount is not taken on them, and they are not in any system's price. `engineVersion` is `hvac-price-engine.v10`. A system no installer carries in the client's state (A29, POR-2562) is still priced, from the catalog or from another state's existing price: its line has no `installer`, and its `offer_rollup` step has status `no_licensed_contractor` and, when the price came from another state, `borrowedFromState` (the state code). A `catalog_table` step carries `default_override_source` (`rep_default` or `company_default`) only when a default override percent (A22) priced at least one size of that system; it never carries the percent. It carries `sub_account_override: true` (POR-2458) only when the sub-account (branch) price layer applied to at least one size of that system; it never carries a percent, cents or baseline. Two or more ducted systems on one catalog line (A20): the highest-priced one keeps its table price and every other is charged the line's Additional zone price (an `additional_zone` step after `branch_adjustment`, with the line id and cents only); those lines and add-ons are not in the discount base. `totals.maxSalesDiscountPercent` is the most the rep may discount the quote (the lower of the seat maximum and the rep baseline limit), and the `sales_discount_cap` step says which one binds. A line the server cannot price is
        listed in `refusals` and `totals` is then `null`. A system line is priced
        once as a whole: a `qty` other than 1 on a system line is refused as
        `system_qty_unsupported` (add-ons keep their quantity). `pricedAt` is when
        the server priced the quote and is never part of anything stored.

        `costCents`, `commissionCents` and `vendorId` are present on a line only
        for principals holding `pricebook:cost:read`; otherwise the fields are
        absent. No trail step carries cost or commission.
      tags: [ShowroomCatalog]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [leadId, lines]
              properties:
                leadId: { type: string, format: uuid }
                estimateId: { type: string, format: uuid }
                lines:
                  type: array
                  maxItems: 200
                  items:
                    type: object
                    additionalProperties: false
                    required: [lineId, itemId, qty]
                    properties:
                      lineId: { type: string, minLength: 1, maxLength: 120 }
                      itemId: { type: string, format: uuid }
                      qty: { type: integer, minimum: 1, maximum: 999 }
                candidates:
                  type: array
                  maxItems: 500
                  items: { type: string, format: uuid }
                adjustments:
                  type: array
                  maxItems: 1
                  items:
                    type: object
                    additionalProperties: false
                    required: [kind, percent]
                    properties:
                      kind: { type: string, enum: [sales_discount_percent] }
                      percent: { type: number, minimum: 0, maximum: 100, multipleOf: 0.5 }
      responses:
        '200':
          description: Server-priced lines, candidates, refusals and totals
          content:
            application/json:
              schema:
                type: object
                required: [engineVersion, lines, candidates, refusals, totals, pricedAt]
                properties:
                  engineVersion: { type: string }
                  lines:
                    type: array
                    items:
                      type: object
                      required: [lineId, unitCents, totalCents, trail]
                      properties:
                        lineId: { type: string }
                        systemKey: { type: string }
                        unitCents: { type: [integer, 'null'] }
                        totalCents: { type: [integer, 'null'] }
                        installer:
                          type: object
                          properties:
                            contractorId: { type: string }
                            status: { type: string, enum: [match, placeholder, no_licensed_contractor] }
                        trail: { type: array, items: { type: object } }
                        costCents: { type: [integer, 'null'] }
                        commissionCents: { type: [integer, 'null'] }
                        vendorId: { type: [string, 'null'] }
                  candidates:
                    type: array
                    items:
                      type: object
                      required: [itemId, unitCents]
                      properties:
                        itemId: { type: string, format: uuid }
                        systemKey: { type: string }
                        unitCents: { type: [integer, 'null'] }
                        refusal: { type: string, enum: [unpriceable, no_offer_in_state, addon_no_price, system_qty_unsupported] }
                  refusals:
                    type: array
                    items:
                      type: object
                      required: [lineId, code]
                      properties:
                        lineId: { type: string }
                        code: { type: string, enum: [unpriceable, no_offer_in_state, addon_no_price, system_qty_unsupported] }
                  totals:
                    type: [object, 'null']
                    properties:
                      subtotalCents: { type: integer }
                      salesDiscountCents: { type: integer }
                      totalCents: { type: integer }
                      maxSalesDiscountPercent: { type: number, minimum: 0, maximum: 100 }
                      trail: { type: array, items: { type: object } }
                  pricedAt: { type: string, format: date-time }
        '400': { description: Validation error (including more than 200 lines or 500 candidates) }
        '401': { description: Unauthorized }
        '403': { description: "Not a tenant user, or missing pricebooks:read, leads:read or estimates:read" }
        '404': { description: "Lead not visible to the caller, or estimate not the lead's HVAC estimate" }
        '503': { description: Database unavailable }

  /showroom-catalog/workspace/{key}/reset:
    post:
      operationId: resetShowroomCatalog
      summary: Remove some or all of one showroom's catalog so it can be re-imported (POR-2421)
      description: |
        Requires `pricebooks:write`, tenant users only, and a fresh step-up (15 minutes, WebAuthn or TOTP)
        when step-up is required. Soft-deletes; quotes and agreements keep their prices.

        `sections` limits the reset: `items` (the industry's pricebook rows), `showroom` (size tiers,
        package groups, add-ons), `price_master` (systems, components, offers, vendor costs; HVAC also
        contractor defaults, zone prices and SKU price overrides) and `price_catalog` (HVAC only: the HVAC
        price catalog). Omitted means all four. `items` requires `price_master`: a selection without it
        is refused with 409 `reset_sections_incomplete` and nothing is deleted. The audit event
        `showroom_catalog.reset` records the sections reset.
      tags: [ShowroomCatalog]
      parameters:
        - name: key
          in: path
          required: true
          schema: { type: string, enum: [adu, hvac, renovation, generac, roofing, water-filtration, solar] }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [confirm]
              properties:
                confirm:
                  type: string
                  description: Must repeat the showroom key in the path.
                sections:
                  type: array
                  minItems: 1
                  items: { type: string, enum: [items, showroom, price_master, price_catalog] }
      responses:
        '200':
          description: The receipt (rows removed per section, and the sections reset) and the new workspace
          content:
            application/json:
              schema:
                type: object
                required: [receipt, workspace]
                properties:
                  receipt:
                    type: object
                    properties:
                      showroomKey: { type: string }
                      industry: { type: string }
                      sections:
                        type: array
                        items: { type: string, enum: [items, showroom, price_master, price_catalog] }
                  workspace: { type: object }
        '400': { description: "Validation error, an empty or unknown sections list, or a confirmation that does not match the key" }
        '401': { description: "Unauthorized, or a fresh step-up is required" }
        '403': { description: "Not a tenant user, or missing pricebooks:write" }
        '409':
          description: A price book write is in progress (`pricebook_write_in_progress`), or the sections miss one they require (`reset_sections_incomplete`)
          content:
            application/json:
              schema:
                type: object
                properties:
                  error: { type: string, enum: [pricebook_write_in_progress, reset_sections_incomplete] }
                  required:
                    type: array
                    items: { type: string, enum: [items, showroom, price_master, price_catalog] }
                  message: { type: string }
        '503': { description: Database unavailable }

  /showroom-catalog/workspace/{key}/financing:
    get:
      operationId: getShowroomFinancing
      summary: Financing partner cards for one dashboard showroom
      tags: [ShowroomCatalog]
      parameters:
        - name: key
          in: path
          required: true
          schema: { type: string, enum: [adu, hvac, renovation] }
      responses:
        '200':
          description: Financing partners for the showroom
        '401': { description: Unauthorized }
        '503': { description: Database unavailable }
    put:
      operationId: putShowroomFinancing
      summary: Replace financing partner cards for one dashboard showroom
      tags: [ShowroomCatalog]
      parameters:
        - name: key
          in: path
          required: true
          schema: { type: string, enum: [adu, hvac, renovation] }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [partners]
              properties:
                partners:
                  type: array
                  items: { type: object }
      responses:
        '200':
          description: Updated financing partners
        '400': { description: Validation error }
        '401': { description: Unauthorized }
        '404': { description: Showroom product not found }
        '503': { description: Database unavailable }

  /agreements/{id}/artifacts:
    get:
      operationId: listAgreementArtifacts
      summary: Read stored agreement stages and proposal acknowledgment together
      description: |
        Tenant staff require contracts:read. An estimate: or lead: parent also
        requires customers:read. A contract: parent retains the contract's project access
        rules and also applies the original estimate's record/branch/assignment
        visibility. Stored source UUIDs and revisions survive conversion. Reads
        never regenerate provider PDFs or move attachment ownership. Private
        evidence is available only through its authorized download URL.
      tags: [Agreements]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, pattern: '^(estimate|lead|contract):[0-9a-fA-F-]{36}$' }
      responses:
        '200':
          description: Stored stages ordered by revision and signing stage
          content:
            application/json:
              schema: { $ref: '#/components/schemas/AgreementArtifactsReply' }
        '401': { description: Unauthorized }
        '403': { description: Tenant staff and required scopes only }
        '404': { description: Parent not found or outside original and linked record access }
        '503': { description: Database unavailable }
  /agreements/{id}/artifacts/{artifactId}/{kind}/preview:
    get:
      operationId: previewAgreementArtifact
      summary: Preview an authorized stored PDF or completion certificate
      description: |
        Uses the same parent and artifact authorization as the shared list.
        Only pdf and certificate kinds may be framed by the same origin.
        Evidence preview returns404. Stored agreement PDFs are checked against
        their immutable SHA-256; no live-render fallback occurs.
      tags: [Agreements]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string }
        - name: artifactId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: kind
          in: path
          required: true
          schema: { type: string, enum: [pdf, evidence, certificate] }
      responses:
        '200':
          description: Exact stored PDF bytes with private no-store and same-origin framing headers
          content:
            application/pdf:
              schema: { type: string, format: binary }
        '400': { description: Invalid artifact id or kind }
        '401': { description: Unauthorized }
        '403': { description: Insufficient scope or cross-origin preview request }
        '404': { description: Parent or artifact hidden; object missing; evidence preview unsupported }
        '409': { description: Stored artifact integrity failure }
        '503': { description: Database unavailable }
  /agreements/{id}/artifacts/{artifactId}/{kind}/download:
    get:
      operationId: downloadAgreementArtifact
      summary: Download stored PDF bytes or decrypt authorized staff evidence
      description: |
        Requires the same parent and artifact authority as the shared list.
        PDF and certificate downloads preserve exact stored bytes. Evidence
        must be an identified KEK encryption envelope and is decrypted server-side
        for a tenant staff JSON attachment. Plaintext fallback and evidence framing
        are forbidden. Customer and integration identities cannot use this route.
      tags: [Agreements]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string }
        - name: artifactId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: kind
          in: path
          required: true
          schema: { type: string, enum: [pdf, evidence, certificate] }
      responses:
        '200':
          description: Private no-store attachment with framing denied
          content:
            application/pdf:
              schema: { type: string, format: binary }
            application/json:
              schema: { type: object, additionalProperties: true }
        '400': { description: Invalid artifact id or kind }
        '401': { description: Unauthorized }
        '403': { description: Tenant staff and required scopes only }
        '404': { description: Parent or artifact hidden; stored object missing }
        '409': { description: Artifact integrity or encrypted evidence validation failure }
        '503': { description: Database unavailable }

  /showroom/agreements/proposal-acknowledgments:
    post:
      operationId: saveShowroomProposalAcknowledgment
      summary: Save bilateral proposal consent without closing a deal
      description: |
        Saves the frozen estimate revision as an immutable proposal acknowledgment
        PDF with encrypted signature/consent evidence. Both local signatures are
        required. No contract signature, customer/project creation, lead promotion,
        economics, or closed-won effects occur. Remote agreement signatures remain separate.
        Requires contracts:sign and contracts:write, tenant_user authentication,
        and the existing 300-second WebAuthn/TOTP step-up posture.
      tags: [Showroom]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [estimate_id, expected_content_revision, saved_draft_sha256, signatures, consent_ack]
              properties:
                estimate_id: { type: string, format: uuid }
                expected_content_revision: { type: integer, minimum: 0 }
                saved_draft_sha256: { type: string, pattern: '^[a-f0-9]{64}$' }
                consent_ack: { type: boolean, enum: [true] }
                signatures:
                  type: object
                  additionalProperties: false
                  required: [rep, homeowner]
                  properties:
                    rep:
                      type: object
                      additionalProperties: false
                      required: [signature_data, signature_method, signer_typed_name]
                      properties:
                        signature_data: { type: string, minLength: 1, maxLength: 262144 }
                        signature_method: { type: string, enum: [pencil, typed] }
                        signer_typed_name: { type: string, minLength: 1, maxLength: 300 }
                    homeowner:
                      type: object
                      additionalProperties: false
                      required: [signature_data, signature_method, signer_typed_name]
                      properties:
                        signature_data: { type: string, minLength: 1, maxLength: 262144 }
                        signature_method: { type: string, enum: [pencil, typed] }
                        signer_typed_name: { type: string, minLength: 1, maxLength: 300 }
      responses:
        '200':
          description: Proposal acknowledgment and evidence saved
          content:
            application/json:
              schema:
                type: object
                additionalProperties: false
                required: [artifactId, purpose, status, closed]
                properties:
                  artifactId: { type: string, format: uuid }
                  purpose: { type: string, enum: [proposal_acknowledgment] }
                  status: { type: string, enum: [acknowledged] }
                  closed: { type: boolean, enum: [false] }
        '400': { description: 'Invalid source tuple, missing signatures, or missing Idempotency-Key' }
        '401': { description: Unauthorized }
        '403': { description: 'Wrong principal, invalid actor, insufficient scope, or step-up required' }
        '404': { description: Estimate not found or outside record/branch write access }
        '409': { description: Stale or invalid frozen source }
        '422': { description: Signer name does not match the frozen homeowner or authenticated actor }
        '503': { description: Archive unavailable; no saved artifact is reported }

  /showroom/agreements/{leadId}/sign:
    post:
      operationId: signShowroomAgreementByLead
      summary: Retired local agreement execution endpoint
      description: Returns proposal_acknowledgment_required without mutation. Save local proposal consent through proposal-acknowledgments; execute the agreement through remote signing.
      deprecated: true
      tags: [Showroom]
      parameters:
        - name: leadId
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object }
      responses:
        '400': { description: Invalid lead id or request }
        '401': { description: Unauthorized }
        '403': { description: Forbidden or step-up required }
        '409': { description: proposal_acknowledgment_required; no deal-closing effects }

  /showroom/agreements/{leadId}/save:
    post:
      operationId: saveShowroomAgreementByLead
      summary: Persist the signature-free, version-fenced showroom agreement draft
      description: |
        Explicit legal Save boundary for a versioned showroom draft. Requires an
        authenticated tenant user with both `leads:write` and `contracts:write`.
        The draft is strict and signature-free; Save never builds or signs a
        contract. `expected_content_revision` must match the selected estimate.
      tags: [Showroom]
      security:
        - bearerToken: []
        - sessionCookie: []
      parameters:
        - name: leadId
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ShowroomAgreementSaveRequest' }
      responses:
        '200':
          description: Draft saved and lead is agreement_pending
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ShowroomAgreementSaveResult' }
        '400': { description: Strict request or draft validation error }
        '401': { description: Unauthorized; tenant authentication is required }
        '404': { description: 'Lead or estimate not found, or not visible to the tenant user' }
        '409': { description: Stale content revision or invalid legal source/lifecycle conflict }
        '422': { description: Draft lead does not match the path leadId }
        '503': { description: Database unavailable }

  /showroom/agreements/{leadId}/cancel-draft:
    post:
      operationId: cancelShowroomAgreementDraftByLead
      summary: Withdraw the current unsigned saved showroom proposal
      description: |
        Requires a tenant user with both `leads:write` and `contracts:write`
        and current record/branch write access. The exact content revision and
        saved hash must match the current editable version. Refuses accepted
        families, linked contracts and signing runs. Clears only the saved legal
        packet and its tuple, preserving quote content, pricing and legal history.
        Moves an agreement_pending lead to appointment_held only when no other
        active proposal, contract or signing run holds that lead pending.
        A retry with the same key/body returns the original receipt without
        changing a newer saved packet. Clients must not adopt an older returned
        revision over a newer local version. No signing or provider send occurs.
      tags: [Showroom]
      security:
        - bearerToken: []
        - sessionCookie: []
      parameters:
        - name: leadId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: Idempotency-Key
          in: header
          required: true
          schema: { type: string, minLength: 1, maxLength: 200, pattern: '^[!-~]+$' }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ShowroomAgreementCancelDraftRequest' }
      responses:
        '200':
          description: Saved packet withdrawn, or the original successful cancellation receipt replayed
          headers:
            Idempotency-Replayed:
              description: Present as true when a completed cancellation is replayed
              schema: { type: string, enum: ['true'] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ShowroomAgreementCancelDraftResult' }
        '400': { description: 'Invalid request tuple, lead id or Idempotency-Key' }
        '401': { description: Tenant authentication is required }
        '403': { description: Wrong principal or insufficient write scopes }
        '404': { description: Lead or estimate not found or outside current record/branch write access }
        '409':
          description: stale_version with optional content_revision, or invalid_legal_source with a lifecycle reason; no mutation
        '422': { $ref: '#/components/responses/IdempotencyConflict' }
        '503': { description: Database unavailable or record busy; retry the same request and key }

  /showroom/client-start:
    post:
      operationId: startShowroomClient
      summary: Mint a linked lead, customer, draft estimate, and agreement-pending skeleton from the showroom New Lead/Customer form
      tags: [Showroom]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [trade, given_name, family_name, email, phone, address]
              properties:
                trade: { type: string, enum: [adu, hvac, renovation, generac, roofing, water-filtration, solar] }
                given_name: { type: string, minLength: 1 }
                family_name: { type: string, minLength: 1 }
                email: { type: string, format: email }
                phone: { type: string }
                address:
                  type: object
                  required: [street, city, state, zip]
                  properties:
                    street: { type: string }
                    city: { type: string }
                    state: { type: string }
                    zip: { type: string }
                    country: { type: string }
                    lat: { type: string, nullable: true }
                    lng: { type: string, nullable: true }
      responses:
        '201':
          description: Lead, customer, and draft estimate created
          content:
            application/json:
              schema:
                type: object
                required: [lead_id, customer_id, estimate_id, person_id, status, sub_account_id]
                properties:
                  lead_id: { type: string, format: uuid }
                  customer_id: { type: string, format: uuid }
                  estimate_id: { type: string, format: uuid }
                  person_id: { type: string, format: uuid }
                  status: { type: string, enum: [appointment_held, agreement_pending] }
                  sub_account_id:
                    type: string
                    format: uuid
                    nullable: true
                    description: Branch (sub-account) the new lead was stored in; null for an account-level lead.
                  lifecycle_mode:
                    type: string
                    enum: [versioned_draft_v1]
                    nullable: true
                    description: Present when the versioned showroom lifecycle is active.
                  reused_customer:
                    type: boolean
                    description: True when an existing customer (matched by normalized email) was reused instead of minting a new one.
        '400': { description: Validation error }
        '401': { description: Unauthorized }
        '503': { description: Database unavailable }

  /showroom/estimates/initialize:
    post:
      operationId: initializeShowroomLead
      summary: Initialize or resume the versioned showroom estimate for a visible lead
      description: Creates the v1 estimate or returns the eligible current version. The route is feature-gated and requires leads:write, customers:write, and estimates:write.
      tags: [Showroom]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [lead_id, showroom_key]
              properties:
                lead_id: { type: string, format: uuid }
                showroom_key: { type: string, enum: [adu, hvac, renovation] }
      responses:
        '200':
          description: Existing current version reused or cloned
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ShowroomInitializeResult' }
        '201':
          description: Initial v1 estimate created
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ShowroomInitializeResult' }
        '400': { description: Validation error }
        '401': { description: Unauthorized }
        '404': { description: Lead not found or not visible }
        '409': { description: 'Identity or estimate lifecycle conflict, including accepted_estimate_conflict' }
        '503': { description: Showroom estimates unavailable }

  /showroom/estimates/sync:
    post:
      operationId: syncShowroomEstimate
      summary: Persist the current showroom configuration onto the lead's draft estimate
      description: For versioned writes, expected_content_revision and recovery_idempotency_key are required together. On a stale revision, the server constructs the caller-owned recovery record from the typed request fields; clients never submit a recovery snapshot. A customer discount cart line may carry discount with kind (percent or fixed), value, and optional scope_line_ids. HVAC accepts percent intent on its sales adjustment only; renovation scopes stay within the matching project. The server computes discounts from eligible full-price lines and excludes add-ons. Requires leads:write and estimates:write.
      tags: [Showroom]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [lead_id, showroom_key, config]
              dependentRequired:
                expected_content_revision: [recovery_idempotency_key]
                recovery_idempotency_key: [expected_content_revision]
              properties:
                lead_id: { type: string, format: uuid }
                showroom_key: { type: string, enum: [adu, hvac, renovation] }
                config: { type: object, additionalProperties: true }
                expected_content_revision: { type: integer, minimum: 0 }
                recovery_idempotency_key: { type: string, minLength: 1, maxLength: 200 }
                estimate_id:
                  type: string
                  format: uuid
                  description: The estimate version the client believes it is editing. Non-roofing showroom keys are refused with head_changed when this does not match the family's current head.
                base_content_sha256:
                  type: string
                  pattern: '^[a-f0-9]{64}$'
                  description: The content_sha256 this client last received. Lets an out-of-date write be fast-forwarded when only office fields moved.
                known_saved_draft_sha256:
                  type: string
                  pattern: '^[a-f0-9]{64}$'
                  nullable: true
                  description: The saved-agreement hash this client knows. A saved agreement the client does not know about is never invalidated by a fast-forward.
                recovery_only:
                  type: boolean
                  description: Store the request as a recovery draft on the current versioned non-roofing draft head and answer 409 stale_version; never write (refused with 409 estimate_not_editable for roofing or without a versioned draft head; requires recovery_idempotency_key).
      responses:
        '200':
          description: Draft estimate created or updated with the showroom snapshot
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ShowroomEstimateSyncResult' }
        '400': { description: Validation error }
        '401': { description: Unauthorized }
        '404': { description: "Lead not found, or estimate_id is not in this lead's showroom family (estimate_not_found)" }
        '409':
          description: Typed stale_version conflict, typed head_changed conflict, or a non-stale estimate lifecycle conflict
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: '#/components/schemas/ShowroomEstimateSyncConflict'
                  - $ref: '#/components/schemas/ShowroomEstimateHeadChanged'
        '422':
          description: >-
            HVAC cart refused (POR-2206); nothing was written. hvac_negative_line — a line
            other than the sales adjustment has a negative price; hvac_sales_adjustment_invalid —
            a second sales-adjustment line, or one not shaped as the showroom sends it;
            hvac_addon_no_price — an add-on line whose tenant price-book row has no price
            (POR-2205; never booked at $0 or at the browser's cents); hvac_duplicate_line_id —
            two cart lines share one id. A sales adjustment above the tenant maximum is not
            refused: it is reduced to the maximum.
          content:
            application/json:
              schema:
                type: object
                required: [error, message]
                properties:
                  error: { type: string, enum: [hvac_negative_line, hvac_sales_adjustment_invalid, hvac_addon_no_price, hvac_duplicate_line_id] }
                  message: { type: string }

  /showroom/estimates/{id}/versions:
    post:
      operationId: createShowroomEstimateVersion
      summary: Create a version from a historical estimate or resolve caller-owned stale edits
      description: Requires leads:write and estimates:write. Historical mode branches the requested estimate; preserve_stale_edits resolves the supplied recovery record only when its base_estimate_id matches the path.
      tags: [Showroom]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              oneOf:
                - type: object
                  additionalProperties: false
                  required: [mode, expected_head_id, expected_head_content_revision, expected_head_status]
                  properties:
                    mode: { type: string, enum: [historical] }
                    expected_head_id: { type: string, format: uuid }
                    expected_head_content_revision: { type: integer, minimum: 0 }
                    expected_head_status: { type: string, minLength: 1 }
                - type: object
                  additionalProperties: false
                  required: [mode, recovery_id, base_estimate_id, expected_head_id, expected_head_content_revision, expected_head_status]
                  properties:
                    mode: { type: string, enum: [preserve_stale_edits] }
                    recovery_id: { type: string, format: uuid }
                    base_estimate_id: { type: string, format: uuid }
                    expected_head_id: { type: string, format: uuid }
                    expected_head_content_revision: { type: integer, minimum: 0 }
                    expected_head_status: { type: string, minLength: 1 }
      responses:
        '201':
          description: New estimate version created
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ShowroomVersionResult' }
        '400': { description: Validation error }
        '401': { description: Unauthorized }
        '404': { description: Estimate or caller-owned recovery not found or not visible }
        '409': { description: 'Version head, terminal, accepted-estimate, or recovery conflict, including recovery_base_not_head when the recovery was not written against the current head' }
        '503': { description: Database unavailable }

  /showroom/estimates/{id}/restore:
    get:
      operationId: restoreShowroomEstimate
      summary: Return the saved showroom configuration for Open in Showroom
      description: Side-effect free restore of the requested visible estimate, including version metadata, the permitted version action, and the caller's own pending changes on the current draft head from the last 24 hours that differ from it (empty for any other estimate). Requires leads:read and estimates:read.
      tags: [Showroom]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Restore snapshot
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ShowroomEstimateRestore' }
        '401': { description: Unauthorized }
        '404': { description: Estimate not found }
        '409': { description: Estimate has no usable showroom snapshot }

  /showroom/estimate-recoveries/{id}:
    delete:
      operationId: discardShowroomEstimateRecovery
      summary: Explicitly discard a caller-owned stale showroom recovery record
      description: Requires leads:write and estimates:write. The recovery and its base estimate must both remain visible to the caller.
      tags: [Showroom]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Recovery record discarded
          content:
            application/json:
              schema:
                type: object
                required: [recovery]
                properties:
                  recovery: { $ref: '#/components/schemas/ShowroomRecoveryView' }
        '401': { description: Unauthorized }
        '404': { description: Recovery not found or not visible }
        '503': { description: Database unavailable }

  /showroom/estimates/{id}/history:
    get:
      operationId: getShowroomQuoteHistory
      summary: Quote history for a visible showroom estimate family
      description: Requires leads:read and estimates:read. Lists every copy in the estimate's family with who last changed it, and pending unexpired unsaved changes. Reps see only their own unsaved changes; account-level owners and admins also see other people's. Editors are named by full name only, never by email. No snapshot payload is returned.
      tags: [Showroom]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: Quote history
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ShowroomQuoteHistory' }
        '401': { description: Unauthorized }
        '404': { description: 'Estimate not found, not a showroom estimate, or not visible' }
        '503': { description: Database unavailable }

  /showroom/estimates/{id}/history/{recoveryId}/restore:
    post:
      operationId: putBackShowroomQuoteChanges
      summary: Put pending unsaved changes back into the current quote
      description: Requires leads:write and estimates:write. Allowed for the person who made the changes or an account-level owner or admin; anyone else gets 404. The changes must be based on the current copy, which must still be editable; the result is a new current copy.
      tags: [Showroom]
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: recoveryId
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '201':
          description: Changes put back as a new current copy
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ShowroomQuoteHistoryRestoreResponse' }
        '401': { description: Unauthorized }
        '404': { description: Estimate or unsaved changes not found or not visible }
        '409': { description: 'recovery_base_not_head, or a head, terminal-lead, expiry, or agreement conflict' }
        '503': { description: Database unavailable }

  /showroom/agreements:
    post:
      operationId: createShowroomAgreement
      summary: Sell-to-sign orchestration - create customer + estimate + project + contract in one saga (POR-464)
      tags: [Showroom]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [client, address, cart]
              properties:
                client:
                  type: object
                  properties:
                    matched_customer_id: { type: string, format: uuid }
                    new_contact:
                      type: object
                      required: [name, email, phone]
                      properties:
                        name: { type: string }
                        email: { type: string, format: email }
                        phone: { type: string }
                address:
                  type: object
                  required: [street, city, state, zip]
                  properties:
                    street: { type: string }
                    city: { type: string }
                    state: { type: string }
                    zip: { type: string }
                    country: { type: string }
                    lat: { type: string, nullable: true }
                    lng: { type: string, nullable: true }
                cart:
                  type: object
                  required: [model, total_cents, source]
                  properties:
                    model:
                      type: object
                      required: [name, price_cents]
                      properties:
                        item_id: { type: string, format: uuid, nullable: true }
                        name: { type: string }
                        price_cents: { type: integer }
                    addons:
                      type: array
                      items:
                        type: object
                        required: [id, name, price_cents]
                        properties:
                          id: { type: string }
                          item_id: { type: string, format: uuid, nullable: true }
                          name: { type: string }
                          price_cents: { type: integer }
                    total_cents: { type: integer }
                    source: { type: string, enum: [pricebook] }
                    configuration:
                      type: object
                      description: Optional showroom configuration frozen with the agreement and signed contract.
                      properties:
                        manufacturer: { type: string }
                        system: { type: string }
                        capacity: { type: string }
                        zones: { type: string }
                        exterior_style:
                          type: string
                          enum: [modern, farmhouse, ranch]
                          description: Client-selected illustrative ADU exterior design style.
                        details:
                          type: array
                          items:
                            type: object
                            required: [label, value]
                            properties:
                              label: { type: string }
                              value: { type: string }
                signing_mode: { type: string, enum: [single] }
      responses:
        '201': { description: Agreement created }
        '400': { description: Validation error }
        '401': { description: Unauthorized }
        '409':
          description: >-
            Conflict - stale or invalid saved legal source, CPM freeze refusal, or
            `quote_expired` on build + send (the saved HVAC quote is older than 720
            hours, or its Save time is unknown; body `{ error, request_id }`).
            Legacy Save for an existing lead with a persisted versioned estimate
            returns `{ error: invalid_legal_source, reason: versioned_lead_requires_save,
            request_id }` without changing the lead or estimate. Use the explicit
            `/showroom/agreements/{lead_id}/save` endpoint with the current estimate.
            Hidden or unbuildable leads return `lead_not_buildable` before this reason
            can disclose a persisted estimate.
        '422': { description: Pricebook item not found }
        '503': { description: Database unavailable }
  /showroom/agreement-pdf:
    post:
      operationId: generateShowroomAgreementPdf
      summary: Generate a Service Agreement PDF
      tags: [Showroom]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [company, client, salesRepName, contractDate, paymentType, deposit_cents, total_cents, lineItems, signatures]
              properties:
                company:
                  type: object
                  required: [name]
                  properties:
                    name: { type: string }
                    license: { type: string }
                    address: { type: string }
                    phone: { type: string }
                    email: { type: string }
                client:
                  type: object
                  required: [name]
                  properties:
                    name: { type: string }
                    address: { type: string }
                    city: { type: string }
                    state: { type: string }
                    zip: { type: string }
                    email: { type: string }
                    phone: { type: string }
                salesRepName: { type: string }
                contractDate: { type: string }
                paymentType: { type: string }
                deposit_cents: { type: integer }
                total_cents: { type: integer }
                paymentSchedule:
                  type: array
                  items:
                    type: object
                    required: [label, amount_cents, dueDate]
                    properties:
                      label: { type: string }
                      amount_cents: { type: integer }
                      dueDate: { type: string }
                lineItems:
                  type: array
                  items:
                    type: object
                    required: [label, price_cents]
                    properties:
                      label: { type: string }
                      price_cents: { type: integer }
                configuration:
                  type: array
                  description: Frozen label/value rows displayed in the agreement configuration summary.
                  items:
                    type: object
                    required: [label, value]
                    properties:
                      label: { type: string }
                      value: { type: string }
                scopeText: { type: string }
                warrantyText: { type: string }
                termsText: { type: string }
                signatures:
                  type: object
                  required: [repName]
                  properties:
                    repName: { type: string }
                    repSignedAt: { type: string, nullable: true }
                    repSignatureData: { type: string }
                    customerName: { type: string }
                    customerAckAt: { type: string, nullable: true }
                    customerSignatureData: { type: string }
      responses:
        '200':
          description: PDF document
          content:
            application/pdf:
              schema:
                type: string
                format: binary
        '400': { description: Validation error }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }

  /showroom/agreement-templates:
    get:
      operationId: listShowroomAgreementTemplates
      summary: List effective agreement template coverage (managed + system) for the tenant
      tags: [Showroom]
      responses:
        '200':
          description: Template coverage rows
          content:
            application/json:
              schema:
                type: object
                required: [items]
                properties:
                  items: { type: array, items: { type: object } }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '503': { description: Database unavailable }

  /showroom/agreement-templates/effective:
    get:
      operationId: getEffectiveShowroomAgreementTemplate
      summary: Resolve the managed-first effective template pack for a trade+state
      tags: [Showroom]
      parameters:
        - name: trade
          in: query
          required: true
          schema: { type: string, enum: [hvac, adu, remodeling] }
        - name: state
          in: query
          required: false
          schema: { type: string, minLength: 2, maxLength: 2 }
      responses:
        '200':
          description: Effective pack (or null when unsupported)
          content:
            application/json:
              schema:
                type: object
                required: [pack, source]
                properties:
                  pack: { type: object, nullable: true }
                  source: { type: string, enum: [managed, static, none] }
        '400': { description: Validation error }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }

  # ── HVAC pricebook + rebate engine (POR-631/POR-632, plan 2026-06-24-001) ──
  # Both routers are always on.
  /hvac-pricebook/catalog:
    get:
      operationId: listHvacPricebookCatalog
      summary: List the curated HVAC reference catalog (price_cents is always null; tenants price equipment in their price book)
      tags: [HvacPricebook]
      responses:
        '200':
          description: Curated catalog for the latest snapshot
          content:
            application/json:
              schema:
                type: object
                properties:
                  snapshot_id: { type: string }
                  effective_date: { type: string }
                  data: { type: array, items: { type: object } }
        '401': { description: Unauthorized }
        '503': { description: Pricebook unavailable / not loaded }
  /hvac-pricebook/catalog/{sku}:
    get:
      operationId: getHvacPricebookCatalogItem
      summary: Get one curated SKU (price_cents is always null)
      tags: [HvacPricebook]
      parameters:
        - { name: sku, in: path, required: true, schema: { type: string } }
      responses:
        '200': { description: Catalog item }
        '401': { description: Unauthorized }
        '404': { description: SKU not found }
        '503': { description: Pricebook unavailable / not loaded }
  /hvac-pricebook/programs:
    get:
      operationId: listHvacPricebookPrograms
      summary: List all rebate programs across the 13 states
      tags: [HvacPricebook]
      responses:
        '200': { description: Programs }
        '401': { description: Unauthorized }
        '503': { description: Pricebook unavailable / not loaded }
  /hvac-pricebook/programs/{state}:
    get:
      operationId: listHvacPricebookProgramsByState
      summary: List rebate programs for one two-letter state code
      tags: [HvacPricebook]
      parameters:
        - { name: state, in: path, required: true, schema: { type: string } }
      responses:
        '200': { description: Programs for the state }
        '401': { description: Unauthorized }
        '503': { description: Pricebook unavailable / not loaded }
  /hvac-pricebook/income-screening/{state}:
    get:
      operationId: getHvacIncomeScreeningBands
      summary: List account-effective, state-aware coarse income screening choices
      description: >
        Derives choices only from enabled, currently quotable programs. A named
        or mixed-basis choice may return null basis/verified_pct and remains
        self-reported, potentially eligible, and verification-required.
      tags: [HvacPricebook]
      parameters:
        - name: state
          in: path
          required: true
          schema: { type: string, pattern: '^[A-Za-z]{2}$' }
      responses:
        '200':
          description: Bands; an empty bands array is valid.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacIncomeScreeningResponse' }
        '400': { description: Invalid state }
        '401': { description: Unauthorized }
        '503': { description: Pricebook unavailable / not loaded }
  /hvac-pricebook/pathways:
    get:
      operationId: listHvacPricebookPathways
      summary: List the distinct application pathways with program counts
      tags: [HvacPricebook]
      responses:
        '200': { description: Pathways }
        '401': { description: Unauthorized }
        '503': { description: Pricebook unavailable / not loaded }
  /hvac-pricebook/cross-state/nehpa:
    get:
      operationId: getHvacPricebookNehpa
      summary: Get the NEHPA cross-state umbrella row(s)
      tags: [HvacPricebook]
      responses:
        '200': { description: NEHPA cross-state program }
        '401': { description: Unauthorized }
        '503': { description: Pricebook unavailable / not loaded }
  /hvac-pricebook/compliance:
    get:
      operationId: getHvacPricebookCompliance
      summary: Get the compliance ruleset (R-454B, federal EXPIRED, HEAR DOE, 35-ton)
      tags: [HvacPricebook]
      responses:
        '200': { description: Compliance ruleset }
        '401': { description: Unauthorized }
        '503': { description: Pricebook unavailable / not loaded }
  /hvac-pricebook/snapshot:
    get:
      operationId: getHvacPricebookSnapshot
      summary: Get the snapshot header metadata (content-hash pin + effective date)
      tags: [HvacPricebook]
      responses:
        '200': { description: Snapshot header }
        '401': { description: Unauthorized }
        '503': { description: Pricebook unavailable / not loaded }

  /hvac-rebate-program-settings:
    get:
      operationId: listHvacRebateProgramSettings
      summary: List account-effective rebate program settings
      description: >
        Cursor-paginated merged view of immutable curated programs and the
        latest account-scoped override versions. Admin notes are omitted unless
        the caller holds pricebooks:write.
      tags: [HvacRebateSettings]
      parameters:
        - { name: state, in: query, schema: { type: string, minLength: 2, maxLength: 2 } }
        - name: source_status
          in: query
          schema:
            type: string
            enum: [active, live, unpublished, not_launched, not_deployed]
        - { name: enabled, in: query, schema: { type: boolean } }
        - { name: q, in: query, schema: { type: string, maxLength: 120 } }
        - { $ref: '#/components/parameters/cursor' }
        - name: limit
          in: query
          schema: { type: integer, minimum: 1, maximum: 100, default: 50 }
      responses:
        '200':
          description: Filtered program settings page
          content:
            application/json:
              schema:
                type: object
                required: [items, summary, page_info, permissions]
                properties:
                  items:
                    type: array
                    items: { $ref: '#/components/schemas/HvacRebateProgramSettingsItem' }
                  summary:
                    type: object
                    required: [total, enabled, disabled, states]
                    properties:
                      total: { type: integer, minimum: 0 }
                      enabled: { type: integer, minimum: 0 }
                      disabled: { type: integer, minimum: 0 }
                      states: { type: integer, minimum: 0 }
                  page_info:
                    type: object
                    required: [next_cursor, has_more]
                    properties:
                      next_cursor: { type: [string, 'null'] }
                      has_more: { type: boolean }
                  permissions:
                    type: object
                    required: [can_manage, can_view_admin_notes]
                    properties:
                      can_manage: { type: boolean }
                      can_view_admin_notes: { type: boolean }
        '400': { description: Invalid filter or cursor }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '503': { description: Pricebook unavailable / not loaded }

  /hvac-rebate-program-settings/knowledge-base:
    get:
      operationId: getRebateKnowledgeDocument
      summary: Read canonical rebate research with Pricebook authorization
      tags: [HvacRebateSettings]
      parameters:
        - name: path
          in: query
          schema:
            type: string
            default: docs/sections/showroom/REBATE_KNOWLEDGE_BASE.md
      responses:
        '200':
          description: Full research document; private and not cacheable
          content:
            application/json:
              schema:
                type: object
                required: [path, source]
                properties:
                  path: { type: string }
                  source: { type: string }
        '400': { description: Document path is outside the research allowlist }
        '401': { description: Unauthorized }
        '403': { description: Pricebook read scope required }
        '404': { description: Research document not found }
        '503': { description: Research document unavailable }

  /hvac-rebate-program-settings/{programExternalId}:
    patch:
      operationId: updateHvacRebateProgramSetting
      summary: Append a new account-scoped rebate program setting version
      description: >
        Sensitive pricebooks:write mutation requiring fresh WebAuthn/TOTP and a
        verified email. This never mutates the curated platform catalog.
        expected_version provides compare-and-swap optimistic concurrency.
      tags: [HvacRebateSettings]
      parameters:
        - { name: programExternalId, in: path, required: true, schema: { type: string } }
        - { $ref: '#/components/parameters/idempotencyKey' }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/HvacRebateProgramSettingsPatch' }
      responses:
        '200':
          description: New version appended and audited
          content:
            application/json:
              schema:
                type: object
                required: [item, audit_event]
                properties:
                  item: { $ref: '#/components/schemas/HvacRebateProgramSettingsItem' }
                  audit_event:
                    type: object
                    required: [action, entity_id]
                    properties:
                      action: { type: string, enum: [rebate_program_setting.updated] }
                      entity_id: { type: string, format: uuid }
        '400': { description: Validation error }
        '401': { description: Unauthorized or fresh step-up required }
        '403': { description: 'Verified email, scope, or account-level membership required' }
        '404': { description: Program not found in the curated snapshot }
        '409':
          description: expected_version did not match the latest version
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacRebateProgramVersionConflict' }
        '422': { description: Official provenance required for amount or eligibility changes }
        '503': { description: Pricebook unavailable / not loaded }

  /hvac-rebate-program-settings/{programExternalId}/history:
    get:
      operationId: listHvacRebateProgramSettingHistory
      summary: List append-only account override versions for one program
      tags: [HvacRebateSettings]
      parameters:
        - { name: programExternalId, in: path, required: true, schema: { type: string } }
        - { $ref: '#/components/parameters/cursor' }
        - name: limit
          in: query
          schema: { type: integer, minimum: 1, maximum: 100, default: 25 }
      responses:
        '200':
          description: Descending version history
          content:
            application/json:
              schema:
                type: object
                required: [items, page_info]
                properties:
                  items:
                    type: array
                    items: { $ref: '#/components/schemas/HvacRebateProgramSettingsItem' }
                  page_info:
                    type: object
                    required: [next_cursor, has_more]
                    properties:
                      next_cursor: { type: [string, 'null'] }
                      has_more: { type: boolean }
        '400': { description: Invalid cursor }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Program not found }
        '503': { description: Pricebook unavailable / not loaded }

  /hvac-price-catalog:
    get:
      operationId: getHvacPriceCatalog
      summary: Read the HVAC price catalog
      description: >
        Every product line with its tables (All states first, then state overrides) and sizes,
        plus the brands to show. Requires pricebooks:read. install_cents is omitted from every
        row unless the caller is an account-level Owner or Admin holding pricebook:cost:read (the CFO is excluded; POR-2457, owner decision
        2026-10-12: the Sub-Account Admin and every other seat read the baseline_cents instead); can_see_install_price
        reports which. can_edit_structure reports
        pricebooks:write; can_edit_prices reports pricebook:prices:write or pricebooks:write.
        A price-only seat (pricebook:prices:write without pricebooks:write) also receives its own
        personal override on every size (my_override_percent, my_override_amount_cents, and
        my_override_inactive when it no longer applies); a structure seat receives personal_override_count
        per table instead. The company override fields are the same for both. A seat holding pricebook:cost:read
        also receives installer_tables on each line (A21 installer install-cost tables) and the installers list;
        both keys are absent for every other seat. price_adjustment is the seat's effective company/branch
        price adjustment (POR-2411), so the page can show each size's branch price.
      tags: [HvacPriceCatalog]
      responses:
        '200':
          description: The catalog
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogResponse' }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '503': { description: Catalog unavailable }

  /hvac-price-catalog/tables/{tableId}:
    put:
      operationId: putHvacPriceCatalogTable
      summary: Replace a price table's sizes and fees
      description: >
        Sensitive pricebooks:write mutation requiring fresh WebAuthn/TOTP and a verified email.
        Sizes are diffed by part and BTU; an absent install_cents keeps the stored install price.
        expected_version is a compare-and-swap; the version is bumped on every write. An installer cost table
        (A21) takes the install-cost-only body HvacCatalogInstallerTablePut and needs pricebook:cost:read
        (403 hvac_price_field_forbidden otherwise); the body is checked against the schema of the stored table kind.
      tags: [HvacPriceCatalog]
      parameters:
        - { name: tableId, in: path, required: true, schema: { type: string, format: uuid } }
        - { $ref: '#/components/parameters/idempotencyKey' }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              oneOf:
                - { $ref: '#/components/schemas/HvacCatalogTablePut' }
                - { $ref: '#/components/schemas/HvacCatalogInstallerTablePut' }
      responses:
        '200':
          description: Done
          content:
            application/json:
              schema:
                oneOf:
                  - { $ref: '#/components/schemas/HvacCatalogTableResponse' }
                  - { $ref: '#/components/schemas/HvacCatalogInstallerTableResponse' }
        '400':
          description: Validation error or hvac_price_rows_mismatch
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }
        '401': { description: 'Unauthorized or fresh step-up required' }
        '403': { description: 'Forbidden (scope, verified email, or account-level membership)' }
        '404':
          description: Not found
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }
        '409':
          description: Conflict (see error code)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }
    delete:
      operationId: deleteHvacPriceCatalogTable
      summary: Delete a state override table
      description: >
        Sensitive pricebooks:write mutation requiring fresh WebAuthn/TOTP and a verified email.
        The All states base table cannot be deleted (409 hvac_base_table_required). Deleting an installer cost table
        (A21) also needs pricebook:cost:read (403 hvac_price_field_forbidden).
      tags: [HvacPriceCatalog]
      parameters:
        - { name: tableId, in: path, required: true, schema: { type: string, format: uuid } }
        - { $ref: '#/components/parameters/idempotencyKey' }
      responses:
        '200':
          description: Done
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogLineResponse' }
        '401': { description: 'Unauthorized or fresh step-up required' }
        '403': { description: 'Forbidden (scope, verified email, or account-level membership)' }
        '404':
          description: Not found
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }
        '409':
          description: Conflict (see error code)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }

  /hvac-price-catalog/tables/{tableId}/prices:
    put:
      operationId: putHvacPriceCatalogTablePrices
      summary: Set the caller's personal overrides on a table's stored sizes
      description: >
        Requires pricebook:prices:write; no step-up. Open to price-only seats: sales manager, sales rep and
        (POR-2458) the sub-account admin, which is not refused by account-level membership on this route.
        Writes ONLY the caller's own overrides (A17 B2): they
        price only quotes whose rep is the caller, and never change the company table or its version. A
        seat that also holds pricebooks:write gets 403 use_structure_route and edits the company prices with
        PUT /hvac-price-catalog/tables/{tableId}. A size that is not stored is a 400 hvac_price_rows_mismatch;
        an override on a size with no SRP, or one that takes the customer price to $0 or below the rep
        baseline, is a 400 validation_error. Any srp_cents, baseline, install or version field is a 400.
        The 200 body is the table as the caller reads it (with my_override_* on each size).
      tags: [HvacPriceCatalog]
      parameters:
        - { name: tableId, in: path, required: true, schema: { type: string, format: uuid } }
        - { $ref: '#/components/parameters/idempotencyKey' }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/HvacCatalogPricesPut' }
      responses:
        '200':
          description: Done
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogTableResponse' }
        '400':
          description: Validation error or hvac_price_rows_mismatch
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }
        '401': { description: 'Unauthorized' }
        '403': { description: 'Forbidden (scope, account-level membership, or a pricebooks:write seat: use_structure_route)' }
        '404':
          description: Not found
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }

  /hvac-price-catalog/default-overrides/mine:
    put:
      operationId: putHvacPriceCatalogMyDefaultOverride
      summary: Set or clear the caller's own default override percent
      description: >
        A22 (POR-2401). Requires pricebook:prices:write; no step-up. Writes ONLY the caller's own default (never a
        user id from the body). It prices every size of a quote whose rep is the caller that has no size override of
        the caller's own, where the price stays above $0 and at or above the rep baseline; the caller's own size
        override wins over it, and it wins over a company size override. A seat that also holds pricebooks:write
        gets 403 use_structure_route and sets the company default instead. null clears it. Audited (an unchanged
        value is audited too). Changes no table and no version.
      tags: [HvacPriceCatalog]
      parameters:
        - { $ref: '#/components/parameters/idempotencyKey' }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/HvacCatalogDefaultOverridePut' }
      responses:
        '200':
          description: Done
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogDefaultOverrideResponse' }
        '400':
          description: Validation error (0, outside (-100, 1000], more than 2 decimals, an extra key)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }
        '401': { description: 'Unauthorized' }
        '403': { description: 'Forbidden (scope, account-level membership, or a pricebooks:write seat: use_structure_route)' }

  /hvac-price-catalog/default-overrides/company:
    put:
      operationId: putHvacPriceCatalogCompanyDefaultOverride
      summary: Set or clear the company default override percent
      description: >
        A22 (POR-2401). Sensitive pricebooks:write mutation requiring fresh WebAuthn/TOTP and a verified email. The
        company default prices every size that has no size override of its own, for every quote (also a quote with no
        rep), where the price stays above $0 and at or above the rep baseline. A rep's own default or size override
        still wins for that rep's quotes. Moves the live price of every rep's unsigned saved quotes. null clears it.
        Audited (the entity is the account). Changes no table and no version.
      tags: [HvacPriceCatalog]
      parameters:
        - { $ref: '#/components/parameters/idempotencyKey' }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/HvacCatalogDefaultOverridePut' }
      responses:
        '200':
          description: Done
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogDefaultOverrideResponse' }
        '400':
          description: Validation error
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }
        '401': { description: 'Unauthorized or fresh step-up required' }
        '403': { description: 'Forbidden (scope, verified email, or account-level membership)' }

  /hvac-price-catalog/sub-account-overrides/tables/{tableId}:
    put:
      operationId: putHvacPriceCatalogSubAccountPrices
      summary: Set or clear the caller's sub-account (branch) price on a table's stored sizes
      description: >
        POR-2458. Requires the sensitive scope hvac_catalog:sub_account_override:write, fresh WebAuthn/TOTP (900 s) and a
        verified email. Only the Sub-Account Admin of its OWN sub-account may write: the role must be sub_account_admin with
        a sub-account on the session, and a request that switches sub-account scope (X-Portrex-Sub-Account-Id naming
        another id, or an owner or admin switching into a branch) is a 403 sub_account_admin_required. The sub-account is the
        session's, never a body, path or query value. An owner or admin who acts as a Sub-Account Admin (tenant
        impersonation) can write; the audit event records the real actor. POR-2497 (R12): each listed size carries two absolute prices (the branch
        percent already included): price_cents the Company price, which is the reps' floor only, and customer_price_cents the
        Customer price, which is the reps' starting quote and the basis of their own overrides. Both keys are required; null
        clears that value and a row with both null removes the size's branch override. A price below the company baseline,
        or a Customer price below the effective floor (the typed Company price, else the baseline raised by the branch
        percent), is a 400 validation_error naming it ("Below the company baseline ($17,000)", "Below the Company price
        ($18,700)", path rows.i.price_cents / rows.i.customer_price_cents; the Sub-Account Admin already reads these).
        A value below the Install price or on a size with no SRP is a 400 hvac_price_below_minimum whose body is identical for
        every cause and names no figure or row; the cause is logged on the server only and nothing is audited. A size that is
        not stored is a 400 hvac_price_rows_mismatch. Rows written as a percent or an amount before POR-2497 keep pricing
        (starting quote and floor in one) but are no longer written. Does not
        bump the table version. The 200 body is the table redacted for the caller: no install_cents key. Audited as
        hvac_price_catalog.sub_account_override_changed with the table address, the sub-account id and the override rows
        (no install, baseline or SRP).
      tags: [HvacPriceCatalog]
      parameters:
        - { name: tableId, in: path, required: true, schema: { type: string, format: uuid } }
        - { $ref: '#/components/parameters/idempotencyKey' }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/HvacCatalogSubAccountPricesPut' }
      responses:
        '200':
          description: Done
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogTableResponse' }
        '400':
          description: Validation error, hvac_price_rows_mismatch or hvac_price_below_minimum
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }
        '401': { description: 'Unauthorized or fresh step-up required' }
        '403': { description: 'Forbidden (scope, verified email, or not the Sub-Account Admin of the session sub-account: sub_account_admin_required)' }
        '404':
          description: Not found
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }

  /hvac-price-catalog/sub-account-overrides:
    delete:
      operationId: resetHvacPriceCatalogSubAccountOverrides
      summary: Reset the caller's sub-account (branch) prices
      description: >
        POR-2458. Same posture as the PUT: scope hvac_catalog:sub_account_override:write, fresh WebAuthn/TOTP, verified
        email, and only the Sub-Account Admin of its OWN sub-account (403 sub_account_admin_required otherwise). Removes
        the session sub-account's overrides on one table (table_id) or on every table (no table_id); sizes return to the
        next price layer. The sub-account is never a parameter. Audited as hvac_price_catalog.sub_account_override_reset
        with the removed rows.
      tags: [HvacPriceCatalog]
      parameters:
        - { name: table_id, in: query, required: false, schema: { type: string, format: uuid } }
        - { $ref: '#/components/parameters/idempotencyKey' }
      responses:
        '200':
          description: Done
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogSubAccountOverridesResetResponse' }
        '400':
          description: Validation error (table_id is not a uuid)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }
        '401': { description: 'Unauthorized or fresh step-up required' }
        '403': { description: 'Forbidden (scope, verified email, or not the Sub-Account Admin of the session sub-account: sub_account_admin_required)' }
        '404':
          description: Table not found
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }

  /hvac-price-catalog/overrides:
    get:
      operationId: listHvacPriceCatalogOverrides
      summary: List the open overrides (company and personal) with who set them
      description: >
        Requires pricebook:prices:write; no step-up. A seat that also holds pricebooks:write (owner, admin) gets
        every open override in the account: the company overrides on hvac_price_rows (kind company, owner null)
        and every rep's personal override (kind personal), each with set_by, the company price and the price it
        gives, rep_earns_cents and the active flag (a personal override is not active when it is saved but the
        customer price is at or below $0, has no SRP, or sits below the rep baseline). install_cents is added
        only for pricebook:cost:read. Any other seat that holds pricebook:prices:write (sales manager, sales
        rep, sub-account admin) gets ONLY its own personal overrides, chosen from the session and never from a query parameter:
        no company rows, no other person, no baseline_cents or install_cents, and set_by.by_admin instead of an
        admin's name. Overrides whose line, table or size is no longer open are not listed.
        POR-2458: the response also carries the sub-account (branch) overrides, read-only, as sub_account_overrides: every
        branch for a seat with pricebooks:write, the sub-account admin's own sub-account otherwise, none for any other seat.
      tags: [HvacPriceCatalog]
      responses:
        '200':
          description: The overrides
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogOverridesResponse' }
        '401': { description: Unauthorized }
        '403': { description: 'Forbidden (scope or account-level membership)' }
        '503': { description: Catalog unavailable }

  /hvac-price-catalog/overrides/history:
    get:
      operationId: listHvacPriceCatalogOverrideHistory
      summary: The last 200 override changes
      description: >
        Requires pricebook:prices:write; no step-up. Read from the audit trail (catalog table saves, personal
        override saves, admin changes and resets): who, when, brand, line, state, size, and the override before
        and after. No cost field is returned. Workbook imports and line or state-table copies are not covered.
        A seat with pricebooks:write sees every change; any other seat sees only changes to its own personal
        overrides, with no actor name for a change someone else made.
        POR-2458: sub_account_changes lists the sub-account (branch) price changes with the same split.
      tags: [HvacPriceCatalog]
      responses:
        '200':
          description: The changes, newest first
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogOverrideHistoryResponse' }
        '401': { description: Unauthorized }
        '403': { description: 'Forbidden (scope or account-level membership)' }
        '503': { description: Catalog unavailable }

  /hvac-price-catalog/personal-overrides/{userId}/tables/{tableId}:
    put:
      operationId: putHvacPriceCatalogPersonalOverridesForUser
      summary: Set or reset a rep's personal overrides on one table
      description: >
        Sensitive pricebooks:write mutation requiring fresh WebAuthn/TOTP and a verified email. Same body and
        rules as the rep's own PUT /hvac-price-catalog/tables/{tableId}/prices, applied to the target rep: both
        override fields null on a size resets it to the company value. The target must be a member of the
        account with a price-only seat, a sales manager or sales rep (404 hvac_rep_not_found, 400
        hvac_rep_not_price_only). A price below the rep baseline is a 400 validation_error. Does not bump the
        table version. The change is audited with the acting admin and the target.
      tags: [HvacPriceCatalog]
      parameters:
        - { name: userId, in: path, required: true, schema: { type: string, format: uuid } }
        - { name: tableId, in: path, required: true, schema: { type: string, format: uuid } }
        - { $ref: '#/components/parameters/idempotencyKey' }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/HvacCatalogPricesPut' }
      responses:
        '200':
          description: Done
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogRepOverridesPutResponse' }
        '400':
          description: Validation error, hvac_price_rows_mismatch or hvac_rep_not_price_only
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }
        '401': { description: 'Unauthorized or fresh step-up required' }
        '403': { description: 'Forbidden (scope, verified email, or account-level membership)' }
        '404':
          description: Not found (table or hvac_rep_not_found)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }

  /hvac-price-catalog/personal-overrides/{userId}:
    delete:
      operationId: deleteHvacPriceCatalogPersonalOverridesForUser
      summary: Reset all of a rep's personal overrides, or one table's
      description: >
        Sensitive pricebooks:write mutation requiring fresh WebAuthn/TOTP and a verified email. Deletes the
        rep's personal overrides in this account (all, or only those on table_id), so their quotes use the
        company price again. Resetting ALL of a rep's overrides (no table_id) also clears the rep's default override
        percent (A22); resetting one table keeps it. A user who is a member of the account, or who still holds
        overrides in it, can be reset (404 hvac_rep_not_found otherwise). Audited with the acting admin and the
        target (default_override_percent_before when a default was cleared).
      tags: [HvacPriceCatalog]
      parameters:
        - { name: userId, in: path, required: true, schema: { type: string, format: uuid } }
        - { name: table_id, in: query, required: false, schema: { type: string, format: uuid } }
        - { $ref: '#/components/parameters/idempotencyKey' }
      responses:
        '200':
          description: Done
          content:
            application/json:
              schema:
                type: object
                additionalProperties: false
                required: [reset]
                properties:
                  reset: { type: integer, description: How many overrides were removed. }
        '400':
          description: Validation error (table_id is not a uuid)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }
        '401': { description: 'Unauthorized or fresh step-up required' }
        '403': { description: 'Forbidden (scope, verified email, or account-level membership)' }
        '404':
          description: Not found (table or hvac_rep_not_found)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }

  /hvac-price-catalog/sub-account-overrides/branches/{subAccountId}:
    delete:
      operationId: deleteHvacPriceCatalogBranchOverridesByAdmin
      summary: Reset all of a branch's prices, or one table's (owner or admin)
      description: >
        Sensitive pricebooks:write mutation requiring fresh WebAuthn/TOTP and a verified email (owner decision
        2026-11-09). Deletes the branch (sub-account) prices of this account's branch subAccountId (all, or only
        those on table_id), so the branch's reps quote from the company prices again. The same reset a branch's
        Sub-Account Admin makes with DELETE /hvac-price-catalog/sub-account-overrides, audited with the same action
        and the acting admin. 404 when the branch or the table is not this account's.
      tags: [HvacPriceCatalog]
      parameters:
        - { name: subAccountId, in: path, required: true, schema: { type: string, format: uuid } }
        - { name: table_id, in: query, required: false, schema: { type: string, format: uuid } }
        - { $ref: '#/components/parameters/idempotencyKey' }
      responses:
        '200':
          description: Done
          content:
            application/json:
              schema:
                type: object
                additionalProperties: false
                required: [reset]
                properties:
                  reset: { type: integer, description: How many branch prices were removed. }
        '400':
          description: Validation error (table_id is not a uuid)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }
        '401': { description: 'Unauthorized or fresh step-up required' }
        '403': { description: 'Forbidden (scope, verified email, or account-level membership)' }
        '404':
          description: Not found (branch or table)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }

  /hvac-price-catalog/lines:
    post:
      operationId: createHvacPriceCatalogLine
      summary: Create a product line with an empty All states table
      description: >
        Sensitive pricebooks:write mutation requiring fresh WebAuthn/TOTP and a verified email.
        The brand takes the casing of an existing line (case- and space-insensitive). A second line
        with the same brand, system type and name is 409 hvac_line_name_taken.
      tags: [HvacPriceCatalog]
      parameters:
        - { $ref: '#/components/parameters/idempotencyKey' }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/HvacCatalogLineCreate' }
      responses:
        '201':
          description: Done
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogLineResponse' }
        '400':
          description: Validation error or hvac_price_rows_mismatch
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }
        '401': { description: 'Unauthorized or fresh step-up required' }
        '403': { description: 'Forbidden (scope, verified email, or account-level membership)' }
        '409':
          description: Conflict (see error code)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }

  /hvac-price-catalog/lines/{lineId}:
    patch:
      operationId: updateHvacPriceCatalogLine
      summary: Rename a product line, change its sub type, its series aliases or its additional zone price
      description: >
        Sensitive pricebooks:write mutation requiring fresh WebAuthn/TOTP and a verified email.
        `series_aliases` replaces the aliases; one that is the name or an alias of another line of
        the same brand and system type is 400 hvac_alias_taken. `additional_zone_cents` sets the
        line's Additional zone price (null = back to the default); on a ductless or multi-zone line
        it is 400 hvac_additional_zone_ducted_only. Concurrent edits are last-write-wins.
      tags: [HvacPriceCatalog]
      parameters:
        - { name: lineId, in: path, required: true, schema: { type: string, format: uuid } }
        - { $ref: '#/components/parameters/idempotencyKey' }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/HvacCatalogLinePatch' }
      responses:
        '200':
          description: Done
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogLineResponse' }
        '400':
          description: Validation error or hvac_price_rows_mismatch
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }
        '401': { description: 'Unauthorized or fresh step-up required' }
        '403': { description: 'Forbidden (scope, verified email, or account-level membership)' }
        '404':
          description: Not found
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }
        '409':
          description: Conflict (see error code)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }
    delete:
      operationId: deleteHvacPriceCatalogLine
      summary: Delete a product line with its tables and sizes
      description: Sensitive pricebooks:write mutation requiring fresh WebAuthn/TOTP and a verified email.
      tags: [HvacPriceCatalog]
      parameters:
        - { name: lineId, in: path, required: true, schema: { type: string, format: uuid } }
        - { $ref: '#/components/parameters/idempotencyKey' }
      responses:
        '200':
          description: Deleted
          content:
            application/json:
              schema:
                type: object
                required: [deleted]
                properties:
                  deleted: { type: boolean }
        '401': { description: 'Unauthorized or fresh step-up required' }
        '403': { description: 'Forbidden (scope, verified email, or account-level membership)' }
        '404':
          description: Not found
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }

  /hvac-price-catalog/lines/{lineId}/duplicate:
    post:
      operationId: duplicateHvacPriceCatalogLine
      summary: Duplicate a product line with all its tables, sizes and fees
      description: >
        Sensitive pricebooks:write mutation requiring fresh WebAuthn/TOTP and a verified email.
        The copy starts with no series aliases (an alias points at one line).
      tags: [HvacPriceCatalog]
      parameters:
        - { name: lineId, in: path, required: true, schema: { type: string, format: uuid } }
        - { $ref: '#/components/parameters/idempotencyKey' }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/HvacCatalogLineDuplicate' }
      responses:
        '201':
          description: Done
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogLineResponse' }
        '400':
          description: Validation error or hvac_price_rows_mismatch
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }
        '401': { description: 'Unauthorized or fresh step-up required' }
        '403': { description: 'Forbidden (scope, verified email, or account-level membership)' }
        '404':
          description: Not found
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }
        '409':
          description: Conflict (see error code)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }

  /hvac-price-catalog/lines/{lineId}/tables:
    post:
      operationId: createHvacPriceCatalogOverrides
      summary: Add state override tables to a product line
      description: >
        Sensitive pricebooks:write mutation requiring fresh WebAuthn/TOTP and a verified email.
        Creates one table per state, copied from the All states table, copied from another
        table of the line, or blank. A state that already has a table is 409 hvac_state_table_exists.
      tags: [HvacPriceCatalog]
      parameters:
        - { name: lineId, in: path, required: true, schema: { type: string, format: uuid } }
        - { $ref: '#/components/parameters/idempotencyKey' }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/HvacCatalogOverrideCreate' }
      responses:
        '201':
          description: Done
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogLineResponse' }
        '400':
          description: Validation error or hvac_price_rows_mismatch
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }
        '401': { description: 'Unauthorized or fresh step-up required' }
        '403': { description: 'Forbidden (scope, verified email, or account-level membership)' }
        '404':
          description: Not found
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }
        '409':
          description: Conflict (see error code)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }

  /hvac-price-catalog/lines/{lineId}/installer-tables:
    post:
      operationId: createHvacPriceCatalogInstallerTables
      summary: Add installer install-cost tables to a product line
      description: >
        Sensitive pricebooks:write mutation requiring fresh WebAuthn/TOTP and a verified email, and
        pricebook:cost:read (403 hvac_price_field_forbidden without it). Creates one install-cost table per state for
        one installer (a live contractor of the account: 400 hvac_installer_unknown otherwise), empty or with the
        install cost (only) copied from another table of the line. A table for that installer and state that
        already exists is 409 hvac_installer_table_exists. An installer table never covers "All states" and has no fees.
      tags: [HvacPriceCatalog]
      parameters:
        - { name: lineId, in: path, required: true, schema: { type: string, format: uuid } }
        - { $ref: '#/components/parameters/idempotencyKey' }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/HvacCatalogInstallerTableCreate' }
      responses:
        '201':
          description: Done
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogLineResponse' }
        '400':
          description: Validation error or hvac_installer_unknown
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }
        '401': { description: 'Unauthorized or fresh step-up required' }
        '403': { description: 'Forbidden (scope, verified email, account-level membership, or hvac_price_field_forbidden)' }
        '404':
          description: Not found
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }
        '409':
          description: Conflict (hvac_installer_table_exists)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }

  /hvac-price-catalog/brands/{brand}:
    patch:
      operationId: renameHvacPriceCatalogBrand
      summary: Rename a brand across its product lines
      description: >
        Sensitive pricebooks:write mutation requiring fresh WebAuthn/TOTP and a verified email.
        Another existing brand's name is 409 hvac_brand_name_taken.
      tags: [HvacPriceCatalog]
      parameters:
        - { name: brand, in: path, required: true, schema: { type: string, minLength: 1, maxLength: 80 } }
        - { $ref: '#/components/parameters/idempotencyKey' }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/HvacCatalogBrandRename' }
      responses:
        '200':
          description: Renamed
          content:
            application/json:
              schema:
                type: object
                required: [brand, lines_updated]
                properties:
                  brand: { type: string }
                  lines_updated: { type: integer, minimum: 1 }
        '400':
          description: Validation error or hvac_price_rows_mismatch
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }
        '401': { description: 'Unauthorized or fresh step-up required' }
        '403': { description: 'Forbidden (scope, verified email, or account-level membership)' }
        '404':
          description: Not found
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }
        '409':
          description: Conflict (see error code)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }
    delete:
      operationId: deleteHvacPriceCatalogBrand
      summary: Remove a brand with all its product lines
      description: Sensitive pricebooks:write mutation requiring fresh WebAuthn/TOTP and a verified email.
      tags: [HvacPriceCatalog]
      parameters:
        - { name: brand, in: path, required: true, schema: { type: string, minLength: 1, maxLength: 80 } }
        - { $ref: '#/components/parameters/idempotencyKey' }
      responses:
        '200':
          description: Removed
          content:
            application/json:
              schema:
                type: object
                required: [removed_lines]
                properties:
                  removed_lines: { type: integer, minimum: 1 }
        '401': { description: 'Unauthorized or fresh step-up required' }
        '403': { description: 'Forbidden (scope, verified email, or account-level membership)' }
        '404':
          description: Not found
          content:
            application/json:
              schema: { $ref: '#/components/schemas/HvacCatalogError' }

  /rebate-quote/preview:
    post:
      operationId: previewRebateQuote
      summary: Preview an HVAC rebate quote (pure compute; nothing persisted)
      description: >
        Each selection names the tenant price-book items that price it in
        `priceRef` (item ids; never cents). The server resolves the equipment
        price from the tenant price book and returns it per system in
        `equipment_pricing`. `priceRef.expectedCents` is only compared: a
        difference (or a customer state that differs from `priceRef.pricedState`)
        sets `price_mismatch` / `state_mismatch` and never fails the preview.
        Every selection carries a `priceRef` or none does. A request that still
        sends `configuredEquipmentRetailCents` is a 400.
        The cart's add-on lines travel as `params.addons` (`{ itemId, quantity }`;
        never cents). The server computes the project total
        (`retail_quote_total_cents`) as the materialized retail plus each add-on
        at the tenant price-book price times max(1, round(quantity)), before any
        sales discount, and uses the same number as the percent-of-cost basis.
        A request that still sends `params.projectTotalCents` or
        `params.percentBasisCents` is a 400.
        An optional `leadId` prices the equipment with that lead's rep's personal catalog overrides
        (A17 B2: assignee, else creator, else the account price), the same rule the cart uses. A supplied
        `leadId` needs a tenant user holding `leads:read` and a lead the price-quote route's branch and
        assignment fences let them see; anything else (an integration credential, a seat without
        `leads:read`, another tenant's or a hidden lead) is a 404 lead_not_found, never a silent fall back to
        the account price. Without `leadId` the account price is used; the viewer's own overrides are never used.
      tags: [RebateQuote]
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, additionalProperties: true }
      responses:
        '200': { description: Net-out-of-pocket breakdown with the server-resolved equipment price }
        '400': { description: Validation error or price_ref_all_or_none }
        '401': { description: Unauthorized }
        '404': { description: Customer or lead not found (lead_not_found) }
        '422': { description: Selection / compliance blocked (including price_ref_invalid and no_price_on_file and addon_ref_invalid and addon_no_price_on_file) }
        '503': { description: Pricebook unavailable / not loaded }
  /rebate-quote:
    post:
      operationId: createRebateQuote
      summary: Persist an HVAC rebate quote (pins the snapshot + breakdown)
      description: >
        Same `priceRef` and `params.addons` contract as the preview. Persist additionally requires
        `priceRef.expectedCents` on every selection (400 expected_cents_required)
        and a `customerId` for any CPM system reference (422
        customer_required_for_cpm_price). A price or state that differs from the
        caller's is a 409 equipment_price_mismatch carrying the server's
        `equipment_pricing`; nothing is persisted.
      tags: [RebateQuote]
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, additionalProperties: true }
      responses:
        '201': { description: Rebate quote created }
        '400': { description: Validation error or a price reference without expectedCents }
        '401': { description: Unauthorized }
        '404': { description: Customer or lead not found (lead_not_found) }
        '409': { description: Equipment price or state differs from the caller's (equipment_price_mismatch) }
        '422': { description: Selection / compliance blocked or a CPM price without a customer }
        '503': { description: Pricebook unavailable / not loaded }
  /rebate-quote/{id}/quote:
    post:
      operationId: materializeRebateQuote
      summary: Materialize a persisted rebate quote into an estimate
      tags: [RebateQuote]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string, format: uuid } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [customerId]
              properties:
                customerId: { type: string, format: uuid }
                estimateNumber: { type: string }
                projectId: { type: string, format: uuid, nullable: true }
                discountId: { type: string, format: uuid, nullable: true }
      responses:
        '201': { description: Estimate created + linked }
        '400': { description: Validation error }
        '401': { description: Unauthorized }
        '404': { description: Quote or customer not found }
        '409': { description: Saved quote context cannot be restored or the quote was priced from a catalog price or a client-supplied equipment price (re-create the quote) or the quote belongs to another customer (quote_customer_mismatch) }
        '422': { description: Selection / compliance blocked }
        '503': { description: Pricebook unavailable / not loaded }
  /rebate-quote/{id}/submit:
    post:
      operationId: submitRebateApplication
      summary: Submit an HVAC rebate application (SENSITIVE; step-up + verified-email)
      description: >
        Files the rebate application externally via the outbox. SENSITIVE
        (rebates:submit) — requires fresh step-up with NO attended-in-person
        bypass and a verified email. Emits rebate.application.submitted.
      tags: [RebateQuote]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string, format: uuid } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [programExternalId]
              properties:
                programExternalId: { type: string }
                acknowledgedRuleIds: { type: array, items: { type: string } }
      responses:
        '202': { description: Application submitted (outbox emit) }
        '400': { description: Validation error }
        '401': { description: Unauthorized / step-up required }
        '403': { description: Email verification required }
        '404': { description: Quote not found }
        '503': { description: Pricebook unavailable / not loaded }
  /rebate-quote/sku-override:
    post:
      operationId: setRebateSkuOverride
      summary: Set a per-account price override for a curated HVAC SKU (SENSITIVE)
      description: >
        Records an explicit per-account retail price for any SKU in the loaded
        HVAC reference WITHOUT mutating the curated cross-tenant row. Curated
        catalog prices are never used, so the override is how a tenant prices
        a SKU it has no price-book row for; a tenant row's own price always
        wins over it. SENSITIVE (pricebooks:write) — requires
        fresh step-up with NO attended-in-person bypass and a verified email.
        An unknown SKU returns 404.
      tags: [RebateQuote]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [sku, retailPriceCents]
              properties:
                sku: { type: string }
                retailPriceCents: { type: integer, minimum: 1 }
                note: { type: string, nullable: true }
                active: { type: boolean, default: true }
      responses:
        '201': { description: Override recorded }
        '400': { description: Validation error }
        '401': { description: Unauthorized / step-up required }
        '403': { description: Email verification required }
        '404': { description: SKU not found in the loaded pricebook }
        '503': { description: Pricebook unavailable / not loaded }

  # ── GoodLeap financing (plan 2026-08-08-001, U6) ──────────────────────────
  # Direct credit submission and its disclosure preview are synchronous because
  # the applicant is on screen; every other provider operation remains durable.
  /finance/goodleap/cases:
    get:
      operationId: listGoodLeapFinanceCases
      summary: List GoodLeap finance cases
      description: |
        Cursor-paginated register with non-PII URL filters. Requires
        `goodleap_finance:read`; Sales Rep sees assigned cases only. Never
        returns the hosted ShareApp link, the borrower email, or a secret.
      tags: [Finance]
      parameters:
        - { name: bucket, in: query, schema: { type: string, enum: [application, contract, install, funded] } }
        - { name: attention, in: query, schema: { type: string } }
        - { name: syncStatus, in: query, schema: { type: string } }
        - { name: propertyState, in: query, schema: { type: string, pattern: '^[A-Z]{2}$' } }
        - { name: sort, in: query, schema: { type: string, enum: [created_at, updated_at, last_successful_sync_at] } }
        - { name: direction, in: query, schema: { type: string, enum: [asc, desc] } }
        - { name: cursor, in: query, schema: { type: string } }
        - { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 100 } }
      responses:
        '200':
          description: Case page
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '410': { description: Cursor no longer valid }
        '503': { description: GoodLeap deps not configured }
    post:
      operationId: createGoodLeapFinanceCase
      summary: Prepare one GoodLeap origination mode (202)
      description: |
        `hosted_share` freezes the offer and enqueues exactly one ShareApp email.
        `direct_application` is authorized only for the Renovation showroom,
        creates or resumes one lead-scoped case, and enqueues no email. The two
        modes are mutually exclusive and durable on the case.

        Hosted finance-workspace preparation requires `goodleap_finance:read`
        plus `finance_records:write`, verified email, origin ABAC, and exact
        readiness. The narrow direct exception is Renovation showroom +
        lead-only: an assigned Sales Rep or Sales Manager may prepare it with
        `goodleap_finance:read`, verified email, and exact assigned-user/team
        ABAC. Project, unassigned, hosted, and cross-team requests remain
        forbidden/not-found. Replaying the same `idempotencyKey` returns the
        SAME case rather than sending twice.
      tags: [Finance]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required:
                - originationMode
                - source
                - customerPersonId
                - organizationMappingId
                - offerSnapshotId
                - remoteOfferId
                - propertyState
                - requestedAmountCents
                - idempotencyKey
              properties:
                originationMode: { type: string, enum: [hosted_share, direct_application] }
                source:
                  oneOf:
                    - type: object
                      additionalProperties: false
                      required: [kind]
                      properties:
                        kind: { type: string, enum: [finance_workspace] }
                    - type: object
                      additionalProperties: false
                      required: [kind, showroom]
                      properties:
                        kind: { type: string, enum: [showroom] }
                        showroom: { type: string, enum: [renovation] }
                projectId: { type: string, format: uuid, nullable: true }
                leadId: { type: string, format: uuid, nullable: true }
                customerPersonId: { type: string, format: uuid }
                estimateId: { type: string, format: uuid, nullable: true }
                organizationMappingId: { type: string, format: uuid }
                offerSnapshotId: { type: string, format: uuid }
                remoteOfferId: { type: string }
                propertyState: { type: string, pattern: '^[A-Z]{2}$' }
                requestedAmountCents: { type: integer, minimum: 1, maximum: 3518437208883199 }
                amountDivergesFromEstimate: { type: boolean }
                applicantRecipientConfirmation: { type: string, pattern: '^[a-f0-9]{64}$' }
                hostedApplicationAcknowledged: { type: boolean, enum: [true] }
                idempotencyKey: { type: string, format: uuid }
      responses:
        '202':
          description: Case prepared or resumed; intent is null for direct mode
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema:
                type: object
                additionalProperties: false
                required: [caseId, referenceNumber, originationMode, reusedCase, intent]
                properties:
                  caseId: { type: string, format: uuid }
                  referenceNumber: { type: string }
                  originationMode: { type: string, enum: [hosted_share, direct_application] }
                  reusedCase: { type: boolean }
                  intent: { type: object, additionalProperties: true, nullable: true }
        '400': { description: Invalid body or environment mismatch }
        '401': { description: Unauthorized }
        '403': { description: 'Forbidden or state not licensed' }
        '404': { description: 'Mapping, offer snapshot, applicant, or origin not found' }
        '409': { description: 'Idempotency, mapping/branch, offer, or applicant-recipient conflict' }
        '503': { description: GoodLeap deps not configured }

  /finance/goodleap/cases/search:
    post:
      operationId: searchGoodLeapFinanceCases
      summary: Search GoodLeap cases by reference or borrower email
      description: |
        Borrower-identifying search. The request body is never audited, logged,
        or echoed; the email is matched against a reachability hash and is never
        decrypted. Requires `goodleap_finance:read`.
      tags: [Finance]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                referenceNumber: { type: string }
                customerEmail: { type: string }
                limit: { type: integer, minimum: 1, maximum: 100 }
      responses:
        '200':
          description: Matching cases
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '400': { description: Invalid body }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '503': { description: GoodLeap deps not configured }

  /finance/goodleap/cases/{caseId}:
    get:
      operationId: getGoodLeapFinanceCase
      summary: GoodLeap case detail
      description: |
        Returns the reduced projection, allowed/blocked actions, the frozen
        offer snapshot, and intents. Carries `shareRecipientMasked` only — never
        the borrower email, and never the hosted application link.
      tags: [Finance]
      parameters:
        - { name: caseId, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        '200':
          description: Case detail
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '400': { description: Invalid case id }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Case not found or not visible to this principal }
        '503': { description: GoodLeap deps not configured }

  /finance/goodleap/cases/{caseId}/events:
    get:
      operationId: listGoodLeapCaseEvents
      summary: GoodLeap case activity
      description: |
        Append-only projection/command events, newest first. Each `before`/`after`
        payload is a tagged union — `{kind:'projection',projection}` or
        `{kind:'command',intentId,outcome}` — and readers MUST switch on `kind`.
        A payload the server cannot parse is rejected as a defect (500) rather
        than passed through.
      tags: [Finance]
      parameters:
        - { name: caseId, in: path, required: true, schema: { type: string, format: uuid } }
        - { name: cursor, in: query, schema: { type: string } }
        - { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 100 } }
      responses:
        '200':
          description: Event page
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Case not found }
        '410': { description: Cursor no longer valid }
        '500': { description: Stored case-event payload is not a known shape }
        '503': { description: GoodLeap deps not configured }

  /finance/goodleap/preflight:
    get:
      operationId: goodLeapOriginationPreflight
      summary: GoodLeap origination readiness
      description: |
        Reports whether a project or lead can originate: active mapping for the
        branch, a linked customer person with first/last/email, and a property
        address carrying a two-letter state (`missing_property_state` otherwise).
        It also requires the acting Portrex user's email to match an enabled,
        present organization user on the exact mapping
        (`organization_user_required` otherwise). This cached preflight is only
        early guidance; direct submit authoritatively repeats the exact-email
        provider `GET /users` and never creates a provider user as a side effect.
        Pass `customerPersonId` so preflight validates the SAME applicant the
        command will submit rather than its own role-ordered pick.
      tags: [Finance]
      parameters:
        - { name: projectId, in: query, schema: { type: string, format: uuid } }
        - { name: leadId, in: query, schema: { type: string, format: uuid } }
        - { name: customerPersonId, in: query, schema: { type: string, format: uuid } }
        - { name: state, in: query, schema: { type: string, pattern: '^[A-Za-z]{2}$' } }
        - { name: requestedAmountCents, in: query, schema: { type: integer, minimum: 1, maximum: 3518437208883199 } }
      responses:
        '200':
          description: Readiness and issues
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/GoodLeapPreflightResponse' }
        '400': { description: Exactly one of projectId / leadId is required }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Project or lead not found }
        '503': { description: GoodLeap deps not configured }

  /finance/goodleap/offers:
    get:
      operationId: getGoodLeapOffers
      summary: Cached, state-filtered GoodLeap offers
      description: |
        Serves the frozen offer snapshot for the origin's (mapping, state) pair.
        Never calls GoodLeap: when the snapshot is stale this enqueues at most
        ONE `refresh_offers` intent per mapping+state+TTL window, so a read-scoped
        user cannot provoke unbounded provider work.

        `state` overrides the state derived from the customer's service address
        (the start flow makes it editable). It is validated against the mapping's
        licensed states and refused with `state_not_licensed` if unlicensed —
        never silently replaced by the derived state. `snapshot.filteredState`
        and `propertyState` always reflect the state actually used.
      tags: [Finance]
      parameters:
        - { name: projectId, in: query, schema: { type: string, format: uuid } }
        - { name: leadId, in: query, schema: { type: string, format: uuid } }
        - { name: customerPersonId, in: query, schema: { type: string, format: uuid } }
        - { name: state, in: query, schema: { type: string, pattern: '^[A-Za-z]{2}$' } }
        - { name: requestedAmountCents, in: query, schema: { type: integer, minimum: 1, maximum: 3518437208883199 } }
      responses:
        '200':
          description: Offer context
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/GoodLeapOffersResponse' }
        '400': { description: Invalid query }
        '401': { description: Unauthorized }
        '403': { description: Forbidden or state not licensed }
        '404': { description: Project or lead not found }
        '503': { description: GoodLeap deps not configured }

  /finance/goodleap/cases/{caseId}/lifecycle:
    get:
      operationId: getGoodLeapLoanLifecycle
      summary: Read the authoritative post-approval lifecycle projection
      description: |
        Returns the privacy-safe projection used as the optimistic command
        baseline plus the latest 100 durable commands. Tenant RLS, case ABAC,
        and `goodleap_finance:read` apply. This route never calls GoodLeap.
      tags: [Finance]
      parameters:
        - { name: caseId, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        '200':
          description: Lifecycle projection and command history
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/GoodLeapLoanLifecycleResponse' }
        '400': { description: Invalid case id }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Case not found or not visible }
        '503': { description: GoodLeap deps not configured }

  /finance/goodleap/cases/{caseId}/loan-stipulations:
    get:
      operationId: listGoodLeapLoanStipulations
      summary: List privacy-safe loan stipulation summaries
      description: |
        Reads the last persisted loan stipulation mirror. No reason prose,
        filenames, attachment ids, signed URLs, tokens, or borrower PII are
        persisted or returned. This route never calls GoodLeap.
      tags: [Finance]
      parameters:
        - { name: caseId, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        '200':
          description: Last persisted stipulation summary
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/GoodLeapLoanStipulationsResponse' }
        '400': { description: Invalid case id }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Case not found or not visible }
        '503': { description: GoodLeap deps not configured }

  /finance/goodleap/cases/{caseId}/change-order-options:
    get:
      operationId: getGoodLeapChangeOrderOptions
      summary: Read fresh loan-scoped change-order catalogs
      description: |
        Performs three authenticated GETs for this exact tenant mapping and
        remote loan: HIC threshold, channels, and products/offers. Catalog
        failure is separate from the persisted core lifecycle read and cannot
        hide authoritative lifecycle facts.
      tags: [Finance]
      parameters:
        - { name: caseId, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        '200':
          description: Fresh privacy-safe change-order options
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/GoodLeapChangeOrderOptionsResponse' }
        '400': { description: Invalid case or provider catalog response }
        '401': { description: Unauthorized }
        '403': { description: Forbidden or connection unavailable }
        '404': { description: Case not found or not visible }
        '409': { description: Case does not yet have a provider loan }
        '502': { description: GoodLeap returned an invalid catalog response }
        '503': { description: GoodLeap deps or change-order catalog temporarily unavailable }

  /finance/goodleap/cases/{caseId}/lifecycle-commands:
    post:
      operationId: createGoodLeapLoanLifecycleCommand
      summary: Enqueue one post-approval GoodLeap command (durable, 202)
      description: |
        Atomically persists one strict action command, its linked generic
        operation intent, and an IDs-only partner outbox row. Requires
        `goodleap_finance:read` plus `finance_records:write`, verified email,
        command role, case ABAC, exact active and verified mapping/connection,
        UUID idempotency, and an exact lifecycle
        projection CAS. A provider POST is attempted at most once; ambiguous
        write outcomes are never automatically retried. A provider 2xx with
        lagging readback remains submitted for read-only reconciliation.
      tags: [Finance]
      parameters:
        - { name: caseId, in: path, required: true, schema: { type: string, format: uuid } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/GoodLeapCreateLoanLifecycleCommand' }
      responses:
        '202':
          description: Lifecycle command accepted
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema:
                type: object
                additionalProperties: false
                required: [command]
                properties:
                  command: { $ref: '#/components/schemas/GoodLeapLoanLifecycleCommand' }
        '400': { description: Invalid body }
        '401': { description: Unauthorized }
        '403': { description: 'Forbidden, unverified email, or exact connection unavailable' }
        '404': { description: Case not found or not visible }
        '409': { description: 'Idempotency/in-flight conflict, stale projection/baseline, no-op, first-send violation, or provider-state refusal' }
        '503': { description: GoodLeap deps not configured }

  /finance/goodleap/cases/{caseId}/documents/embedded:
    post:
      operationId: createGoodLeapEmbeddedSigningCapability
      summary: Mint one ephemeral GoodLeap embedded-signing capability
      description: |
        A deliberate POST (never a prefetchable GET) that performs one
        authenticated provider GET only after verified-email command auth,
        exact tenant/case ABAC, exact mapping/connection/credential readiness,
        and durable evidence that an EMBEDDED first-send documents command
        crossed the irreversible provider boundary. The callback is computed
        server-side from the trusted Portrex app origin; callers cannot supply
        one. The returned URL is never persisted, audited, logged, prefetched,
        or placed on an outbox, and every response is non-cacheable.
      tags: [Finance]
      parameters:
        - { name: caseId, in: path, required: true, schema: { type: string, format: uuid } }
      requestBody:
        required: false
        content:
          application/json:
            schema: { $ref: '#/components/schemas/GoodLeapEmbeddedSigningRequest' }
      responses:
        '200':
          description: Fresh one-time signing capability
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
            Pragma:
              schema: { type: string, enum: [no-cache] }
            Referrer-Policy:
              schema: { type: string, enum: [no-referrer] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/GoodLeapEmbeddedSigningResponse' }
        '400': { description: Invalid case id or document role }
        '401': { description: Unauthorized or email not verified }
        '403': { description: Forbidden or exact connection/credential unavailable }
        '404': { description: Case not found or not visible }
        '409': { description: Embedded documents not prepared or provider loan locked }
        '502': { description: Provider unavailable or returned an invalid/expired signing capability }
        '503': { description: GoodLeap dependencies or trusted app redirect origin not configured }

  /finance/goodleap/cases/{caseId}/credit-disclosure:
    get:
      operationId: getGoodLeapCreditDisclosure
      summary: Preview current direct-application disclosure
      description: |
        Fetches the current provider disclosure and returns only its renderable
        name and sections plus a SHA-256 confirmation. The provider consent
        token is never returned, logged, or persisted. Submit re-fetches the
        current disclosure and refuses if its id or content hash changed.
        Requires the same verified-email, exact lead/case assignment or team
        ABAC, direct Renovation lead-only posture, and exact mapping/connection
        readiness as direct application submission. It grants assigned sales
        users no hosted, project, Finance-workspace, milestone, or lifecycle
        access.
      tags: [Finance]
      parameters:
        - { name: caseId, in: path, required: true, schema: { type: string, format: uuid } }
      responses:
        '200':
          description: Current renderable disclosure
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/GoodLeapCreditDisclosurePreview' }
        '400': { description: Invalid case or disclosure unavailable }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Case not found }
        '409': { description: 'Wrong origination mode, already submitted, or submit in flight' }
        '503': { description: GoodLeap deps not configured }

  /finance/goodleap/cases/{caseId}/milestones:
    post:
      operationId: submitGoodLeapCompletionMilestone
      summary: Submit a GoodLeap completion milestone (durable, 202)
      description: |
        Records one `INSTALL_COMPLETE` or `PTO_COMPLETE` fact and enqueues one
        `submit_milestone` intent. `completedAt` is the actual completion time,
        never defaulted to submission time. A case must already have a provider
        loan id, and the same milestone cannot be submitted twice. Requires
        verified email.
      tags: [Finance]
      parameters:
        - { name: caseId, in: path, required: true, schema: { type: string, format: uuid } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/GoodLeapSubmitMilestoneInput' }
      responses:
        '202':
          description: Milestone intent accepted
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/GoodLeapSubmitMilestoneResponse' }
        '400': { description: 'Invalid case id, body, or environment' }
        '401': { description: Unauthorized }
        '403': { description: 'Forbidden, case not visible, or action not allowed' }
        '404': { description: Case or mapping not found }
        '409': { description: 'Provider loan missing or milestone already submitted' }
        '503': { description: GoodLeap deps not configured }

  /finance/goodleap/cases/{caseId}/application:
    post:
      operationId: submitGoodLeapCreditApplication
      summary: Submit one direct GoodLeap credit application synchronously
      description: |
        Revalidates the exact current disclosure id and content hash before one
        non-retried `POST /loans`. Applicant credit PII and signature exist only
        in this request stack and are never persisted or returned. Unknown
        provider outcomes park the case for reconciliation and must not be
        retried. Only a lead-only Renovation showroom case durably prepared as
        `direct_application` is eligible. Owners/back-office finance roles keep
        their normal write posture; an assigned Sales Rep or Sales Manager may
        use this exact path with `goodleap_finance:read`, verified email,
        assigned-user/team ABAC, and ready exact mapping/connection. It grants
        no hosted, project, Finance-workspace, milestone, or lifecycle access.
      tags: [Finance]
      parameters:
        - { name: caseId, in: path, required: true, schema: { type: string, format: uuid } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/GoodLeapSubmitApplicationInput' }
      responses:
        '200':
          description: Provider decision projection
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/GoodLeapSubmitApplicationResponse' }
        '400': { description: Invalid body or provider/local precondition refused }
        '401': { description: Unauthorized }
        '403': { description: Forbidden or state not licensed }
        '404': { description: Case not found }
        '409': { description: 'Wrong mode, disclosure changed, already submitted/in flight, or no enabled same-organization GoodLeap submitting user' }
        '502': { description: Provider rejected or outcome unknown; inspect error code before retrying }
        '503': { description: GoodLeap deps not configured }

  /finance/goodleap/cases/{caseId}/reconcile:
    post:
      operationId: reconcileGoodLeapFinanceCase
      summary: Reconcile a GoodLeap case (durable, 202)
      description: |
        Enqueues a `reconcile_case` intent under the same command policy as the
        share mutation. Provider reads happen only in the worker; HTTP never
        syncs state. Reconcile stays available on a degraded projection — it is
        the way out of `needs_review`.
      tags: [Finance]
      parameters:
        - { name: caseId, in: path, required: true, schema: { type: string, format: uuid } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [idempotencyKey]
              properties:
                idempotencyKey: { type: string, format: uuid }
      responses:
        '202':
          description: Reconcile intent accepted
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { type: object, additionalProperties: true }
        '400': { description: Invalid body or environment mismatch }
        '401': { description: Unauthorized }
        '403': { description: Forbidden }
        '404': { description: Case not found }
        '409': { description: Idempotency conflict }
        '503': { description: GoodLeap deps not configured }

  /integrations/goodleap:
    get:
      operationId: getGoodLeapConnectionHealth
      summary: GoodLeap connection health (Owner/Admin)
      description: |
        Local state only — GoodLeap exposes no organization-lookup API and this
        route never calls the provider. Reports the exact connection binding's
        configured/not-known-bad credential state, persisted worker health, whether
        a webhook registration is recorded (a human step performed by GoodLeap
        staff), and the first bounded mapping page. Use the mappings endpoint's
        cursor to continue beyond that page. Credentials and secret versions never
        appear.
      tags: [Integrations]
      responses:
        '200':
          description: Connection health
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/GoodLeapConnectionHealth' }
        '401': { description: Unauthorized }
        '403': { description: Owner or Admin required }
        '503': { description: GoodLeap deps not configured }

  /integrations/goodleap/mappings:
    get:
      operationId: listGoodLeapOrganizationMappings
      summary: List GoodLeap organization mappings (Owner/Admin)
      tags: [Integrations]
      parameters:
        - name: cursor
          in: query
          required: false
          schema: { type: string, format: uuid, nullable: true }
        - name: limit
          in: query
          required: false
          schema: { type: integer, minimum: 1, maximum: 100, default: 100 }
      responses:
        '200':
          description: Mappings
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/GoodLeapOrganizationMappingsPage' }
        '400': { description: Invalid cursor or limit }
        '401': { description: Unauthorized }
        '403': { description: Owner or Admin required }
        '503': { description: GoodLeap deps not configured }
    post:
      operationId: createGoodLeapOrganizationMapping
      summary: Create a GoodLeap organization mapping (Owner/Admin)
      description: |
        Runs the LOCAL preflight first (shape, licensed states, channel
        collision, branch ownership) — there is no provider call. The mapping
        lands `pending_validation`; an operator verifies and activates it
        deliberately. The requested environment must match the provider target
        selected by this deployment. Requires verified email.
      tags: [Integrations]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [channel, categoryId, providerOrganizationId, friendlyName, licensedStates]
              properties:
                environment: { type: string, enum: [sandbox, production] }
                channel: { type: string }
                categoryId: { type: string }
                providerOrganizationId: { type: string, minLength: 1, maxLength: 128 }
                friendlyName: { type: string }
                subAccountId: { type: string, format: uuid, nullable: true }
                licensedStates:
                  type: array
                  minItems: 1
                  items: { type: string, pattern: '^[A-Za-z]{2}$' }
                promotionIds: { type: array, items: { type: string } }
                offerSnapshotTtlSeconds:
                  type: integer
                  minimum: 60
                  maximum: 86400
                  default: 3600
      responses:
        '201':
          description: Mapping created
          content:
            application/json:
              schema: { $ref: '#/components/schemas/GoodLeapOrganizationMapping' }
        '400': { description: 'Invalid body, preflight failure, or environment mismatch' }
        '401': { description: Unauthorized }
        '403': { description: Owner/Admin required }
        '503': { description: GoodLeap deps not configured }

  /integrations/goodleap/preflight:
    post:
      operationId: preflightGoodLeapMapping
      summary: Validate a GoodLeap mapping locally (Owner/Admin)
      description: |
        Local validation only — `providerValidated` is always `false`. Live
        channel/offer validation happens on the async rail once the mapping is
        active. The requested environment must match the provider target
        selected by this deployment. Requires verified email.
      tags: [Integrations]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [channel, categoryId]
              properties:
                environment: { type: string, enum: [sandbox, production] }
                channel: { type: string }
                categoryId: { type: string }
                subAccountId: { type: string, format: uuid, nullable: true }
                licensedStates: { type: array, items: { type: string, pattern: '^[A-Za-z]{2}$' } }
      responses:
        '200':
          description: Preflight result
          content:
            application/json:
              schema:
                type: object
                additionalProperties: false
                properties:
                  ok: { type: boolean }
                  errorCode: { type: string, nullable: true }
                  channel: { type: string }
                  categoryId: { type: string }
                  licensedStates: { type: array, items: { type: string } }
                  providerValidated: { type: boolean, enum: [false] }
        '400': { description: Invalid body or environment mismatch }
        '401': { description: Unauthorized }
        '403': { description: Owner/Admin required }
        '503': { description: GoodLeap deps not configured }

  /integrations/goodleap/mappings/{mappingId}:
    patch:
      operationId: updateGoodLeapOrganizationMapping
      summary: Update a GoodLeap organization mapping (Owner/Admin)
      description: |
        Activation stamps `verifiedAt` — the database refuses an active mapping
        without one, and without at least one licensed state.

        `channel` and `categoryId` are editable only while `verifiedAt` is null.
        The partial unique index on `(environment, channel)` is predicated on
        `verified_at IS NOT NULL`, so an unverified mapping is a draft that has
        claimed nothing and a typo can be corrected; once verified the channel is
        the tenant's live provider identity and a rename is refused with
        `mapping_identity_immutable`. A channel edit that would collide with a
        sibling mapping is refused with `channel_already_mapped`.

        `environment` and `subAccountId` are create-only and are not accepted
        here at all. An empty body is refused: a PATCH must change something. A
        status-only disable is permitted for a historical off-target mapping;
        activation and all other edits remain target-bound. Requires verified
        email.
      tags: [Integrations]
      parameters:
        - { name: mappingId, in: path, required: true, schema: { type: string, format: uuid } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              minProperties: 1
              properties:
                friendlyName: { type: string }
                status: { type: string, enum: [active, disabled] }
                licensedStates: { type: array, items: { type: string, pattern: '^[A-Za-z]{2}$' } }
                promotionIds: { type: array, items: { type: string } }
                providerOrganizationId: { type: string, minLength: 1, maxLength: 128 }
                offerSnapshotTtlSeconds: { type: integer, minimum: 60, maximum: 86400 }
                channel: { type: string }
                categoryId: { type: string }
      responses:
        '200':
          description: Updated mapping
          content:
            application/json:
              schema: { $ref: '#/components/schemas/GoodLeapOrganizationMapping' }
        '400': { description: 'Invalid body, mapping id, environment mismatch, channel collision, or identity edit after verification' }
        '401': { description: Unauthorized }
        '403': { description: Owner/Admin required }
        '404': { description: Mapping not found }
        '503': { description: GoodLeap deps not configured }

  /webhooks/goodleap:
    post:
      operationId: receiveGoodLeapWebhook
      summary: GoodLeap fetch-on-notify ingress
      description: |
        GoodLeap publishes no signature scheme, so ingress auth is Portrex's own:
        a static per-registration secret presented in `x-goodleap-webhook-secret`,
        verified as a peppered domain-separated HMAC digest behind a
        per-registration rate limit, BEFORE the body is parsed.

        The payload is never trusted as state. It is decoded to identifiers only
        (`event`, `referenceNumber`, `applicationId`) and used solely to mark a
        case dirty; authoritative state always comes from an authenticated
        provider read. A malformed body is quarantined as a receipt, not
        rejected, so the delivery is auditable.
      tags: [Webhooks]
      security: []
      parameters:
        - name: x-goodleap-webhook-secret
          in: header
          required: true
          schema: { type: string }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: true
              properties:
                event: { type: string }
                applicationId: { type: string }
                referenceNumber: { type: string }
                timestamp: { type: string }
      responses:
        '200':
          description: Receipt durably recorded (including quarantined payloads)
          content:
            application/json:
              schema:
                type: object
                additionalProperties: false
                properties:
                  received: { type: boolean, enum: [true] }
        '400': { description: Missing body }
        '401': { description: Unauthorized }
        '429': { description: Per-registration rate limit exceeded }
        '500': { description: Receipt could not be made durable }

  # Flow 2 — sub-company payer obligations. The head tenant's connected
  # company account is merchant of record; the sub-company is the payer.
  /billing/sub-companies:
    get:
      operationId: listSubCompanyBillingObligations
      summary: List sub-company payer obligations
      description: >-
        Lists sub-company entities visible to the tenant owner/admin or the
        exact sub-account admin branch. Charges are created on the head
        company's connected Stripe account; this is not PORTREX billing and
        does not route through branch-owned Stripe accounts.
      tags: [Billing]
      responses:
        '200':
          description: Sub-company obligation status
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SubAccountBillingList' }
        '401': { description: Unauthorized }
        '403': { description: Owner/Admin or exact sub-account-admin branch required }
        '503': { description: Database unavailable }

  /billing/sub-companies/{subAccountId}/checkout-session:
    post:
      operationId: createSubCompanyBillingCheckoutSession
      summary: Start a sub-company payer Checkout Session
      description: >-
        Creates a separate Flow 2 product/price and direct-charge Checkout
        Session on the active head-company connected account. The caller's
        Idempotency-Key is required and is forwarded to Stripe in a
        Connect-namespaced form. The server builds return URLs.
      tags: [Billing]
      parameters:
        - name: subAccountId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      responses:
        '200':
          description: Checkout session
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SubAccountBillingCheckout' }
        '400': { description: Invalid path or Idempotency-Key }
        '401': { description: Unauthorized }
        '403': { description: 'Role, scope, branch, or impersonation check failed' }
        '409': { description: 'Billing policy, merchant, existing subscription, or checkout claim conflict; W4-C: `processor_mismatch` when the dues binding says Square or the row is live on Square, `charge_in_progress` while a Square attempt of the row is open (a Square row that is not live moves back to Stripe first)' }
        '503': { description: Database unavailable }

  /billing/sub-companies/{subAccountId}/checkout-sync:
    post:
      operationId: syncSubCompanyBillingCheckout
      summary: Sync a completed sub-company Checkout Session
      tags: [Billing]
      parameters:
        - name: subAccountId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [session_id]
              properties:
                session_id: { type: string, minLength: 1, maxLength: 255 }
      responses:
        '200':
          description: Synced obligation
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SubAccountBillingMutation' }
        '400': { description: 'Invalid path, body, or Idempotency-Key' }
        '401': { description: Unauthorized }
        '403': { description: 'Role, scope, branch, or impersonation check failed' }
        '404': { description: Sub-company or Checkout Session not found }
        '409': { description: 'Session incomplete, merchant mismatch, or subscription mismatch; W4-C: `processor_mismatch` for a Square row' }
        '503': { description: Database unavailable }

  /billing/sub-companies/{subAccountId}/portal-session:
    post:
      operationId: createSubCompanyBillingPortalSession
      summary: Open the sub-company payer Billing Portal
      tags: [Billing]
      parameters:
        - name: subAccountId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      responses:
        '200':
          description: Portal session
          content:
            application/json:
              schema:
                type: object
                required: [url]
                properties:
                  url: { type: string, format: uri }
        '400': { description: Invalid path or Idempotency-Key }
        '401': { description: Unauthorized }
        '403': { description: 'Role, scope, branch, or impersonation check failed' }
        '409': { description: 'Merchant or customer unavailable; W4-C: `processor_mismatch` for a Square row' }
        '503': { description: Database unavailable }

  /billing/sub-companies/{subAccountId}/deadline:
    put:
      operationId: setSubCompanyDuesDeadline
      summary: Set or clear the dues date of one sub-company
      description: |
        Plan 2026-11-19-003 D4. Owner or Admin through an account-level
        membership only (the handler requires `integrations:connection:write`);
        a sub-account admin and each other role get 403
        `owner_or_admin_required`. An impersonated session is refused. No
        step-up: a dues date takes no access (remind only). The date is the end
        of the picked day in the sub-company zone; the rules of a member date
        apply (today + 3 days for a new or earlier date, at most 365 days), and
        `deadline_date: null` always clears. A first or an earlier date sends
        one `billing.dues_reminder` to each active sub-account admin of that
        sub-company. 404 `{"error":"not_found"}` for a sub-company that is not
        in the account; 409 `billing_not_enabled` with no policy row; 409
        `cannot_pay` (a date only) when the dues price is 0 or the company
        connection cannot charge. One account event when the date changed.
      tags: [Billing]
      parameters:
        - name: subAccountId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/SubAccountDuesDeadlineInput' }
      responses:
        '200':
          description: The sub-company row with its dues fields
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SubAccountBillingMutation' }
        '400': { description: 'Invalid path or body (`invalid_request`), or a missing Idempotency-Key' }
        '401': { description: Unauthorized }
        '402': { description: The caller's own member billing is locked }
        '403': { description: '`owner_or_admin_required`, `forbidden` (`account_level_membership_required`), `impersonation_forbidden` or `missing_scope`' }
        '404':
          description: '`not_found`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SubAccountDuesError' }
        '409':
          description: '`billing_not_enabled` or `cannot_pay`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SubAccountDuesError' }
        '422':
          description: '`deadline_too_soon` (with `earliest_allowed_date`), `deadline_in_past` or `deadline_too_far`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SubAccountDuesError' }
        '503': { description: Database unavailable }

  /billing/sub-companies/{subAccountId}/reminder:
    post:
      operationId: sendSubCompanyDuesReminder
      summary: Remind the admins of one sub-company to pay its dues
      description: |
        Plan 2026-11-19-003 D4. Owner or Admin through an account-level
        membership only; no body; no step-up. Recipients: each active
        sub-account admin of that sub-company (MD-6), in-app and email, no
        SMS. A person gets at most one admin-caused dues notice for a
        sub-company and a day, from all admins together. Answers: 200 with the
        counts; 404 `{"error":"not_found"}`; 409 `billing_not_enabled`,
        `paid`, `cannot_pay` or `no_branch_admin`. Each 200 writes one
        `billing.reminder.sent` audit row and one account event.
      tags: [Billing]
      parameters:
        - name: subAccountId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      responses:
        '200':
          description: What was sent
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SubAccountDuesReminderResult' }
        '400': { description: 'Invalid path, or a missing Idempotency-Key' }
        '401': { description: Unauthorized }
        '402': { description: The caller's own member billing is locked }
        '403': { description: '`owner_or_admin_required`, `forbidden` (`account_level_membership_required`), `impersonation_forbidden` or `missing_scope`' }
        '404':
          description: '`not_found`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SubAccountDuesError' }
        '409':
          description: '`billing_not_enabled`, `paid`, `cannot_pay` or `no_branch_admin`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SubAccountDuesError' }
        '503': { description: Database unavailable }

  /billing/sub-companies/{subAccountId}/cancel:
    post:
      operationId: cancelSubCompanyBillingSubscription
      summary: Cancel a sub-company payer subscription at period end
      description: |
        Stripe: `cancel_at_period_end` at Stripe. Square (W4-C): the engine rule
        under the payer lock, with no Square call and no Stripe client: an
        active or trialing row is set to end at the period end; a past-due
        row, or a row with an open invoice, ends now (the invoice void, the
        card disabled after the commit). `409 charge_in_progress` while an
        attempt is open.
      tags: [Billing]
      parameters:
        - name: subAccountId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      responses:
        '200':
          description: Updated obligation
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SubAccountBillingMutation' }
        '400': { description: Invalid path or Idempotency-Key }
        '401': { description: Unauthorized }
        '403': { description: 'Role, scope, branch, or impersonation check failed' }
        '409': { description: '`no_subscription`, `already_canceled`, `charge_in_progress`, `subscription_account_mismatch` or `stripe_not_configured` (a Stripe row only)' }
        '503': { description: Database unavailable }

  /billing/sub-companies/{subAccountId}/resume:
    post:
      operationId: resumeSubCompanyBillingSubscription
      summary: Keep the renewal of a sub-company's dues (the undo of a cancel)
      description: |
        W4-C, both processors. A live row (active or trialing) that is set to
        end and whose paid period has not ended renews again. Stripe:
        `cancel_at_period_end: false` at Stripe. Square: the local stamp is
        cleared under the payer lock, with no Square call. A row that is not
        set to end changes nothing (200). The fence of `/cancel`: an Owner or
        Admin needs `integrations:connection:write` (an account-level seat for
        every row, else the own branch row only); a branch admin needs
        `integrations:branch:write` and acts for the own sub-company only. No
        step-up. Refused for an impersonated session.
      tags: [Billing]
      parameters:
        - name: subAccountId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      responses:
        '200':
          description: Updated obligation
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SubAccountBillingMutation' }
        '400': { description: Invalid path or Idempotency-Key }
        '401': { description: Unauthorized }
        '402': { description: The caller's own member billing is locked }
        '403': { description: '`owner_or_admin_required`, `branch_scope_mismatch`, `missing_scope` or `impersonation_forbidden`' }
        '404': { description: '`not_found`: the sub-company is not in the account' }
        '409': { description: '`no_subscription` (nothing to keep, or the paid period has ended), `charge_in_progress`, `subscription_account_mismatch` or `stripe_not_configured`' }
        '503': { description: Database unavailable }

  # Plan 2026-11-19-002 § 18.2.5 (W4) — the Square card routes of dues. Owner
  # or Admin for each sub-company, a branch admin for the own sub-company only.
  /billing/sub-companies/{subAccountId}/subscribe:
    post:
      operationId: subscribeSubCompanyDuesOnSquare
      summary: Save the sub-company's card on Square and start its dues
      description: |
        Square only. Makes the dues obligation when none exists, changes its
        processor when that is necessary, saves the card on the head company's
        Square seller, then starts a trial or opens the period invoice. With
        an open invoice the answer is `payment_required` and the page calls
        `/pay` with the bank check. An Owner or Admin needs
        `integrations:connection:write`; a branch admin needs
        `integrations:branch:write` and acts for the own sub-company only. No
        step-up. Refused for an impersonated session. No answer carries a
        token or Square's `detail` text.
      tags: [Billing]
      parameters:
        - name: subAccountId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/CardSaveRequest' }
      responses:
        '200':
          description: The card is saved (`trialing` or `payment_required`, or `payment_pending` when an attempt is open)
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardSaveResult' }
        '400': { description: 'Invalid path or body, or a missing Idempotency-Key' }
        '401': { description: Unauthorized }
        '402': { description: The caller's own member billing is locked }
        '403':
          description: '`owner_or_admin_required`, `branch_scope_mismatch`, `missing_scope` or `impersonation_forbidden`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SubAccountCardRouteError' }
        '404':
          description: '`not_found`: the sub-company is not in the account'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SubAccountCardRouteError' }
        '409':
          description: '`consent_version_mismatch`, `not_ready` (with the reason of the dues binding), `already_subscribed`, `charge_in_progress`, `demo_account`, `billing_not_enabled` or `billing_price_invalid`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SubAccountCardRouteError' }
        '422':
          description: '`card_refused`: Square refused the card; nothing is stored'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SubAccountCardRouteError' }
        '502':
          description: '`square_unavailable`: no answer from Square after one resend'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SubAccountCardRouteError' }
        '503': { description: Database unavailable }

  /billing/sub-companies/{subAccountId}/payment-method:
    put:
      operationId: replaceSubCompanyDuesCardOnSquare
      summary: Replace the card on file of a sub-company's Square dues
      description: |
        Square only. Saves a new card for a live Square dues obligation and
        makes no charge. With an open invoice and no open attempt the answer
        is `payment_required`. The same fence as `/subscribe`: an Owner or
        Admin needs `integrations:connection:write`; a branch admin needs
        `integrations:branch:write` and acts for the own sub-company only. No
        step-up. Refused for an impersonated session.
      tags: [Billing]
      parameters:
        - name: subAccountId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/CardSaveRequest' }
      responses:
        '200':
          description: 'The card is replaced (`saved`, `payment_required` or `payment_pending`)'
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardSaveResult' }
        '400': { description: 'Invalid path or body, or a missing Idempotency-Key' }
        '401': { description: Unauthorized }
        '402': { description: The caller's own member billing is locked }
        '403':
          description: '`owner_or_admin_required`, `branch_scope_mismatch`, `missing_scope` or `impersonation_forbidden`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SubAccountCardRouteError' }
        '404':
          description: '`not_found`: the sub-company is not in the account'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SubAccountCardRouteError' }
        '409':
          description: '`consent_version_mismatch`, `not_ready`, `no_subscription`, `charge_in_progress`, `demo_account`, `billing_not_enabled` or `billing_price_invalid`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SubAccountCardRouteError' }
        '422':
          description: '`card_refused`: Square refused the card; nothing is stored'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SubAccountCardRouteError' }
        '502':
          description: '`square_unavailable`: no answer from Square after one resend'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SubAccountCardRouteError' }
        '503': { description: Database unavailable }

  /billing/sub-companies/{subAccountId}/pay:
    post:
      operationId: paySubCompanyDuesInvoiceOnSquare
      summary: Pay the open Square dues invoice of a sub-company with the payer present
      description: |
        Square only. Charges exactly the balance of the open dues invoice with
        the stored card and the token of the bank check that the page ran for
        that amount. A different amount or currency answers `409
        amount_changed`; a token that was used, or that Square refuses,
        answers `422 verify_again`. No answer from Square answers `202
        payment_pending`. The same fence as `/subscribe`: an Owner or Admin
        needs `integrations:connection:write`; a branch admin needs
        `integrations:branch:write` and acts for the own sub-company only. No
        step-up. Refused for an impersonated session.
      tags: [Billing]
      parameters:
        - name: subAccountId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/CardPayRequest' }
      responses:
        '200':
          description: Paid
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardPayResult' }
        '202':
          description: '`payment_pending`: no final answer from Square yet; read `GET /v1/billing/sub-companies` until the attempt is finished'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardPayResult' }
        '400': { description: 'Invalid path or body, or a missing Idempotency-Key' }
        '401': { description: Unauthorized }
        '402': { description: The caller's own member billing is locked }
        '403':
          description: '`owner_or_admin_required`, `branch_scope_mismatch`, `missing_scope` or `impersonation_forbidden`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SubAccountCardRouteError' }
        '404':
          description: '`not_found`: the sub-company is not in the account'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SubAccountCardRouteError' }
        '409':
          description: '`amount_changed`, `charge_in_progress`, `no_open_invoice` or `demo_account`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SubAccountCardRouteError' }
        '422':
          description: '`card_declined`, or `verify_again`: run the bank check again'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SubAccountCardRouteError' }
        '503': { description: Database unavailable }

  # Plan 2026-11-19-003 D2 — the tenant admin's member billing surface. The
  # rows and counts come from the same evaluation as the billing gate.
  /billing/members:
    get:
      operationId: listBillingMembers
      summary: Member list with the payment deadline, payment group and last reminder
      description: |
        One row for each member of the member set, with the access state the
        billing gate computes, the effective payment deadline and its source
        (`branch`, `company`, `staff` or `joined`), the payment group, the
        newest reminder and whether an admin may send one now. Requires
        `integrations:read` and `account:read`, and the role Owner, Admin or
        sub-account admin; each other role gets 403 `owner_or_admin_required`.
        A sub-account admin sees only the own branch. While member billing is
        not enabled every row has the group `not_billed`.
      tags: [Billing]
      responses:
        '200':
          description: Member list
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/BillingMembersResponse' }
        '401': { description: Unauthorized }
        '402': { description: The caller's own member billing is locked }
        '403': { description: 'Owner, Admin, or sub-account admin required' }
        '503': { description: Database unavailable }

  /billing/member-deadlines:
    get:
      operationId: getMemberBillingDeadlines
      summary: The member payment deadline card
      description: |
        The company date, the branch dates (read only), the staff default date,
        whether member billing is enabled, what the mode does after the
        deadline, the counts for each payment group, the earliest and latest
        date the PUT accepts, the time zone and its source, whether the caller
        is in the group `unpaid`, why nobody can pay (when that is so) and
        which actions the caller may take. Requires `integrations:read` and
        `account:read`, and the role Owner, Admin or sub-account admin. A
        sub-account admin sees only the own branch row and its counts.
      tags: [Billing]
      responses:
        '200':
          description: Deadline card
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/MemberBillingDeadlinesResponse' }
        '401': { description: Unauthorized }
        '402': { description: The caller's own member billing is locked }
        '403': { description: 'Owner, Admin, or sub-account admin required' }
        '503': { description: Database unavailable }
    put:
      operationId: setMemberBillingDeadline
      summary: Set, move or clear the company member payment deadline
      description: |
        The company date: Owner or Admin through an account-level membership
        only. A branch date (`sub_account_id`, D4): Owner or Admin for any
        branch, or a sub-account admin for the own branch when it receives its
        own payments (else 403 `branch_payments_required`); a branch outside
        the caller's reach answers 404 `{"error":"not_found"}`, like an
        unknown one. The static scope is `integrations:branch:write`; the
        handler also requires `integrations:connection:write` of an Owner or
        Admin. Step-up within one hour. An
        impersonated session is refused. `deadline_date` is a calendar day in
        the account's time zone; the deadline is the end of that day.
        `deadline_date: null` clears the company date. `sub_account_id` must
        be `null` (branch dates come later). The rules: a new or earlier date
        is today + 3 days or later; a later date is today or later, and today
        + 3 days or later after a passed date; at most 365 days ahead; a clear
        that leaves no date, or a date less than 3 days away, is refused. The
        answer is the same body as the GET.
      tags: [Billing]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/MemberBillingDeadlineInput' }
      responses:
        '200':
          description: The deadline card after the write
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/MemberBillingDeadlinesResponse' }
        '400': { description: 'Invalid body (`invalid_request`), or a missing Idempotency-Key' }
        '401': { description: 'Unauthorized, or step-up required' }
        '402': { description: The caller's own member billing is locked }
        '403': { description: '`owner_or_admin_required`, `account_level_membership_required`, `impersonation_forbidden`, `missing_scope` or `branch_payments_required` (a sub-account admin whose branch does not receive its own payments)' }
        '404': { description: '`not_found`' }
        '409': { description: '`billing_not_enabled`: no policy row, or the mode is off' }
        '422':
          description: '`deadline_too_soon` (with `earliest_allowed_date`), `deadline_in_past` or `deadline_too_far`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/MemberBillingDeadlineError' }
        '503': { description: Database unavailable }

  /billing/member-reminders:
    post:
      operationId: sendMemberBillingReminders
      summary: Send a payment reminder to one member, one branch, or every unpaid member
      description: |
        Owner or Admin through an account-level membership (the handler also
        requires `integrations:connection:write`), or a sub-account admin for
        the own branch (static scope `integrations:branch:write`). Each other
        role gets 403 `owner_or_admin_required`. An impersonated session is
        refused. No step-up. The server resolves the recipients from the
        member set; the body names no email and carries no text. A member in
        the group `unpaid` gets `billing.payment_reminder` ("Pay now"), one in
        `failing` gets `billing.payment_update_reminder`; in-app and email,
        no SMS. The answers, in order: (1) a `user_id` or `sub_account_id`
        outside the caller's branch, or one that does not exist, answers 404
        with the body `{"error":"not_found"}`, before any other check of the
        target; (2) `billing_not_enabled`; for one member, 409 `not_billed`,
        `paid`, `cannot_pay` or `reminded_today` (with `next_allowed_on`);
        (3) 200 with the counts. A person gets at most one admin-caused
        notice a day, from all admins together, the notice for a set date
        included. Each 200 writes one `billing.reminder.sent` audit row and
        one account event with the target and the counts; the sender gets no
        copy.
      tags: [Billing]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/MemberReminderInput' }
      responses:
        '200':
          description: What was sent and why the others got nothing
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/MemberReminderResult' }
        '400': { description: 'Invalid body (`invalid_request`), or a missing Idempotency-Key' }
        '401': { description: Unauthorized }
        '402': { description: The caller's own member billing is locked }
        '403': { description: '`owner_or_admin_required`, `forbidden` (`account_level_membership_required`), `impersonation_forbidden` or `missing_scope`' }
        '404':
          description: '`not_found`: an unknown id, or one outside the caller''s branch (the same body)'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/MemberReminderError' }
        '409':
          description: '`billing_not_enabled`; one member: `not_billed`, `paid`, `cannot_pay` or `reminded_today` (with `next_allowed_on`)'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/MemberReminderError' }
        '503': { description: Database unavailable }

  /billing/me:
    get:
      operationId: getMyBillingStatus
      summary: The signed-in member's own subscription status
      description: |
        Everything the member's billing page needs in one call: their access
        state, subscription, the tenant's policy summary, who the merchant is,
        and which actions they may take right now. When the member's billing
        resolves to Square, the answer also has `processor`, the `card_setup`
        block of the card page and `open_attempt` (plan 2026-11-19-002 § 7.1);
        a demo account and the house account get no `card_setup`. Requires `billing:read`,
        which every tenant role holds — a member whose access has lapsed must
        still be able to reach the surface that lets them pay, so this route is
        exempt from billing enforcement and carries no step-up.
      tags: [Billing]
      responses:
        '200':
          description: Billing status
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/UserBillingMe' }
        '401': { description: Unauthorized }
        '503': { description: Database unavailable }

  /billing/me/invoices:
    get:
      operationId: listMyBillingInvoices
      summary: The member's own subscription invoices
      description: |
        Cursor-paginated, newest first, with Stripe's hosted and PDF links so a
        member can download a receipt. Square period invoices are in the same
        list, with `stripe_invoice_id` null and Square's `receipt_url` (plan
        2026-11-19-002 § 7.1). Requires `billing:read`.
      tags: [Billing]
      parameters:
        - { name: cursor, in: query, required: false, schema: { type: string } }
        - { name: limit, in: query, required: false, schema: { type: integer, minimum: 1, maximum: 50 } }
      responses:
        '200':
          description: Invoice page
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema:
                type: object
                required: [data, next_cursor]
                properties:
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/UserBillingInvoice' }
                  next_cursor: { type: string, nullable: true }
        '400': { description: Invalid query }
        '401': { description: Unauthorized }
        '503': { description: Database unavailable }

  /billing/me/checkout-session:
    post:
      operationId: createMyBillingCheckoutSession
      summary: Start a Checkout Session on the tenant's Stripe account
      description: |
        Creates (or reuses) the price and customer on the tenant's connected
        account and returns a Stripe Checkout URL. Requires `billing:read`; the
        success and cancel URLs are built from the server's configured app URL
        and are never accepted from the caller. Refused for an impersonating
        staff member and for service accounts — a subscription is a personal
        payment obligation.
      tags: [Billing]
      responses:
        '200':
          description: Checkout session
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema:
                type: object
                required: [session_id, url]
                properties:
                  session_id: { type: string }
                  url: { type: string, nullable: true }
        '401': { description: Unauthorized }
        '403': { description: Impersonation or service account }
        '409': { description: 'Billing not enabled, Stripe not connected or charges disabled, or already subscribed' }
        '503': { description: Database unavailable }

  /billing/me/checkout-sync:
    post:
      operationId: syncMyBillingCheckout
      summary: Settle the Checkout return leg without waiting for a webhook
      description: |
        Reads the completed session from the connected account and writes the
        resulting subscription, so the member sees the new state the moment they
        land back on the page. Requires `billing:read`. A session whose metadata
        names a different member or account is refused before anything is
        written.
      tags: [Billing]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [session_id]
              additionalProperties: false
              properties:
                session_id: { type: string, maxLength: 255 }
      responses:
        '200':
          description: Subscription after the sync
          content:
            application/json:
              schema:
                type: object
                required: [subscription]
                properties:
                  subscription:
                    allOf: [{ $ref: '#/components/schemas/UserSubscription' }]
                    nullable: true
        '400': { description: Invalid body }
        '401': { description: Unauthorized }
        '403': { description: Impersonation or service account }
        '404': { description: 'Session not found or not this member''s' }
        '409': { description: 'Stripe not connected, or the session has not completed' }
        '503': { description: Database unavailable }

  /billing/me/portal-session:
    post:
      operationId: createMyBillingPortalSession
      summary: Open the Stripe Billing Portal for the member
      description: |
        Returns a Billing Portal URL on the tenant's connected account, where a
        member updates their card, reads invoices, or cancels. Requires
        `billing:read`; the return URL is server-built. Pass
        `payment_method_update` to open Stripe directly in its card-update flow.
      tags: [Billing]
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                flow:
                  type: string
                  enum: [payment_method_update]
      responses:
        '200':
          description: Portal session
          content:
            application/json:
              schema:
                type: object
                required: [url]
                properties:
                  url: { type: string, format: uri }
        '401': { description: Unauthorized }
        '400': { description: Invalid portal flow }
        '403': { description: Impersonation or service account }
        '409': { description: 'Stripe not connected, or the member has no customer yet' }
        '503': { description: Database unavailable }

  /billing/me/cancel:
    post:
      operationId: cancelMyBillingSubscription
      summary: Cancel the member's subscription
      description: |
        A subscription that is `active` or `trialing` is set to end at the end
        of the paid period: the member keeps what they paid for. On Stripe this
        sets cancel-at-period-end on the connected account; on Square it is a
        local stamp.

        A Square subscription whose payment failed (`past_due`, `unpaid`), or
        whose first invoice is not paid yet, ends NOW: the open invoice becomes
        void, the status becomes `canceled`, Portrex makes no later charge and
        no retry, and the card is disabled at Square. The answer then has
        `subscription.status: canceled` with `cancel_at_period_end: false`.
        While a payment is being confirmed the answer is `409` with
        `error: charge_in_progress`; the member tries again in a moment.

        Requires `billing:read`.
      tags: [Billing]
      responses:
        '200':
          description: Subscription after the cancellation (set to end at the period end, or ended now)
          content:
            application/json:
              schema:
                type: object
                required: [subscription]
                properties:
                  subscription:
                    allOf: [{ $ref: '#/components/schemas/UserSubscription' }]
                    nullable: true
        '401': { description: Unauthorized }
        '403': { description: Impersonation or service account }
        '409': { description: "Nothing to cancel (`no_subscription`, `already_canceled`), or a payment is being confirmed (`charge_in_progress`)" }
        '503': { description: Database unavailable }

  /billing/me/resume:
    post:
      operationId: resumeMyBillingSubscription
      summary: Keep the member's subscription — undo a cancel before the period end
      description: |
        "Keep subscription" (plan 2026-11-19-002 § 5.6, § 7.1; W7), both
        processors. Allowed only for a live (active or trialing)
        subscription that is set to end and whose paid period has not ended.
        On Square the stamp is cleared under the payer lock of the cancel,
        with no Square call; while a payment is being confirmed the answer is
        `409 charge_in_progress`. On Stripe Portrex clears
        `cancel_at_period_end` on the connected account with an idempotency
        key of the request, and a fixed `cancel_at` too (a second update with
        its own key); `502 stripe_error` while Stripe still ends the
        subscription. A subscription that is not set to end answers
        200 with no change. Requires `billing:read` and an `Idempotency-Key`;
        no step-up. Refused for an impersonating staff member and for service
        accounts. One audit event `billing.subscription.resumed` for a change.
      tags: [Billing]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      responses:
        '200':
          description: The subscription after the resume (not set to end)
          content:
            application/json:
              schema:
                type: object
                required: [subscription]
                properties:
                  subscription:
                    allOf: [{ $ref: '#/components/schemas/UserSubscription' }]
                    nullable: true
        '400': { description: Missing Idempotency-Key }
        '401': { description: Unauthorized }
        '403': { description: Impersonation or service account }
        '409': { description: "Nothing to keep (`no_subscription`: not live, or the paid period has ended), a payment is being confirmed (`charge_in_progress`), `subscription_account_mismatch`, or `stripe_not_configured`" }
        '502': { description: '`stripe_error`: Stripe still ends the subscription after the resume; nothing changed in Portrex' }
        '503': { description: Database unavailable }

  /billing/me/subscribe:
    post:
      operationId: subscribeMyBillingOnSquare
      summary: Save the member's card on Square and start the subscription
      description: |
        Square only (plan 2026-11-19-002 § 5.1, § 7.1). Changes the processor
        of the member's row when that is necessary, creates the Square customer
        and card on the tenant's seller, then starts a trial or opens the
        period invoice. With an open invoice the answer is `payment_required`
        and the page calls `/v1/billing/me/pay` with the bank check. Requires
        `billing:read`; no step-up, because a locked member must be able to
        pay. Refused for an impersonating staff member and for service
        accounts. No answer carries a token or Square's `detail` text.
      tags: [Billing]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/CardSaveRequest' }
      responses:
        '200':
          description: The card is saved (`trialing` or `payment_required`, or `payment_pending` when an attempt is open)
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardSaveResult' }
        '400': { description: 'Invalid body, or a missing Idempotency-Key' }
        '401': { description: Unauthorized }
        '403': { description: Impersonation or service account }
        '409':
          description: '`consent_version_mismatch`, `not_ready` (with the binding reason), `already_subscribed`, `demo_account`, `billing_not_enabled` or `billing_price_invalid`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardRouteError' }
        '422':
          description: '`card_refused`: Square refused the card; nothing is stored'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardRouteError' }
        '503': { description: 'Database or Square unavailable' }

  /billing/me/payment-method:
    put:
      operationId: replaceMyBillingCardOnSquare
      summary: Replace the card on file of the member's Square subscription
      description: |
        Square only (plan 2026-11-19-002 § 5.5, § 7.1). Saves a new card for
        the same Square customer and makes no charge. The old card stays
        enabled while an open attempt names it. With an open invoice and no
        open attempt the answer is `payment_required`. Requires
        `billing:read`; no step-up. Refused for an impersonating staff member
        and for service accounts.
      tags: [Billing]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/CardSaveRequest' }
      responses:
        '200':
          description: 'The card is replaced (`saved`, `payment_required` or `payment_pending`)'
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardSaveResult' }
        '400': { description: 'Invalid body, or a missing Idempotency-Key' }
        '401': { description: Unauthorized }
        '403': { description: Impersonation or service account }
        '409':
          description: '`consent_version_mismatch`, `not_ready`, `no_subscription` or `demo_account`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardRouteError' }
        '422':
          description: '`card_refused`: Square refused the card; nothing is stored'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardRouteError' }
        '503': { description: 'Database or Square unavailable' }

  /billing/me/pay:
    post:
      operationId: payMyBillingInvoiceOnSquare
      summary: Pay the member's open Square invoice with the payer present
      description: |
        Square only (plan 2026-11-19-002 § 3.5, § 7.1). Charges exactly the
        balance of the open invoice with the stored card and the token of the
        bank check that the page ran for that amount. A different amount or
        currency answers `409 amount_changed`; a token that was used, or that
        Square refuses, answers `422 verify_again`. No answer from Square
        answers `202 payment_pending`. Requires `billing:read`; no step-up.
        Refused for an impersonating staff member and for service accounts.
      tags: [Billing]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/CardPayRequest' }
      responses:
        '200':
          description: Paid
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardPayResult' }
        '202':
          description: '`payment_pending`: no final answer from Square yet; read `GET /v1/billing/me` until the attempt is finished'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardPayResult' }
        '400': { description: 'Invalid body, or a missing Idempotency-Key' }
        '401': { description: Unauthorized }
        '403': { description: Impersonation or service account }
        '409':
          description: '`amount_changed`, `charge_in_progress`, `no_open_invoice`, `not_ready` or `demo_account`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardRouteError' }
        '422':
          description: '`card_declined`, or `verify_again`: run the bank check again'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/CardRouteError' }
        '503': { description: 'Database or Square unavailable' }

  /integrations/square:
    get:
      operationId: getSquareConnectionStatus
      summary: Tenant Square connection status (Owner/Admin, branch admins see their own branch)
      description: |
        Reports whether the platform has a Square application configured,
        whether this tenant collects through one company Square account or one
        account per sub-company, and the connected accounts (merchant ids
        masked) with the location that takes payments. Requires
        `integrations:read` and `account:read`. A sub-account admin sees only
        their own branch row. No token is part of the response.
      tags: [Integrations]
      responses:
        '200':
          description: Connection status
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SquareConnectStatus' }
        '401': { description: Unauthorized }
        '403': { description: 'Owner, Admin, or sub-account admin required' }
        '503': { description: Database unavailable }

  /integrations/square/scope:
    put:
      operationId: setSquareConnectionScope
      summary: Choose one company Square account or one per sub-company (Owner/Admin)
      description: |
        Sets whether every invoice is collected on the company's Square account
        or each sub-company connects its own. Requires
        `integrations:connection:write`; refused for sub-account admins. A
        payment link that already exists stays on the account that created it.
      tags: [Integrations]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [scope]
              additionalProperties: false
              properties:
                scope: { type: string, enum: [company, branch] }
      responses:
        '200':
          description: Scope recorded
          content:
            application/json:
              schema:
                type: object
                required: [connection_scope]
                properties:
                  connection_scope: { type: string, enum: [company, branch] }
        '400': { description: Invalid body }
        '401': { description: Unauthorized }
        '403': { description: Owner or Admin required }
        '503': { description: Database unavailable }

  /integrations/square/connect:
    post:
      operationId: startSquareOAuth
      summary: Start Square OAuth and return the authorization URL
      description: |
        Mints an HMAC state bound to the account, the acting user, the target
        branch and a short expiry, and returns Square's authorization URL (code
        flow). Requires `integrations:branch:write`. A sub-account admin may
        start this only for their own branch and only while the tenant connects
        per sub-company. No Portrex or Square secret is placed in the URL.
      tags: [Integrations]
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                sub_account_id: { type: string, format: uuid, nullable: true }
      responses:
        '200':
          description: Authorization URL
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema:
                type: object
                required: [authorization_url, redirect_uri, expires_at]
                properties:
                  authorization_url: { type: string, format: uri }
                  redirect_uri: { type: string, format: uri }
                  expires_at: { type: string, format: date-time }
        '400': { description: Invalid body }
        '401': { description: Unauthorized }
        '403': { description: 'Branch scope mismatch or role not permitted' }
        '404': { description: Sub-account not found }
        '409': { description: 'Square not configured, or branch connections disabled' }
        '503': { description: Database unavailable }
    get:
      operationId: redirectToSquareOAuth
      summary: Start Square OAuth as a browser redirect
      description: |
        Same flow as the POST form, for a plain link: responds 303 to Square.
        Requires `integrations:branch:write`.
      tags: [Integrations]
      parameters:
        - { name: sub_account_id, in: query, required: false, schema: { type: string, format: uuid } }
      responses:
        '303': { description: Redirect to Square }
        '400': { description: Invalid query }
        '401': { description: Unauthorized }
        '403': { description: 'Branch scope mismatch or role not permitted' }
        '404': { description: Sub-account not found }
        '409': { description: 'Square not configured, or branch connections disabled' }

  /integrations/square/callback:
    get:
      operationId: completeSquareOAuth
      summary: Square OAuth callback (browser redirect from Square)
      description: |
        Public route whose authorization is the signed state minted at connect
        time: nothing is written until that state verifies AND names the account
        and user of the live session. The exchange stores the seller's access
        and refresh tokens as a KEK envelope on the connection row; no token is
        logged or returned. A different seller cannot replace a live connection
        in place. Always answers with a redirect back to the Square settings
        page carrying
        `oauth=connected|no_location|state_invalid|denied|exchange_failed|merchant_in_use|disconnect_first`.
      tags: [Integrations]
      parameters:
        - { name: code, in: query, required: false, schema: { type: string } }
        - { name: state, in: query, required: false, schema: { type: string } }
        - { name: error, in: query, required: false, schema: { type: string } }
        - { name: error_description, in: query, required: false, schema: { type: string } }
      responses:
        '303': { description: Redirect back to the Square settings page }

  /integrations/square/disconnect:
    post:
      operationId: disconnectSquareAccount
      summary: Cancel open payment links and revoke Portrex's access to a Square account
      description: |
        Cancels the open invoice payment links of the connection at Square,
        revokes the authorization, drops the stored tokens and marks the
        connection disconnected. Each link is reconciled with Square first: a
        paid one settles its invoice, a stale processing one whose payment
        failed is cancelled. Requires `integrations:branch:write`; a
        sub-account admin may disconnect only their own branch. Answers 409
        `payment_links_active` while a payment on one of the links is in
        progress (`in_progress`): after a revoke Square sends no more events
        for the seller. It also answers 409 when one request did not reach
        every open link (`more_to_cancel`); the tenant disconnects again. A
        link that Square definitively leaves in place (the order does not
        match the invoice, or Square refuses the delete) does not block: it
        counts in `unconfirmed_payment_links` and raises an alert.
        When the stored token cannot be opened, the links cannot be cancelled;
        the authorization is still revoked with the application credential
        (503 `payment_provider_unavailable` when Square does not answer), and
        `unconfirmed_payment_links` counts the checkouts of the connection
        that Square could not be asked to cancel.
      tags: [Integrations]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [connect_account_id]
              additionalProperties: false
              properties:
                connect_account_id: { type: string, format: uuid }
      responses:
        '200':
          description: Disconnected
          content:
            application/json:
              schema:
                type: object
                required: [disconnected, active_connections, cancelled_payment_links, unconfirmed_payment_links]
                properties:
                  disconnected: { type: boolean }
                  active_connections: { type: integer }
                  cancelled_payment_links: { type: integer }
                  unconfirmed_payment_links:
                    type: integer
                    description: |
                      Checkouts still open on this connection that Square did
                      not cancel: Square could not be asked (no usable token),
                      or Square answered and left the link in place (binding
                      mismatch, refused delete). 0 otherwise.
                  member_subscriptions:
                    type: integer
                    minimum: 0
                    description: |
                      Plan 2026-11-19-002 § 7.3 (W3): the live Square member
                      subscriptions of this seller whose charges stop. The
                      scheduler charges a payer only while its seller has an
                      active connection.
                  dues_subscriptions:
                    type: integer
                    minimum: 0
                    description: 'W4: the live Square sub-company dues obligations of this seller whose charges stop.'
        '400': { description: Invalid body }
        '401': { description: Unauthorized }
        '403': { description: 'Branch scope mismatch or role not permitted' }
        '404': { description: Connection not found }
        '409':
          description: Invoice payments are still in progress on this connection, or more open links remain to cancel (`payment_links_active`)
          content:
            application/json:
              schema:
                type: object
                required: [error, in_progress, more_to_cancel, remaining, cancelled_payment_links]
                properties:
                  error: { type: string, enum: [payment_links_active] }
                  in_progress:
                    type: integer
                    description: Checkouts with a payment under way, or a link being created right now.
                  more_to_cancel:
                    type: integer
                    description: Checkouts this request did not reach. Disconnect again to continue.
                  remaining:
                    type: integer
                    description: in_progress + more_to_cancel.
                  cancelled_payment_links:
                    type: integer
                    description: Links Square confirmed cancelled in this request.
                  request_id: { type: string }
        '503': { description: Database or Square unavailable }

  /integrations/square/sync:
    post:
      operationId: syncSquareConnectAccountSnapshot
      summary: Refresh the connected Square account's status
      description: |
        Re-reads the merchant and the location that takes payments from Square
        onto the stored connection. Requires `integrations:branch:write`; no
        step-up, because the tenant chooses nothing here. A per-account failure
        is recorded on the row and reported in the counts rather than failing
        the request.
      tags: [Integrations]
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                connect_account_id: { type: string, format: uuid }
      responses:
        '200':
          description: Sync result
          content:
            application/json:
              schema:
                type: object
                required: [synced, total]
                properties:
                  synced: { type: integer }
                  total: { type: integer }
        '400': { description: Invalid body }
        '401': { description: Unauthorized }
        '403': { description: Role not permitted }
        '404': { description: Connection not found }
        '409': { description: Square not configured }
        '503': { description: Database unavailable }

  /integrations/square/locations:
    get:
      operationId: listSquareLocations
      summary: Locations of one connected Square account
      description: |
        Reads the seller's locations live from Square, with the one that takes
        payments marked. Requires `integrations:read` and `account:read`; a
        sub-account admin may read only their own branch connection.
      tags: [Integrations]
      parameters:
        - { name: connect_account_id, in: query, required: true, schema: { type: string, format: uuid } }
      responses:
        '200':
          description: Locations
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema:
                type: object
                required: [connect_account_id, selected_location_id, locations]
                properties:
                  connect_account_id: { type: string, format: uuid }
                  selected_location_id: { type: string, nullable: true }
                  locations:
                    type: array
                    items: { $ref: '#/components/schemas/SquareLocation' }
        '400': { description: Invalid query }
        '401': { description: Unauthorized }
        '403': { description: 'Branch scope mismatch or role not permitted' }
        '404': { description: Connection not found }
        '409': { description: 'Square not configured, or the connection must be renewed' }
        '503': { description: Database or Square unavailable }

  /integrations/square/location:
    put:
      operationId: setSquarePaymentLocation
      summary: Choose the Square location that takes payments
      description: |
        Sets the location on which invoice payment links are created for one
        connection. The location must be one that Square lists for that seller.
        Requires `integrations:branch:write`; a sub-account admin may change
        only their own branch connection.
      tags: [Integrations]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [connect_account_id, location_id]
              additionalProperties: false
              properties:
                connect_account_id: { type: string, format: uuid }
                location_id: { type: string }
      responses:
        '200':
          description: Location recorded
          content:
            application/json:
              schema:
                type: object
                required: [connection]
                properties:
                  connection: { $ref: '#/components/schemas/SquareConnectAccountSummary' }
        '400': { description: Invalid body }
        '401': { description: Unauthorized }
        '403': { description: 'Branch scope mismatch or role not permitted' }
        '404': { description: Connection or location not found }
        '409': { description: 'Square not configured, or the connection must be renewed (`square_reconnect_required`), or `payment_link_pending`: a payment link of this connection is being created; try again in a minute' }
        '503': { description: Database or Square unavailable }

  /integrations/square/subscription-agreement:
    post:
      operationId: agreeToSquareMemberBilling
      summary: Record the tenant's agreement to member billing on Square (Owner/Admin)
      description: |
        The tenant agrees that Portrex saves its members' cards with Square and
        charges them each month on the tenant's Square account (plan
        2026-11-19-002 § 4.1, § 7.3, § 10). Until an agreement exists, members
        whose billing resolves to Square are `pending_setup` and nobody is
        charged. Requires `integrations:connection:write` and a 1 hour step-up;
        Owner or Admin through an account-level seat; refused for an
        impersonated session. The body names the version of the sentence the
        page showed. The house account is refused. A second call with the same
        version changes nothing.
      tags: [Integrations]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/SquareSubscriptionsAgreementInput' }
      responses:
        '200':
          description: The agreement (stored now, or already stored)
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SquareSubscriptionsAgreementResult' }
        '400': { description: 'Invalid body, or a missing Idempotency-Key' }
        '401': { description: 'Unauthorized, or a fresh step-up required (`step-up-required`)' }
        '403':
          description: 'Owner or Admin required, an account-level seat required, or impersonation'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SquareSubscriptionsAgreementError' }
        '409':
          description: '`agreement_version_mismatch` or `house_account`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/SquareSubscriptionsAgreementError' }
        '503': { description: Database unavailable }

  /payment-processor:
    get:
      operationId: getInvoicePaymentProcessor
      summary: The tenant's invoice payment processor (Stripe or Square)
      description: |
        Reports the tenant's explicit choice, the processor a new customer
        invoice payment link uses now, and which processors are connected.
        Requires `integrations:read` and `account:read`.
      tags: [Integrations]
      responses:
        '200':
          description: Processor state
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/InvoicePaymentProcessorState' }
        '401': { description: Unauthorized }
        '403': { description: 'Owner, Admin, or sub-account admin required' }
        '503': { description: Database unavailable }
    put:
      operationId: setInvoicePaymentProcessor
      summary: Choose Stripe or Square for new invoice payment links (Owner/Admin)
      description: |
        Sets the processor that creates NEW customer invoice payment links.
        Only a connected processor can be selected. An invoice that already has
        a payment link keeps its processor and merchant. Requires
        `integrations:connection:write`; refused for sub-account admins.
      tags: [Integrations]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [provider]
              additionalProperties: false
              properties:
                provider: { type: string, enum: [stripe, square] }
      responses:
        '200':
          description: Processor recorded
          content:
            application/json:
              schema: { $ref: '#/components/schemas/InvoicePaymentProcessorState' }
        '400': { description: Invalid body }
        '401': { description: Unauthorized }
        '403': { description: Owner or Admin required }
        '409': { description: That processor is not connected }
        '503': { description: Database unavailable }

  /webhooks/stripe/connect:
    post:
      operationId: receiveStripeConnectWebhook
      summary: Stripe webhook for tenants' connected accounts
      description: |
        Public, authenticated by Stripe's signature over the raw request bytes
        using the Connect endpoint's own signing secret. Events are deduplicated
        by Stripe event id in the same transaction as the handler, so a failure
        rolls the ledger row back and Stripe's retry re-processes. An event for
        an account Portrex no longer knows is acknowledged and dropped.
      tags: [Webhooks]
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, additionalProperties: true }
      responses:
        '200': { description: 'Acknowledged: processed, replayed, or dropped' }
        '400': { description: 'Invalid signature or missing raw body' }
        '401': { description: Missing signature header }
        '500': { description: 'Handler failed (transaction rolled back) or endpoint misconfigured' }
        '503': { description: Database unavailable }

  /webhooks/square:
    post:
      operationId: receiveSquareWebhook
      summary: Square webhook for tenants' connected seller accounts
      description: |
        Public, authenticated by Square's `x-square-hmacsha256-signature`: the
        HMAC-SHA256 of the notification URL followed by the raw request bytes,
        keyed by the webhook subscription's signature key. Events are
        deduplicated by Square event id in the same transaction as the handler,
        so a failure rolls the ledger row back and Square's retry re-processes.
        A completed payment settles the invoice whose payment link created the
        order. An event for a seller or an order Portrex does not know is
        acknowledged and dropped.
      tags: [Webhooks]
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, additionalProperties: true }
      responses:
        '200': { description: 'Acknowledged: processed, replayed, or dropped' }
        '400': { description: 'Invalid signature or missing raw body' }
        '401': { description: Missing signature header }
        '500': { description: 'Handler failed (transaction rolled back) or endpoint misconfigured' }
        '503': { description: Database unavailable }

  /webhooks/square/platform:
    post:
      operationId: squarePlatformWebhook
      summary: Square webhook of Portrex's own Square account (the platform seller)
      description: |
        Plan 2026-11-19-002 § 7.8, § 17.2.5 (W5). Signed by Square with
        `SQUARE_PLATFORM_WEBHOOK_SIGNATURE_KEY` over the notification URL and
        the raw body. A webhook is only a trigger to read Square again; the
        handler takes no amount, state or card from the body. The same event
        two times has one effect; an event of another merchant is acknowledged
        and dropped; when Square cannot be read the answer is 503 and no ledger
        row is written.
      tags: [Webhooks]
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object }
      responses:
        '200': { description: Acknowledged }
        '400': { description: 'Invalid signature or missing raw body' }
        '401': { description: Missing signature header }
        '500': { description: 'Endpoint misconfigured (no signature key) or handler failed (transaction rolled back)' }
        '503': { description: 'Database or Square unavailable; Square delivers the event again' }

  /integrations/mattermost/webhook-secret/reveal:
    post:
      operationId: revealMattermostInboundWebhookSecret
      summary: Reveal inbound webhook HMAC secret for mm-inbound-relay (Owner/Admin)
      description: |
        Returns the current inbound webhook secret and can mint or rotate it.
        The declared step-up window is 300 seconds. Freshness is enforced when
        PORTREX_REQUIRE_STEP_UP is exactly true; this gate does not check factor type.
        Authentication and Owner/Admin checks always apply.

        All responses, including errors, use Cache-Control: no-store. Completed
        keys return 409 idempotency_secret_response_unavailable instead of a
        secret replay. Do not automatically retry rotate=true with a fresh key.
        Inspect the integration first. For an explicit current-secret reveal,
        use a fresh key with rotate omitted or false; a missing secret can be generated.
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      tags: [Integrations]
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                rotate:
                  type: boolean
                  description: When true, mint a new secret before reveal (invalidates prior VPS file until updated).
      responses:
        '200':
          description: Plaintext secret returned once in this response (never on GET settings)
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema:
                type: object
                required: [webhook_secret, inbound_webhook_path, generated, rotated]
                additionalProperties: false
                properties:
                  webhook_secret: { type: string }
                  inbound_webhook_path: { type: string }
                  generated: { type: boolean }
                  rotated: { type: boolean }
        '403': { description: Owner or Admin required }
        '409': { $ref: '#/components/responses/SecretOperationConflict' }

  /integrations/mattermost/hooks/{accountId}:
    post:
      operationId: receiveMattermostInboundRelayHook
      summary: mm-inbound-relay ingress (VPS websocket → HMAC JSON)
      tags: [Integrations]
      parameters:
        - name: accountId
          in: path
          required: true
          schema: { type: string, format: uuid }
        - name: X-Portrex-Timestamp
          in: header
          required: true
          schema: { type: string }
        - name: X-Portrex-Signature
          in: header
          required: true
          schema: { type: string, description: 'sha256=<hex HMAC-SHA256(secret, timestamp + "." + raw_body)>' }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [post_id]
              additionalProperties: true
              properties:
                post_id: { type: string }
                root_id: { type: string, nullable: true }
                channel_id: { type: string, nullable: true }
                channel_type: { type: string, nullable: true }
                user_id: { type: string, nullable: true }
                message: { type: string, nullable: true }
                text: { type: string, nullable: true }
                # Relay v2 envelope. All fields are optional so a v1 relay payload
                # (post_id + a few fields, no `event`) stays valid.
                event:
                  type: string
                  enum: [post, post_edited, post_deleted, reaction_added, reaction_removed]
                  default: post
                user_email: { type: string, nullable: true }
                update_at: { type: integer, format: int64, nullable: true }
                create_at: { type: integer, format: int64, nullable: true }
                emoji_name: { type: string, nullable: true }
                file_ids:
                  type: array
                  items: { type: string }
      responses:
        '200': { description: 'Accepted (inserted or duplicate idempotent receipt)' }
        '400': { description: Invalid payload }
        '401': { description: Invalid webhook signature }
        '403': { description: Mattermost not connected for account }
        '503': { description: Webhook secret missing or database unavailable }

  /integrations/mattermost:
    get:
      operationId: getMattermostIntegrationSettings
      summary: Mattermost integration settings (Owner/Admin)
      tags: [Integrations]
      responses:
        '200':
          description: Settings without secrets
          content:
            application/json:
              schema: { $ref: '#/components/schemas/MattermostSettingsResponse' }
        '401': { description: Unauthorized }
        '403': { description: Owner or Admin required }
    put:
      operationId: saveMattermostIntegrationSettings
      summary: Save Mattermost settings with live probe (Owner/Admin)
      tags: [Integrations]
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, additionalProperties: true }
      responses:
        '200':
          description: Saved settings
          content:
            application/json:
              schema: { $ref: '#/components/schemas/MattermostSettingsResponse' }
        '400': { description: Validation error }
        '422': { description: Probe failed }

  /integrations/mattermost/test:
    post:
      operationId: testMattermostIntegrationToken
      summary: Probe Mattermost connectivity (Owner/Admin)
      description: >-
        With no body, tests the sealed token and records the health observation.
        With `bot_token`, probes the pasted token WITHOUT saving it (use this
        before the first Connect). `site_url` and `team_id` may be supplied with
        the token for the probe; they are not persisted.
      tags: [Integrations]
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                bot_token: { type: string, maxLength: 512 }
                site_url: { type: string, format: uri }
                team_id: { type: string, maxLength: 64 }
      responses:
        '200':
          description: Probe outcome (never echoes the token)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/MattermostSettingsResponse' }
        '400': { description: Validation error }
        '401': { description: Unauthorized }
        '403': { description: Owner or Admin required }

  /integrations/mattermost/health:
    post:
      operationId: checkMattermostIntegrationHealth
      summary: Probe Mattermost connectivity (alias of /test)
      tags: [Integrations]
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                bot_token: { type: string, maxLength: 512 }
                site_url: { type: string, format: uri }
                team_id: { type: string, maxLength: 64 }
      responses:
        '200':
          description: Probe outcome (never echoes the token)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/MattermostSettingsResponse' }
        '400': { description: Validation error }
        '401': { description: Unauthorized }
        '403': { description: Owner or Admin required }

  /integrations/mattermost/notifications:
    get:
      operationId: getMattermostNotificationSettings
      summary: Mattermost business notification settings
      tags: [Integrations]
      responses:
        '200':
          description: Notification settings
          content:
            application/json:
              schema: { $ref: '#/components/schemas/MattermostNotificationsSettings' }
        '403': { description: Mattermost not connected }
    put:
      operationId: saveMattermostNotificationSettings
      summary: Save Mattermost business notification settings
      tags: [Integrations]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/MattermostNotificationsSettings' }
      responses:
        '200':
          description: Saved notification settings
          content:
            application/json:
              schema: { $ref: '#/components/schemas/MattermostNotificationsSettings' }

  /integrations/mattermost/channels:
    get:
      operationId: listMattermostTeamChannels
      summary: List Mattermost team channels visible to the bot
      tags: [Integrations]
      responses:
        '200':
          description: Channel list
          content:
            application/json:
              schema:
                type: object
                required: [channels]
                properties:
                  channels:
                    type: array
                    items: { $ref: '#/components/schemas/MattermostChannelSummary' }
        '403': { description: Mattermost is not connected }
        '422': { description: Mattermost channels could not be listed }
        '424': { description: "Mattermost refused the bot (`mattermost_bot_rejected`, upstream 401 or 403) or cannot find the team (`mattermost_team_not_found`, upstream 404). The body carries `upstream_status`. Fix the bot or team in Mattermost." }
        '502': { description: "Mattermost is down or busy (upstream 5xx or 429). The body carries `upstream_status`." }

  /integrations/mattermost/notifications/test:
    post:
      operationId: sendMattermostNotificationTestPost
      summary: Post a fixed test message to a Mattermost channel
      tags: [Integrations]
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                channel_id: { type: string, nullable: true }
      responses:
        '200':
          description: Test post result
          content:
            application/json:
              schema:
                type: object
                required: [ok, channel_id, post_id]
                properties:
                  ok: { type: boolean }
                  channel_id: { type: string, nullable: true }
                  post_id: { type: string, nullable: true }

  /integrations/mattermost/members:
    get:
      operationId: reconcileMattermostMembers
      summary: Compare Portrex members with the Mattermost team (Owner/Admin, read-only)
      tags: [Integrations]
      responses:
        '200':
          description: Reconciliation rows for the connected team
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/MattermostMembersReconciliation' }
        '401': { description: Unauthorized }
        '403': { description: Owner or Admin with an account-level membership required }
        '422': { description: Mattermost team members could not be listed }
        '424': { description: "Mattermost refused the bot (`mattermost_bot_rejected`, upstream 401 or 403) or cannot find the team (`mattermost_team_not_found`, upstream 404). The body carries `upstream_status`. Fix the bot or team in Mattermost." }
        '502': { description: "Mattermost is down or busy (upstream 5xx or 429). The body carries `upstream_status`." }
        '503': { description: Database or integration connection unavailable }

  /integrations/mattermost/members/sync:
    post:
      operationId: syncMattermostMembers
      summary: Add existing Mattermost users to the team (Owner/Admin, step-up)
      tags: [Integrations]
      requestBody:
        required: false
        content:
          application/json:
            schema: { $ref: '#/components/schemas/MattermostMembersSyncRequest' }
      responses:
        '200':
          description: Per-member outcomes and a summary (the bot never creates users)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/MattermostMembersSyncResponse' }
        '400': { description: Validation error }
        '401': { description: Unauthorized }
        '403': { description: Owner or Admin with an account-level membership required }
        '422': { description: Mattermost team members could not be listed }
        '424': { description: "Mattermost refused the bot (`mattermost_bot_rejected`, upstream 401 or 403) or cannot find the team (`mattermost_team_not_found`, upstream 404). The body carries `upstream_status`. Fix the bot or team in Mattermost." }
        '502': { description: "Mattermost is down or busy (upstream 5xx or 429). The body carries `upstream_status`." }
        '503': { description: Database or integration connection unavailable }

  /integrations/mattermost/support-channels:
    get:
      operationId: getMattermostSupportChannels
      summary: Read Mattermost channel mapping for Portrex Support and Tenant Support (Owner/Admin)
      tags: [Integrations]
      responses:
        '200':
          description: Current support channel mapping
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/MattermostSupportChannelsSettings' }
        '401': { description: Unauthorized }
        '403': { description: Owner or Admin with an account-level membership and active Mattermost connection required }
        '503': { description: Database or integration connection unavailable }
    put:
      operationId: saveMattermostSupportChannels
      summary: Save Mattermost channel mapping for Portrex Support and Tenant Support (Owner/Admin, step-up)
      tags: [Integrations]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/MattermostSupportChannelsPutRequest' }
      responses:
        '200':
          description: Saved support channel mapping
          content:
            application/json:
              schema: { $ref: '#/components/schemas/MattermostSupportChannelsSettings' }
        '400': { description: Validation error }
        '401': { description: Unauthorized }
        '403': { description: Owner or Admin with an account-level membership and active Mattermost connection required }
        '422': { description: Selected Mattermost channel was not found or cannot be mirrored }
        '424': { description: Mattermost refused the bot or cannot find the team }
        '502': { description: Mattermost is down or busy }
        '503': { description: Database or integration connection unavailable }

  /integrations/stripe:
    get:
      operationId: getStripeConnectionStatus
      summary: Tenant Stripe connection status (Owner/Admin, branch admins see their own branch)
      description: |
        Reports whether the platform has Stripe Connect configured, whether this
        tenant bills through one company account or one account per sub-company,
        the connected accounts (Stripe account ids masked), the staff-managed
        billing policy, and a rollup of where members stand. Requires
        `integrations:read` and `account:read`. A sub-account admin sees only
        their own branch row and no member rollup.
      tags: [Integrations]
      responses:
        '200':
          description: Connection status
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/StripeConnectStatus' }
        '401': { description: Unauthorized }
        '403': { description: 'Owner, Admin, or sub-account admin required' }
        '503': { description: Database unavailable }

  /integrations/stripe/scope:
    put:
      operationId: setStripeConnectionScope
      summary: Choose company-wide or per-sub-company Stripe billing (Owner/Admin)
      description: |
        Sets whether every member bills through the company's Stripe account or
        each sub-company connects its own. Requires
        `integrations:connection:write`; refused for sub-account admins.
        Changing this changes which connected account a
        member's subscription is created on, so in-flight subscriptions stay on
        the account that created them.
      tags: [Integrations]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [scope]
              additionalProperties: false
              properties:
                scope: { type: string, enum: [company, branch] }
      responses:
        '200':
          description: Scope recorded
          content:
            application/json:
              schema:
                type: object
                required: [connection_scope]
                properties:
                  connection_scope: { type: string, enum: [company, branch] }
        '400': { description: Invalid body }
        '401': { description: Unauthorized }
        '403': { description: Owner or Admin required }
        '503': { description: Database unavailable }

  /integrations/stripe/connect:
    post:
      operationId: startStripeConnectOAuth
      summary: Start Stripe Connect OAuth and return the authorization URL
      description: |
        Mints an HMAC state bound to the account, the acting user, the target
        branch and a short expiry, and returns Stripe's authorization URL
        (`response_type=code`, `scope=read_write`). Requires
        `integrations:branch:write`. A sub-account
        admin may start this only for their own branch and only while the tenant
        bills per sub-company. No Portrex or Stripe secret is placed in the URL.
      tags: [Integrations]
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                sub_account_id: { type: string, format: uuid, nullable: true }
      responses:
        '200':
          description: Authorization URL
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema:
                type: object
                required: [authorization_url, redirect_uri, expires_at]
                properties:
                  authorization_url: { type: string, format: uri }
                  redirect_uri: { type: string, format: uri }
                  expires_at: { type: string, format: date-time }
        '400': { description: Invalid body }
        '401': { description: Unauthorized }
        '403': { description: 'Branch scope mismatch or role not permitted' }
        '404': { description: Sub-account not found }
        '409': { description: 'Stripe Connect not configured, or branch connections disabled' }
        '503': { description: Database unavailable }
    get:
      operationId: redirectToStripeConnectOAuth
      summary: Start Stripe Connect OAuth as a browser redirect
      description: |
        Same flow as the POST form, for a plain link: responds 303 to Stripe.
        Requires `integrations:branch:write`.
      tags: [Integrations]
      parameters:
        - { name: sub_account_id, in: query, required: false, schema: { type: string, format: uuid } }
      responses:
        '303': { description: Redirect to Stripe }
        '400': { description: Invalid query }
        '401': { description: Unauthorized }
        '403': { description: 'Branch scope mismatch or role not permitted' }
        '404': { description: Sub-account not found }
        '409': { description: 'Stripe Connect not configured, or branch connections disabled' }

  /integrations/stripe/callback:
    get:
      operationId: completeStripeConnectOAuth
      summary: Stripe Connect OAuth callback (browser redirect from Stripe)
      description: |
        Public route whose authorization is the signed state minted at connect
        time: nothing is written until that state verifies AND names the account
        and user of the live session. The exchange keeps only the connected
        account id, its livemode flag and the granted scope — no access or
        refresh token is ever persisted. Always answers with a redirect back to
        the Stripe settings page carrying
        `oauth=connected|state_invalid|denied|exchange_failed|merchant_in_use`.
        `merchant_in_use`: the Stripe account is already connected to another
        workspace or branch; nothing is stored and the grant is not revoked.
      tags: [Integrations]
      parameters:
        - { name: code, in: query, required: false, schema: { type: string } }
        - { name: state, in: query, required: false, schema: { type: string } }
        - { name: error, in: query, required: false, schema: { type: string } }
        - { name: error_description, in: query, required: false, schema: { type: string } }
      responses:
        '303': { description: Redirect back to the Stripe settings page }

  /integrations/stripe/disconnect:
    post:
      operationId: disconnectStripeAccount
      summary: Cancel open payment links and revoke Portrex's access to a Stripe account
      description: |
        The same promise as the Square disconnect: Portrex first ends the open
        invoice payment links (Stripe Checkout sessions) of the connection, then
        deauthorizes the platform at Stripe (best effort) and marks the local
        connection disconnected. Requires `integrations:branch:write`; a
        sub-account admin may disconnect only their own branch.
        Option A (plan 2026-11-19-002 § 5.7, W3): while Portrex still has
        access, it expires the open member Checkout sessions of the connection
        and sets each live member subscription of the connection to end at its
        period end (`cancel_at_period_end`); those subscriptions are not
        cancelled at once. A session in progress answers 409
        `member_checkouts_active`; a subscription that could not be set to end
        answers 409 `stripe_subscriptions_not_ended` with `set_to_end` and
        `not_set`, and nothing is disconnected.
        Each open session is read at Stripe first: an open unpaid one is
        expired, a complete or paid one is a payment in progress. Answers 409
        `payment_links_active` while a payment is in progress or a link is
        being created (`in_progress`), or when one request did not reach every
        open link (`more_to_cancel`); the tenant disconnects again. Answers 503
        `payment_provider_unavailable` when Stripe does not answer; the
        connection stays. When Stripe says the account is no longer accessible,
        or answers for a session that does not match the invoice, the
        disconnect is not blocked: those links count in
        `unconfirmed_payment_links` and raise an alert.
      tags: [Integrations]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [connect_account_id]
              additionalProperties: false
              properties:
                connect_account_id: { type: string, format: uuid }
      responses:
        '200':
          description: Disconnected
          content:
            application/json:
              schema:
                type: object
                required: [disconnected, active_connections, cancelled_payment_links, unconfirmed_payment_links, member_subscriptions_set_to_end, member_subscriptions_not_reached]
                properties:
                  disconnected: { type: boolean }
                  active_connections: { type: integer }
                  cancelled_payment_links:
                    type: integer
                    description: Sessions Stripe confirmed expired in this request.
                  unconfirmed_payment_links:
                    type: integer
                    description: |
                      Checkouts still open on this connection that Stripe did
                      not end: Stripe could not be asked (the account is no
                      longer accessible, or the platform has no Stripe client),
                      or Stripe answered for a session that does not match the
                      invoice. 0 otherwise.
                  member_subscriptions_set_to_end:
                    type: integer
                    minimum: 0
                    description: Live member subscriptions of this connection that are set to end at their period end (Option A).
                  member_subscriptions_not_reached:
                    type: integer
                    minimum: 0
                    description: |
                      Live member subscriptions of this connection that Stripe
                      could not be asked about. They did not change. Their
                      members cannot pay in Portrex (`stripe_end_not_confirmed`)
                      until the same Stripe account is connected again, or an
                      Owner or Admin confirms the end
                      (`POST /v1/integrations/stripe/member-subscriptions/confirm-ended`).
                  dues_subscriptions_set_to_end:
                    type: integer
                    minimum: 0
                    description: 'W4: live sub-company dues subscriptions of the Stripe account of this company connection that are set to end at their period end. 0 for a branch connection.'
                  dues_subscriptions_not_reached:
                    type: integer
                    minimum: 0
                    description: 'W4: live dues subscriptions that Stripe could not be asked about. They did not change; the sub-company cannot start on Square (`stripe_end_not_confirmed`) until an Owner or Admin confirms the end, or the same Stripe account is connected again.'
        '400': { description: Invalid body }
        '401': { description: Unauthorized }
        '403': { description: 'Branch scope mismatch or role not permitted' }
        '404': { description: Connection not found }
        '409':
          description: |
            Invoice payments are still in progress on this connection, or more open
            links remain to cancel (`payment_links_active`); a member Checkout
            session is in progress (`member_checkouts_active`); a dues Checkout
            session of the company connection is in progress
            (`dues_checkouts_active`, W4); or a live member or dues subscription
            is not set to end (`stripe_subscriptions_not_ended`).
            Nothing is disconnected.
          content:
            application/json:
              schema:
                oneOf:
                  - type: object
                    required: [error, in_progress, more_to_cancel, remaining, cancelled_payment_links]
                    properties:
                      error: { type: string, enum: [payment_links_active] }
                      in_progress:
                        type: integer
                        description: Checkouts with a payment under way, or a link being created right now.
                      more_to_cancel:
                        type: integer
                        description: Checkouts this request did not reach. Disconnect again to continue.
                      remaining:
                        type: integer
                        description: in_progress + more_to_cancel.
                      cancelled_payment_links:
                        type: integer
                        description: Sessions Stripe confirmed expired in this request.
                      request_id: { type: string }
                  - $ref: '#/components/schemas/StripeMemberCheckoutsActiveError'
                  - $ref: '#/components/schemas/StripeDuesCheckoutsActiveError'
                  - $ref: '#/components/schemas/StripeSubscriptionsNotEndedError'
        '503': { description: 'Database unavailable (`db_unavailable`) or Stripe unavailable (`payment_provider_unavailable`)' }

  /integrations/stripe/sync:
    post:
      operationId: syncStripeConnectAccountSnapshot
      summary: Refresh the connected account's Stripe flags
      description: |
        Re-reads charges/payouts/details flags from Stripe onto the stored
        connection. Requires `integrations:branch:write`; no step-up, because the
        tenant chooses nothing here. A per-account failure is recorded on the row
        as the stable code `stripe_status_unavailable` and reported in the
        counts rather than failing the request.
      tags: [Integrations]
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                connect_account_id: { type: string, format: uuid }
      responses:
        '200':
          description: Sync result
          content:
            application/json:
              schema:
                type: object
                required: [synced, total]
                properties:
                  synced: { type: integer }
                  total: { type: integer }
        '400': { description: Invalid body }
        '401': { description: Unauthorized }
        '403': { description: Role not permitted }
        '404': { description: Connection not found }
        '409': { description: Stripe not configured }
        '503': { description: Database unavailable }

  /integrations/stripe/members:
    get:
      operationId: listStripeMemberBilling
      summary: Per-member subscription rollup for the Stripe settings page
      description: |
        One row per billable member with the billing state the enforcement gate
        would compute for them. Requires `integrations:read` and `account:read`;
        a sub-account admin sees only their own branch.
      tags: [Integrations]
      responses:
        '200':
          description: Member rollup
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema:
                type: object
                required: [data, next_cursor]
                properties:
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/StripeMemberBillingRow' }
                  next_cursor: { type: string, nullable: true }
        '401': { description: Unauthorized }
        '403': { description: 'Owner, Admin, or sub-account admin required' }
        '503': { description: Database unavailable }

  # ---------------------------------------------------------------------------
  # Referral partner portal (design 2026-09-17). Partner and staff scopes plus
  # database transaction checks protect the paths below.
  # ---------------------------------------------------------------------------

  /integrations/stripe/member-subscriptions/confirm-ended:
    post:
      operationId: confirmStripeMemberSubscriptionsEnded
      summary: Confirm that the Stripe member and dues subscriptions of a connection that is not active ended (Owner/Admin)
      description: |
        For a Stripe connection that Portrex can no longer read, the tenant
        confirms that its member subscriptions ended (plan 2026-11-19-002
        § 5.7, § 7.3). Each member subscription of that connection that is
        live on Stripe and not set to end gets `stripe_ended_confirmed_at`, so
        those members can subscribe again. A subscription that is set to end
        gets no stamp: it has paid days left and ends at its period end. If a
        subscription is still active in Stripe, that member can pay twice.
        Requires `integrations:connection:write` and a 1 hour step-up; Owner or
        Admin through an account-level seat; refused for an impersonated
        session. An active connection, or a connection whose Stripe account is
        active again on another connection, answers
        `409 stripe_connection_active`. One audit event with the count.
      tags: [Integrations]
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/StripeConfirmEndedInput' }
      responses:
        '200':
          description: The rows that are now confirmed as ended
          headers:
            Cache-Control:
              schema: { type: string, enum: [no-store] }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/StripeConfirmEndedResult' }
        '400': { description: 'Invalid body, or a missing Idempotency-Key' }
        '401': { description: 'Unauthorized, or a fresh step-up required (`step-up-required`)' }
        '403':
          description: 'Owner or Admin required, an account-level seat required, or impersonation'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/StripeConfirmEndedError' }
        '404': { description: Connection not found }
        '409':
          description: '`stripe_connection_active`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/StripeConfirmEndedError' }
        '503': { description: Database unavailable }

  /affiliate/profile:
    get:
      operationId: getPartnerProfile
      summary: Referral partner profile
      description: >-
        Requires `affiliate_portal:read` on a referral partner session (cookie prefix
        `ptx_a`). Read under the partner GUCs, so RLS confines it to this partner's row.
      tags: [Partners]
      security:
        - partnerBetterAuthCookie: []
      x-portrex-scopes: [affiliate_portal:read]
      responses:
        '200':
          description: Display name, sign-in email, phone, and notification preferences.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PartnerProfile' }
        '401': { description: 'Missing, invalid, or expired partner session.' }
        '404': { description: The partner row is no longer readable for this session. }
        '503': { description: Database unavailable. }
    patch:
      operationId: updatePartnerProfile
      summary: Update the referral partner profile
      description: >-
        Requires `affiliate_portal:write` on a referral partner session. Only display name,
        phone, and notification preferences may change; the sign-in email moves exclusively
        through the step-up'd email-change flow. An omitted `phone` leaves it unchanged; an
        explicit null clears it.
      tags: [Partners]
      security:
        - partnerBetterAuthCookie: []
      x-portrex-scopes: [affiliate_portal:write]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                display_name: { type: string, minLength: 1, maxLength: 160 }
                phone: { type: string, nullable: true }
                notification_preferences:
                  { $ref: '#/components/schemas/PartnerNotificationPreferences' }
      responses:
        '200':
          description: The updated profile.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PartnerProfile' }
        '401': { description: 'Missing, invalid, or expired partner session.' }
        '403': { description: The definer function refused the partner id for this session. }
        '409': { description: The partner is suspended or closed. }
        '422': { description: Validation failed. }
        '503': { description: Database unavailable. }

  /affiliate/agreement/accept:
    post:
      operationId: acceptPartnerAgreement
      summary: Accept a partner agreement version
      description: >-
        Requires `affiliate_portal:write` on a referral partner session. Records the version
        the partner actually saw, not "the latest one".
      tags: [Partners]
      security:
        - partnerBetterAuthCookie: []
      x-portrex-scopes: [affiliate_portal:write]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [version]
              additionalProperties: false
              properties:
                version: { type: string, minLength: 1, maxLength: 64 }
      responses:
        '200':
          description: The accepted version and its timestamp.
          content:
            application/json:
              schema:
                type: object
                required: [agreement_version, agreement_accepted_at]
                properties:
                  agreement_version: { type: string }
                  agreement_accepted_at: { type: string, format: date-time, nullable: true }
        '401': { description: 'Missing, invalid, or expired partner session.' }
        '409': { description: The partner is suspended or closed. }
        '422': { description: Validation failed. }
        '503': { description: Database unavailable. }

  /affiliate/dashboard:
    get:
      operationId: getPartnerDashboard
      summary: Referral partner dashboard summary
      description: >-
        Requires `affiliate_portal:read` on a referral partner session. Built by one definer
        call so the counts, caps, attention list and recent activity are read in a single
        transaction. `recent_activity` is the same allowlisted projection as
        `GET /v1/affiliate/activity`, capped at ten.
      tags: [Partners]
      security:
        - partnerBetterAuthCookie: []
      x-portrex-scopes: [affiliate_portal:read]
      responses:
        '200':
          description: Counts, invitation caps, attention items, and recent activity.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PartnerDashboard' }
        '401': { description: 'Missing, invalid, or expired partner session.' }
        '403': { description: The definer function refused the partner id for this session. }
        '404': { description: The partner row is no longer readable for this session. }
        '503': { description: Database unavailable. }

  /affiliate/activity:
    get:
      operationId: listPartnerActivity
      summary: List this partner's activity
      description: >-
        Requires `affiliate_portal:read` on a referral partner session. `affiliate_audit_events`
        itself stays unreadable to a partner session; this is the one allowlisted definer
        projection of it. Pages backwards with a keyset cursor: pass the previous page's
        `next_before`.


        The query schema is strict — an unrecognized parameter is a 422, not an ignored key.
      tags: [Partners]
      security:
        - partnerBetterAuthCookie: []
      x-portrex-scopes: [affiliate_portal:read]
      parameters:
        - { in: query, name: limit, schema: { type: integer, minimum: 1, maximum: 100, default: 25 } }
        - in: query
          name: before
          description: >-
            OPAQUE cursor. Echo back the previous page's `next_before`; do not construct one.
            It encodes the last returned row's `(occurred_at at microsecond precision, id)`,
            which is the projection's full sort key — `occurred_at` alone is not unique and
            the driver truncates it to milliseconds, so a timestamp cursor skipped rows at a
            page boundary. A token this API did not mint is a 422.
          schema: { type: string, minLength: 1, maxLength: 256 }
      responses:
        '200':
          description: The projected events, the next cursor, and the unseen count.
          content:
            application/json:
              schema:
                type: object
                required: [items, next_before, unseen_count]
                additionalProperties: false
                properties:
                  items:
                    type: array
                    items: { $ref: '#/components/schemas/PartnerActivityEvent' }
                  next_before:
                    type: string
                    nullable: true
                    description: >-
                      Opaque cursor for the next page, or null when this is the last page.
                      Pass it back as `before`.
                    minLength: 1
                  unseen_count: { type: integer, minimum: 0 }
        '401': { description: 'Missing, invalid, or expired partner session.' }
        '403': { description: The definer function refused the partner id for this session. }
        '422': { description: Validation failed. }
        '503': { description: Database unavailable. }

  /affiliate/activity/seen:
    post:
      operationId: markPartnerActivitySeen
      summary: Mark this partner user's activity feed as seen
      description: >-
        Requires `affiliate_portal:write` on a referral partner session. Moves this USER's
        high-water mark, which is what `unseen_count` is measured against. Deliberately
        writes no audit row: auditing it would append an event to the feed it just marked
        as seen.
      tags: [Partners]
      security:
        - partnerBetterAuthCookie: []
      x-portrex-scopes: [affiliate_portal:write]
      responses:
        '200':
          description: The new high-water mark.
          content:
            application/json:
              schema:
                type: object
                required: [seen_at]
                additionalProperties: false
                properties:
                  seen_at: { type: string }
        '401': { description: 'Missing, invalid, or expired partner session.' }
        '403': { description: The definer function refused the partner or user id for this session. }
        '404': { description: The partner user row is no longer readable for this session. }
        '503': { description: Database unavailable. }

  /affiliate/profile/avatar:
    post:
      operationId: setPartnerAvatar
      summary: Upload the referral partner's photo
      description: >-
        Requires `affiliate_portal:write` on a referral partner session. PNG, JPEG or WebP up
        to 2 MB, magic-byte sniffed; `mime_type` is cross-checked against the bytes when
        supplied. Stored under `affiliates/<affiliate_id>/avatar/<uuid>.<ext>` and served by the
        public, immutable-cached image route, so the URL is public behind an unguessable
        UUID — the same posture as the tenant profile avatar.
      tags: [Partners]
      security:
        - partnerBetterAuthCookie: []
      x-portrex-scopes: [affiliate_portal:write]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [data_base64]
              additionalProperties: false
              properties:
                mime_type: { type: string, enum: [image/png, image/jpeg, image/webp] }
                data_base64: { type: string, minLength: 1 }
      responses:
        '200':
          description: The stored avatar URL.
          content:
            application/json:
              schema:
                type: object
                required: [avatar_url]
                additionalProperties: false
                properties:
                  avatar_url: { type: string, nullable: true }
        '400':
          description: >-
            `invalid_base64` or `mime_type_mismatch`. `empty_image` is NOT reachable on this
            operation and is therefore not documented: `data_base64` has `minLength: 1`, so
            an empty payload is a 422, and a whitespace-only or padding-only payload fails
            the strict base64 check as `invalid_base64` before any length test.
        '401': { description: 'Missing, invalid, or expired partner session.' }
        '403': { description: The definer function refused the partner id for this session. }
        '413': { description: '`image_too_large` — images must be 2 MB or smaller.' }
        '415': { description: '`unsupported_image_type` — use a PNG, JPG, or WebP image.' }
        '422': { description: Validation failed. }
        '503': { description: Database unavailable. }
    delete:
      operationId: clearPartnerAvatar
      summary: Remove the referral partner's photo
      description: >-
        Requires `affiliate_portal:write` on a referral partner session. Clears the stored
        reference; the object itself is left behind the unguessable URL an immutable cache
        may still be holding.
      tags: [Partners]
      security:
        - partnerBetterAuthCookie: []
      x-portrex-scopes: [affiliate_portal:write]
      responses:
        '200':
          description: The avatar is cleared.
          content:
            application/json:
              schema:
                type: object
                required: [avatar_url]
                additionalProperties: false
                properties:
                  avatar_url: { type: string, nullable: true }
        '401': { description: 'Missing, invalid, or expired partner session.' }
        '403': { description: The definer function refused the partner id for this session. }
        '503': { description: Database unavailable. }

  /affiliate/invitations:
    get:
      operationId: listPartnerInvitations
      summary: List this partner's invitations
      description: >-
        Requires `affiliate_portal:read` on a referral partner session. Read under the partner
        GUCs, so RLS confines it to this partner's rows. No mail-delivery state is carried,
        and the lifecycle columns are PROJECTED so a suppressed recipient's row is
        byte-identical to a delivered one's — see `PartnerInvitationListRow`.


        The query schema is strict — an unrecognized parameter is a 422, not an ignored key.
      tags: [Partners]
      security:
        - partnerBetterAuthCookie: []
      x-portrex-scopes: [affiliate_portal:read]
      parameters:
        - in: query
          name: q
          description: Matches the invited company name, contact name, or email.
          schema: { type: string, maxLength: 160 }
        - in: query
          name: status
          description: >-
            Compared against the partner-visible projection, not the stored column, so
            `issued` includes a Portrex send whose mail job does not exist. `created` is
            deliberately not offerable: it would isolate exactly the suppressed rows.
          schema: { type: string, enum: [issued, bound, expired, revoked] }
        - { in: query, name: delivery, schema: { type: string, enum: [portrex_email, affiliate_link] } }
        - in: query
          name: sort
          schema:
            type: string
            enum: [created_desc, created_asc, company_asc, expires_asc]
            default: created_desc
        - { in: query, name: page, schema: { type: integer, minimum: 1, default: 1 } }
        - { in: query, name: per_page, schema: { type: integer, minimum: 1, maximum: 100, default: 50 } }
      responses:
        '200':
          description: The invitation rows for this window, and the total for this filter.
          content:
            application/json:
              schema:
                type: object
                required: [items, page, per_page, total]
                additionalProperties: false
                properties:
                  items:
                    type: array
                    items: { $ref: '#/components/schemas/PartnerInvitationListRow' }
                  page: { type: integer, minimum: 1 }
                  per_page: { type: integer, minimum: 1 }
                  total: { type: integer, minimum: 0 }
        '401': { description: 'Missing, invalid, or expired partner session.' }
        '422': { description: Validation failed. }
        '503': { description: Database unavailable. }

  /affiliate/referrals:
    get:
      operationId: listPartnerReferrals
      summary: List this partner's referrals
      description: >-
        Requires `affiliate_portal:read` on a referral partner session. Every row is projected
        through the partner-facing projection: conflict reasons other than self-referral,
        staff notes, registration evidence, and the referred account id are not carried. The
        nested invitation rows carry the partner-visible lifecycle described on
        `PartnerInvitationListRow`, so a suppressed Portrex send is indistinguishable from a
        delivered one here too.


        The query schema is strict — an unrecognized parameter is a 422, not an ignored key.
      tags: [Partners]
      security:
        - partnerBetterAuthCookie: []
      x-portrex-scopes: [affiliate_portal:read]
      parameters:
        - { in: query, name: limit, schema: { type: integer, minimum: 1, maximum: 200 } }
        - { in: query, name: offset, schema: { type: integer, minimum: 0 } }
        - in: query
          name: page
          description: >-
            1-based page. When `page` or `per_page` is supplied it wins over `limit`/`offset`;
            with neither, the window is exactly `limit`/`offset` and a no-parameter call
            answers page 1 of 50.
          schema: { type: integer, minimum: 1 }
        - { in: query, name: per_page, schema: { type: integer, minimum: 1, maximum: 100 } }
        - in: query
          name: q
          description: Matches the company name, contact name, or contact email.
          schema: { type: string, maxLength: 160 }
        - in: query
          name: status
          description: Raw `review_status`, never the projected label.
          schema: { type: string, enum: [pending, accepted, ineligible, expired] }
        - in: query
          name: stage
          schema:
            type: string
            enum: [registered, invited, signed_up, qualifying, qualified, lost]
        - in: query
          name: invitation_status
          description: >-
            `none` means the referral has no invitation at all. The rest is compared against
            the partner-visible projection, not the stored column; `created` is deliberately
            not offerable because it would isolate exactly the suppressed rows.
          schema: { type: string, enum: [none, issued, bound, expired, revoked] }
        - in: query
          name: sort
          schema:
            type: string
            enum: [registered_desc, registered_asc, company_asc, activity_desc]
            default: registered_desc
      responses:
        '200':
          description: The partner-facing referral rows for this window.
          content:
            application/json:
              schema:
                type: object
                required: [items, next_offset, page, per_page, total]
                properties:
                  items:
                    type: array
                    items: { $ref: '#/components/schemas/PartnerReferralRow' }
                  next_offset: { type: integer, nullable: true }
                  page: { type: integer, minimum: 1 }
                  per_page: { type: integer, minimum: 1 }
                  total: { type: integer, minimum: 0 }
        '401': { description: 'Missing, invalid, or expired partner session.' }
        '422': { description: Validation failed. }
        '503': { description: Database unavailable. }
    post:
      operationId: createPartnerReferrals
      summary: Register one or more referrals
      description: >-
        Requires `affiliate_portal:write` on a referral partner session. The whole batch runs
        in one transaction; a company or contact this partner already registered is reported
        in `skipped_duplicates` rather than failing the request.
      tags: [Partners]
      security:
        - partnerBetterAuthCookie: []
      x-portrex-scopes: [affiliate_portal:write]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [items]
              additionalProperties: false
              properties:
                items:
                  type: array
                  minItems: 1
                  maxItems: 25
                  items: { $ref: '#/components/schemas/PartnerReferralCreate' }
      responses:
        '201':
          description: The referrals created, and how many submissions were duplicates.
          content:
            application/json:
              schema:
                type: object
                required: [items, skipped_duplicates]
                properties:
                  items:
                    type: array
                    items: { $ref: '#/components/schemas/PartnerReferralRow' }
                  skipped_duplicates: { type: integer, minimum: 0 }
        '401': { description: 'Missing, invalid, or expired partner session.' }
        '409': { description: The partner is suspended or closed. }
        '422': { description: Validation failed. }
        '503': { description: Database unavailable. }

  /affiliate/referrals/{id}:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
    get:
      operationId: getPartnerReferral
      summary: Read one referral
      description: >-
        Requires `affiliate_portal:read` on a referral partner session. RLS confines the read
        to this partner's rows, so another partner's referral is a 404 and never a 403.
      tags: [Partners]
      security:
        - partnerBetterAuthCookie: []
      x-portrex-scopes: [affiliate_portal:read]
      responses:
        '200':
          description: The partner-facing referral row.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PartnerReferralRow' }
        '400': { description: Malformed referral id. }
        '401': { description: 'Missing, invalid, or expired partner session.' }
        '404': { description: No such referral for this partner. }
        '503': { description: Database unavailable. }
    patch:
      operationId: updatePartnerReferral
      summary: Edit a pending referral
      description: >-
        Requires `affiliate_portal:write` on a referral partner session. Company name and
        contact email are absent by design — they are frozen once an invitation carries them
        to the prospect. Refused once the referral leaves review, leaves the registered or
        invited stage, or has a bound invitation.
      tags: [Partners]
      security:
        - partnerBetterAuthCookie: []
      x-portrex-scopes: [affiliate_portal:write]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/PartnerReferralEdit' }
      responses:
        '200':
          description: The updated partner-facing referral row.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PartnerReferralRow' }
        '400': { description: Malformed referral id. }
        '401': { description: 'Missing, invalid, or expired partner session.' }
        '403': { description: The definer function refused the partner id for this session. }
        '404': { description: No such referral for this partner. }
        '409': { description: The referral can no longer be edited. }
        '422': { description: Validation failed. }
        '503': { description: Database unavailable. }

  /affiliate/referrals/{id}/invitations:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
    post:
      operationId: issuePartnerInvitation
      summary: Issue an invitation for a referral
      description: >-
        Requires `affiliate_portal:write` on a referral partner session. In `affiliate_link` mode
        the response carries the join URL EXACTLY ONCE — only its sha256 is stored and the URL
        cannot be recovered. In `portrex_email` mode Portrex sends the mail and no URL is
        returned. A recipient on the invitation-outreach suppression list receives a normal
        success response by design.
      tags: [Partners]
      security:
        - partnerBetterAuthCookie: []
      x-portrex-scopes: [affiliate_portal:write]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [delivery]
              additionalProperties: false
              properties:
                delivery: { type: string, enum: [portrex_email, affiliate_link] }
      responses:
        '201':
          description: The issued invitation. `url` is non-null for `affiliate_link` only.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PartnerInvitationIssued' }
        '400': { description: Malformed referral id. }
        '401': { description: 'Missing, invalid, or expired partner session.' }
        '409':
          description: >-
            `referral_ineligible` when the referral's review status is ineligible or expired;
            `referral_closed` when its stage is already `signed_up`, `qualifying`,
            `qualified` or `lost`; `affiliate_inactive` for a non-active partner. None of the
            three consumes an invitation cap.
        '422': { description: Validation failed. }
        '429':
          description: >-
            `invitation_cap_reached` for the daily or monthly cap, or
            `invitation_send_cooldown` for a repeat Portrex send to the same address
            inside 14 days.
        '503': { description: Database unavailable. }

  /affiliate/invitations/{id}/revoke:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
    post:
      operationId: revokePartnerInvitation
      summary: Revoke an invitation
      description: >-
        Requires `affiliate_portal:write` on a referral partner session. Also cancels any queued
        invitation mail in the same transaction. Revoking an already-revoked invitation is a
        no-op rather than an error.
      tags: [Partners]
      security:
        - partnerBetterAuthCookie: []
      x-portrex-scopes: [affiliate_portal:write]
      responses:
        '200':
          description: The revoked invitation.
          content:
            application/json:
              schema:
                type: object
                required: [invitation_id, status]
                properties:
                  invitation_id: { type: string, format: uuid }
                  status: { type: string }
        '400': { description: Malformed invitation id. }
        '401': { description: 'Missing, invalid, or expired partner session.' }
        '404': { description: No such invitation for this partner. }
        '409': { description: The invitation cannot be revoked from its current status. }
        '503': { description: Database unavailable. }

  /affiliate/invitations/{id}/replace:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
    post:
      operationId: replacePartnerInvitation
      summary: Generate a new invitation link
      description: >-
        Requires `affiliate_portal:write` on a referral partner session. Atomically revokes the
        previous UNBOUND invitation and issues a fresh link-mode one under the same referral.
        Sends no mail, so it is exempt from the send cooldown and the new-invitation caps and
        carries its own replacement limits instead. A bound invitation can never be replaced.
      tags: [Partners]
      security:
        - partnerBetterAuthCookie: []
      x-portrex-scopes: [affiliate_portal:write]
      responses:
        '201':
          description: The replacement invitation, with its join URL shown once.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PartnerInvitationIssued' }
        '400': { description: Malformed invitation id. }
        '401': { description: 'Missing, invalid, or expired partner session.' }
        '404': { description: No such invitation for this partner. }
        '409': { description: The invitation is bound and cannot be replaced. }
        '429': { description: '`invitation_replace_limit` — 5 per referral per day, 20 per partner per day.' }
        '503': { description: Database unavailable. }

  /affiliate/step-up/request:
    post:
      operationId: requestPartnerStepUp
      summary: Request a partner step-up code
      description: >-
        Requires `affiliate_portal:read` on a referral partner session. Mints a 6-digit code,
        stores only its sha256 bound to this session, and mails it synchronously — a delivery
        failure is returned to the caller rather than leaving an unanswerable challenge.
        Rate limited to 3 per session per 10 minutes and 10 per partner per hour.
      tags: [Partners]
      security:
        - partnerBetterAuthCookie: []
      x-portrex-scopes: [affiliate_portal:read]
      responses:
        '200':
          description: The code was mailed to the partner's verified address.
          content:
            application/json:
              schema:
                type: object
                required: [status, expires_in_seconds]
                properties:
                  status: { type: string, enum: [sent] }
                  expires_in_seconds: { type: integer }
        '401': { description: 'Missing, invalid, or expired partner session.' }
        '429': { description: '`step_up_rate_limited`.' }
        '503':
          description: >-
            `step_up_mail_failed` when the code could not be delivered (recoverable), or when
            the database is unavailable.

  /affiliate/step-up/verify:
    post:
      operationId: verifyPartnerStepUp
      summary: Verify a partner step-up code
      description: >-
        Requires `affiliate_portal:read` on a referral partner session. On success the proof is
        written to the CURRENT session row only, inside the definer function. Five attempts per
        challenge.
      tags: [Partners]
      security:
        - partnerBetterAuthCookie: []
      x-portrex-scopes: [affiliate_portal:read]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [code]
              additionalProperties: false
              properties:
                code: { type: string, pattern: '^[0-9]{6}$' }
      responses:
        '200':
          description: The session now carries a fresh `magic_link` step-up proof.
          content:
            application/json:
              schema:
                type: object
                required: [verified, factor]
                properties:
                  verified: { type: boolean, enum: [true] }
                  factor: { type: string, enum: [magic_link] }
        '401':
          description: >-
            `step_up_failed` with a reason of `invalid_code`, `expired`, `no_challenge`, or
            `attempts_exhausted` — or no partner session at all.
        '422': { description: Validation failed. }
        '503': { description: Database unavailable. }

  /affiliate/profile/email-change:
    post:
      operationId: requestPartnerEmailChange
      summary: Request a partner email change
      description: >-
        Requires `affiliate_portal:write` on a referral partner session AND a step-up proof no
        older than 5 minutes, obtained from `POST /v1/affiliate/step-up/request`. The gate is
        ALWAYS enforced and deliberately ignores the global step-up kill switch. Stores only
        the token hash and mails the verification link synchronously to the NEW address.
      tags: [Partners]
      security:
        - partnerBetterAuthCookie: []
      x-portrex-scopes: [affiliate_portal:write]
      x-portrex-step-up: { window: 300, factors: [magic_link] }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [new_email]
              additionalProperties: false
              properties:
                new_email: { type: string, format: email }
      responses:
        '202':
          description: A verification link was mailed to the new address.
          content:
            application/json:
              schema:
                type: object
                required: [status, expires_in_seconds]
                properties:
                  status: { type: string, enum: [verification_sent] }
                  expires_in_seconds: { type: integer }
        '401':
          description: >-
            No partner session, or no fresh step-up proof — answered with
            `WWW-Authenticate: step-up-required` and `code: step-up-required`.
        '409': { description: The address is already in use by another partner login. }
        '422': { description: Validation failed. }
        '503':
          description: >-
            `email_change_mail_failed` when the verification mail could not be delivered
            (recoverable), or the database is unavailable.

  /affiliate/profile/email-change/confirm:
    post:
      operationId: confirmPartnerEmailChange
      summary: Confirm a partner email change
      description: >-
        Public and token-authenticated: the partner is mid-change and the session that started
        it may be gone, so possession of the single-use, one-hour token mailed to the new
        address is the proof. Updates the Better Auth login, the partner user, and the partner
        row in one transaction, deletes outstanding verification rows, and revokes every other
        session.
      tags: [Partners]
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [token]
              additionalProperties: false
              properties:
                token: { type: string, minLength: 20, maxLength: 128 }
      responses:
        '200':
          description: The address was changed and the old address was notified.
          content:
            application/json:
              schema:
                type: object
                required: [status, email]
                properties:
                  status: { type: string, enum: [confirmed] }
                  email: { type: string }
        '404':
          description: >-
            `invalid_or_expired_token` — one answer for unknown, expired, and already-used
            tokens.
        '422': { description: Validation failed. }
        '503': { description: Database unavailable. }

  /join/{token}:
    parameters:
      - { in: path, name: token, required: true, schema: { type: string } }
    get:
      operationId: resolvePartnerInvitation
      summary: Resolve a partner invitation for the join landing page
      description: >-
        Public and token-authenticated; the prospect has no Portrex identity yet. Grants
        nothing: possession of the token proves access to the invitation, not ownership of
        the recipient mailbox, and binding happens later inside the signup submit transaction.
        Marks the open and never consumes the token. The referring partner's id is
        deliberately absent from the response. Rate limited to 60 resolutions per IP per
        10 minutes.
      tags: [Partners]
      security: []
      responses:
        '200':
          description: The landing projection.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/JoinResolveResponse' }
        '404':
          description: >-
            One answer for unknown, malformed, expired, revoked, already-bound, and
            suspended-partner tokens, so the route cannot be used as an existence oracle.
        '429': { description: '`rate_limited` — the per-IP bucket is spent.' }
        '503': { description: Database unavailable. }

  /affiliate-invitations/opt-out:
    post:
      operationId: optOutOfPartnerInvitations
      summary: Opt out of partner invitation outreach
      description: >-
        Public and signature-authenticated from a one-click link in an invitation email. The
        payload carries the sha256 of the address (not the address), the issue time, and an
        HMAC valid 13 months. Only ever narrows what Portrex sends. The response is identical
        whether the address was already suppressed, was never mailed, or was suppressed by
        this call.
      tags: [Partners]
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/PartnerInvitationOptOut' }
      responses:
        '200':
          description: Invitation outreach to that address is suppressed.
          content:
            application/json:
              schema:
                type: object
                required: [status]
                properties:
                  status: { type: string, enum: [opted_out] }
        '400': { description: '`invalid_token` — malformed, badly signed, or expired.' }
        '500': { description: The suppression could not be recorded. }
        '503': { description: Database unavailable. }

  # ---------------------------------------------------------------------------
  # Staff partner console. `staff:affiliates:read` is held by every staff role;
  # `staff:affiliates:write` and `staff:affiliates:admin` by platform_admin only.
  # Every definer function behind these routes re-reads the live staff role, so
  # a downgraded session loses them on its next call.
  # ---------------------------------------------------------------------------

  /staff/affiliates/applications:
    get:
      operationId: listStaffPartnerApplications
      summary: List partner applications
      description: 'Requires `staff:affiliates:read` on a staff session.'
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:read]
      parameters:
        - { in: query, name: status, schema: { type: string } }
        - { in: query, name: limit, schema: { type: integer, minimum: 1, maximum: 200 } }
        - { in: query, name: offset, schema: { type: integer, minimum: 0 } }
      responses:
        '200':
          description: The application review queue.
          content:
            application/json:
              schema:
                type: object
                required: [items, total, next_offset]
                properties:
                  items:
                    type: array
                    items: { $ref: '#/components/schemas/StaffPartnerApplication' }
                  total: { type: integer }
                  next_offset: { type: integer, nullable: true }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '403': { description: The staff role does not hold the scope. }
        '503': { description: Database unavailable. }

  /staff/affiliates/applications/{id}:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
    get:
      operationId: getStaffPartnerApplication
      summary: Read one partner application
      description: 'Requires `staff:affiliates:read` on a staff session.'
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:read]
      responses:
        '200':
          description: The application.
          content:
            application/json:
              schema:
                type: object
                required: [application]
                properties:
                  application: { $ref: '#/components/schemas/StaffPartnerApplication' }
        '400': { description: Malformed application id. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '404': { description: No such application. }
        '503': { description: Database unavailable. }
    patch:
      operationId: updateStaffPartnerApplication
      summary: Edit a partner application's applicant-entered fields
      description: >-
        Requires `staff:affiliates:write` on a staff session. Only reachable while the
        application is `pending` or `provisioning` — `affiliate_application_update` refuses any
        other status, since an approved/rejected/withdrawn/expired application is a decision
        artifact, not a form to keep correcting.
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:write]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [full_name, email, role, contractor_count]
              additionalProperties: false
              properties:
                full_name: { type: string, minLength: 1, maxLength: 120 }
                email: { type: string, format: email }
                phone: { type: string }
                company: { type: string, maxLength: 160 }
                role: { type: string }
                contractor_count: { type: string }
                how_did_you_hear: { type: string, maxLength: 200 }
                notes: { type: string, maxLength: 2000 }
      responses:
        '200':
          description: The updated application.
          content:
            application/json:
              schema:
                type: object
                required: [application]
                properties:
                  application: { $ref: '#/components/schemas/StaffPartnerApplication' }
        '400': { description: Malformed application id. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '404': { description: No such application. }
        '409': { description: The application cannot be edited from its current status. }
        '422': { description: Validation failed. }
        '503': { description: Database unavailable. }

  /staff/affiliates/applications/{id}/notes:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
    get:
      operationId: listStaffPartnerApplicationNotes
      summary: List an application's notes
      description: 'Requires `staff:affiliates:read` on a staff session.'
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:read]
      responses:
        '200':
          description: The application's notes, newest first.
          content:
            application/json:
              schema:
                type: object
                required: [items]
                properties:
                  items:
                    type: array
                    items: { $ref: '#/components/schemas/StaffPartnerApplicationNote' }
        '400': { description: Malformed application id. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '404': { description: No such application. }
        '503': { description: Database unavailable. }
    post:
      operationId: createStaffPartnerApplicationNote
      summary: Add a note to an application
      description: 'Requires `staff:affiliates:write` on a staff session.'
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:write]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [body]
              additionalProperties: false
              properties:
                body: { type: string, minLength: 1, maxLength: 10000 }
      responses:
        '201':
          description: The created note.
          content:
            application/json:
              schema:
                type: object
                required: [note]
                properties:
                  note: { $ref: '#/components/schemas/StaffPartnerApplicationNote' }
        '400': { description: Malformed application id. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '404': { description: No such application. }
        '422': { description: Validation failed. }
        '503': { description: Database unavailable. }

  /staff/affiliates/applications/{id}/notes/{noteId}:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
      - { in: path, name: noteId, required: true, schema: { type: string, format: uuid } }
    delete:
      operationId: deleteStaffPartnerApplicationNote
      summary: Delete an application note
      description: 'Requires `staff:affiliates:write` on a staff session.'
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:write]
      responses:
        '200':
          description: Deleted.
          content:
            application/json:
              schema:
                type: object
                required: [deleted]
                properties:
                  deleted: { type: boolean }
        '400': { description: Malformed application or note id. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '404': { description: No such note. }
        '503': { description: Database unavailable. }

  /staff/affiliates/applications/{id}/tasks:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
    get:
      operationId: listStaffPartnerApplicationTasks
      summary: List an application's tasks
      description: 'Requires `staff:affiliates:read` on a staff session.'
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:read]
      responses:
        '200':
          description: The application's tasks, newest first.
          content:
            application/json:
              schema:
                type: object
                required: [items]
                properties:
                  items:
                    type: array
                    items: { $ref: '#/components/schemas/StaffPartnerApplicationTask' }
        '400': { description: Malformed application id. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '404': { description: No such application. }
        '503': { description: Database unavailable. }
    post:
      operationId: createStaffPartnerApplicationTask
      summary: Add a task to an application
      description: 'Requires `staff:affiliates:write` on a staff session.'
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:write]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [title]
              additionalProperties: false
              properties:
                title: { type: string, minLength: 1, maxLength: 200 }
                due_at: { type: string }
                assigned_to_staff_user_id: { type: string, format: uuid }
      responses:
        '201':
          description: The created task.
          content:
            application/json:
              schema:
                type: object
                required: [task]
                properties:
                  task: { $ref: '#/components/schemas/StaffPartnerApplicationTask' }
        '400': { description: Malformed application id. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '404': { description: No such application. }
        '422': { description: Validation failed. }
        '503': { description: Database unavailable. }

  /staff/affiliates/applications/{id}/tasks/{taskId}:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
      - { in: path, name: taskId, required: true, schema: { type: string, format: uuid } }
    patch:
      operationId: updateStaffPartnerApplicationTask
      summary: Update an application task
      description: 'Requires `staff:affiliates:write` on a staff session.'
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:write]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [title, status]
              additionalProperties: false
              properties:
                title: { type: string, minLength: 1, maxLength: 200 }
                status: { type: string, enum: [open, done] }
                due_at: { type: string }
                assigned_to_staff_user_id: { type: string, format: uuid }
      responses:
        '200':
          description: The updated task.
          content:
            application/json:
              schema:
                type: object
                required: [task]
                properties:
                  task: { $ref: '#/components/schemas/StaffPartnerApplicationTask' }
        '400': { description: Malformed application or task id. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '404': { description: No such task. }
        '422': { description: Validation failed. }
        '503': { description: Database unavailable. }
    delete:
      operationId: deleteStaffPartnerApplicationTask
      summary: Delete an application task
      description: 'Requires `staff:affiliates:write` on a staff session.'
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:write]
      responses:
        '200':
          description: Deleted.
          content:
            application/json:
              schema:
                type: object
                required: [deleted]
                properties:
                  deleted: { type: boolean }
        '400': { description: Malformed application or task id. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '404': { description: No such task. }
        '503': { description: Database unavailable. }

  /staff/affiliates/applications/{id}/events:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
    get:
      operationId: listStaffPartnerApplicationEvents
      summary: List an application's calendar events
      description: 'Requires `staff:affiliates:read` on a staff session.'
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:read]
      responses:
        '200':
          description: The application's events, ordered by start time.
          content:
            application/json:
              schema:
                type: object
                required: [items]
                properties:
                  items:
                    type: array
                    items: { $ref: '#/components/schemas/StaffPartnerApplicationEvent' }
        '400': { description: Malformed application id. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '404': { description: No such application. }
        '503': { description: Database unavailable. }
    post:
      operationId: createStaffPartnerApplicationEvent
      summary: Add a calendar event to an application
      description: 'Requires `staff:affiliates:write` on a staff session.'
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:write]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [title, starts_at]
              additionalProperties: false
              properties:
                title: { type: string, minLength: 1, maxLength: 200 }
                starts_at: { type: string }
                ends_at: { type: string }
                notes: { type: string, maxLength: 2000 }
      responses:
        '201':
          description: The created event.
          content:
            application/json:
              schema:
                type: object
                required: [event]
                properties:
                  event: { $ref: '#/components/schemas/StaffPartnerApplicationEvent' }
        '400':
          description: >-
            Malformed application id, or a validation error raised by the database (e.g. an
            end time before the start time).
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '404': { description: No such application. }
        '422': { description: Validation failed. }
        '503': { description: Database unavailable. }

  /staff/affiliates/applications/{id}/events/{eventId}:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
      - { in: path, name: eventId, required: true, schema: { type: string, format: uuid } }
    patch:
      operationId: updateStaffPartnerApplicationEvent
      summary: Update an application calendar event
      description: 'Requires `staff:affiliates:write` on a staff session.'
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:write]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [title, starts_at]
              additionalProperties: false
              properties:
                title: { type: string, minLength: 1, maxLength: 200 }
                starts_at: { type: string }
                ends_at: { type: string }
                notes: { type: string, maxLength: 2000 }
      responses:
        '200':
          description: The updated event.
          content:
            application/json:
              schema:
                type: object
                required: [event]
                properties:
                  event: { $ref: '#/components/schemas/StaffPartnerApplicationEvent' }
        '400': { description: 'Malformed ids, or a validation error raised by the database.' }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '404': { description: No such event. }
        '422': { description: Validation failed. }
        '503': { description: Database unavailable. }
    delete:
      operationId: deleteStaffPartnerApplicationEvent
      summary: Delete an application calendar event
      description: 'Requires `staff:affiliates:write` on a staff session.'
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:write]
      responses:
        '200':
          description: Deleted.
          content:
            application/json:
              schema:
                type: object
                required: [deleted]
                properties:
                  deleted: { type: boolean }
        '400': { description: Malformed application or event id. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '404': { description: No such event. }
        '503': { description: Database unavailable. }

  /staff/affiliates/applications/{id}/approve:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
    post:
      operationId: approveStaffPartnerApplication
      summary: Approve a partner application
      description: >-
        Requires `staff:affiliates:write` on a staff session. Claims the application, creates
        the Better Auth login, the partner, and the partner user in ONE transaction, then
        mails the password setup link. A delivery failure returns 200 with
        `setup_mail_status: failed` — the partner exists and staff resend — rather than
        leaving staff unable to tell an approved partner from an unapproved one.
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:write]
      responses:
        '200':
          description: The approved application and the provisioned partner.
          content:
            application/json:
              schema:
                type: object
                required: [application, partner_id, partner_user_id, resumed, setup_mail_status]
                properties:
                  application: { $ref: '#/components/schemas/StaffPartnerApplication' }
                  partner_id: { type: string, format: uuid }
                  partner_user_id: { type: string, format: uuid }
                  resumed: { type: boolean }
                  setup_mail_status: { type: string, enum: [pending, sent, failed, unknown] }
        '400': { description: Malformed application id. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '404': { description: No such application. }
        '409':
          description: >-
            `approval_in_progress` when another approver holds the claim, or the application
            cannot be approved from its current status.
        '503': { description: Database unavailable. }

  /staff/affiliates/applications/{id}/reject:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
    post:
      operationId: rejectStaffPartnerApplication
      summary: Reject a partner application
      description: >-
        Requires `staff:affiliates:write` on a staff session. The rejection mail is best effort;
        a mail failure still returns 200 because the rejection already committed.
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:write]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [reason]
              additionalProperties: false
              properties:
                reason: { type: string, minLength: 1, maxLength: 500 }
      responses:
        '200':
          description: The rejected application.
          content:
            application/json:
              schema:
                type: object
                required: [application]
                properties:
                  application: { $ref: '#/components/schemas/StaffPartnerApplication' }
        '400': { description: Malformed application id. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '404': { description: No such application. }
        '409': { description: The application cannot be rejected from its current status. }
        '422': { description: Validation failed. }
        '503': { description: Database unavailable. }

  /staff/affiliates/applications/{id}/resend-setup:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
    post:
      operationId: resendStaffPartnerSetupMail
      summary: Resend a partner password setup link
      description: 'Requires `staff:affiliates:write` on a staff session.'
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:write]
      responses:
        '200':
          description: The delivery outcome.
          content:
            application/json:
              schema:
                type: object
                required: [setup_mail_status]
                properties:
                  setup_mail_status: { type: string, enum: [sent, failed, unknown] }
        '400': { description: Malformed application id. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '404': { description: The application has no provisioned partner user. }
        '503': { description: Database unavailable. }

  /staff/affiliates:
    get:
      operationId: listStaffPartners
      summary: Partner directory
      description: 'Requires `staff:affiliates:read` on a staff session.'
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:read]
      parameters:
        - { in: query, name: status, schema: { type: string } }
        - { in: query, name: q, schema: { type: string } }
        - { in: query, name: limit, schema: { type: integer, minimum: 1, maximum: 200 } }
        - { in: query, name: offset, schema: { type: integer, minimum: 0 } }
      responses:
        '200':
          description: The partner directory page.
          content:
            application/json:
              schema:
                type: object
                required: [items, total, next_offset]
                properties:
                  items:
                    type: array
                    items: { $ref: '#/components/schemas/StaffPartnerRow' }
                  total: { type: integer }
                  next_offset: { type: integer, nullable: true }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '503': { description: Database unavailable. }
    post:
      operationId: createStaffPartner
      summary: Create and invite a partner
      description: >-
        Requires `staff:affiliates:admin` on a staff session. The Better Auth login and the
        partner rows commit together; the setup mail follows and is reported separately.
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:admin]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [display_name, email]
              additionalProperties: false
              properties:
                display_name: { type: string, minLength: 1, maxLength: 160 }
                email: { type: string, format: email }
                phone: { type: string, nullable: true }
                company: { type: string, maxLength: 160 }
                legal_name: { type: string, maxLength: 160 }
      responses:
        '201':
          description: The created partner.
          content:
            application/json:
              schema:
                type: object
                required: [partner_id, partner_user_id, setup_mail_status]
                properties:
                  partner_id: { type: string, format: uuid }
                  partner_user_id: { type: string, format: uuid }
                  setup_mail_status: { type: string, enum: [sent, failed, unknown] }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '403': { description: The staff role does not hold the scope. }
        '409': { description: The partner code or email already exists. }
        '422': { description: Validation failed. }
        '503': { description: Database unavailable. }

  /staff/affiliates/{id}:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
    get:
      operationId: getStaffPartner
      summary: Partner detail
      description: >-
        Requires `staff:affiliates:read` on a staff session. Includes the owner login and
        referral/invitation counts.
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:read]
      responses:
        '200':
          description: The partner, its owner login, and its counts.
          content:
            application/json:
              schema:
                type: object
                required: [partner, user, referral_counts_by_stage, invitation_counts_by_status]
                properties:
                  partner: { $ref: '#/components/schemas/StaffPartnerRow' }
                  user: { type: object, nullable: true, additionalProperties: true }
                  referral_counts_by_stage: { type: object, additionalProperties: { type: integer } }
                  invitation_counts_by_status: { type: object, additionalProperties: { type: integer } }
        '400': { description: Malformed partner id. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '404': { description: No such partner. }
        '503': { description: Database unavailable. }

  /staff/affiliates/{id}/suspend:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
    post:
      operationId: suspendStaffPartner
      summary: Suspend a partner
      description: >-
        Requires `staff:affiliates:admin` on a staff session. Kills every live partner session,
        revokes active invitations, cancels queued invitation mail, and notifies the partner.
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:admin]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [reason]
              additionalProperties: false
              properties:
                reason: { type: string, minLength: 1, maxLength: 500 }
      responses:
        '200':
          description: The partner was suspended.
          content:
            application/json:
              schema:
                type: object
                required: [partner_id, action]
                properties:
                  partner_id: { type: string, format: uuid }
                  action: { type: string }
        '400': { description: Malformed partner id. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '403': { description: The staff role does not hold the scope. }
        '404': { description: No such partner. }
        '422': { description: Validation failed. }
        '503': { description: Database unavailable. }

  /staff/affiliates/{id}/reactivate:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
    post:
      operationId: reactivateStaffPartner
      summary: Reactivate a suspended partner
      description: >-
        Requires `staff:affiliates:admin` on a staff session. Restores the login status only;
        invitations revoked by the suspension stay revoked. A closed partner cannot be
        reactivated.
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:admin]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [reason]
              additionalProperties: false
              properties:
                reason: { type: string, minLength: 1, maxLength: 500 }
      responses:
        '200':
          description: The partner was reactivated.
          content:
            application/json:
              schema:
                type: object
                required: [partner_id, action]
                properties:
                  partner_id: { type: string, format: uuid }
                  action: { type: string }
        '400': { description: Malformed partner id. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '403': { description: The staff role does not hold the scope. }
        '409': { description: The partner is closed. }
        '422': { description: Validation failed. }
        '503': { description: Database unavailable. }

  /staff/affiliates/{id}/close:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
    post:
      operationId: closeStaffPartner
      summary: Close a partner
      description: >-
        Requires `staff:affiliates:admin` on a staff session. A soft delete on top of a
        suspension; terminal.
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:admin]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [reason]
              additionalProperties: false
              properties:
                reason: { type: string, minLength: 1, maxLength: 500 }
      responses:
        '200':
          description: The partner was closed.
          content:
            application/json:
              schema:
                type: object
                required: [partner_id, action]
                properties:
                  partner_id: { type: string, format: uuid }
                  action: { type: string }
        '400': { description: Malformed partner id. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '403': { description: The staff role does not hold the scope. }
        '422': { description: Validation failed. }
        '503': { description: Database unavailable. }

  /staff/affiliates/{id}/caps:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
    put:
      operationId: setStaffPartnerCaps
      summary: Set partner invitation caps
      description: 'Requires `staff:affiliates:admin` on a staff session.'
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:admin]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [invitation_daily_cap, invitation_monthly_cap]
              additionalProperties: false
              properties:
                invitation_daily_cap: { type: integer, minimum: 0, maximum: 1000 }
                invitation_monthly_cap: { type: integer, minimum: 0, maximum: 10000 }
      responses:
        '200':
          description: The partner with its new caps.
          content:
            application/json:
              schema:
                type: object
                required: [partner]
                properties:
                  partner: { $ref: '#/components/schemas/StaffPartnerRow' }
        '400': { description: Malformed partner id. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '403': { description: The staff role does not hold the scope. }
        '404': { description: No such partner. }
        '422': { description: Validation failed. }
        '503': { description: Database unavailable. }

  /staff/affiliates/{id}/referrals:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
    get:
      operationId: listStaffPartnerReferralsForPartner
      summary: Referrals for one partner
      description: 'Requires `staff:affiliates:read` on a staff session.'
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:read]
      parameters:
        - { in: query, name: review_status, schema: { type: string } }
        - { in: query, name: stage, schema: { type: string } }
        - { in: query, name: q, schema: { type: string } }
        - { in: query, name: limit, schema: { type: integer, minimum: 1, maximum: 200 } }
        - { in: query, name: offset, schema: { type: integer, minimum: 0 } }
      responses:
        '200':
          description: The referral rows for this partner.
          content:
            application/json:
              schema:
                type: object
                required: [items, total, next_offset]
                properties:
                  items:
                    type: array
                    items: { $ref: '#/components/schemas/StaffReferralRow' }
                  total: { type: integer }
                  next_offset: { type: integer, nullable: true }
        '400': { description: Malformed partner id. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '503': { description: Database unavailable. }

  /staff/affiliates/referrals:
    get:
      operationId: listStaffPartnerReferrals
      summary: Cross-partner referral review queue
      description: 'Requires `staff:affiliates:read` on a staff session.'
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:read]
      parameters:
        - { in: query, name: review_status, schema: { type: string } }
        - { in: query, name: stage, schema: { type: string } }
        - { in: query, name: q, schema: { type: string } }
        - { in: query, name: limit, schema: { type: integer, minimum: 1, maximum: 200 } }
        - { in: query, name: offset, schema: { type: integer, minimum: 0 } }
      responses:
        '200':
          description: The referral review queue.
          content:
            application/json:
              schema:
                type: object
                required: [items, total, next_offset]
                properties:
                  items:
                    type: array
                    items: { $ref: '#/components/schemas/StaffReferralRow' }
                  total: { type: integer }
                  next_offset: { type: integer, nullable: true }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '503': { description: Database unavailable. }

  /staff/affiliates/referrals/{id}/accept:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
    post:
      operationId: acceptStaffPartnerReferral
      summary: Accept a referral
      description: >-
        Requires `staff:affiliates:write` on a staff session. Starts the 180-day attribution
        window. An `existing_customer` or `self_referral` conflict is refused without an
        explicit `override`.
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:write]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                reason: { type: string, maxLength: 500 }
                override: { type: boolean }
      responses:
        '200':
          description: The accepted referral.
          content:
            application/json:
              schema:
                type: object
                required: [referral]
                properties:
                  referral: { $ref: '#/components/schemas/StaffReferralRow' }
        '400': { description: Malformed referral id. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '404': { description: No such referral. }
        '409': { description: 'The referral is not pending, or its conflict needs an override.' }
        '422': { description: Validation failed. }
        '503': { description: Database unavailable. }

  /staff/affiliates/referrals/{id}/mark-ineligible:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
    post:
      operationId: markStaffPartnerReferralIneligible
      summary: Mark a referral ineligible
      description: 'Requires `staff:affiliates:write` on a staff session. A conflict and a reason are both required.'
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:write]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [conflict, reason]
              additionalProperties: false
              properties:
                conflict: { type: string, enum: [duplicate, existing_customer, self_referral] }
                reason: { type: string, minLength: 1, maxLength: 500 }
      responses:
        '200':
          description: The ineligible referral.
          content:
            application/json:
              schema:
                type: object
                required: [referral]
                properties:
                  referral: { $ref: '#/components/schemas/StaffReferralRow' }
        '400': { description: Malformed referral id. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '404': { description: No such referral. }
        '422': { description: Validation failed. }
        '503': { description: Database unavailable. }

  /staff/affiliates/referrals/{id}/set-stage:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
    post:
      operationId: setStaffPartnerReferralStage
      summary: Set a referral stage
      description: >-
        Requires `staff:affiliates:write` on a staff session. `signed_up` is absent by design —
        that stage is written by attribution at signup approval, never by hand.
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:write]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [stage, reason]
              additionalProperties: false
              properties:
                stage: { type: string, enum: [qualifying, qualified, lost] }
                reason: { type: string, minLength: 1, maxLength: 500 }
      responses:
        '200':
          description: The referral at its new stage.
          content:
            application/json:
              schema:
                type: object
                required: [referral]
                properties:
                  referral: { $ref: '#/components/schemas/StaffReferralRow' }
        '400': { description: Malformed referral id. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '404': { description: No such referral. }
        '422': { description: Validation failed. }
        '503': { description: Database unavailable. }

  /staff/affiliates/referrals/{id}/confirm-mismatch:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
    post:
      operationId: confirmStaffPartnerReferralMismatch
      summary: Resolve an invitation mismatch
      description: >-
        Requires `staff:affiliates:write` on a staff session. `confirm: true` records that the
        referral still applies and re-runs the attribution rules when the account already
        exists; `confirm: false` records a terminal `rejected` decision for that application.
        A reason is always required.
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:write]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [signup_application_id, confirm, reason]
              additionalProperties: false
              properties:
                signup_application_id: { type: string, format: uuid }
                confirm: { type: boolean }
                reason: { type: string, minLength: 1, maxLength: 500 }
      responses:
        '200':
          description: The decision recorded for the application.
          content:
            application/json:
              schema:
                type: object
                required: [decision, decision_id]
                properties:
                  decision: { type: string, enum: [attributed, rejected, override, deferred] }
                  decision_id: { type: string, format: uuid, nullable: true }
        '400': { description: Malformed referral id. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '404': { description: No such referral or signup application. }
        '409': { description: The application is not bound to this referral. }
        '422': { description: Validation failed. }
        '503': { description: Database unavailable. }

  /staff/affiliates/referrals/{id}/override-attribution:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
    post:
      operationId: overrideStaffPartnerReferralAttribution
      summary: Override attribution for an account
      description: >-
        Requires `staff:affiliates:write` on a staff session. Forces the attribution against the
        eligibility rules, taking the company claim and the account from whatever held them,
        and appends an `override` decision carrying the reason.
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:write]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [account_id, reason]
              additionalProperties: false
              properties:
                account_id: { type: string, format: uuid }
                reason: { type: string, minLength: 1, maxLength: 500 }
      responses:
        '200':
          description: The appended decision.
          content:
            application/json:
              schema:
                type: object
                required: [decision_id]
                properties:
                  decision_id: { type: string, format: uuid }
        '400': { description: Malformed referral id. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '404': { description: No such referral or account. }
        '422': { description: Validation failed. }
        '503': { description: Database unavailable. }

  /staff/affiliates/referrals/{id}/link-account:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
    post:
      operationId: linkStaffPartnerReferralAccount
      summary: Link an account to a referral
      description: >-
        Requires `staff:affiliates:write` on a staff session. Attributes an account that no other
        referral holds — the "signed up without using the link" repair. Taking an attribution
        away from another referral is refused here and goes through override-attribution.
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:write]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [account_id, reason]
              additionalProperties: false
              properties:
                account_id: { type: string, format: uuid }
                reason: { type: string, minLength: 1, maxLength: 500 }
      responses:
        '200':
          description: The appended decision.
          content:
            application/json:
              schema:
                type: object
                required: [decision_id]
                properties:
                  decision_id: { type: string, format: uuid }
        '400': { description: Malformed referral id. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '404': { description: No such referral or account. }
        '409': { description: 'The account or the company is already attributed to another referral.' }
        '422': { description: Validation failed. }
        '503': { description: Database unavailable. }

  /staff/affiliates/mismatches:
    get:
      operationId: listStaffPartnerMismatches
      summary: Invitation-mismatch review queue
      description: >-
        Requires `staff:affiliates:read` on a staff session — deliberately the READ scope. The
        queue is a worklist every staff role may triage, and its rows carry no partner-private
        data beyond what the staff console already shows; the decisions taken on it
        (confirm-mismatch, link-account, override-attribution) are the write-scoped operations.
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:read]
      parameters:
        - { in: query, name: limit, schema: { type: integer, minimum: 1, maximum: 200 } }
        - { in: query, name: offset, schema: { type: integer, minimum: 0 } }
      responses:
        '200':
          description: Unresolved invitation mismatches.
          content:
            application/json:
              schema:
                type: object
                required: [items, total, next_offset]
                properties:
                  items:
                    type: array
                    items: { $ref: '#/components/schemas/StaffPartnerMismatchRow' }
                  total: { type: integer }
                  next_offset: { type: integer, nullable: true }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '503': { description: Database unavailable. }

  /staff/affiliates/invitations:
    get:
      operationId: listStaffPartnerInvitations
      summary: Partner invitation queue
      description: >-
        Requires `staff:affiliates:read` on a staff session. Carries the mismatch kinds and the
        bound signup application the mismatch review queue is built on.
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:read]
      parameters:
        - { in: query, name: status, schema: { type: string } }
        - { in: query, name: partner_id, schema: { type: string, format: uuid } }
        - { in: query, name: limit, schema: { type: integer, minimum: 1, maximum: 200 } }
        - { in: query, name: offset, schema: { type: integer, minimum: 0 } }
      responses:
        '200':
          description: The invitation queue.
          content:
            application/json:
              schema:
                type: object
                required: [items, total, next_offset]
                properties:
                  items:
                    type: array
                    items: { $ref: '#/components/schemas/StaffInvitationRow' }
                  total: { type: integer }
                  next_offset: { type: integer, nullable: true }
        '400': { description: Malformed partner id filter. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '503': { description: Database unavailable. }

  /staff/affiliates/invitations/{id}/revoke:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
    post:
      operationId: revokeStaffPartnerInvitation
      summary: Revoke an invitation as staff
      description: >-
        Requires `staff:affiliates:write` on a staff session. Also cancels any queued invitation
        mail in the same transaction.
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:write]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [reason]
              additionalProperties: false
              properties:
                reason: { type: string, minLength: 1, maxLength: 500 }
      responses:
        '200':
          description: The revoked invitation.
          content:
            application/json:
              schema:
                type: object
                required: [invitation]
                properties:
                  invitation: { $ref: '#/components/schemas/StaffInvitationRow' }
        '400': { description: Malformed invitation id. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '404': { description: No such invitation. }
        '409': { description: The invitation cannot be revoked from its current status. }
        '422': { description: Validation failed. }
        '503': { description: Database unavailable. }

  /staff/affiliates/suppressions:
    get:
      operationId: listStaffPartnerSuppressions
      summary: Invitation-outreach suppression list
      description: >-
        Requires `staff:affiliates:write` on a staff session. Managing suppressions is a control
        surface, not a report, so the list is gated with the write scope. Hashes only: the
        plaintext address is never stored beside the keyed digest.
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:write]
      parameters:
        - { in: query, name: limit, schema: { type: integer, minimum: 1, maximum: 200 } }
        - { in: query, name: offset, schema: { type: integer, minimum: 0 } }
      responses:
        '200':
          description: The suppression list page.
          content:
            application/json:
              schema:
                type: object
                required: [items, total, next_offset]
                properties:
                  items:
                    type: array
                    items: { $ref: '#/components/schemas/StaffSuppressionRow' }
                  total: { type: integer }
                  next_offset: { type: integer, nullable: true }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '503': { description: Database unavailable. }
    post:
      operationId: addStaffPartnerSuppression
      summary: Suppress invitation outreach to an address
      description: >-
        Requires `staff:affiliates:write` on a staff session. The address is hashed with the
        global salt and only the digest is stored; the response echoes the digest, never the
        address.
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:write]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [email]
              additionalProperties: false
              properties:
                email: { type: string, format: email }
      responses:
        '201':
          description: The suppression digest, and whether this call created it.
          content:
            application/json:
              schema:
                type: object
                required: [email_lookup_hash, added]
                properties:
                  email_lookup_hash: { type: string }
                  added: { type: boolean }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '422': { description: Validation failed. }
        '503': { description: Database unavailable. }

  /staff/affiliates/suppressions/{hash}:
    parameters:
      - { in: path, name: hash, required: true, schema: { type: string, pattern: '^[0-9a-fA-F]{64}$' } }
    delete:
      operationId: removeStaffPartnerSuppression
      summary: Remove a suppression
      description: >-
        Requires `staff:affiliates:write` on a staff session. Keyed by the hex digest, because
        the digest is the only handle the list ever showed.
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:write]
      responses:
        '200':
          description: The suppression was removed.
          content:
            application/json:
              schema:
                type: object
                required: [removed]
                properties:
                  removed: { type: boolean }
        '400': { description: Malformed digest. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '404': { description: No such suppression. }
        '503': { description: Database unavailable. }

  /staff/affiliates/{id}/activity:
    parameters:
      - { in: path, name: id, required: true, schema: { type: string, format: uuid } }
    get:
      operationId: listStaffPartnerActivity
      summary: Partner audit trail
      description: >-
        Requires `staff:affiliates:read` on a staff session. `affiliate_audit_events` is deny-all
        to every session, so this is the only way those rows are readable.
      tags: [Staff]
      x-portrex-scopes: [staff:affiliates:read]
      parameters:
        - { in: query, name: limit, schema: { type: integer, minimum: 1, maximum: 200 } }
        - { in: query, name: offset, schema: { type: integer, minimum: 0 } }
      responses:
        '200':
          description: The audit trail page.
          content:
            application/json:
              schema:
                type: object
                required: [items, total, next_offset]
                properties:
                  items:
                    type: array
                    items: { $ref: '#/components/schemas/StaffPartnerActivityRow' }
                  total: { type: integer }
                  next_offset: { type: integer, nullable: true }
        '400': { description: Malformed partner id. }
        '401': { description: 'Missing, invalid, inactive, or revoked staff session.' }
        '503': { description: Database unavailable. }

  /showroom/rebate-research/states:
    get:
      summary: List all50 state coverage summaries
      description: Tenant user session. Requires pricebooks:read.
      tags:
        - Showroom rebate research
      responses:
        "200":
          description: Stored research with explicit evidence and coverage.
        "400":
          description: Invalid public scope or request.
        "401":
          description: Tenant session required.
        "403":
          description: Scope or manager role required.
        "404":
          description: Record not found in authorized account or branch.
        "409":
          description: Idempotency, quality, or revision conflict.
  /showroom/rebate-research/states/{state}:
    get:
      summary: Read current effective public research and private review selection
      description: Tenant user session. Requires pricebooks:read.
      tags:
        - Showroom rebate research
      parameters:
        - name: state
          in: path
          required: true
          schema:
            type: string
      responses:
        "200":
          description: Stored research with explicit evidence and coverage.
        "400":
          description: Invalid public scope or request.
        "401":
          description: Tenant session required.
        "403":
          description: Scope or manager role required.
        "404":
          description: Record not found in authorized account or branch.
        "409":
          description: Idempotency, quality, or revision conflict.
  /showroom/rebate-research/states/{state}/versions/{versionId}:
    get:
      summary: Read one immutable scope version
      description: Tenant user session. Requires pricebooks:read.
      tags:
        - Showroom rebate research
      parameters:
        - name: state
          in: path
          required: true
          schema:
            type: string
        - name: versionId
          in: path
          required: true
          schema:
            type: string
      responses:
        "200":
          description: Stored research with explicit evidence and coverage.
        "400":
          description: Invalid public scope or request.
        "401":
          description: Tenant session required.
        "403":
          description: Scope or manager role required.
        "404":
          description: Record not found in authorized account or branch.
        "409":
          description: Idempotency, quality, or revision conflict.
  /showroom/rebate-research/states/{state}/versions/{versionId}/review:
    post:
      summary: Append a private account or branch evidence decision
      description: Tenant user session. Requires pricebooks:write.
      tags:
        - Showroom rebate research
      parameters:
        - name: state
          in: path
          required: true
          schema:
            type: string
        - name: versionId
          in: path
          required: true
          schema:
            type: string
      responses:
        "200":
          description: Durable run or audited review decision.
        "400":
          description: Invalid public scope or request.
        "401":
          description: Tenant session required.
        "403":
          description: Scope or manager role required.
        "404":
          description: Record not found in authorized account or branch.
        "409":
          description: Idempotency, quality, or revision conflict.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required:
                - decision
                - reason
                - expectedCurrentVersionId
              properties:
                decision:
                  type: string
                  enum:
                    - accept
                    - reject
                reason:
                  type: string
                  minLength: 10
                  maxLength: 2000
                expectedCurrentVersionId:
                  type:
                    - string
                    - "null"
                  format: uuid
  /showroom/rebate-research/runs:
    post:
      summary: Request bounded manual public research
      description: Tenant user session. Requires pricebooks:write.
      tags:
        - Showroom rebate research
      responses:
        "200":
          description: Durable run or audited review decision.
        "202":
          description: Public scopes persisted. Trusted worker execution is pending.
        "400":
          description: Invalid public scope or request.
        "401":
          description: Tenant session required.
        "403":
          description: Scope or manager role required.
        "404":
          description: Record not found in authorized account or branch.
        "409":
          description: Idempotency, quality, or revision conflict.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required:
                - state_codes
                - idempotency_key
              properties:
                state_codes:
                  type: array
                  minItems: 1
                  maxItems: 50
                  items:
                    type: string
                    pattern: ^[A-Z]{2}$
                idempotency_key:
                  type: string
                  minLength: 8
                  maxLength: 180
                include_federal:
                  type: boolean
                  default: true
                include_manufacturers:
                  type: boolean
                  default: true
                utility_scopes:
                  type: array
                  description: Known utilities in the requested states. Hyphen and underscore aliases resolve to the same canonical hyphen scope key.
                  maxItems: 100
                  items:
                    type: string
                    pattern: ^utility:[A-Z]{2}:[a-z0-9_-]+:(electric|gas|combined)$
                max_calls:
                  type: integer
                  minimum: 1
                  maximum: 200
                  default: 64
                max_cost_usd:
                  type: number
                  exclusiveMinimum: 0
                  maximum: 100
                  default: 25
  /showroom/rebate-research/quote-refresh:
    post:
      summary: Request bounded research for one quote state without quote facts
      description: Tenant user session. Requires pricebooks:read.
      tags:
        - Showroom rebate research
      responses:
        "200":
          description: Durable run or audited review decision.
        "202":
          description: Public scopes persisted. Trusted worker execution is pending.
        "400":
          description: Invalid public scope or request.
        "401":
          description: Tenant session required.
        "403":
          description: Scope or manager role required.
        "404":
          description: Record not found in authorized account or branch.
        "409":
          description: Idempotency, quality, or revision conflict.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required:
                - state_codes
                - idempotency_key
              properties:
                state_codes:
                  type: array
                  minItems: 1
                  maxItems: 1
                  items:
                    type: string
                    pattern: ^[A-Z]{2}$
                idempotency_key:
                  type: string
                  minLength: 8
                  maxLength: 180
                include_federal:
                  type: boolean
                  default: true
                include_manufacturers:
                  type: boolean
                  default: true
                utility_scopes:
                  type: array
                  description: Known utilities in the requested states. Hyphen and underscore aliases resolve to the same canonical hyphen scope key.
                  maxItems: 100
                  items:
                    type: string
                    pattern: ^utility:[A-Z]{2}:[a-z0-9_-]+:(electric|gas|combined)$
                max_calls:
                  type: integer
                  minimum: 1
                  maximum: 200
                  default: 64
                max_cost_usd:
                  type: number
                  exclusiveMinimum: 0
                  maximum: 100
                  default: 25
  /showroom/rebate-research/rewiring-live-result:
    post:
      summary: Save a held public-building Rewiring America result from the authenticated web server
      description: Tenant user session with pricebooks:read. Requires a domain-separated server signature. The result is immutable, unverified, and never enters quote savings.
      tags:
        - Showroom rebate research
      parameters:
        - name: x-portrex-rewiring-result-signature
          in: header
          required: true
          schema:
            type: string
      responses:
        "201":
          description: Held provider result saved as an immutable version.
        "400":
          description: Invalid or stale provider result.
        "401":
          description: Tenant session required.
        "403":
          description: Scope or server provenance rejected.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required:
                - stateCode
                - accountId
                - subAccountId
                - result
              properties:
                stateCode:
                  type: string
                  pattern: ^[A-Z]{2}$
                accountId:
                  type: string
                  format: uuid
                subAccountId:
                  type: string
                  format: uuid
                  nullable: true
                result:
                  type: object
                  description: Strict Rewiring provider-result contract; server-signed and validated before held storage.
  /showroom/rebate-research/runs/{runId}:
    get:
      summary: Read one tenant research run
      description: Tenant user session. Requires pricebooks:read.
      tags:
        - Showroom rebate research
      parameters:
        - name: runId
          in: path
          required: true
          schema:
            type: string
      responses:
        "200":
          description: Stored research with explicit evidence and coverage.
        "400":
          description: Invalid public scope or request.
        "401":
          description: Tenant session required.
        "403":
          description: Scope or manager role required.
        "404":
          description: Record not found in authorized account or branch.
        "409":
          description: Idempotency, quality, or revision conflict.
  /showroom/rebate-research/runs/{runId}/cancel:
    post:
      summary: Cancel pending public research scopes
      description: Tenant user session. Requires pricebooks:write.
      tags:
        - Showroom rebate research
      parameters:
        - name: runId
          in: path
          required: true
          schema:
            type: string
      responses:
        "200":
          description: Durable run or audited review decision.
        "400":
          description: Invalid public scope or request.
        "401":
          description: Tenant session required.
        "403":
          description: Scope or manager role required.
        "404":
          description: Record not found in authorized account or branch.
        "409":
          description: Idempotency, quality, or revision conflict.
  /showroom/rebate-research/runs/{runId}/retry:
    post:
      summary: Retry failed or unattempted scopes in a new linked run
      description: Tenant user session. Requires pricebooks:write.
      tags:
        - Showroom rebate research
      parameters:
        - name: runId
          in: path
          required: true
          schema:
            type: string
      responses:
        "200":
          description: Durable run or audited review decision.
        "400":
          description: Invalid public scope or request.
        "401":
          description: Tenant session required.
        "403":
          description: Scope or manager role required.
        "404":
          description: Record not found in authorized account or branch.
        "409":
          description: Idempotency, quality, or revision conflict.
  /me/email-accounts:
    get:
      operationId: listPersonalEmailAccounts
      summary: List caller's personal email connections
      description: Direct tenant user browser session only. Refused during staff or tenant impersonation. Returns redacted mailbox metadata only; never returns passwords, usernames, or ciphertext.
      tags:
        - Personal Email
      security:
        - sessionCookie: []
      responses:
        "200":
          description: Redacted list of personal email connections owned by the caller.
        "401":
          description: Tenant session required.
        "403":
          description: Forbidden while impersonating or principal not permitted.
    post:
      operationId: createPersonalEmailAccount
      summary: Verify and save a personal IMAP/SMTP email connection
      description: Direct tenant user browser session only. Refused during staff or tenant impersonation. Validates public DNS mail hosts and allowed mail ports, verifies SMTP and IMAP credentials over TLS/STARTTLS, and stores credentials KEK-encrypted. Requires Idempotency-Key header.
      tags:
        - Personal Email
      security:
        - sessionCookie: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - provider
                - displayName
                - emailAddress
                - incoming
                - outgoing
              properties:
                provider:
                  type: string
                  enum: [gmail, outlook, custom]
                displayName:
                  type: string
                emailAddress:
                  type: string
                  format: email
                incoming:
                  type: object
                  required: [host, port, password]
                  properties:
                    host:
                      type: string
                    port:
                      type: integer
                    username:
                      type: string
                    password:
                      type: string
                      format: password
                    ssl:
                      type: boolean
                outgoing:
                  type: object
                  required: [host, port, password]
                  properties:
                    host:
                      type: string
                    port:
                      type: integer
                    username:
                      type: string
                    password:
                      type: string
                      format: password
                    ssl:
                      type: boolean
      responses:
        "201":
          description: Personal email connection verified and stored (redacted metadata and sanitized logs).
        "400":
          description: Invalid request payload, disallowed mail port, or blocked SSRF host/IP.
        "401":
          description: Tenant session required.
        "403":
          description: Forbidden while impersonating or principal not permitted.
        "422":
          description: Upstream SMTP or IMAP verification failed.
  /me/email-accounts/{id}:
    patch:
      operationId: updatePersonalEmailAccount
      summary: Update display name, server settings, or credentials for a personal email connection
      description: Direct tenant user browser session only. Refused during staff or tenant impersonation. Re-verifies IMAP and SMTP live whenever server settings or credentials change, preserving saved credentials when omitted. Requires Idempotency-Key header.
      tags:
        - Personal Email
      security:
        - sessionCookie: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
            format: uuid
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                provider:
                  type: string
                  enum:
                    - gmail
                    - outlook
                    - custom
                displayName:
                  type: string
                incoming:
                  type: object
                  properties:
                    host:
                      type: string
                    port:
                      type: integer
                    username:
                      type: string
                    password:
                      type: string
                      format: password
                    ssl:
                      type: boolean
                outgoing:
                  type: object
                  properties:
                    host:
                      type: string
                    port:
                      type: integer
                    username:
                      type: string
                    password:
                      type: string
                      format: password
                    ssl:
                      type: boolean
      responses:
        "200":
          description: Personal email connection updated.
        "400":
          description: Invalid payload, connection ID, or blocked mail host.
        "401":
          description: Tenant session required.
        "403":
          description: Forbidden while impersonating or principal not permitted.
        "404":
          description: Personal email connection not found for caller.
        "422":
          description: Upstream SMTP or IMAP verification failed.
    delete:
      operationId: deletePersonalEmailAccount
      summary: Disconnect and wipe a personal email connection
      description: Direct tenant user browser session only. Refused during staff or tenant impersonation. Soft-deletes the connection and permanently wipes encrypted credentials.
      tags:
        - Personal Email
      security:
        - sessionCookie: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
            format: uuid
      responses:
        "204":
          description: Personal email connection disconnected and credentials wiped.
        "400":
          description: Invalid connection ID.
        "401":
          description: Tenant session required.
        "403":
          description: Forbidden while impersonating or principal not permitted.
        "404":
          description: Personal email connection not found for caller.
  /me/email-accounts/{id}/verify:
    post:
      operationId: verifyPersonalEmailAccount
      summary: Re-verify saved IMAP and SMTP credentials for a personal email connection
      description: Direct tenant user browser session only. Refused during staff or tenant impersonation. Re-validates stored IMAP and SMTP hosts against public DNS/IP guards and tests saved encrypted credentials without modifying last_synced_at. Requires Idempotency-Key header.
      tags:
        - Personal Email
      security:
        - sessionCookie: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
            format: uuid
      responses:
        "200":
          description: Personal email connection verified and marked connected.
        "400":
          description: Invalid connection ID or stored host blocked by SSRF policy.
        "401":
          description: Tenant session required.
        "403":
          description: Forbidden while impersonating or principal not permitted.
        "404":
          description: Personal email connection not found for caller.
        "422":
          description: Upstream SMTP or IMAP verification failed.
        "502":
          description: Unexpected upstream verification failure.
  /me/email-accounts/{id}/sync:
    post:
      operationId: syncPersonalEmailAccount
      summary: Synchronize recent inbox messages for a personal email connection
      description: Direct tenant user browser session only. Refused during staff or tenant impersonation. Re-validates stored IMAP host against public DNS/IP guards and fetches a bounded batch of recent inbox messages. Requires Idempotency-Key header.
      tags:
        - Personal Email
      security:
        - sessionCookie: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
            format: uuid
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                limit:
                  type: integer
                  minimum: 1
                  maximum: 25
      responses:
        "200":
          description: Updated connection metadata and bounded inbox messages.
        "400":
          description: Invalid request or stored host blocked by SSRF policy.
        "401":
          description: Tenant session required.
        "403":
          description: Forbidden while impersonating or principal not permitted.
        "404":
          description: Personal email connection not found for caller.
        "502":
          description: Upstream IMAP server synchronization failed.
  /me/email-accounts/{id}/send:
    post:
      operationId: sendPersonalEmail
      summary: Send an email through a connected personal mailbox
      description: Direct tenant user browser session only. Refused during staff or tenant impersonation. Re-validates stored SMTP host against public DNS/IP guards and forces the From header from the saved personal connection. Requires Idempotency-Key header.
      tags:
        - Personal Email
      security:
        - sessionCookie: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
            format: uuid
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - to
                - subject
                - body
              properties:
                to:
                  type: array
                  items:
                    type: string
                    format: email
                cc:
                  type: array
                  items:
                    type: string
                    format: email
                bcc:
                  type: array
                  items:
                    type: string
                    format: email
                subject:
                  type: string
                body:
                  type: string
                attachments:
                  type: array
                  maxItems: 5
                  description: Optional inline base64-encoded file attachments (max 5 files, 5 MiB per file, 10 MiB decoded total). Filesystem paths and remote URLs are rejected.
                  items:
                    type: object
                    additionalProperties: false
                    required: [filename, contentType, contentBase64]
                    properties:
                      filename:
                        type: string
                        minLength: 1
                        maxLength: 255
                      contentType:
                        type: string
                        minLength: 3
                        maxLength: 128
                      contentBase64:
                        type: string
                activityLink:
                  type: object
                  required: [ownerType, ownerId]
                  properties:
                    ownerType:
                      type: string
                      enum: [lead, customer, project, estimate]
                    ownerId:
                      type: string
                      format: uuid
      responses:
        "200":
          description: Email accepted by the connected SMTP server.
        "400":
          description: Invalid email payload, disallowed field, header injection, or SSRF host blocked.
        "401":
          description: Tenant session required.
        "403":
          description: Forbidden while impersonating or principal not permitted.
        "404":
          description: Personal email connection not found for caller.
        "502":
          description: Upstream SMTP delivery failed.
