{
 "openapi": "3.0.3",
 "info": {
  "title": "Boundless AI — Bot REST API (HCS Admin CRM + BizOp lead CRM)",
  "version": "2026-11-30",
  "description": "JSON in / JSON out. Every timestamp is ISO 8601 with a UTC offset, rendered in **America/Los_Angeles** (`2026-10-22T10:00:00-07:00`).\nInputs accept any ISO 8601 offset; a bare `YYYY-MM-DD HH:MM` is read as Pacific.\n\n**Auth** — one key per bot, `Authorization: Bearer bk_…` (also accepted: `X-Api-Key`). Each key carries scopes;\na route needs the scope listed on it. Missing key → 401, unknown/revoked key → 403, missing scope → 403.\nNarrow sales scopes for call bots: `sales:review` (review flag + decision), `sales:cardlink` (secure card link),\n`sales:calls` (call-result + do-not-contact) — each opens only its routes; `sales:write` still covers all of them.\n`contact:write` (2026-11-21) — set and clear do_not_contact and dispute_hold on a client or a lead, with a reason; nothing else.\n\n**Writes** — every non-GET request is journaled in `bot_api_audit` (bot, path, body, before, after, status, IP).\nSend `X-Dry-Run: 1` (or `?dry_run=1`) on any write to validate and see what *would* happen without changing anything.\n\n**People matching** — phones are normalized to E.164 and matched against EVERY phone on a profile\n(primary, business line, the linked sales-floor lead's phone and alt phones). Emails match case-insensitively against\nthe account email and the client's minted company aliases. A lookup with no match is `200 {is_client:false, client:null}`, never an error.\n\n**Do-not-contact** — every send / call / booking route refuses flagged people: 403 for a plain bot key; **HTTP 200\n`{status: \"refused\", ok: false, code, say, http_status}`** when the caller is an agent (the Chris key, a narrow call-bot\nkey, or `source` ending in `_agent`) so ElevenLabs tools keep the `say` line (2026-10-21).\n\n**Envelope (2026-10-26)** — every response carries `ok: true|false`. Success: `{\"ok\":true,\"status\":\"success\", ...}`.\nError: `{\"ok\":false,\"status\":\"error\",\"code\":\"<snake_case>\",\"message\":\"…\"}` with the HTTP status (400 bad input, 401 no key,\n403 scope / DNC, 404 `not_found` — also for unknown `/api/*` paths, 405 + `Allow` for a wrong method, 409 conflict, 429 rate limit).\n\n**Idempotency** — send `Idempotency-Key: <string>` on any write; the same bot key + the same Idempotency-Key inside 24 h replays the stored\nresponse (header `Idempotent-Replayed: true`) instead of writing twice.\n\n**Rate limits** — per key: 60 reads / 10 writes per minute (`BOT_RATE_READS` / `BOT_RATE_WRITES`); over the limit → 429 + `Retry-After`.\n\n**Audit** — `GET /api/audit` (scope `audit:read`) lists the key's own writes; `approved_by` in a body or `X-Approved-By` is recorded with the write.\n"
 },
 "servers": [
  {
   "url": "https://shannonmanagementco.com",
   "description": "Production (the only environment — use read-only keys + X-Dry-Run as the staging path)"
  },
  {
   "url": "https://get-boundless-ai.com",
   "description": "Same server, same routes"
  }
 ],
 "tags": [
  {
   "name": "Health"
  },
  {
   "name": "Clients"
  },
  {
   "name": "Comms"
  },
  {
   "name": "Mail"
  },
  {
   "name": "Documents"
  },
  {
   "name": "Setup"
  },
  {
   "name": "Cards"
  },
  {
   "name": "Booking"
  },
  {
   "name": "ElevenLabs"
  },
  {
   "name": "Payouts"
  },
  {
   "name": "SFC loans",
   "description": "2026-11-20 — SFC-financed loan payment tracking: loans, payments, audit log, at-risk list, daily report. Scopes sfc:read / sfc:write; payouts:read / payouts:write open the same routes. No SSN, birth date or full bank / card number is accepted — last 4 digits only (400)."
  },
  {
   "name": "SFC loan book",
   "description": "2026-11-22 — lender-grade history on top of the SFC loans: loan terms, an append-only ledger, modifications, complaints, field sources, daily and month-end snapshots, metrics (delinquency, roll rates, first-payment default, vintages, CPR / CDR, recourse, concentration, limits), data tapes and the CSV import of portal exports. Same scopes, same X-Dry-Run, same PII refusal as SFC loans. Blank = not on file; nothing is estimated. Corrections are new rows that name the row they replace."
  },
  {
   "name": "Payroll"
  },
  {
   "name": "Sales"
  },
  {
   "name": "Sales setup",
   "description": "post-intake funnel for the Bizop Sales bot — see docs/BOT_API_SALES_SETUP.md"
  },
  {
   "name": "Page parity",
   "description": "2026-11-13 — everything a coach can click on the advertiser profile",
   "the needs-attention desk": null,
   "the coach calendar and the courtesy payouts board": null,
   "run in-process as \"Bot · <bot>\"; dry runs validate + answer would_* — see docs/BOT_API_PAGES.md": null
  },
  {
   "name": "Calling pipeline",
   "description": "Olivia → Chris calling pipeline (the intake caller is Olivia since 2026-11-08; internal agent id mike; Mike = the finance manager) — progress",
   "by-phone init webhook": null,
   "handoffs": null,
   "post-call": null,
   "dialer — see docs/BOT_API_CALLING_PIPELINE.md": null
  }
 ],
 "components": {
  "securitySchemes": {
   "bearer": {
    "type": "http",
    "scheme": "bearer",
    "description": "Authorization: Bearer bk_<bot>_<hex>"
   }
  },
  "parameters": {
   "dryRun": {
    "name": "X-Dry-Run",
    "in": "header",
    "required": false,
    "schema": {
     "type": "string",
     "enum": [
      "1"
     ]
    },
    "description": "Validate only — nothing is written or sent (write routes only). Runs the same checks and answers the same 4xx as the real call; never returns a real login link (DRY-RUN placeholders instead)."
   },
   "limit": {
    "name": "limit",
    "in": "query",
    "schema": {
     "type": "integer",
     "default": 100,
     "maximum": 500
    }
   },
   "offset": {
    "name": "offset",
    "in": "query",
    "schema": {
     "type": "integer",
     "default": 0
    }
   }
  },
  "schemas": {
   "Error": {
    "type": "object",
    "properties": {
     "status": {
      "type": "string",
      "enum": [
       "error"
      ]
     },
     "message": {
      "type": "string"
     }
    }
   },
   "OptOut": {
    "type": "object",
    "properties": {
     "opted_out": {
      "type": "boolean"
     },
     "reason": {
      "type": "string",
      "description": "STOP, press 9 / blocked caller, DNC via API, …"
     },
     "date": {
      "type": "string",
      "format": "date-time"
     }
    }
   },
   "OptOuts": {
    "type": "object",
    "properties": {
     "calls": {
      "$ref": "#/components/schemas/OptOut"
     },
     "sms": {
      "$ref": "#/components/schemas/OptOut"
     },
     "email": {
      "$ref": "#/components/schemas/OptOut"
     }
    }
   },
   "Client": {
    "type": "object",
    "properties": {
     "client_id": {
      "type": "integer"
     },
     "is_client": {
      "type": "boolean",
      "description": "bought the program (license on file or an approved front-end payment)"
     },
     "first_name": {
      "type": "string"
     },
     "last_name": {
      "type": "string"
     },
     "name": {
      "type": "string"
     },
     "business_name": {
      "type": "string"
     },
     "financed": {
      "type": "boolean",
      "description": "the Financed flag (ALL-1127-1) — the same mark as GET /api/clients/{id}/financed, the profile switch, the pay form tick and the lead reports"
     },
     "net_pct": {
      "type": "number",
      "nullable": true,
      "description": "share of the license received on a financed deal (0.45 = 45 %); null when not financed"
     },
     "phones": {
      "type": "array",
      "items": {
       "type": "object",
       "properties": {
        "phone": {
         "type": "string",
         "example": "+14255551212"
        },
        "label": {
         "type": "string",
         "enum": [
          "primary",
          "business",
          "lead",
          "alt"
         ]
        }
       }
      }
     },
     "emails": {
      "type": "array",
      "items": {
       "type": "object",
       "properties": {
        "email": {
         "type": "string"
        },
        "label": {
         "type": "string",
         "enum": [
          "primary",
          "company_alias"
         ]
        }
       }
      }
     },
     "timezone": {
      "type": "string",
      "example": "America/Los_Angeles"
     },
     "coach": {
      "type": "string",
      "example": "Franco",
      "description": "the client's assigned coach, first name as on People and roles (Franco | Sam | Jo | Jonathan | Michael)"
     },
     "client_stage": {
      "type": "string",
      "enum": [
       "Active",
       "Canceled",
       "Inactive (On Hold)"
      ],
      "description": "2026-11-21 — Inactive (On Hold) while on dispute hold"
     },
     "dispute_hold": {
      "type": "object",
      "description": "2026-11-21 — {on, hold_id, hold_reason, hold_since, released_at, released_by, disputes[{id, dispute_ref, status: open|won|cleared|lost, note, updated_at}], can_release, still_open[], message}"
     },
     "contact_block": {
      "type": "string",
      "enum": [
       "",
       "do_not_contact",
       "dispute_hold",
       "client_canceled"
      ],
      "description": "why automation will not contact or book this person ('' = nothing in the way)"
     },
     "booking_allowed": {
      "type": "boolean"
     },
     "program": {
      "type": "object",
      "properties": {
       "tier": {
        "type": "string",
        "example": "advertiser_pro_plus"
       },
       "label": {
        "type": "string",
        "example": "Advertiser Pro+"
       },
       "license_rate": {
        "type": "number"
       },
       "upgrade_amount": {
        "type": "number"
       }
      }
     },
     "status": {
      "type": "string",
      "enum": [
       "client_setup",
       "active",
       "cancelled",
       "refunded",
       "prospect"
      ]
     },
     "stage": {
      "type": "string",
      "description": "first unfinished Client Setup stage label (empty when not on the board)"
     },
     "setup_progress": {
      "type": "object",
      "properties": {
       "done": {
        "type": "integer"
       },
       "total": {
        "type": "integer"
       }
      }
     },
     "on_client_setup_board": {
      "type": "boolean"
     },
     "signup_date": {
      "type": "string",
      "format": "date-time"
     },
     "first_sale_date": {
      "type": "string",
      "format": "date-time",
      "nullable": true
     },
     "do_not_contact": {
      "type": "boolean"
     },
     "do_not_contact_reason": {
      "type": "string"
     },
     "opt_outs": {
      "$ref": "#/components/schemas/OptOuts"
     },
     "holds": {
      "type": "object",
      "properties": {
       "payouts_held": {
        "type": "boolean"
       },
       "payouts_held_reason": {
        "type": "string",
        "description": "courtesy_exclusions reason or 'account cancelled'"
       },
       "cancelled": {
        "type": "boolean"
       },
       "cancelled_at": {
        "type": "string",
        "format": "date-time",
        "nullable": true
       },
       "rescinded": {
        "type": "boolean",
        "description": "always false — rescission is not tracked as a field"
       }
      }
     },
     "upsold": {
      "type": "boolean"
     },
     "upsold_date": {
      "type": "string",
      "format": "date-time",
      "nullable": true
     },
     "next_booked_call": {
      "type": "object",
      "nullable": true,
      "properties": {
       "booking_id": {
        "type": "string",
        "example": "ncl-4821"
       },
       "next_call_id": {
        "type": "integer"
       },
       "start": {
        "type": "string",
        "format": "date-time"
       },
       "end": {
        "type": "string",
        "format": "date-time"
       },
       "coach": {
        "type": "string"
       },
       "type": {
        "type": "string",
        "example": "30 minutes"
       }
      }
     },
     "last_completed_call": {
      "type": "object",
      "nullable": true,
      "properties": {
       "date": {
        "type": "string",
        "format": "date-time"
       },
       "coach": {
        "type": "string"
       },
       "source": {
        "type": "string",
        "enum": [
         "coach_book",
         "recording"
        ]
       }
      }
     },
     "missed_call_count": {
      "type": "integer",
      "description": "inbound unanswered calls on the RingCentral account since the last completed call (90 days when none)"
     },
     "pipeline_stage": {
      "type": "string",
      "description": "users.rotation_schedule"
     },
     "latest_note": {
      "type": "object",
      "nullable": true,
      "properties": {
       "date": {
        "type": "string",
        "format": "date-time"
       },
       "summary": {
        "type": "string"
       },
       "by": {
        "type": "string"
       }
      }
     },
     "lead_id": {
      "type": "integer",
      "description": "linked sales-floor lead (0 = none)"
     }
    }
   },
   "Lead": {
    "type": "object",
    "properties": {
     "lead_id": {
      "type": "integer"
     },
     "first_name": {
      "type": "string"
     },
     "last_name": {
      "type": "string"
     },
     "name": {
      "type": "string"
     },
     "phone": {
      "type": "string"
     },
     "phones": {
      "type": "array",
      "items": {
       "type": "string"
      }
     },
     "email": {
      "type": "string"
     },
     "state": {
      "type": "string"
     },
     "timezone": {
      "type": "string"
     },
     "signup_date": {
      "type": "string",
      "format": "date-time"
     },
     "status": {
      "type": "string",
      "description": "current pipeline status (bizop.statuses)"
     },
     "location": {
      "type": "string",
      "enum": [
       "Sacramento",
       "Seattle"
      ]
     },
     "source": {
      "type": "string"
     },
     "assigned_to": {
      "type": "string"
     },
     "do_not_contact": {
      "type": "boolean"
     },
     "do_not_contact_reason": {
      "type": "string"
     },
     "opt_outs": {
      "$ref": "#/components/schemas/OptOuts"
     },
     "intake_completed": {
      "type": "boolean"
     },
     "intake_completed_at": {
      "type": "string",
      "format": "date-time",
      "nullable": true
     },
     "intake": {
      "type": "object",
      "description": "answers = the spec's named fields (marital/spouse, income, expenses, debts, credit range, cards, pain points, notes, availability); raw_answers = the full intake form blob"
     },
     "last_call": {
      "type": "object",
      "nullable": true,
      "properties": {
       "date": {
        "type": "string",
        "format": "date-time"
       },
       "outcome": {
        "type": "string"
       },
       "agent": {
        "type": "string"
       },
       "source": {
        "type": "string",
        "enum": [
         "ringcentral",
         "dialer",
         "crm_call_log",
         "ai_agent"
        ]
       }
      }
     },
     "callback_requested_time": {
      "type": "string",
      "format": "date-time",
      "nullable": true
     },
     "appointment_with_michael": {
      "type": "object",
      "nullable": true,
      "properties": {
       "booking_id": {
        "type": "string"
       },
       "start": {
        "type": "string",
        "format": "date-time"
       },
       "status": {
        "type": "string",
        "enum": [
         "booked",
         "kept",
         "missed",
         "cancelled",
         "booked_past_due"
        ]
       },
       "coach": {
        "type": "string"
       }
      }
     },
     "dq": {
      "type": "object",
      "properties": {
       "flag": {
        "type": "boolean"
       },
       "reason": {
        "type": "string"
       },
       "set_by": {
        "type": "string"
       },
       "set_at": {
        "type": "string",
        "nullable": true
       }
      }
     },
     "is_client": {
      "type": "boolean"
     },
     "client_id": {
      "type": "integer"
     },
     "latest_note": {
      "type": "object",
      "nullable": true
     },
     "progress": {
      "type": "object",
      "description": "calling-pipeline progress (2026-10-25): last_step_reached, next_call_at, next_call_agent, call_mode, call_attempts, callback_set_by … — same object as GET /api/leads/{id}/progress"
     }
    }
   },
   "SMSMessage": {
    "type": "object",
    "properties": {
     "id": {
      "type": "string"
     },
     "direction": {
      "type": "string",
      "enum": [
       "inbound",
       "outbound"
      ]
     },
     "body": {
      "type": "string"
     },
     "timestamp": {
      "type": "string",
      "format": "date-time"
     },
     "read": {
      "type": "boolean"
     },
     "from": {
      "type": "string"
     },
     "to": {
      "type": "string"
     }
    }
   },
   "Slot": {
    "type": "object",
    "properties": {
     "start": {
      "type": "string",
      "format": "date-time"
     },
     "end": {
      "type": "string",
      "format": "date-time"
     },
     "tz": {
      "type": "string",
      "example": "America/Los_Angeles"
     }
    }
   },
   "Booking": {
    "type": "object",
    "properties": {
     "booking_id": {
      "description": "integer for API bookings, 'ncl-<id>' for coach-book rows",
      "oneOf": [
       {
        "type": "integer"
       },
       {
        "type": "string"
       }
      ]
     },
     "kind": {
      "type": "string",
      "enum": [
       "client",
       "lead"
      ]
     },
     "client_id": {
      "type": "integer"
     },
     "lead_id": {
      "type": "integer"
     },
     "coach": {
      "type": "string"
     },
     "start": {
      "type": "string",
      "format": "date-time"
     },
     "end": {
      "type": "string",
      "format": "date-time"
     },
     "duration_minutes": {
      "type": "integer"
     },
     "source": {
      "type": "string"
     },
     "notes": {
      "type": "string"
     },
     "status": {
      "type": "string",
      "enum": [
       "booked",
       "cancelled",
       "rescheduled",
       "kept",
       "missed"
      ]
     },
     "next_call_id": {
      "type": "integer"
     },
     "calendar_event_id": {
      "type": "string"
     },
     "tz": {
      "type": "string",
      "example": "America/Los_Angeles"
     },
     "coach_book_status": {
      "type": "string",
      "description": "status of the underlying next_call_logs row (coach book), '' for pure API rows"
     },
     "reason": {
      "type": "string",
      "description": "lead_leaving when Chris booked before step 2 (round 2)"
     },
     "tag": {
      "type": "string",
      "description": "e.g. 'booked before step 2'"
     }
    }
   },
   "Payout": {
    "type": "object",
    "properties": {
     "payout_id": {
      "type": "integer"
     },
     "date": {
      "type": "string",
      "format": "date"
     },
     "client_id": {
      "type": "integer"
     },
     "client_name": {
      "type": "string"
     },
     "business_name": {
      "type": "string"
     },
     "coach": {
      "type": "string"
     },
     "amount": {
      "type": "number"
     },
     "state": {
      "type": "string",
      "enum": [
       "paid",
       "in_batch",
       "planned",
       "missed",
       "skipped",
       "expired",
       "removed",
       "failed"
      ]
     },
     "paid": {
      "type": "boolean"
     },
     "paid_how": {
      "type": "string",
      "enum": [
       "manual",
       "batch",
       ""
      ]
     },
     "paid_note": {
      "type": "string"
     },
     "paid_at": {
      "type": "string",
      "format": "date-time",
      "nullable": true
     },
     "batch_id": {
      "type": "integer",
      "nullable": true
     },
     "batch_status": {
      "type": "string",
      "description": "status of the Mercury batch the row sits in, '' when none"
     },
     "client_email": {
      "type": "string"
     },
     "planned_amount": {
      "type": "number",
      "description": "the amount the cycle plan drew for this date (amount may differ once marked paid)"
     },
     "cycle_start": {
      "type": "string",
      "format": "date",
      "description": "first day of the 30-day cycle this row belongs to"
     },
     "cycle_end": {
      "type": "string",
      "format": "date"
     },
     "payouts_held": {
      "type": "boolean"
     },
     "payouts_held_reason": {
      "type": "string"
     }
    }
   }
  }
 },
 "security": [
  {
   "bearer": []
  }
 ],
 "paths": {
  "/healthz": {
   "get": {
    "tags": [
     "Health"
    ],
    "security": [],
    "summary": "Open liveness probe — same body as /api/health (status, db, build_time, started_at, time); used by scripts/deploy.sh",
    "responses": {
     "200": {
      "description": "ok"
     },
     "503": {
      "description": "db unreachable"
     }
    }
   }
  },
  "/api/health": {
   "get": {
    "tags": [
     "Health"
    ],
    "security": [],
    "summary": "Liveness (no auth, <2 s)",
    "responses": {
     "200": {
      "description": "ok",
      "content": {
       "application/json": {
        "example": {
         "ok": true,
         "status": "ok",
         "db": "ok",
         "deps": {
          "ringcentral": "ok",
          "elevenlabs_key_ok": true,
          "elevenlabs_credits_ok": "no_permission",
          "stripe": "ok",
          "checked_at": "2026-11-12T14:00:00-08:00"
         },
         "build_time": "2026-11-12T13:40:11-08:00",
         "started_at": "2026-11-12T13:41:02-08:00",
         "time": "2026-11-12T14:00:00-08:00",
         "tz": "America/Los_Angeles"
        }
       }
      }
     },
     "503": {
      "description": "db error / timeout (status \"degraded\")"
     }
    }
   }
  },
  "/api/clients/lookup": {
   "get": {
    "tags": [
     "Clients"
    ],
    "summary": "Look a client up by phone, email, name or id   (scope clients:read)",
    "parameters": [
     {
      "name": "phone",
      "in": "query",
      "schema": {
       "type": "string"
      },
      "description": "any format; matched on the last 10 digits against every phone on file"
     },
     {
      "name": "email",
      "in": "query",
      "schema": {
       "type": "string"
      }
     },
     {
      "name": "name",
      "in": "query",
      "schema": {
       "type": "string"
      },
      "description": "substring match; when several match, `ambiguous:true` + `matches[]`"
     },
     {
      "name": "id",
      "in": "query",
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "always 200 — `is_client:false, client:null` when nobody matched (a matching sales-floor lead is returned as `lead`)",
      "content": {
       "application/json": {
        "schema": {
         "type": "object",
         "properties": {
          "status": {
           "type": "string"
          },
          "is_client": {
           "type": "boolean"
          },
          "client": {
           "$ref": "#/components/schemas/Client"
          },
          "matched_by": {
           "type": "string"
          },
          "lead": {
           "type": "object",
           "nullable": true
          }
         }
        }
       }
      }
     }
    }
   }
  },
  "/api/clients/lookup/batch": {
   "post": {
    "tags": [
     "Clients"
    ],
    "summary": "Batch lookup (≤100)   (scope clients:read)",
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "phones": {
          "type": "array",
          "items": {
           "type": "string"
          }
         },
         "emails": {
          "type": "array",
          "items": {
           "type": "string"
          }
         },
         "ids": {
          "type": "array",
          "items": {
           "type": "integer"
          }
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "results[] — one per query, in order: {query, type, is_client, client|null, lead?}"
     }
    }
   }
  },
  "/api/clients": {
   "get": {
    "tags": [
     "Clients"
    ],
    "summary": "List clients   (scope clients:read)",
    "description": "Universe = members with a license on file or on the Client Setup board.",
    "parameters": [
     {
      "name": "coach",
      "in": "query",
      "schema": {
       "type": "string",
       "example": "franco"
      }
     },
     {
      "name": "status",
      "in": "query",
      "schema": {
       "type": "string",
       "enum": [
        "client_setup",
        "active",
        "cancelled",
        "refunded",
        "prospect"
       ]
      }
     },
     {
      "name": "has_future_call",
      "in": "query",
      "schema": {
       "type": "boolean"
      }
     },
     {
      "name": "on_board",
      "in": "query",
      "schema": {
       "type": "boolean"
      }
     },
     {
      "$ref": "#/components/parameters/limit"
     },
     {
      "$ref": "#/components/parameters/offset"
     }
    ],
    "responses": {
     "200": {
      "description": "clients[] (same fields as lookup)"
     }
    }
   }
  },
  "/api/clients/{id}": {
   "get": {
    "tags": [
     "Clients"
    ],
    "summary": "One client by id   (scope clients:read)",
    "description": "2026-11-21: `do_not_contact` now reflects the PERSON (the client record and every lead row with the same e-mail / phone, incl. a lead in CRM status Do Not Call). New: `client_stage` (Active | Canceled | Inactive (On Hold)), `dispute_hold{…}`, `contact_block`, `booking_allowed`; `status` is `on_hold` while on dispute hold; `holds.dispute_hold`.",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{is_client, client}"
     },
     "404": {
      "description": "no such client"
     }
    }
   }
  },
  "/api/clients/{id}/notes": {
   "get": {
    "tags": [
     "Clients"
    ],
    "summary": "Profile notes, newest first   (scope clients:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/limit"
     }
    ],
    "responses": {
     "200": {
      "description": "notes[] {id, date, by, note, protected}"
     }
    }
   },
   "post": {
    "tags": [
     "Clients"
    ],
    "summary": "Add a profile note   (scope comms:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "note"
        ],
        "properties": {
         "note": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{note_id}"
     }
    }
   }
  },
  "/api/clients/{id}/messages": {
   "get": {
    "tags": [
     "Comms"
    ],
    "summary": "SMS or email thread with the client   (scope comms:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "channel",
      "in": "query",
      "schema": {
       "type": "string",
       "enum": [
        "sms",
        "email"
       ],
       "default": "sms"
      }
     },
     {
      "name": "since",
      "in": "query",
      "schema": {
       "type": "string",
       "format": "date-time"
      }
     },
     {
      "$ref": "#/components/parameters/limit"
     }
    ],
    "responses": {
     "200": {
      "description": "sms: messages[] (SMSMessage, newest first) + unread; email: messages[] {id, thread_id, mailbox, direction, from, to, subject, body(snippet), timestamp, read} across the Boundless mailboxes"
     }
    }
   },
   "post": {
    "tags": [
     "Comms"
    ],
    "summary": "Send the client a text or an email   (scope comms:write)",
    "description": "SMS goes out from the main RingCentral line (the same line the Comms tab uses) and lands in the thread.\nEmail goes out from michael@get-boundless-ai.com (\"Michael from Boundless AI\"). Attachments by inline base64 or by `document_id`\nfrom GET /documents. Refuses do-not-contact / opted-out people (403). Brand check: no internal program names.\n",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "channel",
         "body"
        ],
        "properties": {
         "channel": {
          "type": "string",
          "enum": [
           "sms",
           "email"
          ]
         },
         "body": {
          "type": "string"
         },
         "subject": {
          "type": "string",
          "description": "email only"
         },
         "attachments": {
          "type": "array",
          "items": {
           "type": "object",
           "properties": {
            "name": {
             "type": "string"
            },
            "content_base64": {
             "type": "string"
            },
            "mime": {
             "type": "string"
            },
            "document_id": {
             "type": "integer",
             "description": "a document_id from GET /api/clients/{id}/documents (regular section)"
            }
           }
          }
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{channel, to, from}"
     },
     "403": {
      "description": "do-not-contact / opted out"
     }
    }
   }
  },
  "/api/inbox/sms": {
   "get": {
    "tags": [
     "Comms"
    ],
    "summary": "Every client thread with unread inbound texts   (scope comms:read)",
    "parameters": [
     {
      "name": "unread",
      "in": "query",
      "schema": {
       "type": "boolean",
       "default": true
      }
     }
    ],
    "responses": {
     "200": {
      "description": "threads[] {client_id, name, coach, contact, unread, last_text, last_at, waiting_relays, messages[] (the unread ones)}"
     }
    }
   }
  },
  "/api/calls": {
   "get": {
    "tags": [
     "Comms"
    ],
    "summary": "RingCentral account call log   (scope calls:read)",
    "parameters": [
     {
      "name": "since",
      "in": "query",
      "schema": {
       "type": "string",
       "format": "date-time"
      },
      "description": "default 7 days ago"
     },
     {
      "name": "until",
      "in": "query",
      "schema": {
       "type": "string",
       "format": "date-time"
      }
     },
     {
      "name": "direction",
      "in": "query",
      "schema": {
       "type": "string",
       "enum": [
        "inbound",
        "outbound"
       ]
      }
     },
     {
      "name": "missed",
      "in": "query",
      "schema": {
       "type": "boolean"
      },
      "description": "inbound + never answered"
     },
     {
      "name": "client_id",
      "in": "query",
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "lead_id",
      "in": "query",
      "schema": {
       "type": "integer"
      },
      "description": "calls matched to a sales-floor lead"
     },
     {
      "$ref": "#/components/parameters/limit"
     },
     {
      "$ref": "#/components/parameters/offset"
     }
    ],
    "responses": {
     "200": {
      "description": "calls[] {id, client_id, client_name, lead_id?, number, our_number, direction, extension, started_at, answered_at, ended_at, duration_secs, outcome, missed, has_recording}"
     }
    }
   }
  },
  "/api/clients/{id}/documents": {
   "get": {
    "tags": [
     "Documents"
    ],
    "summary": "Documents (portal + Admin-Only + ZEN application slots) and contract compliance   (scope documents:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "documents[] {document_id, name, section: regular|admin_only|zen_application, type: articles|ein|agreement|bank_letter|drivers_license|bank_statement|other, status, signed, uploaded_at, uploaded_by?, docusign_envelope_id (null — not stored), docusign_status (null), download_url}; contract_compliance {transaction_authorization, service_fulfillment, exempt}"
     }
    }
   },
   "post": {
    "tags": [
     "Documents"
    ],
    "summary": "Upload a document (multipart)   (scope documents:write)",
    "description": "Fields `file`, `name` (e.g. \"Articles\"), `section` = regular (default, client-visible) | admin_only. PDFs are brand-redacted; articles/EIN/bank letters are auto-classified into the ZEN application like the profile upload.",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "multipart/form-data": {
       "schema": {
        "type": "object",
        "required": [
         "file"
        ],
        "properties": {
         "file": {
          "type": "string",
          "format": "binary"
         },
         "name": {
          "type": "string"
         },
         "section": {
          "type": "string",
          "enum": [
           "regular",
           "admin_only"
          ]
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{document_id, section, name, type, download_url}"
     }
    }
   }
  },
  "/api/clients/{id}/setup": {
   "get": {
    "tags": [
     "Setup"
    ],
    "summary": "Filing data — legal name, DOB, address, business name, LLC, EIN, registered agent, ZEN app, Mercury, bank   (scope setup:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{legal_name, dob, home_address{line1,line2,city,state,zip}, business_name, llc{status: filed|articles_on_file|not_filed, filed_at, articles_scan}, ein{issued, issued_at, ein_last4, scan}, registered_agent{updated, updated_at}, zen_application{status, application_email, sent_to, submitted_at, approved_at, processor_stage}, mercury_application{status, …}, bank{type: mercury|plaid|statements|none, institution, status: connected|error|not_connected, error, plaid_linked, mercury_key_vaulted, manual_payout_account{bank_name, account_last4, routing_last4, type}}}. No SSN here."
     }
    }
   }
  },
  "/api/clients/{id}/ssn": {
   "get": {
    "tags": [
     "Setup"
    ],
    "summary": "Full SSN + DOB — separate key scope, every read journaled   (scope ssn:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{ssn, dob, found}"
     }
    }
   }
  },
  "/api/clients/{id}/cards": {
   "get": {
    "tags": [
     "Cards"
    ],
    "summary": "Cards on file, financing applications, Card Power, balance transfer   (scope cards:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "cards_on_file[] {issuer, status, credit_limit, balance, monthly_payment, last4}; financing_applications[] {issuer, kind, status: pending|approved|declined, stage, credit_limit, date_applied}; card_power {state, score, cards[], frozen, pulled_at, top_picks{picks[], say, …}}; balance_transfer {state: none|confirmed, confirmed_at, amount: null}"
     }
    }
   }
  },
  "/api/clients/{id}/card-picks": {
   "get": {
    "tags": [
     "Cards"
    ],
    "summary": "Which card should they use — top picks 1–5 off the credit report by client id (same ranking as /api/leads/{id}/card-picks)   (scope clients:read | setup:read | cards:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "picks",
      "in": "query",
      "required": false,
      "schema": {
       "type": "integer",
       "minimum": 1,
       "maximum": 10,
       "default": 5
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{state, picks[], pick_count, eligible_cards, shortlist_cards, best_available, shortlist_floor, excluded, say, client_id, lead_id}"
     }
    }
   }
  },
  "/api/availability": {
   "get": {
    "tags": [
     "Booking"
    ],
    "summary": "Open slots for a coach   (scope bookings:read)",
    "description": "Mon–Fri 09:00–17:00 PT, 30-minute grid, ≥2 h notice, minus Google Calendar blocks and slots with 3 bookings. Josh uses tomorrow → +8 weeks; Chris uses Michael's next 48 h.\n**Chris agent + coach=michael (2026-10-21):** `duration_minutes` defaults to 60 and `to` to `from` + 48 h (explicit values always win).\nUnparseable `from` / `to` / `duration_minutes` → 400.\n",
    "parameters": [
     {
      "name": "coach",
      "in": "query",
      "required": true,
      "schema": {
       "type": "string",
       "description": "any ACTIVE coach, by first name: franco, sam, jo, jonathan, michael (mike = michael) — the same list for every key; GET /api/coaches-list returns it. joshua is retired (his clients moved to Franco) and is refused with code unknown_coach",
       "example": "franco"
      }
     },
     {
      "name": "from",
      "in": "query",
      "schema": {
       "type": "string",
       "format": "date-time"
      },
      "description": "default now"
     },
     {
      "name": "to",
      "in": "query",
      "schema": {
       "type": "string",
       "format": "date-time"
      },
      "description": "default from + 14 days (max 70); Chris + michael → from + 48 h"
     },
     {
      "name": "duration_minutes",
      "in": "query",
      "schema": {
       "type": "integer",
       "enum": [
        15,
        30,
        60,
        120
       ],
       "default": 30
      },
      "description": "Chris + michael → default 60"
     },
     {
      "name": "source",
      "in": "query",
      "schema": {
       "type": "string"
      },
      "description": "chris_agent applies the Chris defaults on any key"
     },
     {
      "name": "include_reserved",
      "in": "query",
      "schema": {
       "type": "boolean"
      },
      "description": "include the Phase-2 coach's reserved window"
     },
     {
      "name": "lead_id",
      "in": "query",
      "schema": {
       "type": "integer"
      },
      "description": "render day_label / local_time / say in this lead's timezone (2026-10-25). Agent callers (Chris's key / source *_agent) MUST send a real lead_id; 0 / empty / junk → lead_id_required, unknown → lead_not_found (200 refused for Chris, 400 otherwise; 2026-10-26)"
     },
     {
      "name": "tz",
      "in": "query",
      "schema": {
       "type": "string"
      },
      "description": "IANA zone for the local rendering (America/Chicago); wins over lead_id"
     },
     {
      "name": "caller_phone",
      "in": "query",
      "schema": {
       "type": "string"
      },
      "description": "resolve the lead by phone when lead_id is unknown (aliases: caller_id, phone); conversation_id resolves it from the live handoff"
     },
     {
      "name": "conversation_id",
      "in": "query",
      "schema": {
       "type": "string"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "slots[] {start, end (Pacific), day_label today|tomorrow|Thursday|'Tuesday Nov 3', weekday, date, local_time, local_start, local_end, local_tz, local_tz_abbr, say}, count, calendar_checked, lead_timezone"
     }
    }
   }
  },
  "/api/bookings": {
   "get": {
    "tags": [
     "Booking"
    ],
    "summary": "Bookings for a client / lead / coach   (scope bookings:read)",
    "parameters": [
     {
      "name": "client_id",
      "in": "query",
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "lead_id",
      "in": "query",
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "coach",
      "in": "query",
      "schema": {
       "type": "string"
      }
     },
     {
      "name": "from",
      "in": "query",
      "schema": {
       "type": "string",
       "format": "date-time"
      }
     },
     {
      "name": "to",
      "in": "query",
      "schema": {
       "type": "string",
       "format": "date-time"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "bookings[] (Booking)"
     }
    }
   },
   "post": {
    "tags": [
     "Booking"
    ],
    "summary": "Book a call   (scope bookings:write) — 2026-10-25: agent callers (Chris / source *_agent) MUST send lead_id > 0 (else lead_id_required, nothing saved) — round 8: with lead_id 0 the lead is first looked up by conversation_id / caller_id / phone; coach=michael also sets the pipeline next_call_at (next_call_agent mike | chris | none, callback_set_by) and the response carries `slot` with day_label / say in the lead's timezone",
    "description": "`source: josh_agent` books a coaching call on the coach's book + Google Calendar (client must have a portal account; nothing is emailed — the calendar invite is silent).\n`source: chris_agent` books a **lead-only** call for Michael: a Google Calendar event on Michael's calendar with no attendee (nothing goes to the lead) carrying the notes\n(income, expenses, pain points), plus a CRM appointment row; the lead flips to Appointment Set. 409 when the slot was just taken.\n**Director-review gate (Chris agent — its key or `source: chris_agent`, 2026-10-21, round 2):** denied review → `review_denied`\n(\"I'm not able to book that.\"); **no review → `review_required`** (\"Let me get you over to the next step first.\") unless the body\ncarries `reason: \"lead_leaving\"` — then it books, saves `reason`, tags the booking `\"booked before step 2\"` (CRM note, appointment\nnote, calendar title \"[Before step 2] …\") so Michael sees every one; pending / approved book normally. Do-not-contact →\n`do_not_contact`; calendar block / full slot → `slot_taken` + `alternatives[]` (next 3 open slots). **For the Chris agent every\nrefusal is HTTP 200 `{status: refused, allowed: false, code, say, message, http_status}`** (ElevenLabs tools drop non-2xx bodies);\nother callers keep 409 / 403. Chris + coach=michael without `duration_minutes` → 60. Dry run answers the same refusal / `would_book`.\n",
    "parameters": [
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "coach",
         "start"
        ],
        "properties": {
         "client_id": {
          "type": "integer"
         },
         "reason": {
          "type": "string",
          "description": "chris_agent only: \"lead_leaving\" lets a no-review booking through, tagged \"booked before step 2\""
         },
         "lead_id": {
          "type": "integer"
         },
         "phone": {
          "type": "string",
          "description": "alternative to client_id / lead_id"
         },
         "coach": {
          "type": "string",
          "description": "any ACTIVE coach, by first name: franco, sam, jo, jonathan, michael (mike = michael) — the same list for every key; GET /api/coaches-list returns it. joshua is retired (his clients moved to Franco) and is refused with code unknown_coach",
          "example": "franco"
         },
         "start": {
          "type": "string",
          "format": "date-time",
          "description": "15-minute boundary"
         },
         "duration_minutes": {
          "type": "integer",
          "enum": [
           15,
           30,
           60,
           120
          ],
          "default": 30
         },
         "source": {
          "type": "string",
          "enum": [
           "josh_agent",
           "chris_agent"
          ]
         },
         "notes": {
          "type": "string"
         },
         "kind": {
          "type": "string",
          "enum": [
           "client",
           "lead"
          ],
          "description": "override the default (lead for chris_agent / no portal account, else client)"
         },
         "include_reserved": {
          "type": "boolean"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{booking, booking_id}"
     },
     "400": {
      "description": "unknown_coach — coach is not an active coach (the message lists them)"
     },
     "409": {
      "description": "slot just taken / calendar conflict — or the PERSON may not be booked (2026-11-21), code: do_not_contact | dispute_hold | client_canceled. Checked for the client record and every lead row of the same person, for every key. Voice agents get HTTP 200 {status: refused, code, say}; for dispute_hold `say` is exactly \"Your account is on hold until your dispute is resolved.\""
     }
    }
   }
  },
  "/api/bookings/{id}": {
   "get": {
    "tags": [
     "Booking"
    ],
    "summary": "One booking (API id or ncl-<id>)   (scope bookings:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "string"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{booking}"
     }
    }
   }
  },
  "/api/bookings/{id}/cancel": {
   "post": {
    "tags": [
     "Booking"
    ],
    "summary": "Cancel   (scope bookings:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "string"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "reason": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{cancelled:true, was}"
     },
     "409": {
      "description": "already cancelled / kept"
     }
    }
   }
  },
  "/api/bookings/{id}/reschedule": {
   "post": {
    "tags": [
     "Booking"
    ],
    "summary": "Reschedule (validates the new slot first, then cancels + rebooks)   (scope bookings:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "string"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "new_start"
        ],
        "properties": {
         "new_start": {
          "type": "string",
          "format": "date-time"
         },
         "duration_minutes": {
          "type": "integer"
         },
         "notes": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{booking (new), booking_id (new), replaced}"
     },
     "409": {
      "description": "new slot taken"
     }
    }
   }
  },
  "/api/bookings/{id}/reassign": {
   "post": {
    "tags": [
     "Booking"
    ],
    "summary": "Move a booked client call to another coach at the same time   (scope bookings:write; PATCH is the same call)",
    "description": "The SAME booking with a new coach — nothing is cancelled and no second booking is made; the booking id stays.\nThe client's assigned coach is NOT changed. `{id}` = `ncl-<id>` or the numeric booking_id of a client booking.\nThe Google Calendar event is taken off the old coach's calendar and written to the new coach's (same title,\nguests and time; the calendar event id changes because each coach's calendar is their own).\nNobody is told by default. `notify: true` = Google Calendar e-mails the client its invitation for the moved\nevent — switched OFF on the server (client appointment messages are stopped); while off the call is still\nmoved and the answer says `notified: false` + `notify_note`.\nThe new coach must be free: a calendar event that is not a call, or a full slot (3 calls; Michael 1), answers\n409 `coach_busy`; the Phase 2 reserved window answers 409 `reserved_window` unless `include_reserved: true`.\nThe same coach again = 200 `{reassigned: false, unchanged: true}`. Every error carries `code`.\nWith `X-Dry-Run: 1` every check runs (including the new coach's calendar) and the answer is `would_reassign`.\n",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "string"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "required": true,
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "coach"
        ],
        "properties": {
         "coach": {
          "type": "string",
          "description": "first name of any active coach (mike = michael)"
         },
         "notify": {
          "type": "boolean",
          "default": false
         },
         "include_reserved": {
          "type": "boolean",
          "default": false
         },
         "reason": {
          "type": "string",
          "description": "free text for the appointment's audit log"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{booking_id, reassigned: true, from_coach, to_coach, client_id, client_assigned_coach, client_assigned_coach_changed: false, calendar: {moved, new_event_id, old_event_id, old_event_removed, note?}, notified, notify_note?, booking (after), was (before)} — dry run: {would_reassign: true, from_coach, to_coach, start, end, calendar: {would_move, old_event_id}, would_notify, booking}"
     },
     "400": {
      "description": "code: invalid_body (no coach) | unknown_coach (unknown or retired, e.g. joshua — the message lists the active coaches) | not_a_client_call (a lead booking)"
     },
     "404": {
      "description": "code: booking_not_found"
     },
     "409": {
      "description": "code: not_booked (cancelled / kept / missed / rescheduled) | call_in_past | coach_busy | reserved_window | booking_settling (booked seconds ago — retry_after) | booking_changed | do_not_contact | dispute_hold"
     },
     "502": {
      "description": "code: calendar_unavailable (the new coach's calendar could not be read) | calendar_failed (the event could not be written) — nothing changed"
     }
    }
   },
   "patch": {
    "tags": [
     "Booking"
    ],
    "summary": "Same as POST /api/bookings/{id}/reassign   (scope bookings:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "string"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "required": true,
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "coach"
        ],
        "properties": {
         "coach": {
          "type": "string"
         },
         "notify": {
          "type": "boolean",
          "default": false
         },
         "include_reserved": {
          "type": "boolean",
          "default": false
         },
         "reason": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "see POST"
     },
     "400": {
      "description": "see POST"
     },
     "404": {
      "description": "see POST"
     },
     "409": {
      "description": "see POST"
     },
     "502": {
      "description": "see POST"
     }
    }
   }
  },
  "/api/elevenlabs/call-init": {
   "post": {
    "tags": [
     "ElevenLabs"
    ],
    "security": [],
    "summary": "Start-of-call webhook for the Josh Coach inbound line",
    "description": "Auth: header `X-Intake-Agent-Key` = ELEVEN_CONVAI_INIT_KEY, **or** `ElevenLabs-Signature` HMAC (ELEVEN_CONVAI_POSTCALL_SECRET), **or** a Bearer bot key with bookings:read.\nReturns ElevenLabs `conversation_initiation_client_data` with string dynamic variables.\n",
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "caller_id": {
          "type": "string"
         },
         "agent_id": {
          "type": "string"
         },
         "called_number": {
          "type": "string"
         },
         "call_sid": {
          "type": "string"
         },
         "conversation_id": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "dynamic variables",
      "content": {
       "application/json": {
        "example": {
         "type": "conversation_initiation_client_data",
         "dynamic_variables": {
          "first_name": "Maria",
          "last_name": "Lopez",
          "coach_name": "Franco",
          "program": "Advertiser Pro+",
          "is_client": "true",
          "client_id": "1234",
          "status": "client_setup",
          "business_name": "Lopez Ventures LLC",
          "next_booked_call": "Thursday October 23 at 10:00 AM PT with Franco",
          "coach_open_times": "Wed Oct 22 9:00 AM, Wed Oct 22 9:30 AM, Wed Oct 22 10:00 AM, Wed Oct 22 10:30 AM (Pacific)",
          "phone_digits": "4255551212"
         }
        }
       }
      }
     }
    }
   }
  },
  "/api/payouts": {
   "get": {
    "tags": [
     "Payouts"
    ],
    "summary": "Courtesy payout rows (the /hcs/payments grid)   (scope payouts:read)",
    "parameters": [
     {
      "name": "from",
      "in": "query",
      "schema": {
       "type": "string",
       "format": "date"
      },
      "description": "default today − 7"
     },
     {
      "name": "to",
      "in": "query",
      "schema": {
       "type": "string",
       "format": "date"
      },
      "description": "default today + 30"
     },
     {
      "name": "paid",
      "in": "query",
      "schema": {
       "type": "boolean"
      }
     },
     {
      "name": "state",
      "in": "query",
      "schema": {
       "type": "string",
       "enum": [
        "paid",
        "in_batch",
        "planned",
        "missed",
        "skipped",
        "expired",
        "removed",
        "failed"
       ]
      },
      "description": "`status` is accepted as an alias"
     },
     {
      "name": "client_id",
      "in": "query",
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "payouts[] (Payout — each row also carries client_email, planned_amount, cycle_start, cycle_end, batch_status, paid_at), count, from, to, total_amount, paid_amount, states{}"
     }
    }
   }
  },
  "/api/payouts/{id}": {
   "get": {
    "tags": [
     "Payouts"
    ],
    "summary": "One payout row   (scope payouts:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{payout}"
     }
    }
   }
  },
  "/api/payouts/{id}/mark-paid": {
   "post": {
    "tags": [
     "Payouts"
    ],
    "summary": "Mark a payout paid — idempotent, refuses held people   (scope payouts:write)",
    "description": "Already paid → 200 `{already_paid:true, changed:false, paid_note}` and nothing changes. Payouts held (removed / cancelled) → 409. A row sitting in a draft batch is pulled out of the batch first, exactly like the grid click.",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "note": {
          "type": "string",
          "example": "RelayFi 10/20"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{payout, changed, paid_note, pulled_from_batch}"
     },
     "409": {
      "description": "held / not payable"
     }
    }
   }
  },
  "/api/clients/{id}/payout-settings": {
   "get": {
    "tags": [
     "Payouts"
    ],
    "summary": "Courtesy rate, reinvestment share, upsold, holds, payout account, Plaid / Mercury status   (scope payouts:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{courtesy_payout_rate_pct, courtesy_rate_is_override, reinvestment_share_pct, payout_basis, upsold, upsold_date, payouts_held, payouts_held_reason, business_name, manual_payout_account{bank_name, account_last4, routing_last4, type}, plaid{linked, status, error}, mercury{key_vaulted, status, error}, bank_source}"
     }
    }
   }
  },
  "/api/payroll": {
   "get": {
    "tags": [
     "Payroll"
    ],
    "summary": "Finalized payroll week → per-person totals   (scope payroll:read)",
    "parameters": [
     {
      "name": "week",
      "in": "query",
      "schema": {
       "type": "string",
       "format": "date"
      },
      "description": "any day of the week (normalized to Monday",
      "Pacific); default = last completed week": null
     },
     {
      "name": "offset",
      "in": "query",
      "schema": {
       "type": "integer"
      },
      "description": "weeks relative to this week (−1 = last week)"
     }
    ],
    "responses": {
     "200": {
      "description": "{week_start, week_end, pay_date, finalized, finalized_at, finalized_by, people[] {key, name, role: floor|coach, email, amount, computed, override_amount, note, paid, paid_at, paid_by, paid_note}, total, count}. Not finalized → people:[] + message"
     }
    }
   }
  },
  "/api/buyers": {
   "get": {
    "tags": [
     "Sales"
    ],
    "summary": "Funnel buyers ($67 store/VSL, $97 protection)   (scope sales:read)",
    "parameters": [
     {
      "name": "since",
      "in": "query",
      "schema": {
       "type": "string",
       "format": "date-time"
      },
      "description": "default 30 days"
     },
     {
      "$ref": "#/components/parameters/limit"
     }
    ],
    "responses": {
     "200": {
      "description": "buyers[] {lead_id, client_id, name, phone, email, state, timezone, purchase_time, product, amount, stripe_payment_id, refunded, lead_status}"
     }
    }
   }
  },
  "/api/leads/lookup": {
   "get": {
    "tags": [
     "Sales"
    ],
    "summary": "Lead profile by phone / email / id   (scope sales:read)",
    "parameters": [
     {
      "name": "phone",
      "in": "query",
      "schema": {
       "type": "string"
      }
     },
     {
      "name": "email",
      "in": "query",
      "schema": {
       "type": "string"
      }
     },
     {
      "name": "id",
      "in": "query",
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{found, is_client, lead (Lead)|null}"
     }
    }
   }
  },
  "/api/leads": {
   "get": {
    "tags": [
     "Sales"
    ],
    "summary": "Lead lists / callback queues   (scope sales:read)",
    "parameters": [
     {
      "name": "status",
      "in": "query",
      "schema": {
       "type": "string"
      },
      "description": "CRM status or spec name (New, Callback Requested, Declined, Refund Requested, Do Not Call, AI Intake Transferred, Appointment Booked, DQ)"
     },
     {
      "name": "callback_due_before",
      "in": "query",
      "schema": {
       "type": "string",
       "format": "date-time"
      }
     },
     {
      "name": "location",
      "in": "query",
      "schema": {
       "type": "string",
       "enum": [
        "Sacramento",
        "Seattle"
       ]
      }
     },
     {
      "name": "since",
      "in": "query",
      "schema": {
       "type": "string",
       "format": "date-time"
      }
     },
     {
      "$ref": "#/components/parameters/limit"
     },
     {
      "$ref": "#/components/parameters/offset"
     }
    ],
    "responses": {
     "200": {
      "description": "leads[] (Lead)"
     }
    }
   }
  },
  "/api/leads/{id}": {
   "get": {
    "tags": [
     "Sales"
    ],
    "summary": "One lead   (scope sales:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{lead}"
     }
    }
   }
  },
  "/api/leads/{id}/calls": {
   "get": {
    "tags": [
     "Sales"
    ],
    "summary": "Every call for the lead (RingCentral, dialer, AI agents), newest first   (scope sales:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/limit"
     }
    ],
    "responses": {
     "200": {
      "description": "calls[]"
     }
    }
   }
  },
  "/api/leads/{id}/call-result": {
   "post": {
    "tags": [
     "Sales"
    ],
    "summary": "Record a call and move the pipeline status   (scope sales:write or sales:calls)",
    "description": "Writes the call to the lead's history (CRM note + call record) and sets the status through the same path as the CRM dropdown.\nAllowed `status`: New, Voicemail/No Answer (history only — no status change), Callback Requested, Declined, Refund Requested,\nDo Not Call (also flags do-not-contact), AI Intake Transferred, Appointment Booked, DQ.\n**Locked leads:** a lead whose current status is DQ (DNQ…), Sold, or Do Not Call never changes status through this route — the call is still\nrecorded as history and the reply carries `status_locked: dq|sold|do_not_call` with `status_changed:false`. (A Do Not Call lead may still be moved to DQ.)\n**Round 8 (2026-10-26 evening):** `status: Callback Requested` with no `callback_time`, or one that cannot be read / is already past, is never dropped — the server schedules the next calling-hours slot ≥ 60 min out (`callback_no_time: true`, `callback_no_time_why`, `auto_scheduled`, `task_id` for the follow-up task, `say`). `callback_set_by` (= `agent`) is returned with every schedule.\n",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "status"
        ],
        "properties": {
         "called_at": {
          "type": "string",
          "format": "date-time"
         },
         "agent": {
          "type": "string",
          "enum": [
           "mike",
           "chris"
          ]
         },
         "conversation_id": {
          "type": "string"
         },
         "status": {
          "type": "string"
         },
         "outcome": {
          "type": "string"
         },
         "motivation_score": {
          "type": "integer",
          "minimum": 0,
          "maximum": 10
         },
         "verdict": {
          "type": "string"
         },
         "notes": {
          "type": "string"
         },
         "callback_time": {
          "type": "string",
          "format": "date-time"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{call_id, status_before, status, status_changed, history_only, status_locked ('' | dq | sold | do_not_call), message, callback_time}"
     }
    }
   }
  },
  "/api/leads/{id}/do-not-contact": {
   "post": {
    "tags": [
     "Sales"
    ],
    "summary": "Flag do-not-contact (every caller + texter refuses from now on) — or clear it with do_not_contact:false   (scope sales:write, sales:calls or contact:write)",
    "description": "**2026-11-21:** body `{do_not_contact: false, reason}` CLEARS the flag (reason required): the API flag and the suppression rows the API wrote come\noff the lead AND the client record of the same person; a lead in status Do Not Call goes back to the status it had before. A STOP the person texted stays.\nWrites the flag, STOP-suppresses every phone, blocks inbound routing, stops the Callback Bot, notes the lead and flags the linked client account.\nStatus becomes **Do Not Call** unless the lead holds a stronger locked disposition: a DQ'd lead stays DQ (moving it would clear the DNQ block list)\nand a sold client stays Sold — the reply says which in `status_note` / `status_changed`. The flag and suppression apply either way.\n",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "reason": {
          "type": "string",
          "example": "STOP text"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{do_not_contact:true, reason, phones_suppressed, status, status_changed, status_note, opt_outs}"
     }
    }
   }
  },
  "/api/leads/{id}/sms": {
   "get": {
    "tags": [
     "Sales"
    ],
    "summary": "Lead SMS thread   (scope sales:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "since",
      "in": "query",
      "schema": {
       "type": "string",
       "format": "date-time"
      }
     },
     {
      "$ref": "#/components/parameters/limit"
     }
    ],
    "responses": {
     "200": {
      "description": "messages[] (SMSMessage), unread"
     }
    }
   },
   "post": {
    "tags": [
     "Sales"
    ],
    "summary": "Text the lead from the main RingCentral line — the shared sender (sms-send.go), same checks as POST /api/sms/send   (scope sales:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "body"
        ],
        "properties": {
         "body": {
          "type": "string"
         },
         "source": {
          "type": "string",
          "description": "chris_agent | sarah_agent | marketing | crm … (agents get 200-shaped refusals)"
         },
         "purpose": {
          "type": "string",
          "description": "portal_link | checkout_link | message | other"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{sms: sent, provider: ringcentral, provider_message_id, to, from} · dry run {would_send, provider, from} · agent refusal {status: refused, code, say}"
     },
     "403": {
      "description": "do-not-contact / STOP / quiet hours (non-agent callers: {code, say, message})"
     },
     "502": {
      "description": "RingCentral error {code: sms_failed, say}"
     }
    }
   }
  },
  "/api/inbox/leads-sms": {
   "get": {
    "tags": [
     "Sales"
    ],
    "summary": "Every lead thread with unread replies   (scope sales:read)",
    "parameters": [
     {
      "name": "unread",
      "in": "query",
      "schema": {
       "type": "boolean",
       "default": true
      }
     }
    ],
    "responses": {
     "200": {
      "description": "threads[] {lead_id, name, lead_status, location, contact, unread, last_text, last_at, messages[]}"
     }
    }
   }
  },
  "/api/leads/{id}/homework": {
   "get": {
    "tags": [
     "Sales setup"
    ],
    "summary": "Step-1 homework assignments, prompts, saved answers, funnel stage, portal link   (scope sales:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, funnel_stage, assignments[{id,title,kind,questions[{type,prompt}],done,answers[],completed_at}], done, total, homework_link, preset_stage, funnel}"
     },
     "409": {
      "description": "no portal account yet"
     }
    }
   }
  },
  "/api/leads/{id}/homework/answers": {
   "post": {
    "tags": [
     "Sales setup"
    ],
    "summary": "Save answers for the client — exactly one answer per question, tf = Yes/No, else 400   (scope sales:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "assignment_id",
         "answers"
        ],
        "properties": {
         "assignment_id": {
          "type": "integer"
         },
         "answers": {
          "type": "array",
          "items": {
           "type": "string"
          },
          "description": "one per question, in order; tf = Yes/No"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{done, total, all_done, funnel_stage}"
     }
    }
   }
  },
  "/api/leads/{id}/credit": {
   "get": {
    "tags": [
     "Sales setup"
    ],
    "summary": "Card Power (filtered, available per card, open-to-spend), credit score, installment loans, cards on file — any CRM lead, + lead_status / intake_completed / status_lock   (scope sales:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{credit_score, card_power{state, cards[], open_to_spend, bank_limit, bank_cards, retail_cards_excluded, authorized_user_cards_excluded, frozen, pulled_at, top_picks{picks[], say, …}}, installment_loans{state, loans[]}, cards_on_file[]}"
     }
    }
   }
  },
  "/api/leads/{id}/card-picks": {
   "get": {
    "tags": [
     "Sales setup"
    ],
    "summary": "Which card should they use — top picks 1–5 off the credit report (bank cards with credit open → shortlist within 50% of the most available → unused / no balance first, then lowest utilization, then most available) — any CRM lead   (scope sales:read | sales:calls | sales:review)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "picks",
      "in": "query",
      "required": false,
      "schema": {
       "type": "integer",
       "minimum": 1,
       "maximum": 10,
       "default": 5
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{state: none|failed|analyzing|ready, picks[{rank, name, issuer, last4, credit_limit, balance, available, utilization_pct, usage: unused|light|moderate|heavy, shortlist, opened_year, why}], pick_count, eligible_cards, shortlist_cards, best_available, shortlist_floor, shortlist_band_pct, excluded{retail, authorized_user, maxed_out}, say, score, frozen, pulled_at, lead_status, intake_completed}"
     }
    }
   }
  },
  "/api/leads/{id}/financing-video": {
   "get": {
    "tags": [
     "Sales setup"
    ],
    "summary": "Step-2 financing video (mp4 url to play as audio) + gate state   (scope sales:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{video_url, preview_url, title, released, released_at, funnel_stage, watch{status, playing_now, …} (live watch state, see …/financing-video/status)}"
     }
    }
   }
  },
  "/api/leads/{id}/financing-video/release": {
   "post": {
    "tags": [
     "Sales setup"
    ],
    "summary": "Release the step-2 video gate (idempotent)   (scope sales:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "responses": {
     "200": {
      "description": "{released:true, released_at, changed}"
     }
    }
   }
  },
  "/api/leads/{id}/financing-video/status": {
   "get": {
    "tags": [
     "Sales setup"
    ],
    "summary": "Live watch state of the step-2 video on the Capital Leverage page — did it start, is it playing right now, did they click   (scope sales:read, sales:calls or sales:review)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{status: not_opened|opened_not_started|clicked_not_started|playing|paused|stopped|ended (the WATCH STATE — envelope is ok:true + result:success since 2026-10-25; also watch_status), video_duration_sec, video_duration (real length via ffprobe, before the first play), summary, on_page_now, playing_now, clicked_play, clicked_play_at, click_count, started, started_at, play_count, position, position_sec, duration, duration_sec, percent, watched_sec, watched_percent, paused_at, ended_at, completed, completed_at, gate_open, gate_opened_by (client_watched|staff_release), last_event, last_event_at, where (gate|modal), recent_events[]}"
     },
     "409": {
      "description": "no portal account yet {code: no_portal_account, say}"
     }
    }
   }
  },
  "/api/clients/{id}/financing-video/status": {
   "get": {
    "tags": [
     "Clients"
    ],
    "summary": "Same live watch state by portal client id   (scope clients:read or setup:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "see /api/leads/{id}/financing-video/status"
     },
     "404": {
      "description": "no such client"
     }
    }
   }
  },
  "/api/leads/{id}/capital": {
   "get": {
    "tags": [
     "Sales setup"
    ],
    "summary": "Capital page: did they set aside a card and verify it yet   (scope sales:read, sales:calls or sales:review)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{status: not_started|cards_added|partly_verified|verified (the STAGE — the envelope is ok:true + result:success since 2026-10-25; also stage, capital_status), summary, cards_added, cards_verified, all_verified, total_leverage, score (0–100), band, band_index, leverage_score{score, max, band, band_index, next_band{label, min, needed}, bands[], breakdown{capital, variety, spread}, how}, cards[{id, name, last4, source, leverage_amount, report_limit, report_balance, verified, verified_at, added_at, credit_card_id}], last_added_at, last_verified_at, card_power{state, bank_cards, total_limit, open_to_spend, total_usable, cushion, pulled_at}, video_gate_open, on_page_now, page_seen_at, funnel_stage}"
     },
     "409": {
      "description": "no portal account yet {code: no_portal_account, say}"
     }
    }
   }
  },
  "/api/clients/{id}/capital": {
   "get": {
    "tags": [
     "Clients"
    ],
    "summary": "Same Capital-page state by portal client id   (scope clients:read or setup:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "see /api/leads/{id}/capital"
     },
     "404": {
      "description": "no such client"
     }
    }
   }
  },
  "/api/leads/{id}/portal-link": {
   "post": {
    "tags": [
     "Sales setup"
    ],
    "summary": "Text / email / both the portal (homework) link — the CRM SMS / Email / SMS+Email buttons; dry run returns a placeholder link   (scope sales:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "channel": {
          "type": "string",
          "enum": [
           "sms",
           "email",
           "both"
          ],
          "default": "both"
         },
         "link_type": {
          "type": "string",
          "enum": [
           "homework",
           "testimonial"
          ]
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{sms, email (sent|failed|no_phone|opted_out|no_email), link, to_phone, to_email}"
     },
     "403": {
      "description": "do-not-contact"
     }
    }
   }
  },
  "/api/leads/{id}/card-link": {
   "get": {
    "tags": [
     "Sales setup"
    ],
    "summary": "Active secure card-entry link + cards on file   (scope sales:read or sales:cardlink)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{link_active, link, expires_at, cards_added_via_link, cards_on_file[{id, issuer, brand, last4, added_at}]} — for the Chris agent `link` is null + `link_hidden` (the link is never handed to the voice agent)"
     }
    }
   },
   "post": {
    "description": "The client enters issuer, name, number, expiry, CVC on a no-login encrypted form; the card lands on the Banking tab with limit/balance 0 for the coach to fill in later.\n**Director-review gate (Chris agent — its key or `source: chris_agent`, 2026-10-21):** ALLOWED when the latest review is `approved`\nOR the lead has an active (future, not cancelled) booking with Michael made by chris_agent; `denied` → `409 {code: review_denied,\nsay: \"I'm not able to send that today.\"}` (even with a booking); none / pending without a booking → `409 {code: review_not_approved,\nsay: \"Let's get your time with Mike locked in first, then I'll text you the secure link.\"}`. Channel is forced to `sms` and the\nresponse carries `link: null` + `link_hidden` — the link is texted, never read aloud. Dry run answers the same refusal / `would_send`.\nHuman / admin keys are not gated.\n",
    "tags": [
     "Sales setup"
    ],
    "summary": "Mint + send the secure card-entry link (/cards/<token>, 30 days)   (scope sales:write or sales:cardlink)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "channel": {
          "type": "string",
          "enum": [
           "sms",
           "email",
           "both",
           "none"
          ],
          "default": "sms"
         },
         "source": {
          "type": "string",
          "description": "chris_agent applies the director-review gate even on a broad key"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{link, expires_at, channel, sms, email, to_phone, to_email} — or, for the Chris agent, a refusal {status: refused, allowed: false, code: review_not_approved | review_denied | no_portal_account | do_not_contact, say, message, http_status} (round 2: Chris refusals are HTTP 200)"
     },
     "403": {
      "description": "do-not-contact {code: do_not_contact, say} (non-Chris callers)"
     },
     "409": {
      "description": "no portal account yet {code: no_portal_account, say} · review gate {status: error, code: review_not_approved | review_denied, say, message} (non-Chris callers)"
     }
    }
   }
  },
  "/api/leads/{id}/transfer-check": {
   "get": {
    "tags": [
     "Sales setup"
    ],
    "summary": "May the Chris agent transfer this caller to the finance manager (Michael)? Since 2026-11-13 the handoff point is the finance video — allowed once the lead's Capital Leverage page / video beacon has fired (video_status ≠ not_opened) or ?video_confirmed=1; no review, no verified card; DQ'd / Sold / Do Not Call / do-not-contact still refuse (code video_not_visible otherwise); answers handoff_mode, video_status, video_visible, transfer_to and stamps handoff_stage pre_video when allowed. CHRIS_HANDOFF_PRE_VIDEO=0 restores the old gate   (scope sales:review or sales:read)",
    "description": "`allowed` = latest review decision is `approved` and the lead is not DQ'd / Sold / Do Not Call / do-not-contact.\n`say` is the line to speak when not allowed (\"My finance manager's tied up right now, so let's get you on his calendar.\"). Every check is logged\n(`bot_review_gate_log`); the newest real check also identifies the lead for the server-gated dial when no caller ID matches.\n",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{status: success, allowed: true, decision, lead_status, michael_booking_id?, michael_booking_start?} — or {status: refused, allowed: false, code: review_none | review_pending | review_denied | dq | dnc | sold, reason, say, decision, lead_status} (always HTTP 200)"
     },
     "404": {
      "description": "no such lead"
     }
    }
   }
  },
  "/api/handoffs/stages": {
   "get": {
    "tags": [
     "Sales setup"
    ],
    "summary": "Handoffs to Michael for the daily report — pre_video_ready → pre_video (transferred) → pre_video_connected | pre_video_no_answer | pre_video_booked, Pacific days (default today)   (scope sales:read | sales:review)",
    "parameters": [
     {
      "name": "from",
      "in": "query",
      "schema": {
       "type": "string",
       "format": "date"
      }
     },
     {
      "name": "to",
      "in": "query",
      "schema": {
       "type": "string",
       "format": "date"
      }
     },
     {
      "name": "stage",
      "in": "query",
      "schema": {
       "type": "string"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{from, to, handoffs[{lead_id, name, lead_status, handoff_stage, at, how, last_step_reached}], count, counts_by_stage{}, transferred_to_michael, mode}"
     }
    }
   }
  },
  "/api/voice/director-transfer": {
   "post": {
    "tags": [
     "Sales setup"
    ],
    "security": [],
    "summary": "Twilio voice webhook — server-gated dial to the director (the ElevenLabs transfer tool dials the dedicated DIRECTOR_TRANSFER_DID, not Michael's cell)",
    "description": "Signature-checked (X-Twilio-Signature). Lead = `lead_id` param / SIP header `X-Lead-Id` / caller ID / the newest real transfer-check in the last\n5 minutes. Allowed → TwiML `<Dial>` to Michael (answerOnBridge, 25 s, action `/api/voice/director-transfer/after`); otherwise `<Say>` \"My finance\nmanager's not available right now. We'll get you booked.\" + hangup (`DIRECTOR_TRANSFER_DENY_MODE=reject` answers `<Reject>` instead). No answer → the same line.\n",
    "responses": {
     "200": {
      "description": "TwiML"
     },
     "403": {
      "description": "bad signature"
     }
    }
   }
  },
  "/api/leads/{id}/contact": {
   "post": {
    "tags": [
     "Sales setup"
    ],
    "summary": "Change the primary phone / email on the lead + portal account   (scope sales:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "phone": {
          "type": "string"
         },
         "email": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{phone, email, changes[]} — the old phone is kept as an alt phone"
     },
     "409": {
      "description": "phone/email belongs to someone else"
     }
    }
   }
  },
  "/api/leads/{id}/alt-phones": {
   "get": {
    "tags": [
     "Sales setup"
    ],
    "summary": "Round 12 — the lead's primary phone + alt phones   (scope sales:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{lead_id, name, primary, alt_phones[] {id, phone, digits, label, added_at}}"
     }
    }
   }
  },
  "/api/leads/{id}/alt-phones/{phone}": {
   "delete": {
    "tags": [
     "Sales setup"
    ],
    "summary": "Round 12 — remove an alt phone from the lead (calls / texts from it stop matching)   (scope sales:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "phone",
      "in": "path",
      "required": true,
      "schema": {
       "type": "string"
      },
      "description": "10-digit US number, any format"
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "responses": {
     "200": {
      "description": "{removed, label, primary, alt_phones[]} · dry run {would_remove}"
     },
     "400": {
      "description": "bad_phone | is_primary (change the primary with POST /contact first)"
     },
     "404": {
      "description": "alt_phone_not_found"
     }
    }
   }
  },
  "/api/leads/{id}/status-history": {
   "get": {
    "tags": [
     "Sales setup"
    ],
    "summary": "Round 14 — the lead's status history, newest first   (scope sales:read | sales:calls | sales:review)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "limit",
      "in": "query",
      "schema": {
       "type": "integer",
       "default": 50,
       "maximum": 200
      }
     },
     {
      "name": "cursor",
      "in": "query",
      "schema": {
       "type": "integer"
      },
      "description": "next_cursor from the previous page"
     },
     {
      "name": "since",
      "in": "query",
      "schema": {
       "type": "string"
      },
      "description": "ISO-8601"
     }
    ],
    "responses": {
     "200": {
      "description": "{lead_id, name, status, history[] {id, from, to, changed_by, changed_at, changed_local}, count, next_cursor}"
     },
     "404": {
      "description": "no such lead"
     }
    }
   }
  },
  "/api/leads/{id}/notes": {
   "get": {
    "tags": [
     "Sales setup"
    ],
    "summary": "Round 14 — the lead's CRM notes, newest first, card / routing numbers masked   (scope sales:read | sales:calls | sales:review)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "limit",
      "in": "query",
      "schema": {
       "type": "integer",
       "default": 50,
       "maximum": 200
      }
     },
     {
      "name": "cursor",
      "in": "query",
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "since",
      "in": "query",
      "schema": {
       "type": "string"
      },
      "description": "ISO-8601"
     },
     {
      "name": "type",
      "in": "query",
      "schema": {
       "type": "string"
      },
      "description": "note_type filter (human, …)"
     }
    ],
    "responses": {
     "200": {
      "description": "{lead_id, name, status, notes[] {id, note, by, at, at_local, direction, type, protected, call_recording_id?}, count, next_cursor}"
     },
     "404": {
      "description": "no such lead"
     }
    }
   }
  },
  "/api/leads/{id}/alt-phones/remove": {
   "post": {
    "tags": [
     "Sales setup"
    ],
    "summary": "Round 12 — same as DELETE …/alt-phones/{phone} for callers that cannot send DELETE   (scope sales:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "phone"
        ],
        "properties": {
         "phone": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{removed, label, primary, alt_phones[]}"
     },
     "404": {
      "description": "alt_phone_not_found"
     }
    }
   }
  },
  "/cards/{token}": {
   "get": {
    "tags": [
     "Sales setup"
    ],
    "security": [],
    "summary": "Public secure card-entry page (token from POST /api/leads/{id}/card-link)",
    "parameters": [
     {
      "name": "token",
      "in": "path",
      "required": true,
      "schema": {
       "type": "string"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "HTML form"
     },
     "404": {
      "description": "expired"
     }
    }
   }
  },
  "/api/card-collect/submit": {
   "post": {
    "tags": [
     "Sales setup"
    ],
    "security": [],
    "summary": "Public — the page posts the card here (token-authenticated)",
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "token",
         "card_holder_name",
         "card_number",
         "expiry",
         "cvc"
        ],
        "properties": {
         "token": {
          "type": "string"
         },
         "card_holder_name": {
          "type": "string"
         },
         "card_number": {
          "type": "string"
         },
         "expiry": {
          "type": "string",
          "example": "04/29"
         },
         "cvc": {
          "type": "string"
         },
         "issuer": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{card_id, last4, brand, issuer, cards_on_file[]}"
     },
     "400": {
      "description": "validation"
     },
     "404": {
      "description": "expired link"
     }
    }
   }
  },
  "/api/leads/{id}/review": {
   "get": {
    "tags": [
     "Sales setup"
    ],
    "summary": "Latest review + decision (none | pending | approved | denied)   (scope sales:read or sales:review)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{under_review, decision, review{review_id, status, reason, previous_status, requested_by, requested_at, decided_by, decision_note, decided_at, lead_status}}"
     }
    }
   },
   "post": {
    "tags": [
     "Sales setup"
    ],
    "summary": "Flag the lead for review — status Under Review, Approve / Deny on the CRM lead profile; texts Michael once per review; DQ'd / Sold / Do Not Call → 409 (Chris agent → 200 refused {code: dq|sold|dnc, say}); dry run too   (scope sales:write or sales:review)",
    "description": "A new pending review texts Michael's cell (`REVIEW_ALERT_TO`, default +14255633624) once — \"Under review: <name>, <phone>. Notes: <CRM link>. Approve to get them\ntransferred.\" — deduped by `lead_reviews.notified_at`. The CRM link opens the lead. `REVIEW_ALERT_ENABLED=0` turns the text off. The agent then polls\n`GET /api/leads/{id}/review` (reads the row directly; the Approve click is visible immediately) and calls transfer-check.\n",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "reason": {
          "type": "string"
         },
         "source": {
          "type": "string",
          "description": "chris_agent → refusals answer 200 {status: refused}"
         },
         "call_sid": {
          "type": "string",
          "description": "Twilio CallSid of the LIVE call ({{system__call_sid}}) → the caller is moved into hold music until Approve / Deny / 20 min (review-hold.go). Chris speaks the hold line BEFORE calling the tool."
         },
         "conversation_id": {
          "type": "string",
          "description": "ElevenLabs conversation id (log only)"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{review, under_review:true, notified, notify_to, hold: {hold_id, status: holding|failed|skipped|disabled, say, max_minutes, reason?}} · dry run {would_flag, would_notify, notify_to, would_hold, hold: {status: would_hold|skipped|disabled}} · Chris refusal {status: refused, code: dq|sold|dnc, say}"
     },
     "409": {
      "description": "DQ'd / Sold / Do Not Call lead {code: dq|sold|dnc, say} (non-Chris callers)"
     }
    }
   }
  },
  "/api/sms/send": {
   "post": {
    "tags": [
     "Comms"
    ],
    "summary": "Send ONE text through RingCentral from the business line — the one SMS path for every bot / agent / CRM caller   (scope comms:write, sales:write or sms:send)",
    "description": "Provider is RingCentral only (+1 425-818-3778, the same send the admin Comms tab uses). Twilio never texts anyone.\nChecks, in order: valid US mobile → brand guard → do-not-contact / DQ-blocked (`bot_api_dnc`, status Do Not Call, DNQ…) → SMS consent\n(STOP / per-channel opt-out). Quiet hours are OFF (texts are never blocked by the hour; `SMS_QUIET_HOURS=1` would enforce 8 AM–9 PM\nlead-local, code `quiet_hours`). `source: crm` (a human on the floor) runs the STOP check only. \"sent\" is returned ONLY after RingCentral accepted the\nmessage; any provider error / timeout is `{status: failed, code: sms_failed, say}` — never `sent` on failure.\nAgent callers (`source` ending in `_agent`, or a gated key) receive refused / failed as HTTP 200 so the voice agent reads `code` + `say`;\nother callers get 409 (refused) / 502 (failed) with the same body. Every attempt → `sms_send_log` (+ the lead's CRM Comms thread:\na sent text as an SMS row, a refusal / failure as a 📵 note). `X-Dry-Run: 1` runs the same checks → `would_send` + the provider.\n",
    "parameters": [
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "body"
        ],
        "properties": {
         "to": {
          "type": "string",
          "description": "E.164 (+1…) — optional when lead_id / client_id is given (the lead's / client's phone is used)"
         },
         "body": {
          "type": "string"
         },
         "source": {
          "type": "string",
          "description": "chris_agent | sarah_agent | marketing | crm | bot:<name>"
         },
         "lead_id": {
          "type": "integer"
         },
         "client_id": {
          "type": "integer"
         },
         "purpose": {
          "type": "string",
          "description": "portal_link | checkout_link | card_link | review_alert | message | other"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{status: success, sms: sent, provider: ringcentral, provider_message_id, from, to, lead_id?, log_id} · dry run {status: success, sms: would_send, would_send: true, provider: ringcentral, from, to, local_time} · agent refusal {status: refused, code: do_not_contact | no_consent | quiet_hours | no_phone | brand_violation, say, message, local_time?} · agent failure {status: failed, code: sms_failed, say, message}"
     },
     "409": {
      "description": "refused (non-agent callers) — same body"
     },
     "502": {
      "description": "RingCentral error (non-agent callers) — {status: failed, code: sms_failed, say, message}"
     }
    }
   }
  },
  "/api/mail/send": {
   "post": {
    "tags": [
     "Mail"
    ],
    "summary": "Send an email as Michael Shannon <michael@boundless-ai-academy.com> — From is fixed   (scope mail:send — master key only)",
    "description": "Own mail server: direct to the recipient's mail server, DKIM-signed for boundless-ai-academy.com (SPF / DKIM / DMARC pass).\nHTTPS only. 30 sends per hour, 200 per day. Optional allowlist `MAIL_API_ALLOWLIST`. Every recipient is checked against\ndo-not-contact / dispute hold / canceled client. A `from`, `sender` or `from_name` field is refused (400 from_fixed); unknown fields → 400.\nLogged in `mail_api_send_log` (time, recipients, subject, message_id) — never the body. Guide: docs/BOT_API_MAIL.md.\nExample: `curl -s https://shannonmanagementco.com/api/mail/send -H \"Authorization: Bearer $KEY\" -H 'Content-Type: application/json' -d '{\"to\":[\"someone@example.com\"],\"subject\":\"Hello\",\"text\":\"Plain-text body\"}'`\n",
    "parameters": [
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "to",
         "subject",
         "text"
        ],
        "additionalProperties": false,
        "properties": {
         "to": {
          "type": "array",
          "items": {
           "type": "string"
          },
          "description": "addresses, \"Name <addr>\" ok"
         },
         "cc": {
          "type": "array",
          "items": {
           "type": "string"
          }
         },
         "bcc": {
          "type": "array",
          "items": {
           "type": "string"
          }
         },
         "subject": {
          "type": "string"
         },
         "text": {
          "type": "string"
         },
         "html": {
          "type": "string",
          "description": "optional HTML version"
         },
         "reply_to": {
          "type": "string"
         },
         "in_reply_to_message_id": {
          "type": "string",
          "description": "a stored message's id or its RFC message_id — same thread"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{id, message_id, thread_id, sent_at, from, delivered[], failed[]?, dkim_signed} · dry run {would_send, from, recipients[], subject, message_id}"
     },
     "400": {
      "description": "bad_input | bad_recipient | from_fixed | too_many_recipients | too_large"
     },
     "403": {
      "description": "recipient_not_allowed | https_required | key lacks mail:send"
     },
     "404": {
      "description": "in_reply_to_message_id not found"
     },
     "409": {
      "description": "do_not_contact {recipients[]} — nothing sent"
     },
     "429": {
      "description": "rate_limited {limit: hourly|daily, max}"
     },
     "502": {
      "description": "delivery_failed {failed[]}"
     },
     "503": {
      "description": "dkim_unavailable"
     }
    }
   }
  },
  "/api/mail/messages": {
   "get": {
    "tags": [
     "Mail"
    ],
    "summary": "List messages sent and received by michael@boundless-ai-academy.com, newest first   (scope mail:read)",
    "description": "Example: `curl -s \"https://shannonmanagementco.com/api/mail/messages?query=invoice&since=2026-12-01&limit=25\" -H \"Authorization: Bearer $KEY\"`",
    "parameters": [
     {
      "name": "query",
      "in": "query",
      "schema": {
       "type": "string"
      },
      "description": "matches subject / from / to / cc / snippet"
     },
     {
      "name": "since",
      "in": "query",
      "schema": {
       "type": "string"
      },
      "description": "YYYY-MM-DD (Pacific) or RFC 3339"
     },
     {
      "name": "limit",
      "in": "query",
      "schema": {
       "type": "integer",
       "default": 25,
       "maximum": 200
      }
     },
     {
      "name": "direction",
      "in": "query",
      "schema": {
       "type": "string",
       "enum": [
        "in",
        "out"
       ]
      }
     },
     {
      "name": "thread_id",
      "in": "query",
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{mailbox, count, messages[] {id, thread_id, direction, message_id, from, to, cc, subject, snippet, date, size_bytes}}"
     }
    }
   }
  },
  "/api/mail/messages/{id}": {
   "get": {
    "tags": [
     "Mail"
    ],
    "summary": "One message: full text + html body and attachment metadata   (scope mail:read)",
    "description": "Example: `curl -s https://shannonmanagementco.com/api/mail/messages/42 -H \"Authorization: Bearer $KEY\"`",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "row fields + text, html, attachments[] {filename, content_type, size_bytes}, reply_to, in_reply_to, header_date, body_stored"
     },
     "404": {
      "description": "not_found"
     }
    }
   }
  },
  "/api/mail/health": {
   "get": {
    "tags": [
     "Mail"
    ],
    "summary": "Mailbox readiness: SPF / DKIM / DMARC in DNS, send counts vs limits, allowlist on/off   (scope mail:read or mail:send)",
    "description": "Example: `curl -s https://shannonmanagementco.com/api/mail/health -H \"Authorization: Bearer $KEY\"`",
    "responses": {
     "200": {
      "description": "{ready, mailbox, from, provider, dns{mx, spf, spf_ok, dmarc, dmarc_ok, dkim_selector, dkim_published, dkim_dns_ok}, limits{hourly_max, daily_max, sent_last_hour, sent_last_24h}, allowlist, stored{total, inbound, outbound}}"
     }
    }
   }
  },
  "/api/sms/log": {
   "get": {
    "tags": [
     "Comms"
    ],
    "summary": "Send attempts (sent / refused / failed / dry runs), newest first. 2026-11-21: lead_id is OPTIONAL — with no lead_id / client_id / since it lists the last 24 hours across everyone   (scope comms:read, sales:read or sms:send)",
    "parameters": [
     {
      "name": "lead_id",
      "in": "query",
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "client_id",
      "in": "query",
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "since",
      "in": "query",
      "schema": {
       "type": "string"
      },
      "description": "ISO 8601, YYYY-MM-DD, or a span back from now: 90m / 24h / 7d"
     },
     {
      "name": "result",
      "in": "query",
      "schema": {
       "type": "string",
       "enum": [
        "sent",
        "failed",
        "refused",
        "would_send"
       ]
      },
      "description": "failed = the provider did not take it; refused = do-not-contact, dispute hold, canceled client, STOP, quiet hours, brand / sensitive content"
     },
     {
      "$ref": "#/components/parameters/limit"
     }
    ],
    "responses": {
     "200": {
      "description": "{attempts[] {id, to, from, source, purpose, provider, provider_message_id, result, code, error, body, dry_run, local_time, at, lead_id, client_id}, count, by_result{sent, failed, refused, would_send}, since, result}"
     },
     "400": {
      "description": "bad since / result"
     }
    }
   }
  },
  "/api/sms/recent": {
   "get": {
    "tags": [
     "Comms"
    ],
    "summary": "The same list as GET /api/sms/log (same filters); with no filters = the last 24 hours across all leads and clients   (scope comms:read, sales:read or sms:send)",
    "parameters": [
     {
      "name": "since",
      "in": "query",
      "schema": {
       "type": "string"
      }
     },
     {
      "name": "result",
      "in": "query",
      "schema": {
       "type": "string",
       "enum": [
        "sent",
        "failed",
        "refused",
        "would_send"
       ]
      }
     },
     {
      "$ref": "#/components/parameters/limit"
     }
    ],
    "responses": {
     "200": {
      "description": "see /api/sms/log"
     }
    }
   }
  },
  "/api/voice/review-hold": {
   "post": {
    "tags": [
     "Sales setup"
    ],
    "security": [],
    "summary": "Twilio voice webhooks for the review hold (also /wait, /left, /bridge, /bridge/go, /end) — not called by bots",
    "description": "`POST /api/leads/{id}/review` with `source: chris_agent` + `call_sid` moves the live call here after ~4 s: `<Enqueue>` with a waitUrl loop\n(hold music, \"Thanks for holding, just a moment longer\" every ~60 s). Approve in the CRM → Michael's cell is rung from `DIRECTOR_TRANSFER_DID`\n(\"<name> is holding for you, press 1 to connect\") → `<Dial><Queue>` bridges him to the caller (re-rung every 2 min, max 3, while the caller holds).\nDeny → \"My finance manager will call you right back.\" + hangup. 3 minutes (`REVIEW_HOLD_MAX_MINS`, was 20 until round 18) without a decision → \"Thanks for holding. My finance manager couldn't break free just now, so we'll call you right back at this number.\", hangup,\nand a callback is booked on Michael's next open hour (`bot_api_bookings` source `review_hold`, reason `hold_timeout`); the caller hanging up\nwhile holding books the same callback (reason `hold_abandoned`). Signature-checked. `REVIEW_HOLD_ENABLED=0` turns the hold off.\n",
    "responses": {
     "200": {
      "description": "TwiML"
     },
     "403": {
      "description": "bad signature"
     }
    }
   }
  },
  "/api/reviews": {
   "get": {
    "tags": [
     "Sales setup"
    ],
    "summary": "Review queue   (scope sales:read or sales:review)",
    "parameters": [
     {
      "name": "status",
      "in": "query",
      "schema": {
       "type": "string",
       "enum": [
        "pending",
        "approved",
        "denied",
        "all"
       ],
       "default": "pending"
      }
     },
     {
      "$ref": "#/components/parameters/limit"
     }
    ],
    "responses": {
     "200": {
      "description": "reviews[]"
     }
    }
   }
  },
  "/api/leads/{id}/progress": {
   "get": {
    "tags": [
     "Calling pipeline"
    ],
    "summary": "Pipeline progress — last_step_reached, next_call_at (+agent, call_mode), call_attempts, last outcome / conversation, handoff   (scope sales:read, sales:calls, sales:review or bookings:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{lead_id, last_step_reached, step_index, next_call_at, next_call_at_utc, next_call_local, next_call_agent mike|chris|none, call_mode transfer|callback|resume|'', call_attempts, no_answer_streak, auto_scheduled, callback_set_by mike|chris|dialer|watchdog|review_hold|booking|post_call|<bot> (round 8), last_call_outcome, last_conversation_id, last_call_at, last_call_agent, reschedule_texted_at, due_now, in_queue, queue_why, will_call_at, timezone (the lead's IANA zone), updated_at, updated_by, steps[], handoff{}}"
     }
    }
   },
   "post": {
    "tags": [
     "Calling pipeline"
    ],
    "summary": "Set progress fields — a key present with null / \"\" clears it; steps never go backwards, unknown step names warn; next_call_at snaps into 8 AM–8 PM lead time   (scope sales:write, sales:calls or sales:review)",
    "description": "**Round 7 (2026-10-26):** `next_call_at` accepts ISO 8601 or plain text in the lead's timezone (\"tomorrow 10am\", \"Thursday afternoon\", \"in 2 hours\"; a zone word like \"Eastern\" overrides). The stored time is snapped into calling hours\n(`schedule.next_call_at` = the time the dialer will actually call, `requested_at`, `snapped`, `say`). A step behind the current one is kept (`changed.step_kept` + a warning); an unknown step name is a warning, not a 400. `next_call_agent` reads `\"none\"` when cleared.\n",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "last_step_reached": {
          "type": "string",
          "enum": [
           "intake_started",
           "intake_done",
           "transferred",
           "portal_link_sent",
           "website_seen",
           "google_done",
           "business_steps_done",
           "video_done",
           "capital_started",
           "card_added",
           "verified",
           "director_review",
           "booked",
           "closed",
           "dq"
          ]
         },
         "next_call_at": {
          "type": "string",
          "nullable": true,
          "description": "ISO 8601 or plain text in the lead's timezone; null clears"
         },
         "next_call_agent": {
          "type": "string",
          "enum": [
           "mike",
           "chris",
           "none"
          ]
         },
         "call_mode": {
          "type": "string",
          "enum": [
           "transfer",
           "callback",
           "resume"
          ]
         },
         "call_attempts": {
          "type": "integer"
         },
         "last_call_outcome": {
          "type": "string"
         },
         "last_conversation_id": {
          "type": "string"
         },
         "note": {
          "type": "string"
         },
         "source": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{lead_id, progress, changed, warnings[], schedule{next_call_at, next_call_local, requested_at, snapped, say}} · dry run {would_set} · agent refusal {status: refused, code: do_not_contact, say} when a next_call_at is set on a blocked lead"
     },
     "400": {
      "description": "bad enum / time"
     }
    }
   }
  },
  "/api/leads/{id}/callback": {
   "post": {
    "tags": [
     "Calling pipeline"
    ],
    "summary": "Agents set a callback (NOT a booking with Michael) — callback_time ISO 8601 or plain text in the lead's timezone, agent chris|mike; a time the lead gives is stored EXACTLY (24/7, lead_agreed_time), vague text auto-schedules the next valid slot, explicit past times are refused   (scope sales:write, sales:calls or sales:review)",
    "description": "**Round 7, item 16.** Sets `next_call_at` / `next_call_agent` / `call_mode=callback`, keeps the handoff alive until 24 h after the call, leaves a CRM note. Agent default: Chris once intake is done (or a handoff to him exists), else the caller.\n**Round 9c:** a time the lead gives is stored EXACTLY (no 8 AM–8 PM snap, `lead_agreed_time: true`, rings 24/7); an explicit past time is refused (`callback_time_past`). **Round 9:** a vague (\"later\", \"whenever\") or missing callback_time is never refused — the next valid slot ≥ 60 min out inside 8 AM–8 PM lead time is booked (`auto_scheduled: true`, `callback_no_time`, `callback_no_time_why`, `task_id`) and `say` names the chosen time. The only refusal left is `do_not_contact` (200 `{status: refused, ok: false, code, say}` for the Chris key / source *_agent; 409 for plain bot keys). `callback_set_by` (mike | chris | …) is recorded from the agent / key / source — optional `set_by` overrides.\n",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "callback_time"
        ],
        "properties": {
         "callback_time": {
          "type": "string",
          "description": "ISO 8601 (any offset) or plain text in the lead's timezone, e.g. \"tomorrow 10am Pacific\""
         },
         "agent": {
          "type": "string",
          "enum": [
           "chris",
           "mike"
          ]
         },
         "note": {
          "type": "string"
         },
         "source": {
          "type": "string"
         },
         "conversation_id": {
          "type": "string"
         },
         "set_by": {
          "type": "string",
          "description": "optional: who booked it (default = the calling agent / key)"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{ok, lead_id, name, next_call_at (the time the dialer will call), next_call_at_utc, next_call_local, requested_at, requested_local, snapped, say, parsed_as, next_call_agent, call_mode, callback_set_by, calling_hours, timezone, progress, handoff} · dry run adds would_set"
     },
     "404": {
      "description": "no such lead"
     }
    }
   }
  },
  "/api/leads/by-phone": {
   "get": {
    "tags": [
     "Calling pipeline"
    ],
    "summary": "Lead by phone for the agents — lead_id, names, timezone, last_step_reached, intake answers, do_not_contact, handoff; unknown → found:false, lead_id \"\"   (scope sales:read, sales:calls, sales:review or bookings:read)",
    "parameters": [
     {
      "name": "phone",
      "in": "query",
      "required": true,
      "schema": {
       "type": "string"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{found, lead_id, first_name, last_name, name, phone, phones[], email, timezone, local_time, local_day, state, status, status_lock, do_not_contact, do_not_contact_reason, opt_outs, last_step_reached, progress{}, intake{completed, completed_at, answers{q1_…}, availability}, handoff{}, client_id, is_client}"
     }
    }
   },
   "post": {
    "tags": [
     "Calling pipeline"
    ],
    "security": [],
    "summary": "The ONE workspace conversation-initiation webhook (Chris 425, Olivia 510, Josh Coach) — dispatches on agent_id; auth X-Intake-Agent-Key = ELEVEN_CONVAI_INIT_KEY (or ElevenLabs-Signature, or a bot key)",
    "description": "**Round 5 (2026-10-25 night):** the init webhook is one setting for the whole workspace, so this route answers every variable any of the three prompts use.\nChris / Olivia extras (always present, \"\" when unknown): first_line (the opening line for the call_mode), greet_name (first name or \"there\"), handoff\n(summary — notes), intake_summary, crm_status, city, signup_date / signup_local / signup_days_ago / signup_source / signup_location, local_timezone\n(\"America/Chicago (Central)\"), today_local (\"Monday, October 27, 2026\"), today_date, appointment_booked / appointment_start / appointment_local /\nappointment_day_label / appointment_coach / appointment_status / appointment_booking_id / appointment_in_hours, channel (phone), hold_plan (no), agent (mike|chris|josh).\nJosh Coach (ELEVEN_COACHING_AGENT_ID) and any other agent: today's payload from /api/elevenlabs/call-init + /api/elevenlabs/convai/init is merged in unchanged\n(incl. its conversation_config_override first message). **branch_id:** test leads (BOT_TEST_LEADS, default 37487) on Chris get top-level `branch_id` =\nBOT_TEST_BRANCH_ID (default agtbrch_8501m5ecsw1tetr8t0c3v12rkrg0) + the same dynamic variable; everyone else has no branch_id (main).\nBody `{caller_id, called_number, agent_id, call_sid, conversation_id}` → `{type: conversation_initiation_client_data, dynamic_variables}` (every value a string):\nlead_id (\"\" when unknown), lead_found, first_name, last_name, phone_digits, timezone, local_time, local_day, lead_status, is_client, client_id, do_not_contact,\nintake_completed, every intake answer under its own key (q1_financial_difficulty … q23_notes, q_avail_days, q_avail_windows), intake_answers (one line),\navailability_days/windows, last_step_reached, call_mode (transfer | callback | resume | inbound), next_call_agent, call_attempts, last_call_outcome,\nlast_conversation_id, handoff_present, handoff_from, handoff_to, handoff_notes, handoff_summary, handoff_step, handoff_minutes_ago, agent, direction.\nThe lead is the dial attempt matched by conversation_id / call_sid (else the lead's newest open attempt within 30 min), else whichever number is not one of ours (ELEVEN_MIKE_DID / ELEVEN_CHRIS_DID / DIRECTOR_TRANSFER_DID).\n**Round 8 (2026-10-26 evening):** `first_line` always holds the opener for the call type and `first_line_mode` names it — inbound_unknown | inbound | calling_back | transfer | callback | followup (auto-scheduled, no agreed time) | resume | dnc;\ndo-not-contact leads get `dnc: yes`, `dnc_reason`, a neutral first_line and no calling_back / route_to / pending callback; `pending_callback_time` (clock form), `pending_callback_agent`, `pending_callback_set_by` ride as their own variables;\n`dial_attempt_id` is set (and `direction: outbound`) when the call is one the dialer placed; `do_not_contact_reason` on the base set.\n",
    "responses": {
     "200": {
      "description": "conversation_initiation_client_data"
     },
     "401": {
      "description": "no valid key / signature"
     }
    }
   }
  },
  "/api/handoffs": {
   "post": {
    "tags": [
     "Calling pipeline"
    ],
    "summary": "Olivia → Chris handoff keyed by lead_id — upsert, lives 24 h (HANDOFF_TTL_HOURS) or until 24 h after the scheduled call, never deleted on read; without lead_id the lead is found by conversation_id / phone_digits / caller_id, else lead_id_required   (Bearer sales:write, sales:calls or sales:review — OR header X-Handoff-Secret = HANDOFF_SECRET, Olivia's save_handoff tool)",
    "description": "**Round 7 (2026-10-26):** accepts Olivia's save_handoff body as-is — `{first_name, last_name, phone_digits, signup_date, signup_ago, city, intake_summary}` with the tool's `X-Handoff-Secret` header: lead by `phone_digits`, `intake_summary` → summary, name / city / signup fields → `data`, mike → chris, `call_mode transfer`.\nPoint the tool's URL at this route and the Twilio function is no longer needed. `summary` is rebuilt on every read with \"Callback scheduled <when> · …\" once a call is on the books (`scheduled_call_at`, `scheduled_call_local`, `summary_raw`). Unknown step names warn; the lead's progress step never moves backwards.\n",
    "parameters": [
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "lead_id": {
          "type": "integer"
         },
         "from_agent": {
          "type": "string",
          "enum": [
           "mike",
           "chris"
          ]
         },
         "to_agent": {
          "type": "string",
          "enum": [
           "mike",
           "chris"
          ]
         },
         "call_mode": {
          "type": "string",
          "enum": [
           "transfer",
           "callback",
           "resume"
          ],
          "default": "transfer"
         },
         "last_step_reached": {
          "type": "string",
          "description": "default transferred when call_mode is transfer"
         },
         "notes": {
          "type": "string"
         },
         "summary": {
          "type": "string"
         },
         "conversation_id": {
          "type": "string"
         },
         "call_sid": {
          "type": "string"
         },
         "data": {
          "type": "object"
         },
         "source": {
          "type": "string"
         },
         "phone_digits": {
          "type": "string"
         },
         "caller_id": {
          "type": "string"
         },
         "phone": {
          "type": "string"
         },
         "intake_summary": {
          "type": "string"
         },
         "first_name": {
          "type": "string"
         },
         "last_name": {
          "type": "string"
         },
         "city": {
          "type": "string"
         },
         "signup_date": {
          "type": "string"
         },
         "signup_ago": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{lead_id, lead_resolved_by lead_id|conversation_id|phone, handoff{found, from_agent, to_agent, call_mode, last_step_reached, notes, summary, summary_raw, scheduled_call_at, scheduled_call_local, data, conversation_id, call_sid, created_at, expires_at, read_count, age_minutes}, stored:true, warnings[]} · dry run {would_store} · agent refusal {status: refused, code: lead_id_required, say}"
     },
     "401": {
      "description": "no key and no matching X-Handoff-Secret"
     },
     "404": {
      "description": "no such lead"
     }
    }
   },
   "get": {
    "tags": [
     "Calling pipeline"
    ],
    "summary": "Handoff by phone   (scope sales:read, sales:calls or sales:review)",
    "parameters": [
     {
      "name": "phone",
      "in": "query",
      "required": true,
      "schema": {
       "type": "string"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{lead_id, found, handoff (+ picked_up_at, transferred_at, watchdog_at, transfer_state — round 13)}"
     }
    }
   }
  },
  "/api/handoffs/{lead_id}": {
   "get": {
    "tags": [
     "Calling pipeline"
    ],
    "summary": "Handoff for a lead — {found:false} when missing / expired, never another lead's   (scope sales:read, sales:calls or sales:review)",
    "parameters": [
     {
      "name": "lead_id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{lead_id, found, handoff{…, picked_up_at, transferred_at, watchdog_at (ISO-8601 | null), transfer_state pending|picked_up|connected|watchdog_resume_queued (round 13)}}"
     }
    }
   }
  },
  "/api/calls/complete": {
   "post": {
    "tags": [
     "Calling pipeline"
    ],
    "security": [],
    "summary": "Post-call — ElevenLabs post-call webhook (HMAC) or a bot-posted summary (Bearer sales:calls | sales:review | sales:write) → progress, lead status only if they talked, dropped → resume in 2 min, no answer → +10 min once then a text",
    "description": "**Signature:** `ElevenLabs-Signature: t=<unix>,v0=<hex hmac-sha256(\"<t>.<body>\")>` verified with ELEVEN_CONVAI_POSTCALL_SECRET (the workspace post-call webhook secret, set 2026-10-25).\n**Round 13:** a booking Chris claimed without the tool is scheduled for the time the lead heard (claim sentence, then the lead's lines; spoken numbers normalized) → `callback_time_source` claim line | lead line | none heard, `callback_time_heard`; a real `conv_…` conversation is claimed atomically (`bot_postcall_seen`) — a second delivery (retry or sweep) answers `{duplicate: true, recorded_by, recorded_at}` and writes nothing; synthetic ids are never deduped. **Round 14:** claims without \"for\" (you're all set / Mike will call you) count; an auto-scheduled callback answers `say` = \"Mike will give you a call to confirm a time — what time works best for you?\" (never the picked slot); every duplicate answer carries `recorded_by` + `recorded_at`.\n**call_initiation_failure** (outbound no-answer / busy / failed): matched to the dial attempt by conversation_id / call_sid / lead_id variable / phone → attempt marked\nno_answer and the dialer rule runs (+10 min once, then one text) → `{event, lead_id, attempt_id, reason, no_answer_action, progress}`.\nData-collection values are read from `analysis.data_collection_results.<key>.value`.\nNative payload: `post_call_transcription` (audio / failure events are acknowledged; audio is archived as before). Data-collection keys read: outcome | call_outcome | disposition,\nstatus | lead_status, last_step_reached, talked | lead_talked, dropped, callback_time (ISO 8601), next_call_agent, lead_id. Lead = `lead_id` dynamic variable → dial attempt\n(conversation id / call sid) → external phone. Simple payload: `{lead_id, conversation_id, agent, outcome, status, last_step_reached, summary, data_collection{}, talked, dropped,\ncallback_time, next_call_agent, duration_secs, phone, direction}`.\nStatus is applied ONLY when the lead talked (explicit `talked`, else ≥ 1 user turn and ≥ 5 s): Declined, Callback Requested, Do Not Call (+ DNC flags), AI Intake Transferred,\nAppointment Booked → Appointment Set, DQ, Refund Requested, New → Live; DQ'd / Sold / Do Not Call stay (`status_locked`). Dropped = talked, not terminal (booked / closed / dq /\ndeclined / two NOs / transferred) and dropped flag or a dropped-sounding outcome → next_call_at now + 2 min, call_mode resume. No answer on an outbound → first miss +10 min,\nsecond miss one RingCentral text asking for a time. Writes a bot_api_lead_calls row + a 🤖 CRM note.\n**Round 7 (2026-10-26):** Olivia's `survey_outcome` is the outcome (completed / partial / declined / wrong_person / callback_requested / no_answer / do_not_call / refund_request); `callback_time` may be plain text in the lead's timezone\n(`callback_time_parsed` / `callback_time_ignored`); every scheduled time snaps into 8 AM–8 PM lead time (`snapped`, `requested_at`, `next_call_local`, `say`); a talked, unfinished call with no time → auto-scheduled 60 min out (`auto_scheduled: true`);\n**Round 9:** stale compares call START times (Chris is never stale; `last_call_started_at`), do_not_call ALWAYS applies (`dnc`, `dnc_applied`), outcome precedence dnc > booked > dropped > callback (`outcome_primary`), a Chris result supersedes Olivia's pending callback (`mike_callback_dropped`), Olivia `completed` folds q-answers into the intake (`intake_answers_folded`, `intake_summary`); **Round 9c:** a Chris call with `call_outcome: callback_no_time` hands the lead back to Olivia (`handback_to_mike`, next_call_agent mike, DIALER_HANDBACK_MIN) and a parsed callback_time is stored exactly (`lead_agreed_time`); steps never go backwards (`step_kept`), unknown steps → `warnings[]`; `call_initiation_failure` counts an attempt (`call_attempts`, `attempt_counted_here`) and records the agent;\nmax attempts → `final{status_new: Unreachable, sms, sms_text, task_id}`. Dry runs answer `would{would_action, would_next_call_at, would_next_call_local, sms_text, sms_to, reason}`.\n**Round 8 (2026-10-26 evening):** a *callback requested* outcome (outcome / status / Olivia's `survey_outcome=callback_requested`) with a missing, unparseable or past `callback_time` is NEVER dropped — the next calling-hours slot ≥ DIALER_CALLBACK_NO_TIME_MIN (60) min out is scheduled (`callback_no_time: true`, `callback_no_time_why`, `auto_scheduled: true`) and a follow-up task opens for a person (`task_id`; `would_task` on dry runs) — talked or not.\nThe call is matched to the dialer's attempt by conversation_id → call_sid → the lead's newest open attempt (30 min / 2 h when ElevenLabs says outbound) → `direction: outbound|inbound`, `direction_source: dial_attempt|elevenlabs_metadata|no dial attempt matched`, `dial_attempt_id`. `callback_set_by` = the agent whose call just ended.\n",
    "parameters": [
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "responses": {
     "200": {
      "description": "{ok, lead_id, name, agent, direction, direction_source, dial_attempt_id, talked, outcome, last_step_reached, status_requested, status_mapped, status_set, status_new, status_locked, dropped, stale, stale_why, superseded_by, callback_requested, callback_no_time, callback_no_time_why, task_id?, auto_scheduled, snapped, requested_at, next_call_at, next_call_local, say, call_mode, next_call_agent, callback_set_by, no_answer_action retry_10_min|text_for_new_time|max_attempts_final|no_answer_sms_off|already_texted|'', sms?, final?, warnings[], progress}"
     },
     "401": {
      "description": "no key / bad signature"
     },
     "403": {
      "description": "scope"
     }
    }
   }
  },
  "/api/leads/{id}/test-reset": {
   "post": {
    "tags": [
     "Calling pipeline"
    ],
    "summary": "TEST LEADS ONLY (BOT_TEST_LEADS, default 37487) — clear Capital-page picks + cards on file, un-release the video, reset watch state / progress / handoff / dial attempts / API DNC flags / STOP + blocked-caller rows / card links   (scope sales:write or sales:calls)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "status": {
          "type": "string",
          "description": "optional: set the lead status (e.g. Live) — must be a real CRM status on the lead's floor, else 400 with the valid list (round 7). Round 8: when omitted and the lead sits in Do Not Call / Unreachable it is restored to Live by default (status_defaulted: true)"
         },
         "reviews": {
          "type": "boolean",
          "description": "cancel pending reviews too"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{lead_id, client_id, reset{step: rows}, status, status_applied (round 12: written straight to the lead, bypassing the floor's post-intake guard), status_after, status_defaulted, status_before, progress, capital} · dry run {would_reset[], status_defaulted, status_before}"
     },
     "403": {
      "description": "not a test lead"
     }
    }
   }
  },
  "/api/leads/callback-words": {
   "post": {
    "tags": [
     "Calling pipeline"
    ],
    "security": [],
    "summary": "Round 15 — Olivia's set_callback tool: the lead's own words for a callback time → transcript → LLM → ISO in the lead's tz; 'dropped call, call back right now' / {dropped:true} arms the immediate redial (round 19)   (auth inside: X-Intake-Agent-Key, ElevenLabs HMAC, or a bot key with sales:write | sales:calls | sales:review)",
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "conversation_id": {
          "type": "string"
         },
         "lead_id": {
          "type": "integer"
         },
         "phone_digits": {
          "type": "string"
         },
         "words": {
          "type": "string",
          "description": "what the lead said, e.g. 'tomorrow after lunch'"
         },
         "agent": {
          "type": "string",
          "enum": [
           "mike",
           "chris"
          ]
         },
         "dropped": {
          "type": "boolean"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{ok, lead_id, next_call_at, say, …} — see botCallbackWordsRoute (round 15 / 19)"
     },
     "401": {
      "description": "no accepted credential"
     }
    }
   }
  },
  "/api/dialer": {
   "get": {
    "tags": [
     "Calling pipeline"
    ],
    "summary": "Callback dialer — switch state (DB toggle on /hcs/bot-api + DIALER_ENABLED=0 hard kill; the toggle has been ON since 2026-11-09), config readiness (ELEVEN_* ids), due count, callable queue + held-back leads with why, follow-up tasks, recent attempts (status placed | no_answer | talked | dropped | stalled (R21) | provider_error (R21) | …)   (scope sales:read, sales:calls or sales:review)",
    "responses": {
     "200": {
      "description": "{config{enabled, hard_off, dry_run, max_attempts, max_per_tick, hours_start, hours_end, no_answer_sms, last_tick_at, last_tick_note}, configured{eleven_api_key, mike_agent_id, mike_phone_id, chris_agent_id, chris_phone_id, init_webhook_key, post_call_secret, ready}, due_now, queue[] (eligible, why, will_call_at, auto_scheduled, call_attempts/max_attempts), excluded[] (same rows with why: max attempts / outside calling hours → will_call_at / do_not_contact / status lock / agent not configured), queued_total, followup_tasks[] {id, lead_id, name, phone, kind, reason, created_at}, transfer_watchdog_minutes, recent_attempts[], hours}"
     }
    }
   }
  },
  "/api/changelog": {
   "get": {
    "tags": [
     "Changelog"
    ],
    "summary": "The Bot API changelog — one entry per request id (SH-1, BIZ-7, CS-3, FD-2 …), newest first   (any bot key, or an admin session)",
    "description": "Filters: since (ISO, entries changed after), team all|shared|bizop|client-success|finance|assistant (all = an entry that concerns every bot), status requested|in_progress|partial|deployed|needs_info|declined|superseded, limit (50, max 200), cursor (next_cursor from the previous page). Entry: {id, team, requested_by, requested_at, title, request, status, deployed_at, build, changes[], scopes_added[], example, how_to_test, notes, questions, replies[], verifications[], updated_at}. Also GET /api/changelog.md?month=YYYY-MM (markdown, last 30 days by default) and the page /changelog.",
    "parameters": [
     {
      "name": "since",
      "in": "query",
      "schema": {
       "type": "string"
      }
     },
     {
      "name": "team",
      "in": "query",
      "schema": {
       "type": "string"
      }
     },
     {
      "name": "status",
      "in": "query",
      "schema": {
       "type": "string"
      }
     },
     {
      "name": "limit",
      "in": "query",
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "cursor",
      "in": "query",
      "schema": {
       "type": "string"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{entries[], count, next_cursor, statuses[], teams[], build}"
     }
    }
   }
  },
  "/api/changelog.md": {
   "get": {
    "tags": [
     "Changelog"
    ],
    "security": [],
    "summary": "The changelog as markdown (last 30 days by default; ?month=YYYY-MM)   (any bot key, or an admin session)",
    "parameters": [
     {
      "name": "month",
      "in": "query",
      "schema": {
       "type": "string",
       "example": "2026-11"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "text/markdown"
     }
    }
   }
  },
  "/api/changelog/latest": {
   "get": {
    "tags": [
     "Changelog"
    ],
    "summary": "The last deploy and every entry that shipped in it   (any bot key)",
    "responses": {
     "200": {
      "description": "{deployed_at, build, current_build, started_at, entries[], count}"
     }
    }
   }
  },
  "/api/changelog/{id}": {
   "get": {
    "tags": [
     "Changelog"
    ],
    "summary": "One entry with its full event history (status changes, replies, verifications)   (any bot key)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "string"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{entry{…, events[]}}"
     },
     "404": {
      "description": "no such id"
     }
    }
   }
  },
  "/api/changelog/{id}/reply": {
   "post": {
    "tags": [
     "Changelog"
    ],
    "summary": "Bot write-back: answer the developer's question on an entry   (any bot key; records the key name + time)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "string"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "answer"
        ],
        "properties": {
         "answer": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{id, reply{at, by, answer}, entry}"
     },
     "400": {
      "description": "sensitive_content"
     }
    }
   }
  },
  "/api/changelog/{id}/verify": {
   "post": {
    "tags": [
     "Changelog"
    ],
    "summary": "Bot write-back: record a re-test result   (any bot key)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "string"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "result"
        ],
        "properties": {
         "result": {
          "type": "string",
          "enum": [
           "verified",
           "failed"
          ]
         },
         "note": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{id, verification{at, by, result, note, build}, entry}"
     }
    }
   }
  },
  "/api/audit": {
   "get": {
    "tags": [
     "Platform"
    ],
    "summary": "Audit log of every bot write — time, key, route, target, before, after, approved_by   (scope audit:read)",
    "parameters": [
     {
      "name": "since",
      "in": "query",
      "schema": {
       "type": "string"
      }
     },
     {
      "name": "until",
      "in": "query",
      "schema": {
       "type": "string"
      }
     },
     {
      "name": "bot",
      "in": "query",
      "schema": {
       "type": "string"
      }
     },
     {
      "name": "path",
      "in": "query",
      "schema": {
       "type": "string"
      }
     },
     {
      "name": "method",
      "in": "query",
      "schema": {
       "type": "string"
      }
     },
     {
      "name": "limit",
      "in": "query",
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "cursor",
      "in": "query",
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{rows[] {id, at, bot, key_id, method, path, target, scope, status_code, dry_run, approved_by, ip, request_body, before, after}, count, next_cursor}"
     }
    }
   }
  },
  "/api/dialer/test-call": {
   "post": {
    "tags": [
     "Calling pipeline"
    ],
    "summary": "BIZ-7 — ONE real outbound call on the test lead only (403 for any other lead), 1 per 2 minutes   (scope sales:write or sales:calls)",
    "description": "Places the call through ElevenLabs with the same variables the dialer sends (first_line per call type, handoff, intake…), records a dial attempt so the init / post-call webhooks label it outbound. X-Dry-Run answers would_dial + the variables. 429 inside 2 min, 409 agent_not_configured / dialer_hard_off, 502 call_failed.",
    "parameters": [
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "lead_id",
         "agent"
        ],
        "properties": {
         "lead_id": {
          "type": "integer"
         },
         "agent": {
          "type": "string",
          "enum": [
           "mike",
           "chris"
          ]
         },
         "call_mode": {
          "type": "string",
          "enum": [
           "callback",
           "resume",
           "transfer"
          ],
          "default": "callback"
         },
         "branch": {
          "type": "string",
          "description": "round 12: test (BOT_TEST_BRANCH_ID / BOT_TEST_BRANCH_ID_MIKE) | main | agtbrch_… — default = what the dialer uses (the test lead's test branch)"
         },
         "branch_id": {
          "type": "string",
          "description": "explicit ElevenLabs branch id (wins over branch)"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{placed, dial_attempt_id, conversation_id, call_sid, first_line, first_line_mode, branch test|main|custom, branch_id, attempt_no, verify, progress}"
     },
     "400": {
      "description": "bad_branch"
     },
     "403": {
      "description": "not_a_test_lead"
     },
     "429": {
      "description": "one per 2 minutes"
     }
    }
   }
  },
  "/api/finance-manager/status": {
   "get": {
    "tags": [
     "Calling pipeline"
    ],
    "summary": "BIZ-9 — is the finance manager (Michael) free for a live transfer right now: his RingCentral line + his calendar   (scope sales:read | sales:calls | sales:review | bookings:read)",
    "parameters": [
     {
      "name": "lead_id",
      "in": "query",
      "schema": {
       "type": "integer"
      },
      "description": "renders next_open_slot in the lead's timezone"
     }
    ],
    "responses": {
     "200": {
      "description": "{status_now available|busy, available, say, line{extension, state, detail, ready}, calendar{free, why, checked}, next_open_slot{start, day_label, say}, checked_at}"
     }
    }
   }
  },
  "/api/login-attempts": {
   "get": {
    "tags": [
     "Client Success"
    ],
    "summary": "CS-1 — login attempts from /hcs/login-geo with the matched client + coach   (scope clients:read | calls:read)",
    "parameters": [
     {
      "name": "since",
      "in": "query",
      "schema": {
       "type": "string"
      }
     },
     {
      "name": "until",
      "in": "query",
      "schema": {
       "type": "string"
      }
     },
     {
      "name": "email",
      "in": "query",
      "schema": {
       "type": "string"
      }
     },
     {
      "name": "result",
      "in": "query",
      "schema": {
       "type": "string",
       "enum": [
        "OK",
        "BAD_PASSWORD",
        "UNKNOWN_USER",
        "OUTSIDE_LOGIN_HOURS",
        "ACCOUNT_DISABLED",
        "FAILED"
       ]
      }
     },
     {
      "name": "limit",
      "in": "query",
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "cursor",
      "in": "query",
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{attempts[] {id, time, email, portal, result, reason, ip, city, country, device, client_id, client_name, coach, matched_by email|ip}, count, since, next_cursor}"
     }
    }
   }
  },
  "/api/clients/search": {
   "get": {
    "tags": [
     "Client Success"
    ],
    "summary": "CS-2 — client lookup with flags   (scope clients:read)",
    "parameters": [
     {
      "name": "q",
      "in": "query",
      "schema": {
       "type": "string"
      },
      "description": "email / phone / id / name by shape"
     },
     {
      "name": "id",
      "in": "query",
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "phone",
      "in": "query",
      "schema": {
       "type": "string"
      }
     },
     {
      "name": "email",
      "in": "query",
      "schema": {
       "type": "string"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{matches[] {client_id, lead_id, name, email, phone, coach, tier, stage prospect|client|client_setup|client_setup_phase_N, status, lead_status, license_rate, flags{financed, do_not_contact, do_not_contact_reason, dispute_open, chargeback, canceled, rescission_hold, payouts_held, payouts_held_reason}}, count, matched_by, lead?}"
     }
    }
   }
  },
  "/api/clients/call-overview": {
   "get": {
    "tags": [
     "Client Success"
    ],
    "summary": "CS-6 — each active client's next booked call, last finished call and status; ?no_future_call=true for clients with nothing booked   (scope clients:read | bookings:read)",
    "parameters": [
     {
      "name": "coach",
      "in": "query",
      "schema": {
       "type": "string"
      }
     },
     {
      "name": "no_future_call",
      "in": "query",
      "schema": {
       "type": "boolean"
      }
     },
     {
      "name": "limit",
      "in": "query",
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{clients[] {client_id, name, email, coach, status, on_client_setup_board, next_call{booking_id, start, end, coach, type}, last_finished_call{start, coach, status|duration_secs, source}}, count}"
     }
    }
   }
  },
  "/api/sms/threads": {
   "get": {
    "tags": [
     "Client Success"
    ],
    "summary": "CS-3 — client text threads from the inbox (unread=true for unread only)   (scope comms:read)",
    "parameters": [
     {
      "name": "unread",
      "in": "query",
      "schema": {
       "type": "boolean"
      }
     },
     {
      "name": "coach",
      "in": "query",
      "schema": {
       "type": "string"
      }
     },
     {
      "name": "limit",
      "in": "query",
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{threads[] {client_id, name, coach, contact, unread, read, last_text, last_direction, last_at, waiting_relays, flagged, phase}, count, unread_messages}"
     }
    }
   }
  },
  "/api/sms/threads/{client_id}": {
   "get": {
    "tags": [
     "Client Success"
    ],
    "summary": "CS-3 — one client's thread: messages with direction, exact time and read flag   (scope comms:read)",
    "parameters": [
     {
      "name": "client_id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "limit",
      "in": "query",
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, name, coach, phones[], messages[] {id, direction, body, timestamp, read, from, to}, count, unread, read}"
     }
    }
   },
   "patch": {
    "tags": [
     "Client Success"
    ],
    "summary": "CS-3 — {read:true} marks the thread read (also closes the client's pending check-in relays like the page). {read:false} (2026-11-21) puts it back to UNREAD: the newest inbound text is flagged unread here and in RingCentral, so the thread returns to GET /api/sms/threads?unread=true (e.g. a money text for Finance Director). POST is the same operation   (scope comms:write | desk:write)",
    "parameters": [
     {
      "name": "client_id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "read"
        ],
        "properties": {
         "read": {
          "type": "boolean"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, read:true, messages_marked, relays_cleared} | {client_id, read:false, messages_marked_unread}"
     },
     "409": {
      "description": "no_inbound_message — the thread has no inbound text to mark unread"
     }
    }
   },
   "post": {
    "tags": [
     "Client Success"
    ],
    "summary": "CS-3 — same as PATCH: mark the thread read {read:true}   (scope comms:write)",
    "parameters": [
     {
      "name": "client_id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "read": {
          "type": "boolean"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, read:true, messages_marked}"
     }
    }
   }
  },
  "/api/missed-calls": {
   "get": {
    "tags": [
     "Client Success"
    ],
    "summary": "CS-5 — open missed client calls (who, when, line, coach callback booked); a call back inside 2 h marks a miss handled automatically   (scope calls:read | comms:read)",
    "parameters": [
     {
      "name": "open",
      "in": "query",
      "schema": {
       "type": "boolean"
      },
      "description": "accepted and ignored — the route always returns the OPEN misses"
     },
     {
      "name": "coach",
      "in": "query",
      "schema": {
       "type": "string"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{missed_calls[] {id, client_id, name, coach, caller_phone, line, at, open_calls, coach_callback_booked, next_appt, phase}, count, auto_handled_now, rule}"
     }
    }
   }
  },
  "/api/missed-calls/{id}/resolve": {
   "post": {
    "tags": [
     "Client Success"
    ],
    "summary": "CS-5 — resolve a missed call with a note (closes every open miss from that client up to it)   (scope comms:write | desk:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "note": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{id, client_id, resolved, calls_closed, note}"
     }
    }
   }
  },
  "/api/clients/{id}/contracts": {
   "get": {
    "tags": [
     "Client Success"
    ],
    "summary": "CS-7 — DocuSign envelopes (sent / viewed / signed / voided, from the Connect webhook) + the CRM's compliance tracker   (scope clients:read | documents:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, docusign_envelopes[] {envelope_id, subject, status, sent_at, viewed_at, signed_at, voided_at}, docusign_connected, compliance_tracker{transaction_authorization, service_fulfillment, flagged, exempt}}"
     }
    }
   }
  },
  "/api/webhooks/docusign": {
   "post": {
    "tags": [
     "Client Success"
    ],
    "security": [],
    "summary": "CS-7 — DocuSign Connect receiver (JSON; HMAC-SHA256 of the raw body with DOCUSIGN_CONNECT_SECRET in X-DocuSign-Signature-1). 503 not_configured until the secret is set.",
    "responses": {
     "200": {
      "description": "{stored, envelope_id, status, client_id, event}"
     },
     "401": {
      "description": "signature did not verify"
     }
    }
   }
  },
  "/api/clients/{id}/recordings": {
   "get": {
    "tags": [
     "Client Success"
    ],
    "summary": "CS-8 — the client's call recordings   (scope calls:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "limit",
      "in": "query",
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{recordings[] {id, at, duration_secs, direction, source, has_audio, has_transcript, transcribe_status, sentiment, transcript_url}, count}"
     }
    }
   }
  },
  "/api/recordings/{id}/transcript": {
   "get": {
    "tags": [
     "Client Success"
    ],
    "summary": "CS-8 — a recording's transcript with card numbers, routing numbers and SSNs masked server-side   (scope calls:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{id, client_id, lead_id, at, duration_secs, direction, transcript, has_transcript, summary, masked:true}"
     }
    }
   }
  },
  "/api/payouts/mark": {
   "post": {
    "tags": [
     "Payouts"
    ],
    "summary": "FD-1 — mark ONE courtesy payout cell paid or returned; amount must match the cell (409 amount_mismatch); undo with /api/payouts/undo   (scope payouts:write)",
    "parameters": [
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "client_id",
         "date",
         "status",
         "amount",
         "note"
        ],
        "properties": {
         "client_id": {
          "type": "integer"
         },
         "date": {
          "type": "string",
          "format": "date"
         },
         "status": {
          "type": "string",
          "enum": [
           "paid",
           "returned"
          ]
         },
         "amount": {
          "type": "number"
         },
         "note": {
          "type": "string"
         },
         "approved_by": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{audit_id, payout_id, client_id, date, amount, status_before, status_after, note, undo}"
     },
     "404": {
      "description": "no_cell"
     },
     "409": {
      "description": "amount_mismatch | already_paid | already_returned | in_batch"
     }
    }
   }
  },
  "/api/payouts/undo": {
   "post": {
    "tags": [
     "Payouts"
    ],
    "summary": "FD-1 — undo a mark by its audit_id   (scope payouts:write)",
    "parameters": [
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "audit_id"
        ],
        "properties": {
         "audit_id": {
          "type": "integer"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{audit_id, payout_id, status_before, status_after, undone:true}"
     },
     "409": {
      "description": "already_undone | changed_since | in_batch"
     }
    }
   }
  },
  "/api/clients/{id}/bank-status": {
   "get": {
    "tags": [
     "Payouts"
    ],
    "summary": "FD-2 — Banking-tab bank status, LAST 4 ONLY, no Plaid call: Plaid bank / type / holder / last 4s, manual payout account last 4s, match true|false   (scope payouts:read | clients:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{plaid{linked, bank_name, account_type, holder_name, routing_last4, account_last4, fetched_at}, manual_payout_account{bank_name, type, routing_last4, account_last4}, match, why, business_bank{kind, label, verdict, warn}}"
     }
    }
   }
  },
  "/api/clients/{id}/coach-brief": {
   "get": {
    "tags": [
     "Clients"
    ],
    "summary": "ONE read for the coaching / support bot (2026-11-12) — everything a human reads off the profile tabs to answer a client's call: coach + next call, portal login state + URL, training progress, Client Setup checklist, Mercury application + sign-in readiness (no secrets), bank verdict, courtesy payout rate / basis / why-not-receiving / next payout / totals / recent + upcoming rows, reinvestment, processor cards + ZEN, campaign stats + credits. Read-only, DB only, ~2 s. Built from the 331-call question pass over Joshua's coaching calls (docs/BOT_API.md §4a)   (scope clients:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, client{name, first_name, business_name, email, phone, timezone, program{tier,label,license_rate,upgrade_amount}, signup_date, cancelled, on_client_setup_board, stage, setup_progress{done,total}}, coach{name, email, phone, next_booked_call, last_completed_call}, portal{url, login_email, logged_in_ever, login_count, first_login_at, last_login_at, failed_logins_7d, login_stage_done, login_stage_at, company_email, effective_domain, domains[], store{has_store, domain, variation, live, products}}, training{modules_done, modules_total, lessons_completed, current_lesson{name,status}, last_activity_at, module_1_visible, modules[{module_id, order, name, status, progress_pct, lessons_done, lessons_total, avg_score, started_at, completed_at}], rule}, client_setup{next_stage, next_client_stage, open_items[], items[], board_added_at, board_added_by, note}, mercury{application_status: no_application_tracked|application_part1_done|id_verification_done|application_part2_done|account_open_key_vaulted, part1_done_at, id_verification_done_at, part2_done_at, login_on_file, login_email, password_vaulted, authenticator_set, connected_via_api_key, alias_emails[], how_to_sign_in}, bank{plaid{linked, bank_name, holder_category, holder_name, account_last4, routing_last4, fetched_at}, payout_account{bank_name, type, account_last4, routing_last4, on_file}, same_account, business_bank{kind, label, verdict, warn, mode}, payouts_go_to}, courtesy_payouts{rate_pct, rate_is_override, rate_default_pct, basis{license, upgrade, reinvested, total, per_30_days}, receiving, why_not_receiving, held, held_reason, included_by_hand, eligibility{first_sale, last_sale, window_end, in_window, recent_months_rule, has_payout_account}, cycle{start, end, total, rows_paid, rows_planned, due_now, due_count}, next_payout{date, amount}, totals{confirmed, confirmed_count, sent, sent_count, scheduled, scheduled_count, missed, missed_count, paid_total, first_paid_date}, recent[] (last 6), upcoming[] (next 6; payout_id, date, amount, state paid|in_batch|planned|missed, paid_how, note, batch_id, cycle_start, cycle_end), all_rows_count, schedule_rule}, reinvestment{enabled, pct, pct_percent, started_on, set_via, updated_at, overhead_pct, overhead_monthly, daily_expense, avg_deposit, avg_deposit_count, license, upgrade, reinvested, position, courtesy_pct, courtesy_monthly, cycle_days, settle_days, min_amount, example, totals, worker_on, debits_count, recent_debits[], rule}, processors{cards[{id, name, status, kind, tasks_done, tasks_total, open_tasks[]}], count, zen_application{status, application_email, sent_to, submitted_at, approved_at}, note}, campaigns{campaigns[{campaign_id, name, status, active, industry, last_used}], last_7_days{days, messages_sent, leads, cost, cost_per_lead, last_activity_date}, last_30_days{…}, credits_balance, daily_limit, home_scans_30d{homes_scanned, leads}, leads_recorded_30d, note}, see_also{documents, contracts, charges, cards, capital, setup, payout_rows, bank_status, messages, recordings, availability, bookings}, note}"
     },
     "404": {
      "description": "unknown client id"
     }
    }
   }
  },
  "/api/payout-recipients": {
   "get": {
    "tags": [
     "Payouts"
    ],
    "summary": "FD-3 — who is receiving courtesy payouts and who is not, with the note   (scope payouts:read)",
    "parameters": [
     {
      "name": "status",
      "in": "query",
      "schema": {
       "type": "string",
       "enum": [
        "receiving",
        "not_receiving"
       ]
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{recipients[] {client_id, name, email, coach, receiving, note, excluded, excluded_by, excluded_at, standing_include, canceled, next_pay_date, paid_count, paid_total}, count, receiving, not_receiving}"
     }
    }
   }
  },
  "/api/payout-recipients/{client_id}": {
   "post": {
    "tags": [
     "Payouts"
    ],
    "summary": "FD-3 — stop (receiving:false) or resume (receiving:true) one client's courtesy payouts; note required   (scope payouts:write)",
    "parameters": [
     {
      "name": "client_id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "receiving",
         "note"
        ],
        "properties": {
         "receiving": {
          "type": "boolean"
         },
         "note": {
          "type": "string"
         },
         "approved_by": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, name, receiving, receiving_before, note}"
     }
    }
   }
  },
  "/api/payout-batches": {
   "get": {
    "tags": [
     "Payouts"
    ],
    "summary": "FD-4 — the day's payout cells with amount, state and payee last 4   (scope payouts:read)",
    "parameters": [
     {
      "name": "date",
      "in": "query",
      "schema": {
       "type": "string",
       "format": "date"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{date, rows[] {payout_id, client_id, client_name, amount, state, paid_how, paid_note, payee{bank_name, account_last4, routing_last4, type}, payee_last4, batch_id, batch_status}, count, total, paid_total, batch_ids[]}"
     }
    }
   }
  },
  "/api/clients/{id}/charges": {
   "get": {
    "tags": [
     "Payouts"
    ],
    "summary": "FD-5 — every charge for the client + upsell / upgrade totals   (scope payouts:read | clients:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{charges[] {id, transaction_id, amount, sale_type, status, date, merchant, card_last4, refund_amount, setter, closer}, count, upsell_total, front_end_total, refunded_total, upgrade_amount, license_rate, banking_tab_basis}"
     }
    }
   }
  },
  "/api/payroll/weeks/{week_start}": {
   "get": {
    "tags": [
     "Payroll"
    ],
    "summary": "FD-6 — one payroll week: finalized, people, total, rows   (scope payroll:read)",
    "parameters": [
     {
      "name": "week_start",
      "in": "path",
      "required": true,
      "schema": {
       "type": "string",
       "format": "date"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{week_start, finalized, finalized_at, finalized_by, people, total, rows[] {key, name, role, computed, final, paid}, hours:null}"
     }
    }
   }
  },
  "/api/clients/{id}/cancel": {
   "post": {
    "tags": [
     "Payouts"
    ],
    "summary": "FD-7 — cancel a client: off the Client Setup board, courtesy payouts stopped, future planned cells voided, account marked canceled; approved_by REQUIRED; dry-run answers the plan. 2026-11-21: clear_coach:true also unassigns the coach (logged as a coach decision)   (scope payouts:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "approved_by"
        ],
        "properties": {
         "approved_by": {
          "type": "string"
         },
         "reason": {
          "type": "string"
         },
         "clear_coach": {
          "type": "boolean"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{canceled, removed_from_board, payouts_stopped, future_cells_voided, drafted_cells_left_alone, coach_cleared, coach_before, approved_by, reason}"
     },
     "400": {
      "description": "approved_by_required"
     }
    }
   }
  },
  "/api/desk": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Needs-attention desk — the seven queues the modal shows (missed, texts, approved, booking, actions, voice, bank) + counts + which route handles each   (scope desk:read | clients:read)",
    "responses": {
     "200": {
      "description": "{missed[], texts[], approved[], booking[], actions[], voice[], bank[], counts{…}, total, queues[], actions{queue: route}}"
     }
    }
   }
  },
  "/api/desk/{queue}": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "One desk queue   (scope desk:read | clients:read)",
    "parameters": [
     {
      "name": "queue",
      "in": "path",
      "required": true,
      "schema": {
       "type": "string"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{queue, count, items[]}"
     },
     "404": {
      "description": "unknown queue"
     }
    }
   }
  },
  "/api/clients/{id}/voice-notes": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Voice-note thread (in + out) for a client   (scope desk:read | comms:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, name, notes[]}"
     }
    }
   }
  },
  "/api/voice-notes/{id}/heard": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Mark a client voice note heard (desk Voice tab)   (scope desk:write | comms:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "responses": {
     "200": {
      "description": "{voice_note_id, client_id, heard:true | changed:false}"
     }
    }
   }
  },
  "/api/clients/{id}/voice-notes/reply": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Send a voice reply (multipart file, mime, in_reply_to): stored, transcribed, listen link texted; refused sms_opted_out   (scope desk:write | comms:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, id, link, transcript, sms_sent, audio_url}"
     }
    }
   }
  },
  "/api/clients/{id}/onboard-checks": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Onboarding checker view for one client (no fixes run)   (scope desk:read | clients:read | setup:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, results[], log[]}"
     }
    }
   }
  },
  "/api/clients/{id}/onboard-checks/fix": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Desk Fix now / Re-check (check:\"\") / Mark handled (feedback, coachline); Missing-bank tab = check:bank (signed bank letter → payout account). Runs the checker with auto-fix like the page   (scope desk:write | clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "check"
        ],
        "properties": {
         "check": {
          "type": "string",
          "enum": [
           "",
           "coach",
           "type",
           "credits",
           "product",
           "daily",
           "bank",
           "feedback",
           "coachline"
          ]
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, fixed, open[{key,label,detail,action,can_fix}]}; dry run {would_fix, open_flags_now}"
     }
    }
   }
  },
  "/api/clients/{id}/checklist": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Profile Checklist tab — per-client step state   (scope clients:read | setup:read | desk:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, steps[], cabana…}"
     }
    }
   }
  },
  "/api/checklist-template": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Every checklist step key (for POST /api/clients/{id}/checklist/{key})   (scope clients:read | setup:read | desk:read)",
    "responses": {
     "200": {
      "description": "{items[{key,label,note,client_hidden,phase,sort_order}], count}"
     }
    }
   }
  },
  "/api/clients/{id}/checklist/{key}": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Tick / untick / void a checklist step (desk Approved MIDs → Mark set up uses done:true)   (scope desk:write | clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "key",
      "in": "path",
      "required": true,
      "schema": {
       "type": "string"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "done": {
          "type": "boolean"
         },
         "voided": {
          "type": "boolean"
         },
         "note": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, key, label, steps, cabana}; dry run {would_set: done|owed|voided}"
     },
     "404": {
      "description": "unknown key — see /api/checklist-template"
     }
    }
   }
  },
  "/api/clients/{id}/client-setup": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Add to / remove from the Client Setup board   (scope desk:write | clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         true
        ],
        "properties": {
         "true": {
          "type": "boolean"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, on_board, changed}"
     }
    }
   }
  },
  "/api/calendar/events": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Coach calendar month grid — every coach's Google Calendar events   (scope calendar:read | bookings:read)",
    "parameters": [
     {
      "name": "month",
      "in": "query",
      "schema": {
       "type": "string"
      }
     },
     {
      "name": "coach",
      "in": "query",
      "schema": {
       "type": "string"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{month, events[{event_id, coach, title, date, start, end, description, all_day}], coaches[], edit_calendars[], count}"
     }
    }
   },
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "The page's + Add — a Google Calendar block on a coach's calendar (not a client call; book those with POST /api/bookings)   (scope calendar:write | bookings:write)",
    "parameters": [
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "coach",
         "title",
         "date"
        ],
        "properties": {
         "coach": {
          "type": "string"
         },
         "title": {
          "type": "string"
         },
         "date": {
          "type": "string",
          "format": "date"
         },
         "start": {
          "type": "string",
          "example": "09:00"
         },
         "end": {
          "type": "string",
          "example": "10:00"
         },
         "description": {
          "type": "string"
         },
         "all_day": {
          "type": "boolean"
         },
         "repeat": {
          "type": "string",
          "enum": [
           "",
           "daily",
           "weekly",
           "biweekly",
           "monthly"
          ]
         },
         "repeat_until": {
          "type": "string",
          "format": "date"
         },
         "repeat_count": {
          "type": "integer"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{event_id, coach, title, date, start, end, all_day, recurring}"
     },
     "404": {
      "description": "unknown coach"
     },
     "409": {
      "description": "coach_no_calendar"
     }
    }
   }
  },
  "/api/calendar/day": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "One coach's busy slots for a day (the Schedule-Next-Call timeline)   (scope calendar:read | bookings:read)",
    "parameters": [
     {
      "name": "coach",
      "in": "query",
      "schema": {
       "type": "string"
      }
     },
     {
      "name": "date",
      "in": "query",
      "schema": {
       "type": "string",
       "format": "date"
      }
     },
     {
      "name": "phase2",
      "in": "query",
      "schema": {
       "type": "string"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{coach, date, busy_slots[{start,end,title}]}"
     }
    }
   }
  },
  "/api/calendar/shares": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Calendar shares (read only) — who shares a calendar with whom, straight from calendar_shares; ?coach= filters on owner or recipient   (scope calendar:read | bookings:read)",
    "parameters": [
     {
      "name": "coach",
      "in": "query",
      "schema": {
       "type": "string"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{shares[{owner_coach, shared_with, can_edit, shared_by, created_at}], count}"
     }
    }
   }
  },
  "/api/coaches-list": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Coach roster for coach / calendar writes   (scope calendar:read | bookings:read | clients:read)",
    "responses": {
     "200": {
      "description": "{coaches[{id, name, email, phone, role, rc_extension, restricted, intro_calls, phase2_calls, assignable, has_calendar}], count}"
     }
    }
   }
  },
  "/api/coaches-list/{id}/assignable": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Coach list switch — false = only a super admin can assign / book this person on the admin pages   (scope clients:write | calendar:write)",
    "description": "POST /api/bookings is intentionally NOT gated by this switch (the dialer books leads with Michael whatever his switch says). Assigning a switched-off coach through the page routes answers 403. Errors: 404 coach_not_found, 400 invalid_body.",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "description": "coach id or name",
      "schema": {
       "type": "string"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "assignable"
        ],
        "properties": {
         "assignable": {
          "type": "boolean"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{coach_id, coach, assignable, was_assignable}; dry run {would_set_assignable, assignable_now}"
     },
     "404": {
      "description": "{ok:false, status:error, code:coach_not_found, message}"
     }
    }
   }
  },
  "/api/clients/filter": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "The clients page list narrowed by the page's filters   (scope clients:read | payouts:read)",
    "description": "THE LIST is exactly what the clients page shows: active client accounts (advertiser, pro, pro plus, starter, preset) with a license of $1,000 or more, or $1,000 or more of approved / authorized payments, plus every preset. 1,132 rows on 2026-11-27. It includes $0 presets, clients with no coach, and canceled clients (the page keeps them in its own Canceled group — `canceled` on each row, ?canceled=false to leave them out). Default sort is name. Dates are YYYY-MM-DD, Pacific, both ends inclusive. `next_call` is the next-call date on the client's profile (users.next_call): written when a call is booked and never cleared, so it can be in the past and the call may since have been completed, missed or cancelled; null when no call was ever booked. It is NOT next_booked_call on GET /api/clients/{id}, which is the next still-scheduled call from now. `coach=unassigned` matches every client with no coach, whether stored blank or as the word Unassigned (rows return the stored value). Unknown parameters and out-of-range values answer 400 with a code: unknown_parameter, invalid_date, invalid_financed, invalid_canceled, invalid_amount, invalid_sort, invalid_limit, invalid_offset. Rows carry no phone or e-mail.",
    "parameters": [
     {
      "name": "created_from",
      "in": "query",
      "description": "account created on or after (Pacific)",
      "schema": {
       "type": "string",
       "format": "date"
      }
     },
     {
      "name": "created_to",
      "in": "query",
      "description": "account created on or before (Pacific)",
      "schema": {
       "type": "string",
       "format": "date"
      }
     },
     {
      "name": "next_call_from",
      "in": "query",
      "description": "profile next-call date on or after",
      "schema": {
       "type": "string",
       "format": "date"
      }
     },
     {
      "name": "next_call_to",
      "in": "query",
      "description": "profile next-call date on or before",
      "schema": {
       "type": "string",
       "format": "date"
      }
     },
     {
      "name": "coach",
      "in": "query",
      "description": "coach name (case-insensitive), or unassigned = blank or the word Unassigned",
      "schema": {
       "type": "string"
      }
     },
     {
      "name": "financed",
      "in": "query",
      "description": "true | false | 1 | 0 — anything else is 400 invalid_financed",
      "schema": {
       "type": "boolean"
      }
     },
     {
      "name": "canceled",
      "in": "query",
      "description": "true | false | 1 | 0; omitted = canceled clients are included",
      "schema": {
       "type": "boolean"
      }
     },
     {
      "name": "amount_min",
      "in": "query",
      "description": "license rate + upgrade amount, dollars, at least",
      "schema": {
       "type": "number",
       "minimum": 0
      }
     },
     {
      "name": "amount_max",
      "in": "query",
      "description": "license rate + upgrade amount, dollars, at most",
      "schema": {
       "type": "number",
       "minimum": 0
      }
     },
     {
      "name": "sort",
      "in": "query",
      "schema": {
       "type": "string",
       "enum": [
        "name",
        "created_desc",
        "created_asc"
       ],
       "default": "name"
      }
     },
     {
      "name": "limit",
      "in": "query",
      "description": "1 to 500; 0, negative, 501+ or not a number is 400 invalid_limit",
      "schema": {
       "type": "integer",
       "minimum": 1,
       "maximum": 500,
       "default": 100
      }
     },
     {
      "name": "offset",
      "in": "query",
      "schema": {
       "type": "integer",
       "minimum": 0,
       "default": 0
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{clients[{client_id, name, tier, coach, created_on, next_call (date | null), license_rate, upgrade_amount, deal_amount, financed, net_pct (number | null), canceled}], count, total, limit, offset, sort, filters}"
     },
     "400": {
      "description": "{ok:false, status:error, code, message}"
     }
    }
   }
  },
  "/api/clients/{id}/financed": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Is this client financed   (scope clients:read | payouts:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "Always {client_id, financed, net_pct, updated_by, updated_at}. net_pct, updated_by and updated_at are null when the flag has never been set; updated_at is ISO 8601 with the Pacific offset."
     },
     "404": {
      "description": "{ok:false, status:error, code:client_not_found, message}"
     },
     "400": {
      "description": "code not_a_client (a staff login)"
     }
    }
   },
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Mark a client financed / not financed — the same mark as the profile switch, the pay form tick and the lead reports   (scope clients:write | payouts:write)",
    "description": "financed:false also clears the pay form's Financed tick on the client's transactions, so the next payment event does not mark them financed again. A dry run shows it: would_clear_payform_ticks (boolean) + payform_ticks (how many transactions carry the tick).",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "financed"
        ],
        "properties": {
         "financed": {
          "type": "boolean"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, financed, net_pct, updated_by, updated_at, was_financed}; dry run {would_set_financed, financed_now} and, for financed:false, {would_clear_payform_ticks, payform_ticks}"
     },
     "400": {
      "description": "code invalid_body"
     },
     "404": {
      "description": "code client_not_found"
     }
    }
   }
  },
  "/api/calendar/events/{event_id}/delete": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Delete Event — removes the Google event and cancels the linked client call if it is still scheduled (dry run: would_cancel_client_call | linked_call_left_as_is)   (scope calendar:write | bookings:write)",
    "parameters": [
     {
      "name": "event_id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "string"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "coach"
        ],
        "properties": {
         "coach": {
          "type": "string",
          "description": "a coach name, or \"\" / Unassigned to clear"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{logs_canceled}; dry run {would_delete_google_event, would_cancel_client_call{…}}"
     }
    }
   }
  },
  "/api/calendar/events/{event_id}/mark-missed": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "⚠ Missed — the linked booked client call → missed (no-show)   (scope calendar:write | bookings:write)",
    "parameters": [
     {
      "name": "event_id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "string"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "responses": {
     "200": {
      "description": "{next_call_id, client_id, coach}; dry run {would_set_status: missed}"
     },
     "404": {
      "description": "no_linked_call"
     },
     "409": {
      "description": "not_scheduled"
     }
    }
   }
  },
  "/api/clients/{id}/call-history": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Profile Call History — every next_call_logs row, newest first (booking_id = ncl-<id> for the bookings routes)   (scope calendar:read | bookings:read | clients:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "limit",
      "in": "query",
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "offset",
      "in": "query",
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, calls[{next_call_id, booking_id, date, time_pt, duration, status, coach, calendar_event_id, source, created_at}], count, statuses[]}"
     }
    }
   }
  },
  "/api/clients/{id}/call-history/{log_id}/status": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Call History status dropdown   (scope calendar:write | bookings:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "log_id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "status"
        ],
        "properties": {
         "status": {
          "type": "string",
          "enum": [
           "scheduled",
           "completed",
           "missed",
           "canceled",
           "rescheduled"
          ]
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, next_call_id, status | changed:false}"
     }
    }
   }
  },
  "/api/clients/{id}/call-history/{log_id}/cancel": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Call History row delete — the page's /delete-next-call-log (any status; removes the Google event); checks the call belongs to the client   (scope calendar:write | bookings:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "log_id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "reason": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, next_call_id, status_before, would_set_status canceled, would_remove_calendar_event | changed:false}"
     }
    }
   }
  },
  "/api/sms/threads/{client_id}/reply": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "The desk's Reply on an unread text — the page's /api/hcs/sms-inbox/reply: one Boundless SMS (opt-out gated), mirrored to the dashboard thread, pending check-in relays closed, thread marked read   (scope comms:write | desk:write)",
    "parameters": [
     {
      "name": "client_id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "text"
        ],
        "properties": {
         "text": {
          "type": "string"
         },
         "contact": {
          "type": "string",
          "description": "E.164 phone of the thread; default the client's phone"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, contact, messages[] | would_send, would_close_relays, would_mark_read}"
     },
     "403": {
      "description": "sms_opted_out"
     },
     "400": {
      "description": "brand_violation"
     }
    }
   }
  },
  "/api/clients/{id}/merchants/companies": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Merchants tab entity picker — the client's existing companies   (scope clients:read | setup:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{companies[]}"
     }
    }
   }
  },
  "/api/merchants/registry": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Add-transaction modal → add a merchant / licensor entity to the shared registry (bizop.pay_merchants upsert)   (scope clients:write | payouts:write)",
    "parameters": [
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "name"
        ],
        "properties": {
         "name": {
          "type": "string"
         },
         "address": {
          "type": "string"
         },
         "entity_type": {
          "type": "string"
         },
         "state": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{id, name | would_upsert_merchant, exists_already}"
     }
    }
   }
  },
  "/api/payouts/board": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "The whole /hcs/payments grid: people × pay dates, ranges, due-next total (same side effects as opening the page)   (scope payouts:read)",
    "parameters": [
     {
      "name": "client_id",
      "in": "query",
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "status",
      "in": "query",
      "schema": {
       "type": "string"
      }
     },
     {
      "name": "receiving",
      "in": "query",
      "schema": {
       "type": "boolean"
      }
     },
     {
      "name": "q",
      "in": "query",
      "schema": {
       "type": "string"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{as_of, next_pay_date, dates[], pct, range_pct_lo, range_pct_hi, people[{client_id, user_id, name, email, tier, status, receiving, included, base, license, upgrade, reinvest, range_lo, range_hi, pct, cycle_start, cycle_end, cycle_total, paid_total, payments[{id, pay_date, amount, state, paid_how, batch_id, note}]}], receiving, not_receiving, due_next_total, people_count}"
     }
    }
   }
  },
  "/api/payouts/{id}/undo-paid": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "The grid's Undo on a manually-paid cell (paid → planned) by schedule id   (scope payouts:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "note": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{payout_id, client_id, pay_date, amount, message}"
     },
     "409": {
      "description": "not_paid | paid_by_batch"
     }
    }
   }
  },
  "/api/payout-recipients/exclusions": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Standing exclusions (who was removed, why, by whom) + standing includes   (scope payouts:read)",
    "responses": {
     "200": {
      "description": "{exclusions[], includes[{client_id, name, reason, by, since}]}"
     }
    }
   }
  },
  "/api/payout-recipients/{client_id}/action": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "The page's Remove (exclude) / Add back (add_back — restores the struck rows) / Add (include — waives the recent-transaction rule) / uninclude   (scope payouts:write)",
    "parameters": [
     {
      "name": "client_id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "action"
        ],
        "properties": {
         "action": {
          "type": "string",
          "enum": [
           "exclude",
           "add_back",
           "include",
           "uninclude",
           "add",
           "remove"
          ],
          "description": "add / remove keep the PAGE's meaning (add = exclude, remove = add back)"
         },
         "note": {
          "type": "string",
          "description": "optional like the page"
         },
         "approved_by": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, name, action, message, restored}; dry run {would, rows_to_restore}"
     },
     "409": {
      "description": "not_excluded"
     }
    }
   }
  },
  "/api/clients/{id}/payout-schedule": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Every scheduled cell for the person (last 90 days + future) + cycle summary   (scope payouts:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, rows[], summary{…}}"
     }
    }
   },
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "replan = re-spread the open cycle on the current basis + rate; regenerate = fresh 30-day cycle from the next pay day   (scope payouts:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "action"
        ],
        "properties": {
         "action": {
          "type": "string",
          "enum": [
           "replan",
           "regenerate"
          ]
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, …}; dry run {basis, rate_pct, per_30_days, planned_rows_now, new_cycle_dates[]}"
     }
    }
   }
  },
  "/api/clients/{id}/payout-rate": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "The person's courtesy rate (override or default), basis, per-30-days, the 5–7 % range   (scope payouts:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, rate_pct, rate_is_override, default_pct, set_by, set_at, basis, license_rate, upgrade_amount, per_30_days, range{lo_pct, hi_pct, lo, hi}}"
     }
    }
   },
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Overview → Finances Courtesy Payout Rate: percent (3.5); null / 0 clears the override; a changed rate re-plans the open cycle   (scope payouts:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "pct"
        ],
        "properties": {
         "pct": {
          "type": "number",
          "nullable": true
         },
         "approved_by": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{courtesy_pct, courtesy_replanned}; dry run {rate_pct_before, would_set_rate_pct, per_30_days_before, per_30_days_after, would_replan}"
     }
    }
   }
  },
  "/api/clients/{id}/payouts-tab": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Profile Payouts tab (schedule strip, confirmed deposits, store products, plan model)   (scope payouts:read | clients:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, …the tab payload}"
     }
    }
   }
  },
  "/api/clients/{id}/overview": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Header + Overview: contact, business, addresses, sales, finances, KPIs; editable{…} = current values of every field the write routes change   (scope clients:read | setup:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, name, …the tab payload (scrubbed)}"
     }
    }
   }
  },
  "/api/clients/{id}/campaigns": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Campaigns tab: metrics + geo_campaigns   (scope clients:read | setup:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, name, …the tab payload (scrubbed)}"
     }
    }
   }
  },
  "/api/clients/{id}/credit-ledger": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Marketing credits ledger   (scope clients:read | setup:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, name, …the tab payload (scrubbed)}"
     }
    }
   }
  },
  "/api/clients/{id}/merchants": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Merchants tab (processor cards, tasks, entity — keys / logins scrubbed)   (scope clients:read | setup:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, name, …the tab payload (scrubbed)}"
     }
    }
   },
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Merchants: start a processor card   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "name"
        ],
        "properties": {
         "name": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, name, …the page answer}; dry run {would_*, would_call}"
     }
    }
   }
  },
  "/api/clients/{id}/tickets": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Tickets tab   (scope clients:read | setup:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, name, …the tab payload (scrubbed)}"
     }
    }
   },
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Create a ticket   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "title"
        ],
        "properties": {
         "title": {
          "type": "string"
         },
         "description": {
          "type": "string"
         },
         "assigned_coach": {
          "type": "string"
         },
         "priority": {
          "type": "string"
         },
         "due_date": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, name, …the page answer}; dry run {would_*, would_call}"
     }
    }
   }
  },
  "/api/clients/{id}/funding-apps": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Financing Applications (scope also cards:read)   (scope clients:read | setup:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, name, …the tab payload (scrubbed)}"
     }
    }
   },
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Financing Applications: add (no id) / edit (id)   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "kind"
        ],
        "properties": {
         "id": {
          "type": "integer"
         },
         "issuer": {
          "type": "string"
         },
         "kind": {
          "type": "string",
          "enum": [
           "credit_card",
           "loan",
           "line_of_credit",
           "existing_funds",
           "other"
          ]
         },
         "amount": {
          "type": "number"
         },
         "stage": {
          "type": "string"
         },
         "event_date": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, name, …the page answer}; dry run {would_*, would_call}"
     }
    }
   }
  },
  "/api/clients/{id}/card-power": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Card Power (scope also cards:read)   (scope clients:read | setup:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, name, …the tab payload (scrubbed)}"
     }
    }
   }
  },
  "/api/clients/{id}/bank-profile": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Business bank card (mercury / relay / external verdict)   (scope clients:read | payouts:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, name, …the tab payload (scrubbed)}"
     }
    }
   },
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Business bank card: Save (mercury / relay / external) or Back to auto-detect (\"\") (scope also payouts:write)   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "bank_kind": {
          "type": "string",
          "enum": [
           "",
           "mercury",
           "relay",
           "external"
          ]
         },
         "bank_name": {
          "type": "string"
         },
         "note": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, name, …the page answer}; dry run {would_*, would_call}"
     }
    }
   }
  },
  "/api/clients/{id}/bank-info": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Bank account (Plaid) card, numbers masked to last 4; ?refresh=1 re-pulls   (scope clients:read | payouts:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "refresh",
      "in": "query",
      "schema": {
       "type": "string"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, name, …the tab payload (scrubbed)}"
     }
    }
   }
  },
  "/api/clients/{id}/banking": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Bank statements & cash flow ledger (?month=YYYY-MM for one month, ?refresh=1 syncs)   (scope clients:read | payouts:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "month",
      "in": "query",
      "schema": {
       "type": "string"
      }
     },
     {
      "name": "refresh",
      "in": "query",
      "schema": {
       "type": "string"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, name, …the tab payload (scrubbed)}"
     }
    }
   }
  },
  "/api/clients/{id}/plaid-transactions": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Plaid bank transactions (?days=30)   (scope clients:read | payouts:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "days",
      "in": "query",
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, name, …the tab payload (scrubbed)}"
     }
    }
   }
  },
  "/api/clients/{id}/mercury": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Mercury live balance + recent transactions from the vaulted key (?refresh=1)   (scope clients:read | payouts:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "refresh",
      "in": "query",
      "schema": {
       "type": "string"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, name, …the tab payload (scrubbed)}"
     }
    }
   }
  },
  "/api/clients/{id}/reinvest": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Reinvestment plan card   (scope clients:read | payouts:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, name, …the tab payload (scrubbed)}"
     }
    }
   }
  },
  "/api/clients/{id}/credentials": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Credentials vault — labels / kinds / URLs only, never the secrets   (scope clients:read | setup:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, name, …the tab payload (scrubbed)}"
     }
    }
   }
  },
  "/api/clients/{id}/zen-application": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "ZEN merchant application (answers, docs, status)   (scope clients:read | setup:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, name, …the tab payload (scrubbed)}"
     }
    }
   },
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "ZEN application: save answers {key: value}   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "answers"
        ],
        "properties": {
         "answers": {
          "type": "object"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, name, …the page answer}; dry run {would_*, would_call}"
     }
    }
   }
  },
  "/api/clients/{id}/bank-statements": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Statement-collection link state   (scope clients:read | setup:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, name, …the tab payload (scrubbed)}"
     }
    }
   }
  },
  "/api/clients/{id}/training": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Training quizzes (modules are in coach-brief.training)   (scope clients:read | setup:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, name, …the tab payload (scrubbed)}"
     }
    }
   }
  },
  "/api/clients/{id}/shares": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Shared access   (scope clients:read | setup:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, name, …the tab payload (scrubbed)}"
     }
    }
   },
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Share access with a coach   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "coach_name"
        ],
        "properties": {
         "coach_name": {
          "type": "string"
         },
         "duration_hours": {
          "type": "integer"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, name, …the page answer}; dry run {would_*, would_call}"
     }
    }
   }
  },
  "/api/clients/{id}/domains": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Company domains   (scope clients:read | setup:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, name, …the tab payload (scrubbed)}"
     }
    }
   }
  },
  "/api/clients/{id}/company-inbox": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Company-alias inboxes (?alias=, ?message_id= for one message) (scope also comms:read)   (scope clients:read | setup:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "alias",
      "in": "query",
      "schema": {
       "type": "string"
      }
     },
     {
      "name": "message_id",
      "in": "query",
      "schema": {
       "type": "string"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, name, …the tab payload (scrubbed)}"
     }
    }
   }
  },
  "/api/clients/{id}/admin-docs": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Admin-only documents   (scope clients:read | documents:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, name, …the tab payload (scrubbed)}"
     }
    }
   }
  },
  "/api/clients/{id}/client-docs": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Portal (client-visible) documents   (scope clients:read | documents:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, name, …the tab payload (scrubbed)}"
     }
    }
   }
  },
  "/api/clients/{id}/transactions": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Payment transactions tab (ledger rows)   (scope clients:read | payouts:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, name, …the tab payload (scrubbed)}"
     }
    }
   },
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Payment transactions: log a manual transaction (scope payouts:write); approved_by REQUIRED   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "amount",
         "sale_type",
         "method",
         "approved_by"
        ],
        "properties": {
         "amount": {
          "type": "number"
         },
         "sale_type": {
          "type": "string",
          "enum": [
           "front-end",
           "upsell"
          ]
         },
         "method": {
          "type": "string",
          "enum": [
           "cash",
           "wire",
           "check",
           "zelle",
           "venmo",
           "crypto",
           "other"
          ]
         },
         "extra": {
          "type": "boolean"
         },
         "reference": {
          "type": "string"
         },
         "date": {
          "type": "string"
         },
         "setter": {
          "type": "string"
         },
         "closer": {
          "type": "string"
         },
         "merchant": {
          "type": "string"
         },
         "card_last4": {
          "type": "string"
         },
         "approved_by": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, name, …the page answer}; dry run {would_*, would_call}"
     }
    }
   }
  },
  "/api/clients/{id}/pro-pipeline": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Pro Pipeline stage   (scope clients:read | setup:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, name, …the tab payload (scrubbed)}"
     }
    }
   },
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Pro Pipeline stage (0 removes)   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "stage_id"
        ],
        "properties": {
         "stage_id": {
          "type": "integer"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, name, …the page answer}; dry run {would_*, would_call}"
     }
    }
   }
  },
  "/api/clients/{id}/upgrade-history": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Upgrade history   (scope clients:read | setup:read)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, name, …the tab payload (scrubbed)}"
     }
    }
   }
  },
  "/api/transactions/options": {
   "get": {
    "tags": [
     "Page parity"
    ],
    "summary": "Setters / closers + merchant registry + allowed sale types / methods / editable fields for ledger writes   (scope clients:read | payouts:read)",
    "responses": {
     "200": {
      "description": "{sale_types[], methods[], editable_fields[], sales_reps, merchants}"
     }
    }
   }
  },
  "/api/clients/{id}/profile": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Save Profile — partial update of name, email, phone, address, business_phone, physical_address{street,street2,city,state,zip}   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "name": {
          "type": "string"
         },
         "email": {
          "type": "string"
         },
         "phone": {
          "type": "string"
         },
         "address": {
          "type": "string",
          "description": "at least 'street, city'; a US state in the last part sets users.state"
         },
         "funding_available": {
          "type": "integer"
         },
         "business_phone": {
          "type": "string"
         },
         "physical_address": {
          "type": "object"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, name, …the page answer}; dry run {would_*, would_call}"
     }
    }
   }
  },
  "/api/clients/{id}/coach": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Assigned coach   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "coach"
        ],
        "properties": {
         "coach": {
          "type": "string",
          "description": "a coach name, or \"\" / Unassigned to clear"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, name, …the page answer}; dry run {would_*, would_call}"
     }
    }
   }
  },
  "/api/clients/{id}/pipeline-stage": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Sales card: pipeline stage (rotation_schedule)   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "stage"
        ],
        "properties": {
         "stage": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, name, …the page answer}; dry run {would_*, would_call}"
     }
    }
   }
  },
  "/api/clients/{id}/anxiety": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Anxiety level   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "level"
        ],
        "properties": {
         "level": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, name, …the page answer}; dry run {would_*, would_call}"
     }
    }
   }
  },
  "/api/clients/{id}/user-type": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "User type   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "user_type"
        ],
        "properties": {
         "user_type": {
          "type": "string",
          "enum": [
           "advertiser",
           "advertiser_pro",
           "advertiser_pro_plus",
           "starter",
           "contractor"
          ]
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, name, …the page answer}; dry run {would_*, would_call}"
     }
    }
   }
  },
  "/api/clients/{id}/skip-restriction": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Restriction Active (false) / Skip (true)   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "skip"
        ],
        "properties": {
         "skip": {
          "type": "boolean"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, name, …the page answer}; dry run {would_*, would_call}"
     }
    }
   }
  },
  "/api/clients/{id}/rates": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Finances card: license_rate / upgrade_amount (re-plans the courtesy cycle) (scope also payouts:write)   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "license_rate": {
          "type": "number"
         },
         "upgrade_amount": {
          "type": "number"
         },
         "approved_by": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, name, …the page answer}; dry run {would_*, would_call}"
     }
    }
   }
  },
  "/api/clients/{id}/credits": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Marketing credits ± (signed amount)   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "amount"
        ],
        "properties": {
         "amount": {
          "type": "number"
         },
         "approved_by": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, name, …the page answer}; dry run {would_*, would_call}"
     }
    }
   }
  },
  "/api/clients/{id}/sending-limit": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Sending limit   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "limit"
        ],
        "properties": {
         "limit": {
          "type": "integer"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, name, …the page answer}; dry run {would_*, would_call}"
     }
    }
   }
  },
  "/api/clients/{id}/business-name": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Business name   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "business_name"
        ],
        "properties": {
         "business_name": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, name, …the page answer}; dry run {would_*, would_call}"
     }
    }
   }
  },
  "/api/clients/{id}/portal-email": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Company Email (member portal) alias; empty = automatic   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "alias": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, name, …the page answer}; dry run {would_*, would_call}"
     }
    }
   }
  },
  "/api/clients/{id}/domains/primary": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Company Domains: pin the primary domain; empty = automatic   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "domain": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, name, …the page answer}; dry run {would_*, would_call}"
     }
    }
   }
  },
  "/api/clients/{id}/domains/site": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Company Domains: store / reseller site on a domain   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "domain",
         "kind"
        ],
        "properties": {
         "domain": {
          "type": "string"
         },
         "kind": {
          "type": "string",
          "enum": [
           "store",
           "reseller"
          ]
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, name, …the page answer}; dry run {would_*, would_call}"
     }
    }
   }
  },
  "/api/clients/{id}/set-password": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "🔑 Set portal password (blank = generated); the password is returned ONLY with reveal:true (audited)   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "password": {
          "type": "string"
         },
         "reveal": {
          "type": "boolean"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, name, …the page answer}; dry run {would_*, would_call}"
     }
    }
   }
  },
  "/api/clients/{id}/contact-reviewed": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Clear the 📨 reached-out flag   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, name, …the page answer}; dry run {would_*, would_call}"
     }
    }
   }
  },
  "/api/clients/{id}/cancel-attempt": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Cancel attempt — texts the closer + opens a Cancel-Save (approved_by)   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "approved_by": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, name, …the page answer}; dry run {would_*, would_call}"
     }
    }
   }
  },
  "/api/clients/{id}/meet": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Create a Google Meet link for the client   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, name, …the page answer}; dry run {would_*, would_call}"
     }
    }
   }
  },
  "/api/clients/{id}/shares/remove": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Remove a share   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "coach_name"
        ],
        "properties": {
         "coach_name": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, name, …the page answer}; dry run {would_*, would_call}"
     }
    }
   }
  },
  "/api/clients/{id}/training/force-complete": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Training: Force Complete & Unlock Next   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "module_id"
        ],
        "properties": {
         "module_id": {
          "type": "integer"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, name, …the page answer}; dry run {would_*, would_call}"
     }
    }
   }
  },
  "/api/clients/{id}/training/regrade": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Training: Regrade   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "module_item_id"
        ],
        "properties": {
         "module_item_id": {
          "type": "integer"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, name, …the page answer}; dry run {would_*, would_call}"
     }
    }
   }
  },
  "/api/clients/{id}/training/review-quiz": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Training: Pass / Fail a quiz   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "quiz_id",
         "pass"
        ],
        "properties": {
         "quiz_id": {
          "type": "integer"
         },
         "pass": {
          "type": "boolean"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, name, …the page answer}; dry run {would_*, would_call}"
     }
    }
   }
  },
  "/api/clients/{id}/card-power/pull": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Card Power Pull / Re-pull — one paid SimpleCheck pull; approved_by REQUIRED   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "approved_by"
        ],
        "properties": {
         "force": {
          "type": "boolean"
         },
         "approved_by": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, name, …the page answer}; dry run {would_*, would_call}"
     }
    }
   }
  },
  "/api/clients/{id}/bank-statements/link": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Create the bank-statements collection link; send_sms:true texts it (scope also comms:write)   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "send_sms": {
          "type": "boolean"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, name, …the page answer}; dry run {would_*, would_call}"
     }
    }
   }
  },
  "/api/clients/{id}/document-status": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Document status   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "document_name",
         "status"
        ],
        "properties": {
         "document_name": {
          "type": "string"
         },
         "status": {
          "type": "string",
          "enum": [
           "pending",
           "sent",
           "signed",
           "approved",
           "rejected"
          ]
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, name, …the page answer}; dry run {would_*, would_call}"
     }
    }
   }
  },
  "/api/clients/{id}/contracts/send": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Send a contract: txn_auth | svc_fulfillment | both | cancellation (+sale_type_filter all|upsell|front-end) | upgrade (+upgrade_amount, contract_type pro_plus|platinum) | signature (+document_name)   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "doc"
        ],
        "properties": {
         "doc": {
          "type": "string",
          "enum": [
           "txn_auth",
           "svc_fulfillment",
           "both",
           "cancellation",
           "upgrade",
           "signature"
          ]
         },
         "sale_type_filter": {
          "type": "string"
         },
         "upgrade_amount": {
          "type": "number"
         },
         "contract_type": {
          "type": "string"
         },
         "document_name": {
          "type": "string"
         },
         "approved_by": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, name, …the page answer}; dry run {would_*, would_call}"
     }
    }
   }
  },
  "/api/clients/{id}/fetch-docs": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Fetch signed documents (DocuSign completions from Gmail)   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, name, …the page answer}; dry run {would_*, would_call}"
     }
    }
   }
  },
  "/api/clients/{id}/company-email/send": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Comms composer: send AS the client's company alias (scope comms:write)   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "from_alias",
         "to",
         "subject",
         "body"
        ],
        "properties": {
         "from_alias": {
          "type": "string"
         },
         "to": {
          "type": "string"
         },
         "subject": {
          "type": "string"
         },
         "body": {
          "type": "string"
         },
         "doc_ids": {
          "type": "array",
          "items": {
           "type": "integer"
          }
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, name, …the page answer}; dry run {would_*, would_call}"
     }
    }
   }
  },
  "/api/clients/{id}/notes/{note_id}/delete": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Delete a note   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "note_id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "responses": {
     "200": {
      "description": "{client_id, deleted}"
     }
    }
   }
  },
  "/api/clients/{id}/tickets/{ticket_id}": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Update a ticket (status, priority, assigned_coach, due_date, title, description)   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "ticket_id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "status": {
          "type": "string"
         },
         "priority": {
          "type": "string"
         },
         "assigned_coach": {
          "type": "string"
         },
         "due_date": {
          "type": "string"
         },
         "title": {
          "type": "string"
         },
         "description": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, ticket_id, …}"
     }
    }
   }
  },
  "/api/clients/{id}/tickets/{ticket_id}/notes": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Add a ticket note   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "ticket_id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "note"
        ],
        "properties": {
         "note": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{client_id, ticket_id, …}"
     }
    }
   }
  },
  "/api/clients/{id}/merchants/{pid}/status": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Mark approved / back to pending   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "pid",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "status"
        ],
        "properties": {
         "status": {
          "type": "string",
          "enum": [
           "approved",
           "pending"
          ]
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{processor_id, status_before, …}"
     }
    }
   }
  },
  "/api/clients/{id}/merchants/{pid}/delete": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Delete a processor card   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "pid",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "responses": {
     "200": {
      "description": "{processor_id, …}"
     }
    }
   }
  },
  "/api/clients/{id}/merchants/{pid}/entity": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Set the entity on a processor card   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "pid",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "name": {
          "type": "string"
         },
         "address": {
          "type": "string"
         },
         "entity_type": {
          "type": "string"
         },
         "state": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{processor, …}"
     }
    }
   }
  },
  "/api/clients/{id}/merchants/{pid}/tasks": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Add (no task_id) / rename (task_id) a task step   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "pid",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "label"
        ],
        "properties": {
         "label": {
          "type": "string"
         },
         "task_type": {
          "type": "string"
         },
         "task_id": {
          "type": "integer"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{processor, …}"
     }
    }
   }
  },
  "/api/clients/{id}/merchants/tasks/{tid}": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Task ○/✓   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "tid",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "done"
        ],
        "properties": {
         "done": {
          "type": "boolean"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{task_id, done_before, …}"
     }
    }
   }
  },
  "/api/clients/{id}/merchants/tasks/{tid}/delete": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Delete a task step   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "tid",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "responses": {
     "200": {
      "description": "{task_id, …}"
     }
    }
   }
  },
  "/api/clients/{id}/merchants/tasks/{tid}/request-doc": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Text the client an upload link for a doc task; refused sms_opted_out   (scope clients:write | comms:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "tid",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "responses": {
     "200": {
      "description": "{task_id, …}"
     }
    }
   }
  },
  "/api/clients/{id}/funding-apps/{aid}/delete": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Delete a financing application   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "aid",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "responses": {
     "200": {
      "description": "{…}"
     }
    }
   }
  },
  "/api/clients/{id}/documents/{doc_id}/delete": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Delete a portal (regular) or admin-only document   (scope clients:write | documents:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "doc_id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "section": {
          "type": "string",
          "enum": [
           "regular",
           "admin_only"
          ]
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{…}"
     }
    }
   }
  },
  "/api/clients/{id}/zen-application/{action}": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "ZEN: request-doc {doc_type} · generate-pdf · auto-attach · reopen · ai-prefill · generate-agreement (send-for-approval stays on the page)   (scope clients:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "action",
      "in": "path",
      "required": true,
      "schema": {
       "type": "string"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "doc_type": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{…}"
     }
    }
   }
  },
  "/api/transactions/{tid}": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Edit one ledger field: sale_type | setter | closer | merchant | card_last4   (scope payouts:write)",
    "parameters": [
     {
      "name": "tid",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "field",
         "value"
        ],
        "properties": {
         "field": {
          "type": "string",
          "enum": [
           "sale_type",
           "setter",
           "closer",
           "merchant",
           "card_last4"
          ]
         },
         "value": {
          "type": "string"
         },
         "approved_by": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{transaction_id, field, value_before, …}"
     }
    }
   }
  },
  "/api/transactions/{tid}/date": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Edit the sale date (split parts follow; audited in hcs_transaction_edits)   (scope payouts:write)",
    "parameters": [
     {
      "name": "tid",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "created_at"
        ],
        "properties": {
         "created_at": {
          "type": "string"
         },
         "approved_by": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{transaction_id, date_before, …}"
     }
    }
   }
  },
  "/api/transactions/{tid}/refund": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Set the refund mark on a ledger row (no money moves); approved_by REQUIRED   (scope payouts:write)",
    "parameters": [
     {
      "name": "tid",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "refund_amount",
         "approved_by"
        ],
        "properties": {
         "refund_amount": {
          "type": "number"
         },
         "approved_by": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{transaction_id, refund_before, …}"
     }
    }
   }
  },
  "/api/transactions/{tid}/delete": {
   "post": {
    "tags": [
     "Page parity"
    ],
    "summary": "Delete a ledger row; approved_by REQUIRED   (scope payouts:write)",
    "parameters": [
     {
      "name": "tid",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "approved_by"
        ],
        "properties": {
         "approved_by": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{transaction_id, …}"
     }
    }
   }
  },
  "/api/payouts/daily": {
   "get": {
    "tags": [
     "Payouts"
    ],
    "summary": "ONE day of courtesy payouts — every scheduled row for the date plus every held Client Setup member, with totals. Same function the /hcs/payments page uses (2026-11-20)   (scope payouts:read)",
    "parameters": [
     {
      "name": "date",
      "in": "query",
      "schema": {
       "type": "string",
       "format": "date"
      },
      "description": "defaults to today (Pacific)"
     }
    ],
    "responses": {
     "200": {
      "description": "{date, as_of, payouts[{payout_id, date, client_id, client_name, payee_name, business_name, coach, amount, planned_amount, basis, pct, state, paid, paid_how, note, batch_id, batch_status, scheduled, receiving, hold_code, hold_reason, no_bank, bank_last4, bank_source}], count, scheduled_rows, scheduled_total, receiving_count, receiving_total, payable_count, payable_total, paid_count, paid_total, held_count, held_total, held_not_scheduled, no_bank_count, no_bank_total} — receiving = real money on this date; hold_reason says why not (held / excluded / dispute DNC / no bank on file / removed from its batch); held people with nothing scheduled are listed with scheduled:false"
     }
    }
   }
  },
  "/api/payouts/reconcile": {
   "get": {
    "tags": [
     "Payouts"
    ],
    "summary": "The API's day against the /hcs/payments page and the raw table — differences should be empty   (scope payouts:read)",
    "parameters": [
     {
      "name": "date",
      "in": "query",
      "schema": {
       "type": "string",
       "format": "date"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{date, in_sync, differences[{client_id, client_name, issue, api_amount, crm_amount}], api{rows, total, receiving_count, receiving_total, held_count, held_total}, crm{rows, receiving_count, receiving_total}, table{rows, total}, before_the_fix{rows, total}, draft_batch{lines, total}}"
     }
    }
   }
  },
  "/api/sfc/loans": {
   "get": {
    "tags": [
     "SFC loans"
    ],
    "summary": "List SFC loans   (scope sfc:read | payouts:read)",
    "parameters": [
     {
      "name": "status",
      "in": "query",
      "schema": {
       "type": "string"
      }
     },
     {
      "name": "banking_update_status",
      "in": "query",
      "schema": {
       "type": "string"
      }
     },
     {
      "name": "due_before",
      "in": "query",
      "schema": {
       "type": "string",
       "format": "date"
      }
     },
     {
      "name": "due_after",
      "in": "query",
      "schema": {
       "type": "string",
       "format": "date"
      }
     },
     {
      "name": "client_id",
      "in": "query",
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "do_not_contact",
      "in": "query",
      "schema": {
       "type": "boolean"
      }
     },
     {
      "name": "at_risk",
      "in": "query",
      "schema": {
       "type": "boolean"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{loans[{id, sfc_loan_number, client_id, client_name, borrower_name, merchant, sfc_statement_period, amount_financed, funding_amount, start_date, first_payment_date, monthly_payment, autopay_day_of_month, next_due_date, days_until_due, next_payment_amount, current_balance, current_due, autopay_enabled, autopay_method, ach_last4, backup_card_last4, backup_card_status, banking_update_status, banking_update_requested_at, banking_verified_at, welcome_sent, consumer_docs_signed, status, bought_back_at, recourse_window_end, do_not_contact, contact_allowed, last_synced_at, notes, reasons[{code, text, severity: risk|watch}], at_risk, created_at, updated_at}], count, total}"
     }
    }
   },
   "post": {
    "tags": [
     "SFC loans"
    ],
    "summary": "Create a loan, or update it when sfc_loan_number already exists. Every changed field is logged to the loan's events with the bot's name   (scope sfc:write | payouts:write)",
    "parameters": [
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "sfc_loan_number"
        ],
        "properties": {
         "sfc_loan_number": {
          "type": "string"
         },
         "client_id": {
          "type": "integer"
         },
         "borrower_name": {
          "type": "string"
         },
         "merchant": {
          "type": "string"
         },
         "sfc_statement_period": {
          "type": "string"
         },
         "amount_financed": {
          "type": "number"
         },
         "funding_amount": {
          "type": "number"
         },
         "start_date": {
          "type": "string",
          "format": "date"
         },
         "first_payment_date": {
          "type": "string",
          "format": "date"
         },
         "monthly_payment": {
          "type": "number"
         },
         "autopay_day_of_month": {
          "type": "integer"
         },
         "next_due_date": {
          "type": "string",
          "format": "date"
         },
         "current_balance": {
          "type": "number"
         },
         "current_due": {
          "type": "number"
         },
         "autopay_enabled": {
          "type": "boolean"
         },
         "autopay_method": {
          "type": "string",
          "enum": [
           "ach",
           "card"
          ]
         },
         "ach_last4": {
          "type": "string",
          "pattern": "^[0-9]{4}$"
         },
         "backup_card_last4": {
          "type": "string",
          "pattern": "^[0-9]{4}$"
         },
         "backup_card_status": {
          "type": "string",
          "enum": [
           "",
           "active",
           "suspended",
           "invalid"
          ]
         },
         "banking_update_status": {
          "type": "string",
          "enum": [
           "needed",
           "requested",
           "client_confirmed",
           "verified_in_sfc"
          ]
         },
         "welcome_sent": {
          "type": "boolean"
         },
         "consumer_docs_signed": {
          "type": "boolean"
         },
         "status": {
          "type": "string",
          "enum": [
           "active",
           "past_due",
           "bought_back",
           "canceled_not_funded",
           "paid_off",
           "disputed",
           "charged_off",
           "pending_funding",
           "application_withdrawn",
           "canceled_after_verification"
          ],
          "description": "canceled_not_funded = SFC canceled the loan or returned it before funding; pending_funding = SFC shows it Not Funded yet (stub created from an SFC e-mail); application_withdrawn (2026-11-22) = the application was started and dropped BEFORE the verbal verification, never funded — not a loan, left out of GET /api/sfc/loans unless status=application_withdrawn or include_withdrawn=1, out of every total and alert; canceled_after_verification (2026-11-22) = the verbal verification was done and the client canceled afterwards, before funding. A bulk-upsert that says pending_funding never reopens either of the two (the answer row carries kept)"
         },
         "verbal_verified": {
          "type": "boolean",
          "description": "SFC's verbal verification call with the consumer was completed (2026-11-22)"
         },
         "verbal_verified_at": {
          "type": "string",
          "format": "date",
          "description": "sets verbal_verified"
         },
         "canceled_at": {
          "type": "string",
          "format": "date",
          "description": "stamped today (Pacific) when a canceled status is set without it"
         },
         "cancel_reason": {
          "type": "string",
          "maxLength": 255
         },
         "bought_back_at": {
          "type": "string",
          "format": "date"
         },
         "buyback_amount": {
          "type": "number"
         },
         "buyback_reason": {
          "type": "string"
         },
         "cancel_client": {
          "type": "boolean",
          "description": "with status bought_back or canceled_not_funded: also cancel the linked client in the same step — same logic as POST /api/clients/{id}/cancel plus the coach is cleared"
         },
         "approved_by": {
          "type": "string"
         },
         "recourse_window_end": {
          "type": "string",
          "format": "date"
         },
         "do_not_contact": {
          "type": "boolean"
         },
         "last_synced_at": {
          "type": "string"
         },
         "notes": {
          "type": "string"
         },
         "note": {
          "type": "string",
          "description": "adds a note event"
         },
         "source": {
          "type": "string",
          "description": "sfc_portal = values come from the portal: stamps last_synced_at and logs the change as synced"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{result: created|updated|unchanged, created, changes{field: {from, to}}, loan_number, loan}"
     },
     "400": {
      "description": "a field failed validation, or the payload carries an SSN / birth date / full account or card number"
     },
     "409": {
      "description": "do_not_contact cannot be cleared through the API"
     }
    }
   }
  },
  "/api/sfc/loans/bulk-upsert": {
   "post": {
    "tags": [
     "SFC loans"
    ],
    "summary": "A portal sync: an array of loans, each created or updated by sfc_loan_number and stamped last_synced_at. One bad row does not stop the rest   (scope sfc:write | payouts:write)",
    "parameters": [
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "loans"
        ],
        "properties": {
         "loans": {
          "type": "array",
          "maxItems": 500,
          "items": {
           "type": "object",
           "required": [
            "sfc_loan_number"
           ],
           "properties": {
            "sfc_loan_number": {
             "type": "string"
            },
            "client_id": {
             "type": "integer"
            },
            "borrower_name": {
             "type": "string"
            },
            "merchant": {
             "type": "string"
            },
            "sfc_statement_period": {
             "type": "string"
            },
            "amount_financed": {
             "type": "number"
            },
            "funding_amount": {
             "type": "number"
            },
            "start_date": {
             "type": "string",
             "format": "date"
            },
            "first_payment_date": {
             "type": "string",
             "format": "date"
            },
            "monthly_payment": {
             "type": "number"
            },
            "autopay_day_of_month": {
             "type": "integer"
            },
            "next_due_date": {
             "type": "string",
             "format": "date"
            },
            "current_balance": {
             "type": "number"
            },
            "current_due": {
             "type": "number"
            },
            "autopay_enabled": {
             "type": "boolean"
            },
            "autopay_method": {
             "type": "string",
             "enum": [
              "ach",
              "card"
             ]
            },
            "ach_last4": {
             "type": "string",
             "pattern": "^[0-9]{4}$"
            },
            "backup_card_last4": {
             "type": "string",
             "pattern": "^[0-9]{4}$"
            },
            "backup_card_status": {
             "type": "string",
             "enum": [
              "",
              "active",
              "suspended",
              "invalid"
             ]
            },
            "banking_update_status": {
             "type": "string",
             "enum": [
              "needed",
              "requested",
              "client_confirmed",
              "verified_in_sfc"
             ]
            },
            "welcome_sent": {
             "type": "boolean"
            },
            "consumer_docs_signed": {
             "type": "boolean"
            },
            "status": {
             "type": "string",
             "enum": [
              "active",
              "past_due",
              "bought_back",
              "canceled_not_funded",
              "paid_off",
              "disputed",
              "charged_off",
              "pending_funding",
              "application_withdrawn",
              "canceled_after_verification"
             ],
             "description": "canceled_not_funded = SFC canceled the loan or returned it before funding; pending_funding = SFC shows it Not Funded yet (stub created from an SFC e-mail); application_withdrawn (2026-11-22) = the application was started and dropped BEFORE the verbal verification, never funded — not a loan, left out of GET /api/sfc/loans unless status=application_withdrawn or include_withdrawn=1, out of every total and alert; canceled_after_verification (2026-11-22) = the verbal verification was done and the client canceled afterwards, before funding. A bulk-upsert that says pending_funding never reopens either of the two (the answer row carries kept)"
            },
            "verbal_verified": {
             "type": "boolean",
             "description": "SFC's verbal verification call with the consumer was completed (2026-11-22)"
            },
            "verbal_verified_at": {
             "type": "string",
             "format": "date",
             "description": "sets verbal_verified"
            },
            "canceled_at": {
             "type": "string",
             "format": "date",
             "description": "stamped today (Pacific) when a canceled status is set without it"
            },
            "cancel_reason": {
             "type": "string",
             "maxLength": 255
            },
            "bought_back_at": {
             "type": "string",
             "format": "date"
            },
            "buyback_amount": {
             "type": "number"
            },
            "buyback_reason": {
             "type": "string"
            },
            "cancel_client": {
             "type": "boolean",
             "description": "with status bought_back or canceled_not_funded: also cancel the linked client in the same step — same logic as POST /api/clients/{id}/cancel plus the coach is cleared"
            },
            "approved_by": {
             "type": "string"
            },
            "recourse_window_end": {
             "type": "string",
             "format": "date"
            },
            "do_not_contact": {
             "type": "boolean"
            },
            "last_synced_at": {
             "type": "string"
            },
            "notes": {
             "type": "string"
            },
            "note": {
             "type": "string",
             "description": "adds a note event"
            },
            "source": {
             "type": "string",
             "description": "sfc_portal = values come from the portal: stamps last_synced_at and logs the change as synced"
            }
           }
          }
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{results[{loan_number, result: created|updated|unchanged|error, changes, message}], count, created, updated, unchanged, errors}"
     }
    }
   }
  },
  "/api/sfc/loans/upcoming": {
   "get": {
    "tags": [
     "SFC loans"
    ],
    "summary": "Payments due in the next N days   (scope sfc:read | payouts:read)",
    "parameters": [
     {
      "name": "days",
      "in": "query",
      "schema": {
       "type": "integer",
       "default": 7
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{payments[{payment_id, loan_number, borrower_name, client_id, due_date, days_until_due, amount_due, status, autopay_enabled, ach_last4, banking_update_status, banking_verified, do_not_contact, contact_allowed}], count, total_due, days, from, to}"
     }
    }
   }
  },
  "/api/sfc/loans/at-risk": {
   "get": {
    "tags": [
     "SFC loans"
    ],
    "summary": "Loans at risk: past due · a failed / returned / late payment · autopay off · backup card suspended or invalid · banking not verified in SFC within 7 days of the due date · a due date that passed without a confirmed payment · recourse window closing on a loan that is not current   (scope sfc:read | payouts:read)",
    "responses": {
     "200": {
      "description": "{loans[loan + payments[]], count} — each loan's reasons[] says why (severity risk); watch reasons ride along"
     }
    }
   }
  },
  "/api/sfc/loans/{loan_number}": {
   "get": {
    "tags": [
     "SFC loans"
    ],
    "summary": "One loan with its payments and the 50 newest events   (scope sfc:read | payouts:read)",
    "parameters": [
     {
      "name": "loan_number",
      "in": "path",
      "required": true,
      "schema": {
       "type": "string"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{loan, payments[{id, due_date, amount_due, amount_paid, paid_date, method, status, return_code, source, notes}], events[{id, event_type, old_value, new_value, actor, created_at}]}"
     },
     "404": {
      "description": "no such loan"
     }
    }
   },
   "patch": {
    "tags": [
     "SFC loans"
    ],
    "summary": "Update any field (due date, autopay day, balance, banking status, notes …). POST to the same path does the same for clients that cannot PATCH. A new due date moves the autopay day with it; banking requested / verified stamp their times; bought_back or disputed sets do_not_contact for good   (scope sfc:write | payouts:write)",
    "parameters": [
     {
      "name": "loan_number",
      "in": "path",
      "required": true,
      "schema": {
       "type": "string"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "sfc_loan_number": {
          "type": "string"
         },
         "client_id": {
          "type": "integer"
         },
         "borrower_name": {
          "type": "string"
         },
         "merchant": {
          "type": "string"
         },
         "sfc_statement_period": {
          "type": "string"
         },
         "amount_financed": {
          "type": "number"
         },
         "funding_amount": {
          "type": "number"
         },
         "start_date": {
          "type": "string",
          "format": "date"
         },
         "first_payment_date": {
          "type": "string",
          "format": "date"
         },
         "monthly_payment": {
          "type": "number"
         },
         "autopay_day_of_month": {
          "type": "integer"
         },
         "next_due_date": {
          "type": "string",
          "format": "date"
         },
         "current_balance": {
          "type": "number"
         },
         "current_due": {
          "type": "number"
         },
         "autopay_enabled": {
          "type": "boolean"
         },
         "autopay_method": {
          "type": "string",
          "enum": [
           "ach",
           "card"
          ]
         },
         "ach_last4": {
          "type": "string",
          "pattern": "^[0-9]{4}$"
         },
         "backup_card_last4": {
          "type": "string",
          "pattern": "^[0-9]{4}$"
         },
         "backup_card_status": {
          "type": "string",
          "enum": [
           "",
           "active",
           "suspended",
           "invalid"
          ]
         },
         "banking_update_status": {
          "type": "string",
          "enum": [
           "needed",
           "requested",
           "client_confirmed",
           "verified_in_sfc"
          ]
         },
         "welcome_sent": {
          "type": "boolean"
         },
         "consumer_docs_signed": {
          "type": "boolean"
         },
         "status": {
          "type": "string",
          "enum": [
           "active",
           "past_due",
           "bought_back",
           "canceled_not_funded",
           "paid_off",
           "disputed",
           "charged_off",
           "pending_funding",
           "application_withdrawn",
           "canceled_after_verification"
          ],
          "description": "canceled_not_funded = SFC canceled the loan or returned it before funding; pending_funding = SFC shows it Not Funded yet (stub created from an SFC e-mail); application_withdrawn (2026-11-22) = the application was started and dropped BEFORE the verbal verification, never funded — not a loan, left out of GET /api/sfc/loans unless status=application_withdrawn or include_withdrawn=1, out of every total and alert; canceled_after_verification (2026-11-22) = the verbal verification was done and the client canceled afterwards, before funding. A bulk-upsert that says pending_funding never reopens either of the two (the answer row carries kept)"
         },
         "verbal_verified": {
          "type": "boolean",
          "description": "SFC's verbal verification call with the consumer was completed (2026-11-22)"
         },
         "verbal_verified_at": {
          "type": "string",
          "format": "date",
          "description": "sets verbal_verified"
         },
         "canceled_at": {
          "type": "string",
          "format": "date",
          "description": "stamped today (Pacific) when a canceled status is set without it"
         },
         "cancel_reason": {
          "type": "string",
          "maxLength": 255
         },
         "bought_back_at": {
          "type": "string",
          "format": "date"
         },
         "buyback_amount": {
          "type": "number"
         },
         "buyback_reason": {
          "type": "string"
         },
         "cancel_client": {
          "type": "boolean",
          "description": "with status bought_back or canceled_not_funded: also cancel the linked client in the same step — same logic as POST /api/clients/{id}/cancel plus the coach is cleared"
         },
         "approved_by": {
          "type": "string"
         },
         "recourse_window_end": {
          "type": "string",
          "format": "date"
         },
         "do_not_contact": {
          "type": "boolean"
         },
         "last_synced_at": {
          "type": "string"
         },
         "notes": {
          "type": "string"
         },
         "note": {
          "type": "string",
          "description": "adds a note event"
         },
         "source": {
          "type": "string",
          "description": "sfc_portal = values come from the portal: stamps last_synced_at and logs the change as synced"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{result, changes, loan}"
     },
     "400": {
      "description": "validation or PII refusal"
     },
     "404": {
      "description": "no such loan"
     },
     "409": {
      "description": "do_not_contact is permanent"
     }
    }
   }
  },
  "/api/sfc/loans/{loan_number}/payments": {
   "get": {
    "tags": [
     "SFC loans"
    ],
    "summary": "The loan's payment history   (scope sfc:read | payouts:read)",
    "parameters": [
     {
      "name": "loan_number",
      "in": "path",
      "required": true,
      "schema": {
       "type": "string"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{loan_number, payments[{id, due_date, amount_due, amount_paid, paid_date, method, status, return_code, source, notes}], count}"
     },
     "404": {
      "description": "no such loan"
     }
    }
   },
   "post": {
    "tags": [
     "SFC loans"
    ],
    "summary": "Add or record a payment. One row per loan + due date: posting an existing due date updates that row. failed / returned marks the loan past due, logs payment_failed and alerts Michael the same day; paid moves the loan's next due date on a month   (scope sfc:write | payouts:write)",
    "parameters": [
     {
      "name": "loan_number",
      "in": "path",
      "required": true,
      "schema": {
       "type": "string"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "due_date"
        ],
        "properties": {
         "due_date": {
          "type": "string",
          "format": "date"
         },
         "amount_due": {
          "type": "number"
         },
         "amount_paid": {
          "type": "number"
         },
         "paid_date": {
          "type": "string",
          "format": "date"
         },
         "method": {
          "type": "string",
          "enum": [
           "ach",
           "card",
           "other"
          ]
         },
         "status": {
          "type": "string",
          "enum": [
           "scheduled",
           "pending",
           "paid",
           "failed",
           "returned",
           "late",
           "waived"
          ]
         },
         "return_code": {
          "type": "string",
          "description": "R01, R02 … only with failed / returned"
         },
         "source": {
          "type": "string",
          "enum": [
           "sfc_portal",
           "manual",
           "api"
          ]
         },
         "notes": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{result, created, changes, payment, loan_number, loan_status, next_due_date, loan_changes, alerted}"
     }
    }
   }
  },
  "/api/sfc/loans/{loan_number}/events": {
   "get": {
    "tags": [
     "SFC loans"
    ],
    "summary": "The loan's event log, newest first   (scope sfc:read | payouts:read)",
    "parameters": [
     {
      "name": "loan_number",
      "in": "path",
      "required": true,
      "schema": {
       "type": "string"
      }
     },
     {
      "$ref": "#/components/parameters/limit"
     }
    ],
    "responses": {
     "200": {
      "description": "{loan_number, events[{id, event_type, old_value, new_value, actor, created_at}], count}"
     },
     "404": {
      "description": "no such loan"
     }
    }
   },
   "post": {
    "tags": [
     "SFC loans"
    ],
    "summary": "Add a note or an event to the loan's log. client_contacted is refused (409) for a do-not-contact loan   (scope sfc:write | payouts:write)",
    "parameters": [
     {
      "name": "loan_number",
      "in": "path",
      "required": true,
      "schema": {
       "type": "string"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "event_type": {
          "type": "string",
          "default": "note",
          "enum": [
           "note",
           "client_contacted",
           "synced",
           "banking_requested",
           "banking_verified",
           "due_date_changed",
           "autopay_changed",
           "payment_failed",
           "bought_back"
          ]
         },
         "note": {
          "type": "string"
         },
         "new_value": {
          "type": "object"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{loan_number, event_type, new_value}"
     }
    }
   }
  },
  "/api/sfc/payments/{id}": {
   "patch": {
    "tags": [
     "SFC loans"
    ],
    "summary": "Mark a payment paid / failed / returned (with the return code), or correct a field. POST to the same path does the same   (scope sfc:write | payouts:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "due_date": {
          "type": "string",
          "format": "date"
         },
         "amount_due": {
          "type": "number"
         },
         "amount_paid": {
          "type": "number"
         },
         "paid_date": {
          "type": "string",
          "format": "date"
         },
         "method": {
          "type": "string",
          "enum": [
           "ach",
           "card",
           "other"
          ]
         },
         "status": {
          "type": "string",
          "enum": [
           "scheduled",
           "pending",
           "paid",
           "failed",
           "returned",
           "late",
           "waived"
          ]
         },
         "return_code": {
          "type": "string",
          "description": "R01, R02 … only with failed / returned"
         },
         "source": {
          "type": "string",
          "enum": [
           "sfc_portal",
           "manual",
           "api"
          ]
         },
         "notes": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{result, changes, payment, loan_status, next_due_date, loan_changes, alerted}"
     },
     "404": {
      "description": "no such payment"
     }
    }
   }
  },
  "/api/sfc/summary": {
   "get": {
    "tags": [
     "SFC loans"
    ],
    "summary": "Counts and totals   (scope sfc:read | payouts:read)",
    "responses": {
     "200": {
      "description": "{active_loans, total_balance, due_next_7_days{count, amount}, past_due{count, amount}, banking_not_verified, at_risk, bought_back, paid_off, do_not_contact, total_loans, funded{count, amount_financed, funded_to_merchant, bought_back, amount_financed_not_on_file, funded_to_merchant_not_on_file}, not_funded{count, amount_financed, verbal_verified, amount_financed_not_on_file}, canceled_before_funding{count, amount_financed}, oldest_sync, as_of}"
     }
    }
   }
  },
  "/api/sfc/report/daily": {
   "get": {
    "tags": [
     "SFC loans"
    ],
    "summary": "The morning report: everything at risk, payments due in the next 5 days where banking is not verified in SFC, reminders to approve (5 days and 1 day before the due date, never a do-not-contact client), loans not checked against the portal lately. Posted to the Finance Director queue once a day   (scope sfc:read | payouts:read)",
    "responses": {
     "200": {
      "description": "{date, summary, at_risk[], due_in_5_days_banking_not_verified[], reminders_due[], stale_sync[], watch[], text, note}"
     }
    }
   }
  },
  "/api/sfc/reconcile": {
   "get": {
    "tags": [
     "SFC loans"
    ],
    "summary": "Monthly reconciliation, our side: what is recorded as paid per loan in the month   (scope sfc:read | payouts:read)",
    "parameters": [
     {
      "name": "month",
      "in": "query",
      "schema": {
       "type": "string",
       "example": "2026-12"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{month, loans[{loan_number, borrower_name, status, paid_total, paid_count, due_total, failed_or_returned}], total_paid}"
     }
    }
   },
   "post": {
    "tags": [
     "SFC loans"
    ],
    "summary": "Monthly reconciliation: post the SFC Loan Statement totals, get the differences against our records. Nothing is written   (scope sfc:read | payouts:read)",
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "month",
         "statements"
        ],
        "properties": {
         "month": {
          "type": "string",
          "example": "2026-12"
         },
         "statements": {
          "type": "array",
          "items": {
           "type": "object",
           "properties": {
            "loan_number": {
             "type": "string"
            },
            "total_paid": {
             "type": "number"
            }
           }
          }
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{month, loans[{loan_number, borrower_name, our_paid, sfc_paid, difference, issue}], differences[], in_sync, our_total_paid, sfc_total_paid, difference}"
     }
    }
   }
  },
  "/api/clients/{id}/do-not-contact": {
   "post": {
    "tags": [
     "Clients"
    ],
    "summary": "Set or clear do-not-contact on a CLIENT (2026-11-21) — the flag goes on the client record AND every lead record of the same person (same e-mail / phone)   (scope contact:write, clients:write, sales:write or sales:calls)",
    "description": "Setting writes the flag, STOP-suppresses the phones, blocks inbound routing, takes the lead out of the dialer queue and moves an unlocked lead to status Do Not Call. Clearing (do_not_contact:false) removes exactly what the API wrote — a STOP the person texted themselves stays — and a lead in Do Not Call goes back to its previous status. reason is required either way. After this, every automated text, call, e-mail, booking and payout skips the person; POST /api/bookings answers 409 do_not_contact.",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "reason"
        ],
        "properties": {
         "do_not_contact": {
          "type": "boolean",
          "default": true
         },
         "reason": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{name, do_not_contact, reason, client_ids[], lead_ids[], lead_status{lead_id: what happened to its status}, dispute_hold, note} — dry run: {would_set_do_not_contact, do_not_contact_now, client_ids, lead_ids}"
     },
     "400": {
      "description": "reason_required"
     },
     "404": {
      "description": "no such client"
     }
    }
   }
  },
  "/api/clients/{id}/dispute-hold": {
   "get": {
    "tags": [
     "Clients"
    ],
    "summary": "The person's dispute hold (active, else the last released one)   (scope clients:read, sales:read or contact:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{dispute_hold{…}, do_not_contact, client_ids[], lead_ids[]}"
     }
    }
   },
   "post": {
    "tags": [
     "Clients"
    ],
    "summary": "Place, update or release a dispute hold (2026-11-21)   (scope contact:write, clients:write, sales:write or sales:calls)",
    "description": "A person on dispute hold gets no outreach, upsells, payouts, Client Setup automation or bookings (the same blocks as do-not-contact); the client stage is Inactive (On Hold). If they text in, the ONLY automatic reply is exactly \"Your account is on hold until your dispute is resolved.\" — once per 24 hours, through the normal RingCentral path, logged. Release: on:false with approved_by naming Michael, and only when every dispute is won or cleared (else 409 disputes_not_resolved / 403 michael_only); the client goes back to Active. Nothing releases a hold automatically. One hold covers the person — the client record and the lead record, whichever route sets it. Every change is in /api/audit.",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         true
        ],
        "properties": {
         "true": {
          "type": "boolean",
          "description": "true = place the hold (or add / update disputes on it); false = release it"
         },
         "reason": {
          "type": "string",
          "description": "required when placing"
         },
         "disputes": {
          "type": "array",
          "items": {
           "type": "object",
           "required": [
            "dispute_ref"
           ],
           "properties": {
            "dispute_ref": {
             "type": "string",
             "example": "Commas, Visa ••9914",
             "description": "last 4 digits only — never a full card number"
            },
            "status": {
             "type": "string",
             "enum": [
              "open",
              "won",
              "cleared",
              "lost"
             ],
             "default": "open"
            },
            "note": {
             "type": "string"
            }
           }
          }
         },
         "approved_by": {
          "type": "string",
          "description": "release only: must name Michael"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{dispute_hold{on, hold_id, client_id, lead_id, hold_reason, hold_since, set_by, released_at, released_by, disputes[{id, dispute_ref, status, note, updated_by, updated_at}], can_release, still_open[], stage, message}, stage} — release: {dispute_hold, released: true, stage: Active}"
     },
     "400": {
      "description": "reason_required | dispute_ref_required | bad_dispute_status | sensitive_content"
     },
     "403": {
      "description": "michael_only"
     },
     "404": {
      "description": "no_hold"
     },
     "409": {
      "description": "disputes_not_resolved"
     }
    }
   }
  },
  "/api/clients/{id}/dispute-hold/disputes": {
   "post": {
    "tags": [
     "Clients"
    ],
    "summary": "Update ONE dispute's status on the hold (open | won | cleared | lost)   (scope contact:write, clients:write, sales:write or sales:calls)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "status"
        ],
        "properties": {
         "dispute_id": {
          "type": "integer"
         },
         "dispute_ref": {
          "type": "string",
          "description": "instead of dispute_id"
         },
         "status": {
          "type": "string",
          "enum": [
           "open",
           "won",
           "cleared",
           "lost"
          ]
         },
         "note": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{dispute{id, dispute_ref, status}, dispute_hold{…}}"
     },
     "404": {
      "description": "no_hold | no_such_dispute"
     }
    }
   }
  },
  "/api/leads/{id}/dispute-hold": {
   "get": {
    "tags": [
     "Sales"
    ],
    "summary": "The same person-level dispute hold, addressed by lead id   (scope clients:read, sales:read or contact:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{dispute_hold{…}, do_not_contact, client_ids[], lead_ids[]}"
     }
    }
   },
   "post": {
    "tags": [
     "Sales"
    ],
    "summary": "Place, update or release a dispute hold by lead id — same body and rules as POST /api/clients/{id}/dispute-hold   (scope contact:write, clients:write, sales:write or sales:calls)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         true
        ],
        "properties": {
         "true": {
          "type": "boolean",
          "description": "true = place the hold (or add / update disputes on it); false = release it"
         },
         "reason": {
          "type": "string",
          "description": "required when placing"
         },
         "disputes": {
          "type": "array",
          "items": {
           "type": "object",
           "required": [
            "dispute_ref"
           ],
           "properties": {
            "dispute_ref": {
             "type": "string",
             "example": "Commas, Visa ••9914",
             "description": "last 4 digits only — never a full card number"
            },
            "status": {
             "type": "string",
             "enum": [
              "open",
              "won",
              "cleared",
              "lost"
             ],
             "default": "open"
            },
            "note": {
             "type": "string"
            }
           }
          }
         },
         "approved_by": {
          "type": "string",
          "description": "release only: must name Michael"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{dispute_hold{on, hold_id, client_id, lead_id, hold_reason, hold_since, set_by, released_at, released_by, disputes[{id, dispute_ref, status, note, updated_by, updated_at}], can_release, still_open[], stage, message}, stage}"
     },
     "403": {
      "description": "michael_only"
     },
     "409": {
      "description": "disputes_not_resolved"
     }
    }
   }
  },
  "/api/leads/{id}/dispute-hold/disputes": {
   "post": {
    "tags": [
     "Sales"
    ],
    "summary": "Update one dispute's status, by lead id   (scope contact:write, clients:write, sales:write or sales:calls)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "status"
        ],
        "properties": {
         "dispute_id": {
          "type": "integer"
         },
         "dispute_ref": {
          "type": "string"
         },
         "status": {
          "type": "string",
          "enum": [
           "open",
           "won",
           "cleared",
           "lost"
          ]
         },
         "note": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{dispute, dispute_hold}"
     }
    }
   }
  },
  "/api/contact-guard/log": {
   "get": {
    "tags": [
     "Platform"
    ],
    "summary": "Every text, call, e-mail, booking or Meet invite the do-not-contact / dispute-hold guard REFUSED (2026-11-21)   (scope audit:read, contact:write or clients:read)",
    "parameters": [
     {
      "name": "since",
      "in": "query",
      "schema": {
       "type": "string"
      },
      "description": "YYYY-MM-DD, default 7 days ago"
     },
     {
      "$ref": "#/components/parameters/limit"
     }
    ],
    "responses": {
     "200": {
      "description": "{refused[{id, channel: sms|call|email|booking|meet, code: do_not_contact|dispute_hold|client_canceled, client_id, lead_id, target (masked), what, at}], count, since}"
     }
    }
   }
  },
  "/api/sfc/buybacks": {
   "get": {
    "tags": [
     "SFC loans"
    ],
    "summary": "Every bought_back or canceled_not_funded loan with the client's current CRM state (2026-11-21)   (scope sfc:read | payouts:read)",
    "parameters": [
     {
      "name": "since",
      "in": "query",
      "schema": {
       "type": "string",
       "format": "date"
      },
      "description": "only loans whose effective date (bought_back_at, else the SFC BuyBack e-mail's return date) is on or after this day"
     }
    ],
    "responses": {
     "200": {
      "description": "{buybacks[{loan_number, client_id, borrower_name, status, bought_back_at, buyback_amount, buyback_reason, amount_financed, funding_amount, do_not_contact, effective_date, effective_date_source (bought_back_at | sfc_email | last_change), sfc_email{return_date, reason, potential_buyback_amount_due}, client{stage, coach, canceled, on_client_setup, payouts_on, do_not_contact, dispute_hold, do_not_contact_reason, dispute_hold_reason}}], count, buyback_amount_total, since}"
     },
     "400": {
      "description": "bad since"
     }
    }
   }
  },
  "/api/sfc/sync-report": {
   "get": {
    "tags": [
     "SFC loans"
    ],
    "summary": "Sync health (2026-11-21): last sync time, loans the portal showed, what was imported, and loan numbers seen in SFC e-mails or the portal that are not in the database   (scope sfc:read | payouts:read)",
    "description": "The server has no SFC portal login: 'last sync' = the last POST /api/sfc/loans/bulk-upsert. SFC's own e-mails (info@sfc.us) are read every 20 minutes from the company inboxes; a loan number seen only there is created as a stub (status pending_funding, never synced) and listed under in_database_from_email_only until a portal sync fills it in.",
    "responses": {
     "200": {
      "description": "{loans_in_database, last_sync_at, hours_since_last_sync, stale (true when older than 24 h), last_sync_run{ran_at, by, source, loans_seen_in_portal, imported{created, updated, unchanged, errors}} | null, open_loans_not_in_last_sync[], never_synced_from_portal[{loan_number, borrower_name, status, client_id, created_at}], sfc_emails{last_scan_at, notices, loan_numbers_seen[], seen_in_emails_not_in_database[{loan_number, consumer_name, first_email_at, last_email_at, emails{type: count}}], in_database_from_email_only[]}, note}"
     }
    }
   }
  },
  "/api/sfc/alerts": {
   "get": {
    "tags": [
     "SFC loans"
    ],
    "summary": "What is red on the SFC page and not yet marked reviewed: failed / returned payments, past due, suspended backup cards, unsigned docs, disputes, buybacks / canceled_not_funded, stale sync, loans known only from SFC e-mails, and returned loans whose client is still active / coached / on Client Setup / paid / unflagged   (scope sfc:read | payouts:read)",
    "parameters": [
     {
      "name": "all",
      "in": "query",
      "schema": {
       "type": "boolean"
      },
      "description": "also return the reviewed ones under `all`"
     }
    ],
    "responses": {
     "200": {
      "description": "{alerts[{key, kind, loan_number, borrower_name, client_id, text, since}], count, reviewed}"
     }
    }
   }
  },
  "/api/sfc/alerts/review": {
   "post": {
    "tags": [
     "SFC loans"
    ],
    "summary": "Mark one alert reviewed — it leaves the panel; logged on the loan and in /api/audit   (scope sfc:write | payouts:write)",
    "parameters": [
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "key"
        ],
        "properties": {
         "key": {
          "type": "string"
         },
         "note": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{reviewed{…the alert…}, note}"
     },
     "404": {
      "description": "no such alert"
     }
    }
   }
  },
  "/api/sfc/emails/scan": {
   "post": {
    "tags": [
     "SFC loans"
    ],
    "summary": "Read SFC's e-mails now (the worker does it every 20 minutes). Stores each notice once; creates a stub loan for a loan number not in the database. Never changes an existing loan, never marks a payment failed, never texts anyone   (scope sfc:write | payouts:write)",
    "parameters": [
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "responses": {
     "200": {
      "description": "{inboxes_read, inboxes_not_readable, emails_fetched, new_notices, loans_created_from_email[]}"
     }
    }
   }
  },
  "/api/sfc/loan-book/fields": {
   "get": {
    "tags": [
     "SFC loan book"
    ],
    "summary": "The loan-book fields a loan accepts on POST / PATCH / bulk-upsert, with kind, section, definition and origin (2026-11-22)   (scope sfc:read | payouts:read)",
    "description": "About 75 nullable fields: terms (origination_date, funding_date, apr as a decimal, term_months, scheduled_payment, total_of_payments, finance_charge, maturity_date, cash_down_amount, total_sale_price, product_type, sale_type, merchant_id …), SFC economics (purchase_price_pct, discount_amount, holdback_amount, recourse_type, recourse_demand_amount …), borrower attributes (borrower_state, borrower_zip3, credit_score_band — never a score), document flags, lifecycle (payoff_*, chargeoff_*, recovery_*, refund_*), disputes, lineage (source_system, servicer …), portfolio (portfolio, owner_entity, pledged_to), bureau placeholders. Blank = not on file. purchase_price_pct, discount_amount, total_sale_price and maturity_date are worked out when their inputs are known and they were not sent. Every loan also answers performance_status, days_past_due, delinquency_bucket and funded. The PII refusal applies to every field: any 9-digit run is refused, references included.",
    "responses": {
     "200": {
      "description": "{fields[{name, kind (text | money | rate | int | date | datetime | tbool | enum | state | zip3 | band | merchant), enum, section, label, definition, origin (sfc | manual | derived | system), read_only}], transaction_types[], modification_types[]}"
     }
    }
   }
  },
  "/api/sfc/loans/{loan_number}/transactions": {
   "get": {
    "tags": [
     "SFC loan book"
    ],
    "summary": "The loan's ledger: one row per money event, and whether the ledger reproduces the balance   (scope sfc:read | payouts:read)",
    "parameters": [
     {
      "name": "loan_number",
      "in": "path",
      "required": true,
      "schema": {
       "type": "string"
      }
     },
     {
      "name": "include_all",
      "in": "query",
      "schema": {
       "type": "string",
       "enum": [
        "1"
       ]
      },
      "description": "also the rows a correction replaced"
     }
    ],
    "responses": {
     "200": {
      "description": "{loan_number, transactions[{id, txn_date, posted_date, txn_type, amount (signed), principal, interest, fees, method, ach_return_code, return_reason_text, source, source_ref, unconfirmed, payment_id, supersedes_id, correction_reason, live, status (posted | returned | failed | presented | unconfirmed | superseded)}], count, ledger{state (match | mismatch | incomplete | no_opening | no_balance | not_applicable), ledger_balance, current_balance, difference}}"
     },
     "404": {
      "description": "no such loan"
     }
    }
   },
   "post": {
    "tags": [
     "SFC loan book"
    ],
    "summary": "Append one ledger row. Idempotent on source_ref; a changed row is a correction (supersedes_id + correction_reason). Nothing is ever edited or deleted   (scope sfc:write | payouts:write)",
    "description": "amount is signed — positive toward the lender, negative back out; the sign is set from the type for ach_return, refund, chargeback and fee_waiver. payment = money that posted; a debit that never posted is a scheduled_debit with the return code; ach_return reverses a posted payment; balance_forward opens the ledger. principal + interest + fees must add up to the amount when all three are sent. The same row again answers result unchanged; another row under the same source_ref is a 409.",
    "parameters": [
     {
      "name": "loan_number",
      "in": "path",
      "required": true,
      "schema": {
       "type": "string"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "txn_type",
         "txn_date",
         "amount"
        ],
        "properties": {
         "txn_type": {
          "type": "string",
          "enum": [
           "scheduled_debit",
           "payment",
           "partial_payment",
           "extra_principal",
           "payoff",
           "ach_return",
           "nsf_fee",
           "late_fee",
           "fee_waiver",
           "refund",
           "chargeback",
           "buyback",
           "chargeoff",
           "recovery",
           "adjustment",
           "reversal",
           "balance_forward"
          ]
         },
         "txn_date": {
          "type": "string",
          "format": "date"
         },
         "posted_date": {
          "type": "string",
          "format": "date"
         },
         "amount": {
          "type": "number"
         },
         "principal": {
          "type": "number"
         },
         "interest": {
          "type": "number"
         },
         "fees": {
          "type": "number"
         },
         "method": {
          "type": "string",
          "enum": [
           "ach",
           "card",
           "cash",
           "wire",
           "other"
          ]
         },
         "ach_return_code": {
          "type": "string",
          "description": "R01 to R99"
         },
         "return_reason_text": {
          "type": "string"
         },
         "source": {
          "type": "string",
          "enum": [
           "sfc_portal",
           "sfc_email",
           "manual",
           "api",
           "internal_servicer"
          ]
         },
         "source_ref": {
          "type": "string",
          "description": "the source's own reference — one row per loan and reference"
         },
         "payment_id": {
          "type": "integer"
         },
         "due_date": {
          "type": "string",
          "format": "date",
          "description": "links the row to the installment of that due date"
         },
         "supersedes_id": {
          "type": "integer"
         },
         "correction_reason": {
          "type": "string"
         },
         "unconfirmed": {
          "type": "boolean"
         },
         "notes": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{result (created | unchanged), transaction{…}, superseded_id, sign_normalized}"
     },
     "400": {
      "description": "validation or PII refusal"
     },
     "409": {
      "description": "the reference is recorded with other values",
      "or the row was already replaced": null
     }
    }
   }
  },
  "/api/sfc/transactions/{id}/confirm": {
   "post": {
    "tags": [
     "SFC loan book"
    ],
    "summary": "Confirm an unconfirmed ledger row (one written from an SFC e-mail): a confirmed copy supersedes it   (scope sfc:write | payouts:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "txn_type": {
          "type": "string"
         },
         "txn_date": {
          "type": "string",
          "format": "date"
         },
         "amount": {
          "type": "number"
         },
         "principal": {
          "type": "number"
         },
         "interest": {
          "type": "number"
         },
         "fees": {
          "type": "number"
         },
         "ach_return_code": {
          "type": "string"
         },
         "note": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{result, transaction{…}, superseded_id}"
     },
     "404": {
      "description": "no such transaction"
     },
     "409": {
      "description": "already replaced"
     }
    }
   }
  },
  "/api/sfc/loans/{loan_number}/modifications": {
   "get": {
    "tags": [
     "SFC loan book"
    ],
    "summary": "Modifications recorded for the loan   (scope sfc:read | payouts:read)",
    "parameters": [
     {
      "name": "loan_number",
      "in": "path",
      "required": true,
      "schema": {
       "type": "string"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{loan_number, modifications[{id, mod_type, effective_date, old_terms, new_terms, months_deferred, reason, approved_by, source, actor, supersedes_id, correction_reason, live}], count, mod_types[]}"
     }
    }
   },
   "post": {
    "tags": [
     "SFC loan book"
    ],
    "summary": "Record a modification (append-only); the loan's modification_count / extension_count go up. The terms themselves change with a loan write   (scope sfc:write | payouts:write)",
    "description": "A PATCH of next_due_date or autopay_day_of_month with borrower_requested: true records a due_date_change modification by itself.",
    "parameters": [
     {
      "name": "loan_number",
      "in": "path",
      "required": true,
      "schema": {
       "type": "string"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "mod_type",
         "effective_date"
        ],
        "properties": {
         "mod_type": {
          "type": "string",
          "enum": [
           "deferral",
           "extension",
           "due_date_change",
           "rate_change",
           "settlement",
           "hardship_plan",
           "re_age"
          ]
         },
         "effective_date": {
          "type": "string",
          "format": "date"
         },
         "old_terms": {
          "type": "object"
         },
         "new_terms": {
          "type": "object"
         },
         "months_deferred": {
          "type": "integer"
         },
         "reason": {
          "type": "string"
         },
         "approved_by": {
          "type": "string"
         },
         "supersedes_id": {
          "type": "integer"
         },
         "correction_reason": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{id, loan_number, mod_type, effective_date}"
     }
    }
   }
  },
  "/api/sfc/complaints": {
   "get": {
    "tags": [
     "SFC loan book"
    ],
    "summary": "Disputes and complaints   (scope sfc:read | payouts:read)",
    "parameters": [
     {
      "name": "loan_number",
      "in": "query",
      "schema": {
       "type": "string"
      }
     },
     {
      "name": "open",
      "in": "query",
      "schema": {
       "type": "boolean"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{complaints[{id, loan_number, opened_at, channel, category, root_cause, merchant_tag, summary, resolved_at, outcome, holder_claim, open, source}], count}"
     }
    }
   }
  },
  "/api/sfc/loans/{loan_number}/complaints": {
   "post": {
    "tags": [
     "SFC loan book"
    ],
    "summary": "Open a complaint on a loan (idempotent on source_ref)   (scope sfc:write | payouts:write)",
    "parameters": [
     {
      "name": "loan_number",
      "in": "path",
      "required": true,
      "schema": {
       "type": "string"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "opened_at": {
          "type": "string",
          "format": "date"
         },
         "channel": {
          "type": "string"
         },
         "category": {
          "type": "string"
         },
         "root_cause": {
          "type": "string"
         },
         "merchant_tag": {
          "type": "string"
         },
         "summary": {
          "type": "string",
          "description": "no phone numbers or identifiers"
         },
         "holder_claim": {
          "type": "boolean"
         },
         "source_ref": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{result (created | unchanged), id}"
     }
    }
   }
  },
  "/api/sfc/complaints/{id}": {
   "patch": {
    "tags": [
     "SFC loan book"
    ],
    "summary": "Update or resolve a complaint (POST works too)   (scope sfc:write | payouts:write)",
    "parameters": [
     {
      "name": "id",
      "in": "path",
      "required": true,
      "schema": {
       "type": "integer"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "resolved_at": {
          "type": "string",
          "format": "date"
         },
         "outcome": {
          "type": "string"
         },
         "category": {
          "type": "string"
         },
         "root_cause": {
          "type": "string"
         },
         "merchant_tag": {
          "type": "string"
         },
         "summary": {
          "type": "string"
         },
         "holder_claim": {
          "type": "boolean"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{result (updated | unchanged), id}"
     },
     "404": {
      "description": "no such complaint"
     }
    }
   }
  },
  "/api/sfc/loans/{loan_number}/sources": {
   "get": {
    "tags": [
     "SFC loan book"
    ],
    "summary": "Where each value of the loan came from (portal / SFC e-mail / a person / worked out here), and where the sources disagree   (scope sfc:read | payouts:read)",
    "parameters": [
     {
      "name": "loan_number",
      "in": "path",
      "required": true,
      "schema": {
       "type": "string"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{loan_number, sources[{field, value, source, source_ref, actor, observed_at}], conflicts[{field, sources[{source, value, observed_at}]}]}"
     }
    }
   }
  },
  "/api/sfc/loans/{loan_number}/sources/resolve": {
   "post": {
    "tags": [
     "SFC loan book"
    ],
    "summary": "Settle a disagreement: the loan's current value of the field stands until a source says something new   (scope sfc:write | payouts:write)",
    "parameters": [
     {
      "name": "loan_number",
      "in": "path",
      "required": true,
      "schema": {
       "type": "string"
      }
     },
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "field"
        ],
        "properties": {
         "field": {
          "type": "string"
         },
         "note": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{loan_number, field, value_kept, resolved}"
     }
    }
   }
  },
  "/api/sfc/conflicts": {
   "get": {
    "tags": [
     "SFC loan book"
    ],
    "summary": "Every loan where the sources disagree about a set-once value (terms, economics, borrower attributes, documents)   (scope sfc:read | payouts:read)",
    "responses": {
     "200": {
      "description": "{conflicts[{loan_number, borrower_name, field, current_value, sources[{source, value, observed_at, actor}]}], count}"
     }
    }
   }
  },
  "/api/sfc/loans/{loan_number}/book": {
   "get": {
    "tags": [
     "SFC loan book"
    ],
    "summary": "The loan-book side of one loan: ledger + ledger check, modifications, complaints, sources, performance today, borrowing-base eligibility with the reasons   (scope sfc:read | payouts:read)",
    "parameters": [
     {
      "name": "loan_number",
      "in": "path",
      "required": true,
      "schema": {
       "type": "string"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{loan_number, transactions[], ledger{}, modifications[], complaints[], sources[], conflicts[], performance{performance_status, days_past_due, delinquency_bucket, months_on_book, …}, eligible_for_borrowing_base, not_eligible_because[], corrected_installments[]}. GET /api/sfc/loans/{loan_number} carries the same under book."
     }
    }
   }
  },
  "/api/sfc/snapshots": {
   "get": {
    "tags": [
     "SFC loan book"
    ],
    "summary": "Snapshot dates on file; with as_of, type or loan_number the rows themselves (one per loan per as-of date, never edited)   (scope sfc:read | payouts:read)",
    "parameters": [
     {
      "name": "as_of",
      "in": "query",
      "schema": {
       "type": "string",
       "format": "date"
      }
     },
     {
      "name": "type",
      "in": "query",
      "schema": {
       "type": "string",
       "enum": [
        "daily",
        "month_end"
       ]
      }
     },
     {
      "name": "loan_number",
      "in": "query",
      "schema": {
       "type": "string"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{dates[{as_of_date, daily, month_end}], snapshots[{as_of_date, snapshot_type, loan_number, status, performance_status, days_past_due, delinquency_bucket, current_balance, principal_balance, interest_accrued, amount_past_due, scheduled_payment, payments_made_count, months_on_book, cumulative_principal_paid, cumulative_interest_paid, cumulative_chargeoff, cumulative_recovery, modification_count, autopay_enabled, banking_update_status, at_risk, source_of_last_update, last_synced_at}]}"
     }
    }
   }
  },
  "/api/sfc/snapshots/run": {
   "post": {
    "tags": [
     "SFC loan book"
    ],
    "summary": "Write the snapshot rows of a date now (the worker does it every 20 minutes and after each sync). An unchanged loan is left alone; a changed one gets a new row that supersedes the old   (scope sfc:write | payouts:write)",
    "parameters": [
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "as_of": {
          "type": "string",
          "format": "date",
          "description": "default today; never in the future"
         },
         "snapshot_type": {
          "type": "string",
          "enum": [
           "daily",
           "month_end"
          ]
         },
         "force": {
          "type": "boolean",
          "description": "rewrite a closed month's month_end rows — needs reason"
         },
         "reason": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{as_of_date, snapshot_type, written, superseded, unchanged, not_on_book_that_day}"
     },
     "409": {
      "description": "the month is closed"
     }
    }
   }
  },
  "/api/sfc/metrics/{name}": {
   "get": {
    "tags": [
     "SFC loan book"
    ],
    "summary": "Lender metrics from the snapshots and the ledger: delinquency | roll-rates | fpd | vintages | prepayment | recourse | disputes | concentration | kpis | ledger-check | summary   (scope sfc:read | payouts:read)",
    "description": "Rates are fractions (0.08 = 8%); null = not enough data. 30+ = more than 30 days past due. A withdrawn application is in no numerator or denominator; a funded-loan denominator counts loans SFC funded. delinquency takes as_of; roll-rates takes from / to (default: the last two month-ends, or the first snapshot against today); fpd = first / second / third installment not paid within 30 days; vintages = by month of funding_date (start_date while that is blank) and month on book; prepayment = month by month SMM / CPR (borrower and refinance payoffs only), MDR / CDR, recoveries, yield; recourse = exposure inside the window, exposure with no window on file, paid vs demanded; kpis = the limits with red / amber / ok / na.",
    "parameters": [
     {
      "name": "name",
      "in": "path",
      "required": true,
      "schema": {
       "type": "string",
       "enum": [
        "delinquency",
        "roll-rates",
        "fpd",
        "vintages",
        "prepayment",
        "recourse",
        "disputes",
        "concentration",
        "kpis",
        "ledger-check",
        "summary"
       ]
      }
     },
     {
      "name": "merchant_id",
      "in": "query",
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "sale_type",
      "in": "query",
      "schema": {
       "type": "string",
       "enum": [
        "front_end",
        "upsell"
       ]
      }
     },
     {
      "name": "product_type",
      "in": "query",
      "schema": {
       "type": "string"
      }
     },
     {
      "name": "borrower_state",
      "in": "query",
      "schema": {
       "type": "string"
      }
     },
     {
      "name": "vintage",
      "in": "query",
      "schema": {
       "type": "string",
       "description": "YYYY-MM"
      }
     },
     {
      "name": "as_of",
      "in": "query",
      "schema": {
       "type": "string",
       "format": "date"
      }
     },
     {
      "name": "from",
      "in": "query",
      "schema": {
       "type": "string",
       "format": "date"
      }
     },
     {
      "name": "to",
      "in": "query",
      "schema": {
       "type": "string",
       "format": "date"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "the metric + filters{}"
     },
     "404": {
      "description": "unknown metric",
      "or no snapshot of the date asked for": null
     }
    }
   }
  },
  "/api/sfc/report/weekly": {
   "get": {
    "tags": [
     "SFC loan book"
    ],
    "summary": "Weekly: first-payment default and early delinquency (three months on book or younger) by merchant and product   (scope sfc:read | payouts:read)",
    "responses": {
     "200": {
      "description": "{as_of, first_payment_default{}, early_delinquency_by_merchant[], early_delinquency_by_product[], early_delinquent_loans[]}"
     }
    }
   }
  },
  "/api/sfc/report/monthly": {
   "get": {
    "tags": [
     "SFC loan book"
    ],
    "summary": "Month-end pack: delinquency, roll-rate matrix, vintages, the month's CPR / CDR / losses, recourse, disputes / refunds / cancellations, concentration, limits, the stored SFC statement reconcile, close status   (scope sfc:read | payouts:read)",
    "parameters": [
     {
      "name": "month",
      "in": "query",
      "schema": {
       "type": "string",
       "description": "YYYY-MM, default the current month (in progress)"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "{month, month_end, as_of, in_progress, delinquency{}, roll_rates{}, vintages{}, month_performance{}, recourse{}, disputes_refunds_cancellations{}, concentration{}, kpis{}, reconciliation{} | null, closed{} | null}"
     }
    }
   }
  },
  "/api/sfc/month-end": {
   "get": {
    "tags": [
     "SFC loan book"
    ],
    "summary": "Closed months and the months that have ended and are waiting to be closed   (scope sfc:read | payouts:read)",
    "responses": {
     "200": {
      "description": "{closed[{month, closed_at, closed_by, note, loans}], ready_to_close[], month_in_progress}"
     }
    }
   }
  },
  "/api/sfc/month-end/close": {
   "post": {
    "tags": [
     "SFC loan book"
    ],
    "summary": "Close a month that has ended: write its month_end snapshots, keep the month's report with them, lock them   (scope sfc:write | payouts:write)",
    "parameters": [
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "month"
        ],
        "properties": {
         "month": {
          "type": "string",
          "description": "YYYY-MM"
         },
         "note": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{month, closed, month_end, snapshots{}, loans, report{}}"
     },
     "400": {
      "description": "the month has not ended"
     },
     "409": {
      "description": "already closed"
     }
    }
   }
  },
  "/api/sfc/tape/dictionary": {
   "get": {
    "tags": [
     "SFC loan book"
    ],
    "summary": "Data dictionary of the four tapes: column, type, definition, source, and whether it is SFC-sourced, derived, filled in by us or kept by the system   (scope sfc:read | payouts:read)",
    "responses": {
     "200": {
      "description": "{loans[], payments[], transactions[], snapshots[], origins{}, conventions[]}"
     }
    }
   }
  },
  "/api/sfc/tape/{kind}": {
   "get": {
    "tags": [
     "SFC loan book"
    ],
    "summary": "Data tape as CSV (format=json for JSON): loans | payments (installments) | transactions (the payment tape) | snapshots   (scope sfc:read | payouts:read)",
    "description": "Blank where a value is not on file — nothing is estimated. anonymize=1 is the lender version: no borrower_name, no client_id, no sfc_loan_number; loan_id identifies the loan. The loan tape of an earlier date uses the latest stored snapshot on or before it (404 before the first snapshot); close-out values only show once their date is on or before as_of. Withdrawn applications are not on the tapes.",
    "parameters": [
     {
      "name": "kind",
      "in": "path",
      "required": true,
      "schema": {
       "type": "string",
       "enum": [
        "loans",
        "payments",
        "transactions",
        "snapshots"
       ]
      }
     },
     {
      "name": "as_of",
      "in": "query",
      "schema": {
       "type": "string",
       "format": "date"
      }
     },
     {
      "name": "anonymize",
      "in": "query",
      "schema": {
       "type": "string",
       "enum": [
        "1"
       ]
      }
     },
     {
      "name": "format",
      "in": "query",
      "schema": {
       "type": "string",
       "enum": [
        "csv",
        "json"
       ]
      }
     },
     {
      "name": "include_all",
      "in": "query",
      "schema": {
       "type": "string",
       "enum": [
        "1"
       ]
      },
      "description": "transactions: also unconfirmed and replaced rows"
     },
     {
      "name": "type",
      "in": "query",
      "schema": {
       "type": "string",
       "enum": [
        "daily",
        "month_end"
       ]
      },
      "description": "snapshots only"
     },
     {
      "name": "merchant_id",
      "in": "query",
      "schema": {
       "type": "integer"
      }
     },
     {
      "name": "vintage",
      "in": "query",
      "schema": {
       "type": "string"
      }
     }
    ],
    "responses": {
     "200": {
      "description": "text/csv (attachment), or with format=json {tape, as_of, rows, anonymized, columns[], data[]}"
     },
     "404": {
      "description": "no snapshot on or before as_of"
     }
    }
   }
  },
  "/api/sfc/import/csv": {
   "post": {
    "tags": [
     "SFC loan book"
    ],
    "summary": "Import an SFC portal export — loan list, payment history, transactions or a funding statement — with a column mapping, a preview and a commit   (scope sfc:write | payouts:write)",
    "description": "Send the table as csv (text) or as columns + rows. Only mapped columns are read; every other column is dropped before anything is stored, and the request's audit row keeps a summary, never the file. A column whose name reads like an SSN, birth date or account number cannot be mapped, and every row passes the PII refusal. Without commit: true (or with X-Dry-Run) nothing is written and the answer is the preview. A commit writes a sync run (source sfc_portal_csv, the kind, the file's SHA-256) and remembers the mapping for that kind of file. Idempotent: loans by loan number, payments by loan + due date, transactions by source_ref (made from the row when the file has no id column).",
    "parameters": [
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "required": [
         "kind"
        ],
        "properties": {
         "kind": {
          "type": "string",
          "enum": [
           "loans",
           "payments",
           "transactions",
           "funding_statement"
          ]
         },
         "csv": {
          "type": "string"
         },
         "columns": {
          "type": "array",
          "items": {
           "type": "string"
          }
         },
         "rows": {
          "type": "array",
          "items": {
           "type": "array",
           "items": {
            "type": "string"
           }
          }
         },
         "mapping": {
          "type": "object",
          "description": "{column header: field} — an empty value leaves the column out"
         },
         "commit": {
          "type": "boolean"
         },
         "file_name": {
          "type": "string"
         },
         "file_hash": {
          "type": "string",
          "description": "SHA-256 of the file, when the caller has it"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{kind, columns[], mapping{}, ignored_columns[], fields_available[], needs_mapping[], rows, created, updated, unchanged, errors, results[{row, loan_number, result, changes, message}], committed, file_sha256}"
     }
    }
   }
  },
  "/api/sfc/merchants": {
   "get": {
    "tags": [
     "SFC loan book"
    ],
    "summary": "Merchants of the loan book (merchant_id on a loan)   (scope sfc:read | payouts:read)",
    "responses": {
     "200": {
      "description": "{merchants[{id, name, vertical, affiliate, active, notes}], count}"
     }
    }
   },
   "post": {
    "tags": [
     "SFC loan book"
    ],
    "summary": "Add a merchant, or change one by id or name   (scope sfc:write | payouts:write)",
    "parameters": [
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "id": {
          "type": "integer"
         },
         "name": {
          "type": "string"
         },
         "vertical": {
          "type": "string"
         },
         "affiliate": {
          "type": "boolean",
          "description": "an affiliate merchant's loans are not eligible for the borrowing base"
         },
         "active": {
          "type": "boolean"
         },
         "notes": {
          "type": "string"
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{id, name, result (created | updated)}"
     }
    }
   }
  },
  "/api/sfc/kpi-thresholds": {
   "get": {
    "tags": [
     "SFC loan book"
    ],
    "summary": "The limits the KPIs are judged against, and the licensed states used for borrowing-base eligibility   (scope sfc:read | payouts:read)",
    "responses": {
     "200": {
      "description": "{thresholds{fpd_rate_max, rate_30_plus_max, disputes_refunds_max, autopay_min, largest_merchant_max, nco_plan_monthly, eligibility_max_modifications}, defaults{}, licensed_states[]}"
     }
    }
   },
   "post": {
    "tags": [
     "SFC loan book"
    ],
    "summary": "Change the limits (a value above 1 is read as a percentage) and the licensed states   (scope sfc:write | payouts:write)",
    "parameters": [
     {
      "$ref": "#/components/parameters/dryRun"
     }
    ],
    "requestBody": {
     "content": {
      "application/json": {
       "schema": {
        "type": "object",
        "properties": {
         "fpd_rate_max": {
          "type": "number"
         },
         "rate_30_plus_max": {
          "type": "number"
         },
         "disputes_refunds_max": {
          "type": "number"
         },
         "autopay_min": {
          "type": "number"
         },
         "largest_merchant_max": {
          "type": "number"
         },
         "nco_plan_monthly": {
          "type": "number",
          "description": "below 0 = no plan"
         },
         "eligibility_max_modifications": {
          "type": "number"
         },
         "licensed_states": {
          "type": "array",
          "items": {
           "type": "string"
          }
         }
        }
       }
      }
     }
    },
    "responses": {
     "200": {
      "description": "{thresholds{}, changed{}}"
     }
    }
   }
  }
 }
}