openapi: 3.0.3 info: title: Admin API version: 0.3.0 description: | API contract for routes currently wired in `backend/infrastructure/lib/api-stack.ts`. The current API Gateway deployment exposes: - `GET /health` - `GET /v1/admin/geographic-areas` - `GET|POST /v1/admin/locations` - `POST /v1/admin/locations/geocode` - `PUT|PATCH|DELETE /v1/admin/locations/{id}` - `GET /v1/admin/users` - `GET /v1/admin/instructors` - `GET|POST /v1/admin/cognito-users` (paginated user-pool listing; create) - `GET|PATCH|DELETE /v1/admin/cognito-users/{username}` - `GET /v1/admin/audit-logs` (optional `table`, `record_id`, `user_id`, `email`, `action`, `since`, `cursor`, `limit`) - `GET|POST /v1/admin/api-keys` (create returns plaintext `api_token` once) - `DELETE /v1/admin/api-keys/{id}` (revokes the token) - `GET|POST /v1/admin/services` - `GET /v1/admin/services/instances` - `GET|PUT|PATCH|DELETE /v1/admin/services/{id}` - `GET /v1/admin/services/{id}/discount-code-usage-summary` - `POST /v1/admin/services/{id}/cover-image` - `GET|POST /v1/admin/services/{id}/instances` - `GET|PUT|DELETE /v1/admin/services/{id}/instances/{instance_id}` - `GET|POST /v1/admin/services/{id}/instances/{instance_id}/enrollments` - `PATCH|DELETE /v1/admin/services/{id}/instances/{instance_id}/enrollments/{enrollment_id}` - `GET|POST /v1/admin/discount-codes` - `PUT|DELETE /v1/admin/discount-codes/{id}` - `GET|POST /v1/admin/completion-certificates` - `POST /v1/admin/completion-certificates/preview` - `DELETE /v1/admin/completion-certificates/{id}` - `GET /v1/admin/completion-certificates/{id}/pdf` - `POST /v1/admin/completion-certificates/{id}/void` - `GET|POST /v1/admin/calendar/manual-blocks` (GET requires `purpose`, `from`, `to`) - `PATCH|DELETE /v1/admin/calendar/manual-blocks/{id}` - `GET|POST /v1/admin/tags` (optional `include_archived`, `archived_only`) - `PATCH|DELETE /v1/admin/tags/{id}` (DELETE returns JSON with `deleted` and `usage_count`) - `GET /v1/admin/contacts/tags` - `GET /v1/admin/contacts/search` - `POST /v1/admin/contacts/merge` - `POST /v1/admin/contacts/mailchimp-sync-run` - `POST /v1/admin/contacts/mailchimp-sync-orphans` - `GET /v1/admin/contacts/mailchimp-sync-status` - `GET /v1/admin/contacts/map-pins` - `GET|POST /v1/admin/contacts` - `GET|PATCH|DELETE /v1/admin/contacts/{id}` - `GET|POST /v1/admin/contacts/{id}/notes` - `PATCH|DELETE /v1/admin/contacts/{id}/notes/{note_id}` - `GET /v1/admin/contacts/{id}/services` - `GET /v1/admin/families/picker` - `GET|POST /v1/admin/families` - `PATCH|DELETE /v1/admin/families/{id}` - `GET /v1/admin/families/{id}/services` - `POST /v1/admin/families/{id}/members` - `PATCH|DELETE /v1/admin/families/{id}/members/{member_id}` - `GET /v1/admin/organizations/picker` - `GET|POST /v1/admin/organizations` - `PATCH|DELETE /v1/admin/organizations/{id}` - `GET /v1/admin/organizations/{id}/services` - `POST /v1/admin/organizations/{id}/members` - `PATCH /v1/admin/organizations/{id}/members/{member_id}` - `DELETE /v1/admin/organizations/{id}/members/{member_id}` - `GET /v1/admin/forms` (lists form slugs with answer counts from DynamoDB) - `GET|DELETE /v1/admin/forms/{form_slug}/answers` (`DELETE` removes all stored answers for the form) - `GET /v1/admin/forms/{form_slug}/answers/export` (CSV export of all answers for the form) - `GET /v1/admin/polls` (lists poll slugs with answer counts from DynamoDB) - `GET|DELETE /v1/admin/polls/{poll_slug}/answers` (`DELETE` removes all stored answers for the poll) - `GET /v1/admin/polls/{poll_slug}/answers/export` (CSV export of all answers for the poll) - `GET|POST /v1/admin/expenses` - `POST /v1/admin/expenses/import-from-bulk-pdf` (returns **202** with a job id; poll `GET /v1/admin/expenses/bulk-import-jobs/{job_id}` until `succeeded`, `succeeded_with_errors`, or `failed`) - `GET /v1/admin/expenses/bulk-import-jobs` (creator-scoped list of recent jobs) - `GET|DELETE /v1/admin/expenses/bulk-import-jobs/{job_id}` (`DELETE` removes the job record for the creator; it does not delete expenses created by the job) - `PATCH|DELETE /v1/admin/expenses/{id}` - `POST /v1/admin/expenses/{id}/cancel` - `POST /v1/admin/expenses/{id}/mark-paid` - `POST /v1/admin/expenses/{id}/reparse` - `POST /v1/admin/expenses/{id}/amend` - `GET /v1/admin/billing/export` - `GET|POST /v1/admin/billing/payments` (list is cursor-paginated (`cursor`, `limit`) and supports optional `?invoice_id=` to return payments with an allocation to that invoice; `POST` creates either a refund row (`direction: refund`) or a manual inbound customer payment (`direction: inbound` + `enrollmentId`)) - `GET|PATCH|DELETE /v1/admin/billing/payments/{id}` (`GET` returns payment detail including `allocationInvoices` and `unappliedAmount`; `PATCH` updates manual inbound rows without a Stripe PaymentIntent; enrollment is immutable; succeeded rows allow method and external reference only; `DELETE` removes eligible orphan inbound payments, including pending rows still linked to an active enrollment) - `POST /v1/admin/billing/payments/{id}/confirm` - `GET /v1/admin/billing/enrollments/recent-for-invoicing` - `GET|POST /v1/admin/billing/invoices` (GET optional `status`, `currency`, `contact_id`, `family_id`, `organization_id`, `cursor`, `limit`; POST is either enrollment-based draft (`draftKind: enrollment_merge`, `enrollmentIds`, `currency` optional when derivable) or customized draft (`draftKind: customized_manual`, `billTo`, `currency`, `lines`); see request schemas) - `GET|DELETE /v1/admin/billing/invoices/{id}` (`DELETE` removes **draft** invoices only) - `GET /v1/admin/billing/invoices/{id}/pdf` - `POST /v1/admin/billing/invoices/{id}/issue` (creates a pending inbound customer payment for positive totals unless a succeeded Stripe payment already exists for an enrollment on the invoice; `enrollmentId` is set only when the invoice has exactly one enrollment line) - `POST /v1/admin/billing/invoices/{id}/void` - `POST /v1/admin/billing/invoices/{id}/email` - `POST /v1/admin/billing/dashboard/resolve-bill-to-primary-contacts` (bulk lookup of primary CRM contact ids for family and organisation ids; used to roll up issued invoice totals to main contacts in admin dashboard spend rankings) - `POST /v1/admin/billing/allocations` - `GET|POST /v1/admin/leads` - `POST /v1/admin/leads/merge` - `GET|PATCH /v1/admin/leads/{id}` - `POST /v1/admin/leads/{id}/notes` - `GET|POST /v1/admin/leads/{id}/ai-suggestion` (POST queues async job; poll `.../ai-suggestion/jobs/{job_id}`) - `GET /v1/admin/leads/analytics` - `GET|POST|DELETE /v1/admin/leads/daily-plan` (POST queues async job with optional `operator_input` and `operator_input_scope` of `today` or `standing`; poll `.../daily-plan/jobs/{job_id}`; DELETE resets stored plans, item state, and instructions) - `GET|POST /v1/admin/leads/daily-plan/instructions` and `DELETE /v1/admin/leads/daily-plan/instructions/{instruction_id}` (active refinements; `today` lasts until the next 06:00 HKT, `standing` until removed) - `POST /v1/admin/leads/daily-plan/priority-completions` (tick or untick a priority until the next 06:00 HKT; identity is org-wide) - `GET|PATCH /v1/admin/leads/settings` - `GET /v1/admin/whatsapp/conversations` - `GET /v1/admin/whatsapp/conversations/{id}/messages` - `GET|POST /v1/admin/whatsapp/import-jobs` - `GET /v1/admin/meta/conversations` - `GET /v1/admin/meta/conversations/{id}/messages` - `GET|POST /v1/admin/meta/import-jobs` - `GET|POST /v1/admin/assets` - `GET|PUT|PATCH|DELETE /v1/admin/assets/{id}` - `POST /v1/admin/assets/{id}/content/init` - `POST /v1/admin/assets/{id}/content/complete` - `GET|POST /v1/admin/assets/{id}/grants` - `DELETE /v1/admin/assets/{id}/grants/{grantId}` - `GET|POST|DELETE /v1/admin/assets/{id}/share-link` - `POST /v1/admin/assets/{id}/share-link/rotate` - `GET /v1/user/assets` - `GET /v1/user/assets/{id}/download` servers: - url: https://api.evolvesprouts.com/prod description: Production API. Paths below are appended to this URL. The execute-api hostname does not accept calls. paths: /health: get: operationId: getHealth summary: Health check description: Returns backend health status and dependency checks. security: - SigV4Auth: [] responses: "200": description: Service is healthy. content: application/json: schema: $ref: "#/components/schemas/HealthResponse" "503": description: Service is unhealthy. content: application/json: schema: $ref: "#/components/schemas/HealthResponse" "403": description: API Gateway rejected the caller signature. /v1/admin/assets: get: operationId: getV1AdminAssets summary: List admin assets description: Admin-only route for listing managed assets. security: - AdminBearerAuth: [] parameters: - name: query in: query required: false schema: type: string description: > Case-insensitive match on title, file name, or resource key. For assets linked to a customer invoice, also matches `bill_to_display_name` and `invoice_number`. - name: visibility in: query required: false schema: type: string enum: [public, restricted] - name: asset_type in: query required: false schema: type: string enum: [guide, video, pdf, document] - name: tag_name in: query required: false schema: type: string maxLength: 100 description: > When set, return only assets that have this tag (case-insensitive name match). The tag must be linked to at least one asset that matches the optional asset_type filter. - name: cursor in: query required: false schema: type: string - name: limit in: query required: false schema: type: integer minimum: 1 maximum: 100 responses: "200": description: Asset list response. content: application/json: schema: $ref: "#/components/schemas/AssetListResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" post: operationId: postV1AdminAssets summary: Create admin asset description: > Admin-only route for creating an asset. When `visibility` is `public`, the handler also creates a share-link row seeded from `ASSET_SHARE_LINK_DEFAULT_ALLOWED_DOMAINS` (public website hostnames from stack parameters). Restricted assets do not receive a share link until an operator creates one. security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CreateAssetRequest" responses: "201": description: Asset create response. content: application/json: schema: $ref: "#/components/schemas/CreateAssetResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/assets/{id}: parameters: - $ref: "#/components/parameters/AssetId" get: operationId: getV1AdminAssetsById summary: Get admin asset security: - AdminBearerAuth: [] responses: "200": description: Asset response. content: application/json: schema: $ref: "#/components/schemas/AssetResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" put: operationId: putV1AdminAssetsById summary: Update admin asset security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/UpdateAssetRequest" responses: "200": description: Asset update response. content: application/json: schema: $ref: "#/components/schemas/AssetResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" patch: operationId: patchV1AdminAssetsById summary: Partially update admin asset security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/PartialUpdateAssetRequest" responses: "200": description: Asset update response. content: application/json: schema: $ref: "#/components/schemas/AssetResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" delete: operationId: deleteV1AdminAssetsById summary: Delete admin asset description: > Permanently deletes the asset metadata and its S3 object. Not allowed when the asset has the `expense_attachment` or `customer_invoice` tag (400). security: - AdminBearerAuth: [] responses: "204": description: Asset deleted. "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/assets/{id}/content/init: parameters: - $ref: "#/components/parameters/AssetId" post: operationId: postV1AdminAssetsByIdContentInit summary: Begin admin asset file replacement description: > Step 1 of 2 for replacing the binary stored for an asset while keeping the same asset id. Returns a presigned upload URL for a new S3 key under `assets/{id}/...`. Call `POST /v1/admin/assets/{id}/content/complete` after the client uploads to that URL. Not allowed when the asset has the `expense_attachment` or `customer_invoice` tag (400). The presigned PUT binds `Content-Type: application/pdf` regardless of optional `content_type` in the body. security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/InitAssetContentReplaceRequest" responses: "200": description: Presigned upload details and pending object key. content: application/json: schema: $ref: "#/components/schemas/InitAssetContentReplaceResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/assets/{id}/content/complete: parameters: - $ref: "#/components/parameters/AssetId" post: operationId: postV1AdminAssetsByIdContentComplete summary: Complete admin asset file replacement description: > Step 2 of 2: verifies the object exists at `pending_s3_key`, updates the asset to point at it, deletes the previous S3 object, and returns the updated asset. The `pending_s3_key` must be the value returned by `POST .../content/init` for this asset id. Not allowed when the asset has the `expense_attachment` or `customer_invoice` tag (400). `file_name` must match the filename embedded in `pending_s3_key` after server-side sanitization (same rules as init). The object name segment must begin with a standard UUID prefix (`xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx-`) from init. Stored `content_type` is always `application/pdf`; the uploaded object's S3 Content-Type and size are validated on complete (max 50 MiB). This call is not idempotent across different `pending_s3_key` values: repeating complete with a stale key after a successful replace returns 400. Concurrent replaces for the same asset are last-writer-wins; earlier pending keys may become orphans if never completed. BadRequest responses may include `field` values such as `pending_s3_key`, `file_name`, `content_type`, or `asset` depending on the failure. security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CompleteAssetContentReplaceRequest" responses: "200": description: Updated asset after successful replacement. content: application/json: schema: $ref: "#/components/schemas/AssetResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/assets/{id}/grants: parameters: - $ref: "#/components/parameters/AssetId" get: operationId: getV1AdminAssetsByIdGrants summary: List asset grants security: - AdminBearerAuth: [] responses: "200": description: Grant list response. content: application/json: schema: $ref: "#/components/schemas/AssetGrantListResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" post: operationId: postV1AdminAssetsByIdGrants summary: Create asset grant security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CreateAssetGrantRequest" responses: "201": description: Grant create response. content: application/json: schema: $ref: "#/components/schemas/AssetGrantResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/assets/{id}/grants/{grantId}: parameters: - $ref: "#/components/parameters/AssetId" - $ref: "#/components/parameters/GrantId" delete: operationId: deleteV1AdminAssetsByIdGrantsByGrantId summary: Delete asset grant security: - AdminBearerAuth: [] responses: "204": description: Grant deleted. "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/assets/{id}/share-link: parameters: - $ref: "#/components/parameters/AssetId" get: operationId: getV1AdminAssetsByIdShareLink summary: Get stable asset share link security: - AdminBearerAuth: [] responses: "200": description: Existing share link returned. content: application/json: schema: $ref: "#/components/schemas/AssetShareLinkResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" post: operationId: postV1AdminAssetsByIdShareLink summary: Get or create stable asset share link security: - AdminBearerAuth: [] requestBody: required: false content: application/json: schema: $ref: "#/components/schemas/AssetShareLinkPolicyRequest" responses: "200": description: Existing share link returned. content: application/json: schema: $ref: "#/components/schemas/AssetShareLinkResponse" "201": description: Share link created. content: application/json: schema: $ref: "#/components/schemas/AssetShareLinkResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" delete: operationId: deleteV1AdminAssetsByIdShareLink summary: Revoke stable asset share link security: - AdminBearerAuth: [] responses: "204": description: Share link revoked. "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/assets/{id}/share-link/rotate: parameters: - $ref: "#/components/parameters/AssetId" post: operationId: postV1AdminAssetsByIdShareLinkRotate summary: Rotate stable asset share link security: - AdminBearerAuth: [] requestBody: required: false content: application/json: schema: $ref: "#/components/schemas/AssetShareLinkPolicyRequest" responses: "200": description: Share link rotated. content: application/json: schema: $ref: "#/components/schemas/AssetShareLinkResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/geographic-areas: get: operationId: getV1AdminGeographicAreas summary: List geographic areas description: | Returns geographic areas used for address/location selection. Use `parent_id` to fetch direct children, or `flat=true` to return a flattened tree. security: - AdminBearerAuth: [] parameters: - name: parent_id in: query required: false schema: type: string format: uuid - name: flat in: query required: false schema: type: boolean default: false - name: active_only in: query required: false schema: type: boolean default: true responses: "200": description: Geographic area list response. content: application/json: schema: $ref: "#/components/schemas/GeographicAreaListResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/locations: get: operationId: getV1AdminLocations summary: List locations security: - AdminBearerAuth: [] parameters: - name: limit in: query required: false schema: type: integer minimum: 1 maximum: 100 default: 25 - name: cursor in: query required: false schema: type: string - name: area_id in: query required: false schema: type: string format: uuid - name: search in: query required: false description: Case-insensitive substring match on location name or address. schema: type: string maxLength: 500 - name: exclude_addresses in: query required: false description: | When `true`, omit locations linked as the saved venue for a non-archived family or organisation (so Services → Venues lists only service-oriented venues). Partner organisations are still included when they use the same location row; those rows remain visible with partner lock metadata. schema: type: boolean default: false responses: "200": description: Location list response. content: application/json: schema: $ref: "#/components/schemas/LocationListResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" post: operationId: postV1AdminLocations summary: Create location security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CreateLocationRequest" responses: "201": description: Location create response. content: application/json: schema: $ref: "#/components/schemas/LocationResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/locations/geocode: post: operationId: postV1AdminLocationsGeocode summary: Geocode a venue address description: | Resolves latitude and longitude using OpenStreetMap's public geocoder via the AWS HTTP proxy. The free-text query keeps the street-number, street/road, and neighbourhood portions of the submitted address. Comma-separated unit, floor, block, tower, and estate/building segments are dropped (including floor markers such as ``G/F`` or ``5/F``). District and country names from the geographic area are not appended. The ``countrycodes`` query parameter is built from the root area ISO code plus the sovereign country row's code when ``sovereign_country_id`` is set (see ``GET /v1/admin/geographic-areas``). security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/GeocodeLocationRequest" responses: "200": description: Geocoding result. content: application/json: schema: $ref: "#/components/schemas/GeocodeLocationResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" "502": description: Geocoding provider or proxy error. content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" "503": description: Geocoding is not configured (for example missing proxy or headers). content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" /v1/admin/locations/{id}: parameters: - $ref: "#/components/parameters/LocationId" put: operationId: putV1AdminLocationsById summary: Update location security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/UpdateLocationRequest" responses: "200": description: Location update response. content: application/json: schema: $ref: "#/components/schemas/LocationResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" patch: operationId: patchV1AdminLocationsById summary: Partially update location security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/PartialUpdateLocationRequest" responses: "200": description: Location update response. content: application/json: schema: $ref: "#/components/schemas/LocationResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" delete: operationId: deleteV1AdminLocationsById summary: Delete location security: - AdminBearerAuth: [] responses: "204": description: Location deleted. "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" "409": description: Location is linked to an active partner organisation. content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" /v1/admin/cognito-users: get: operationId: getV1AdminCognitoUsers summary: List Cognito users description: > Returns a page of users from the Cognito user pool. Optional `name` and `email` filters use Cognito `ListUsers` prefix/exact match (`email` with `@` is exact). When both are set, `email` is applied in Cognito and `name` is a case-insensitive substring on that page. Staff groups (`admin`, `manager`, `instructor`) are attached from `ListUsersInGroup`. security: - AdminBearerAuth: [] parameters: - name: limit in: query required: false schema: type: integer minimum: 1 maximum: 100 default: 25 - name: cursor in: query required: false description: Opaque continuation token from `next_cursor`. schema: type: string - name: name in: query required: false schema: type: string - name: email in: query required: false schema: type: string responses: "200": description: Paginated Cognito user list. content: application/json: schema: $ref: "#/components/schemas/CognitoUserListResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" post: operationId: postV1AdminCognitoUsers summary: Create a Cognito user description: > Creates a user in the Cognito user pool (username is the email). Passwordless sign-in is unchanged: Cognito's temporary-password email is suppressed. Optional `group` must be a staff group (`admin`, `manager`, or `instructor`). security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CreateCognitoUserRequest" responses: "201": description: Created Cognito user. content: application/json: schema: $ref: "#/components/schemas/CognitoUser" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "409": description: A user with this email already exists. content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" /v1/admin/cognito-users/{username}: parameters: - name: username in: path required: true schema: type: string get: operationId: getV1AdminCognitoUsersByUsername summary: Get a Cognito user description: Returns one user from the Cognito user pool by username. security: - AdminBearerAuth: [] responses: "200": description: Cognito user. content: application/json: schema: $ref: "#/components/schemas/CognitoUser" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" patch: operationId: patchV1AdminCognitoUsersByUsername summary: Update a Cognito user description: > Updates email, name, staff group, and/or enabled state. Omitting a field leaves it unchanged. `group` of `null` removes staff groups. Callers cannot disable themselves or remove their own staff group. security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/UpdateCognitoUserRequest" responses: "200": description: Updated Cognito user. content: application/json: schema: $ref: "#/components/schemas/CognitoUser" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" "409": description: A user with this email already exists. content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" delete: operationId: deleteV1AdminCognitoUsersByUsername summary: Delete a Cognito user description: Permanently deletes the user from the Cognito user pool. Callers cannot delete themselves. security: - AdminBearerAuth: [] responses: "200": description: Delete confirmation. content: application/json: schema: $ref: "#/components/schemas/DeleteCognitoUserResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/users: get: operationId: getV1AdminUsers summary: List admin users description: Returns users in the admin Cognito group for assignee selection. security: - AdminBearerAuth: [] responses: "200": description: Admin user list response. content: application/json: schema: $ref: "#/components/schemas/AdminUserListResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/instructors: get: operationId: getV1AdminInstructors summary: List instructor users description: Returns users in the instructor Cognito group for service instance assignment. security: - AdminBearerAuth: [] responses: "200": description: Instructor user list response. content: application/json: schema: $ref: "#/components/schemas/AdminUserListResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/audit-logs: get: operationId: getV1AdminAuditLogs summary: List audit log entries description: > Returns database audit history (trigger- and application-sourced rows in `audit_log`). Optional filters combine as in the admin Lambda handler: when `record_id` is set, `table` is required; `user_id` is a Cognito subject (sub), `api-key:`, or a system actor (`system`, `webhook:whatsapp`, `webhook:meta`, `alembic`, `system:sales-daily-plan`). Use `email` to filter by Cognito email, API key name, or system-actor label (server resolves to sub, `api-key:`, or the system `user_id`); do not pass `user_id` together with `email`. security: - AdminBearerAuth: [] parameters: - name: limit in: query required: false schema: type: integer minimum: 1 maximum: 100 default: 25 - name: cursor in: query required: false description: Opaque continuation token from `next_cursor` for the default recent listing. schema: type: string - name: table in: query required: false schema: type: string enum: - api_keys - asset_access_grants - asset_share_links - asset_tags - assets - bulk_expense_import_jobs - calendar_manual_blocks - completion_certificates - consultation_details - contact_tags - contacts - customer_invoice_lines - customer_invoices - customer_payments - customer_receipts - discount_codes - document_counters - enrollments - event_details - event_ticket_tiers - expense_attachments - expenses - families - family_members - family_tags - geographic_areas - inbound_emails - instance_session_slots - legacy_import_refs - locations - meta_conversations - meta_messages - notes - organization_members - organization_tags - organizations - payment_allocations - sales_lead_events - sales_leads - service_assets - service_instance_organizations - service_instance_tags - service_instances - service_tags - services - tags - training_course_details - training_instance_details - whatsapp_conversations - whatsapp_messages - name: record_id in: query required: false schema: type: string - name: user_id in: query required: false schema: type: string - name: email in: query required: false description: > Filter by Cognito email, API key name, or system-actor label. Values containing `@` resolve to a Cognito `sub` via `list_users`. Other values first match known system actors (`System`, `WhatsApp webhook`, `Meta webhook`, `Alembic`, `Sales daily plan schedule`, or stored ids `system`, `webhook:whatsapp`, `webhook:meta`, `alembic`, `system:sales-daily-plan`), then `api_keys.name` (case-insensitive) which becomes `api-key:`. Mutually exclusive with `user_id`. When no actor matches, the response is an empty list. schema: type: string - name: action in: query required: false schema: type: string enum: [INSERT, UPDATE, DELETE] - name: since in: query required: false description: ISO 8601 timestamp; only entries at or after this time are returned where applicable. schema: type: string format: date-time responses: "200": description: Paginated audit log list. content: application/json: schema: $ref: "#/components/schemas/AuditLogListResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/api-keys: get: operationId: getV1AdminApiKeys summary: List API tokens description: | Lists hashed API tokens used by the `x-api-token` authorizer. The plaintext token is never stored and is not returned here. security: - AdminBearerAuth: [] parameters: - name: limit in: query required: false schema: type: integer minimum: 1 maximum: 100 default: 25 - name: cursor in: query required: false description: Opaque continuation token from `next_cursor`. schema: type: string responses: "200": description: Paginated API token list. content: application/json: schema: $ref: "#/components/schemas/ApiKeyListResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" post: operationId: postV1AdminApiKeys summary: Create an API token description: | Creates a hashed API token. The plaintext `api_token` is returned once in this response and cannot be retrieved again. security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CreateApiKeyRequest" responses: "201": description: Token created; plaintext included once. content: application/json: schema: $ref: "#/components/schemas/ApiKeyCreatedResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" /v1/admin/api-keys/{id}: parameters: - name: id in: path required: true schema: type: string format: uuid delete: operationId: deleteV1AdminApiKeysById summary: Revoke an API token description: Soft-revokes the token. Idempotent if already revoked. security: - AdminBearerAuth: [] responses: "200": description: Revoked token metadata. content: application/json: schema: $ref: "#/components/schemas/ApiKeySummary" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/leads: get: operationId: getV1AdminLeads summary: List sales leads security: - AdminBearerAuth: [] parameters: - name: limit in: query required: false schema: type: integer minimum: 1 maximum: 100 default: 25 - name: cursor in: query required: false description: Opaque continuation token from `next_cursor`; only valid when `sort` is `created_at`. schema: type: string - name: stage in: query required: false schema: type: string - name: source in: query required: false schema: type: string - name: lead_type in: query required: false schema: type: string - name: assigned_to in: query required: false schema: type: string - name: unassigned in: query required: false schema: type: boolean default: false - name: date_from in: query required: false schema: type: string format: date-time - name: date_to in: query required: false schema: type: string format: date-time - name: search in: query required: false schema: type: string - name: sort in: query required: false schema: type: string enum: [created_at, updated_at, funnel_stage, contact_name] default: created_at - name: sort_dir in: query required: false schema: type: string enum: [asc, desc] default: desc responses: "200": description: Lead list response. content: application/json: schema: $ref: "#/components/schemas/LeadListResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" post: operationId: postV1AdminLeads summary: Create sales lead description: > Always inserts a new lead (`is_manual: true`) even when the contact already has an open automated lead. Automated public and inbox paths reuse or reopen the contact's existing lead instead. security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CreateLeadRequest" responses: "201": description: Lead create response. content: application/json: schema: $ref: "#/components/schemas/LeadDetailResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/leads/merge: post: operationId: postV1AdminLeadsMerge summary: Merge selected sales leads description: > Merges two or more leads into the chosen keeper lead. When selected leads belong to different contacts, loser identity and related records are folded onto the keeper contact through the shared record-merge helpers (notes, enrollments, invoices, payments, conversations, certificates, tags, and remaining leads). Orphaned loser contacts are deleted. Non-selected leads on loser contacts remain on the keeper contact as separate lead rows except uniqueness conflicts. Selected lead rows are collapsed onto the keeper lead first. A leftover open automated lead on a loser contact is folded onto the keeper contact's open lead before the move is saved. The surviving lead keeps the higher lead-type rank and the further-along funnel stage. A remaining one-open-lead conflict returns 409. security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/MergeLeadsRequest" responses: "200": description: Surviving lead detail after merge. content: application/json: schema: $ref: "#/components/schemas/LeadDetailResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" "409": description: > The selected leads belong to contacts that each already have an open automated sales lead, and the merge could not fold them. content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" /v1/admin/leads/analytics: get: operationId: getV1AdminLeadsAnalytics summary: Lead analytics summary security: - AdminBearerAuth: [] parameters: - name: date_from in: query required: false schema: type: string format: date-time - name: date_to in: query required: false schema: type: string format: date-time responses: "200": description: Lead analytics response. content: application/json: schema: $ref: "#/components/schemas/LeadAnalyticsResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/leads/settings: get: operationId: getV1AdminLeadsSettings summary: Get sales lead assignment and OpenRouter model settings security: - AdminBearerAuth: [] responses: "200": description: Sales settings response. content: application/json: schema: $ref: "#/components/schemas/SalesSettingsResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" patch: operationId: patchV1AdminLeadsSettings summary: Update sales lead assignment and OpenRouter model settings security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/UpdateSalesSettingsRequest" responses: "200": description: Updated sales settings. content: application/json: schema: $ref: "#/components/schemas/SalesSettingsResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/leads/daily-plan: get: operationId: getV1AdminLeadsDailyPlan summary: Get latest org-wide sales plan of the day description: > Returns the newest stored org-wide AI sales daily plan, including staleness metadata, plus `memory` (up to the five newest stored plans, including the latest) and active `instructions`. `plan` is null when none has been generated yet. `suppressed_items` lists priorities the generator hid because they were done today, dismissed, or snoozed. A scheduled job also generates a new plan every day at 06:00 HKT. A plan is stale when it is older than 24 hours, when a newer WhatsApp/Meta message exists after the stored conversation watermark, when a lead was created or a funnel-stage event occurred after the stored pipeline watermark, or when a contact was created or updated after that watermark. `stale_counts` reports how many conversation, pipeline, and contact changes landed after those watermarks. `job` is the newest generation job (including a failed 06:00 HKT run). The serialized plan includes item keys, annotations, and follow-up `questions`. Pass `compare=true` to include `dropped_priorities` and per-priority `compare_status` versus the previous plan. `stale_counts` are populated only when activity (not age alone) made the plan stale. All stored plans are retained until `DELETE /v1/admin/leads/daily-plan`. security: - AdminBearerAuth: [] parameters: - name: compare in: query required: false description: > When `true`, `1`, or `yes`, compute new/carried/dropped priority comparison against the previous stored plan. schema: type: string enum: ["true", "false", "1", "0", "yes", "no"] responses: "200": description: Latest daily plan payload (or null) plus memory. content: application/json: schema: $ref: "#/components/schemas/SalesDailyPlanResponse" "403": $ref: "#/components/responses/Forbidden" post: operationId: postV1AdminLeadsDailyPlan summary: Queue org-wide sales plan of the day generation description: > Enqueues an asynchronous job that generates a sales-focused plan of the day via the shared OpenRouter pipeline (same Secrets Manager key, allow-listed chat-completions URL, and AWS HTTP proxy as lead AI suggestions). Context includes open pipeline, unanswered threads, unpaid issued invoices, and the published catalogue. Optional `operator_input` is stored on the job and the resulting plan and is saved as an instruction. `operator_input_scope` `today` (default) lasts until the next 06:00 HKT; `standing` is included until removed. Done, dismissed, and snoozed items are omitted in code after the model responds. Poll `GET /v1/admin/leads/daily-plan/jobs/{job_id}` for status, timing (`queue_wait_ms`, `duration_ms`), and the resulting plan. Does not send messages or payment reminders. security: - AdminBearerAuth: [] requestBody: required: false content: application/json: schema: $ref: "#/components/schemas/SalesDailyPlanGenerateRequest" responses: "202": description: Generation job accepted. content: application/json: schema: $ref: "#/components/schemas/SalesDailyPlanJobResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" delete: operationId: deleteV1AdminLeadsDailyPlan summary: Reset sale plan memory description: > Permanently deletes every stored sales daily plan, generation job, org-wide done/dismiss/snooze state, and instruction. Live contacts, leads, and messages are not affected. This cannot be undone. security: - AdminBearerAuth: [] responses: "204": description: Memory deleted. "403": $ref: "#/components/responses/Forbidden" /v1/admin/leads/daily-plan/jobs/{job_id}: parameters: - name: job_id in: path required: true schema: type: string format: uuid get: operationId: getV1AdminLeadsDailyPlanJobsByJobId summary: Get sales daily plan job status description: > Returns job status and timing. When `status` is `succeeded`, includes the serialized plan. Use `queue_wait_ms` (created→started) and `duration_ms` (started→finished) to time OpenRouter runs. security: - AdminBearerAuth: [] responses: "200": description: Job status payload. content: application/json: schema: $ref: "#/components/schemas/SalesDailyPlanJobResponse" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/leads/daily-plan/priority-completions: post: operationId: postV1AdminLeadsDailyPlanPriorityCompletions summary: Mark or unmark an insight priority as done description: > Ticks or unticks one priority. Done state is org-wide and hides the same invoice, conversation, lead-and-kind, or instruction until the next 06:00 HKT, including after the insight is regenerated. `done: false` clears that suppression. `plan_id` is ignored. security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/SalesDailyPlanPriorityCompletionRequest" responses: "200": description: Updated plan plus the completion row (null when undone). content: application/json: schema: $ref: "#/components/schemas/SalesDailyPlanPriorityCompletionResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/leads/daily-plan/item-annotations: post: operationId: postV1AdminLeadsDailyPlanItemAnnotations summary: Upsert insight-board item annotation description: > Stores feedback (`up`, `down`, `not_relevant`), a snooze (`tomorrow`, `next_week`, or `clear`), and/or an edited outreach draft. Feedback and snooze are org-wide: `down` and `not_relevant` hide the item for 30 days, and snooze hides it until the chosen time. An edited `draft_reply` stays on the current plan; send `plan_id` and a mismatch with the latest plan returns 409. `item_key` is capped at 1024 characters. Omitted fields are left unchanged. security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/SalesDailyPlanItemAnnotationRequest" responses: "200": description: Updated plan plus the annotation row. content: application/json: schema: $ref: "#/components/schemas/SalesDailyPlanItemAnnotationResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" "409": description: The stored insight was refreshed after this page loaded. content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" /v1/admin/leads/daily-plan/questions: post: operationId: postV1AdminLeadsDailyPlanQuestions summary: Ask a follow-up question about the stored insight description: > Sends the stored plan JSON (not a fresh CRM snapshot) to OpenRouter using the Sales Config model, with a short timeout. The model call does not hold a database session. Send `plan_id` of the plan on screen; a mismatch with the latest plan at request start returns 409. GET responses return at most the 20 newest questions in chronological order. security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/SalesDailyPlanQuestionRequest" responses: "200": description: Updated plan plus the new question row. content: application/json: schema: $ref: "#/components/schemas/SalesDailyPlanQuestionResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" "409": description: The stored insight was refreshed after this page loaded. content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" "502": description: The model returned an empty or invalid answer. content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" "504": description: The model timed out. content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" /v1/admin/leads/daily-plan/instructions: get: operationId: getV1AdminLeadsDailyPlanInstructions summary: List active insight instructions description: > Returns refinements that later generations must honour. `today` instructions drop out after the next 06:00 HKT. `standing` instructions stay until deleted. security: - AdminBearerAuth: [] responses: "200": description: Active instructions. content: application/json: schema: $ref: "#/components/schemas/SalesDailyPlanInstructionListResponse" "403": $ref: "#/components/responses/Forbidden" post: operationId: postV1AdminLeadsDailyPlanInstructions summary: Save an insight instruction without generating description: > Stores a refinement. `scope` defaults to `today` (until the next 06:00 HKT). `standing` is included in every later generation until removed. An active instruction with the same scope and wording is reused. security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/SalesDailyPlanInstructionRequest" responses: "200": description: Saved instruction. content: application/json: schema: $ref: "#/components/schemas/SalesDailyPlanInstructionResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" /v1/admin/leads/daily-plan/instructions/{instruction_id}: parameters: - name: instruction_id in: path required: true schema: type: string format: uuid delete: operationId: deleteV1AdminLeadsDailyPlanInstructionsByInstructionId summary: Remove an insight instruction description: > Archives one instruction so later generations no longer include it. Stored plans are kept. security: - AdminBearerAuth: [] responses: "200": description: Archived instruction and the latest plan when one exists. content: application/json: schema: $ref: "#/components/schemas/SalesDailyPlanInstructionArchiveResponse" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/whatsapp/conversations: get: operationId: getV1AdminWhatsappConversations summary: List captured WhatsApp conversations security: - AdminBearerAuth: [] parameters: - name: limit in: query required: false schema: type: integer minimum: 1 maximum: 100 default: 25 - name: cursor in: query required: false description: Opaque continuation token from `next_cursor`. schema: type: string - name: q in: query required: false description: Case-insensitive search on profile name or WhatsApp id. schema: type: string - name: contact_id in: query required: false description: > Restrict results to conversations linked to this CRM contact. Mutually exclusive with `family_id` and `organization_id`. schema: type: string format: uuid - name: family_id in: query required: false description: > Restrict results to conversations linked to any member contact of this family. Mutually exclusive with `contact_id` and `organization_id`. schema: type: string format: uuid - name: organization_id in: query required: false description: > Restrict results to conversations linked to any member contact of this organisation. Mutually exclusive with `contact_id` and `family_id`. schema: type: string format: uuid responses: "200": description: Paginated WhatsApp conversation list. content: application/json: schema: $ref: "#/components/schemas/WhatsAppConversationListResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" /v1/admin/whatsapp/conversations/{id}/messages: parameters: - name: id in: path required: true schema: type: string format: uuid get: operationId: getV1AdminWhatsappConversationsByIdMessages summary: List messages for a WhatsApp conversation security: - AdminBearerAuth: [] parameters: - name: limit in: query required: false schema: type: integer minimum: 1 maximum: 100 default: 25 responses: "200": description: Conversation header plus newest-first messages. content: application/json: schema: $ref: "#/components/schemas/WhatsAppMessageListResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/whatsapp/import-jobs: get: operationId: getV1AdminWhatsappImportJobs summary: List WhatsApp export import jobs security: - AdminBearerAuth: [] parameters: - name: limit in: query required: false schema: type: integer minimum: 1 maximum: 100 default: 25 - name: cursor in: query required: false schema: type: string format: uuid responses: "200": description: Paginated WhatsApp export import jobs. content: application/json: schema: $ref: "#/components/schemas/InboxImportJobListResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" post: operationId: postV1AdminWhatsappImportJobs summary: Queue a WhatsApp chat export import description: > Upload a `.txt` or `.zip` WhatsApp Business App export as a restricted document asset first, then pass its id. Does not create new sales leads. Graph Cloud API cannot pull WhatsApp history; this parses a phone export. security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CreateWhatsAppExportImportJobRequest" responses: "202": description: Import job queued. content: application/json: schema: $ref: "#/components/schemas/InboxImportJobResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" /v1/admin/meta/conversations: get: operationId: getV1AdminMetaConversations summary: List captured Messenger and Instagram conversations security: - AdminBearerAuth: [] parameters: - name: limit in: query required: false schema: type: integer minimum: 1 maximum: 100 default: 25 - name: cursor in: query required: false description: Opaque continuation token from `next_cursor`. schema: type: string - name: q in: query required: false description: Case-insensitive search on profile name or Page-scoped user id. schema: type: string - name: channel in: query required: false description: Restrict results to `facebook` (Messenger) or `instagram`. schema: $ref: "#/components/schemas/MetaChannel" - name: contact_id in: query required: false description: > Restrict results to conversations linked to this CRM contact. Mutually exclusive with `family_id` and `organization_id`. schema: type: string format: uuid - name: family_id in: query required: false description: > Restrict results to conversations linked to any member contact of this family. Mutually exclusive with `contact_id` and `organization_id`. schema: type: string format: uuid - name: organization_id in: query required: false description: > Restrict results to conversations linked to any member contact of this organisation. Mutually exclusive with `contact_id` and `family_id`. schema: type: string format: uuid responses: "200": description: Paginated Meta conversation list. content: application/json: schema: $ref: "#/components/schemas/MetaConversationListResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" /v1/admin/meta/conversations/{id}/messages: parameters: - name: id in: path required: true schema: type: string format: uuid get: operationId: getV1AdminMetaConversationsByIdMessages summary: List messages for a Messenger or Instagram conversation security: - AdminBearerAuth: [] parameters: - name: limit in: query required: false schema: type: integer minimum: 1 maximum: 100 default: 25 responses: "200": description: Conversation header plus newest-first messages. content: application/json: schema: $ref: "#/components/schemas/MetaMessageListResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/meta/import-jobs: get: operationId: getV1AdminMetaImportJobs summary: List Messenger and Instagram Graph import jobs security: - AdminBearerAuth: [] parameters: - name: limit in: query required: false schema: type: integer minimum: 1 maximum: 100 default: 25 - name: cursor in: query required: false schema: type: string format: uuid responses: "200": description: Paginated Meta Graph import jobs. content: application/json: schema: $ref: "#/components/schemas/InboxImportJobListResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" post: operationId: postV1AdminMetaImportJobs summary: Queue a Messenger or Instagram recent-history import description: > Pulls Graph Conversations API threads for the configured Page. Meta only returns message bodies for the last 20 messages per thread. Does not create new sales leads. Creates placeholder contacts when a thread has no contact yet. security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CreateMetaImportJobRequest" responses: "202": description: Import job queued. content: application/json: schema: $ref: "#/components/schemas/InboxImportJobResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" /v1/admin/leads/{id}: parameters: - $ref: "#/components/parameters/LeadId" get: operationId: getV1AdminLeadsById summary: Get lead detail security: - AdminBearerAuth: [] responses: "200": description: Lead detail response. content: application/json: schema: $ref: "#/components/schemas/LeadDetailResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" patch: operationId: patchV1AdminLeadsById summary: Update lead stage or assignee security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/UpdateLeadRequest" responses: "200": description: Lead update response. content: application/json: schema: $ref: "#/components/schemas/LeadDetailResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/leads/{id}/notes: parameters: - $ref: "#/components/parameters/LeadId" post: operationId: postV1AdminLeadsByIdNotes summary: Add lead note security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CreateNoteRequest" responses: "201": description: Lead note created. content: application/json: schema: type: object required: [note] properties: note: $ref: "#/components/schemas/Note" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/leads/{id}/ai-suggestion: parameters: - $ref: "#/components/parameters/LeadId" get: operationId: getV1AdminLeadsByIdAiSuggestion summary: Get latest AI close suggestion for a lead description: > Returns the newest stored AI closing suggestion for the lead, including staleness metadata. `suggestion` is null when none has been generated yet. A suggestion is stale when it is older than 24 hours or when a newer WhatsApp/Meta message exists for the lead contact after the stored conversation watermark. security: - AdminBearerAuth: [] responses: "200": description: Latest suggestion payload (or null). content: application/json: schema: $ref: "#/components/schemas/LeadAiSuggestionResponse" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" post: operationId: postV1AdminLeadsByIdAiSuggestion summary: Queue AI close suggestion generation for a lead description: > Enqueues an asynchronous job that generates a closing/follow-up suggestion via the shared OpenRouter pipeline (same Secrets Manager key, allow-listed chat-completions URL, and AWS HTTP proxy as expense invoice parsing). Poll `GET /v1/admin/leads/{id}/ai-suggestion/jobs/{job_id}` for status, timing (`queue_wait_ms`, `duration_ms`), and the resulting suggestion. Does not send messages. security: - AdminBearerAuth: [] responses: "202": description: Generation job accepted. content: application/json: schema: $ref: "#/components/schemas/LeadAiSuggestionJobResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/leads/{id}/ai-suggestion/jobs/{job_id}: parameters: - $ref: "#/components/parameters/LeadId" - name: job_id in: path required: true schema: type: string format: uuid get: operationId: getV1AdminLeadsByIdAiSuggestionJobsByJobId summary: Get lead AI suggestion job status description: > Returns job status and timing. When `status` is `succeeded`, includes the serialized suggestion. Use `queue_wait_ms` (created→started) and `duration_ms` (started→finished) to time OpenRouter runs. security: - AdminBearerAuth: [] responses: "200": description: Job status payload. content: application/json: schema: $ref: "#/components/schemas/LeadAiSuggestionJobResponse" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/services: get: operationId: getV1AdminServices summary: List services security: - AdminBearerAuth: [] parameters: - name: limit in: query required: false schema: type: integer minimum: 1 maximum: 100 default: 25 - name: cursor in: query required: false description: | Opaque continuation token from `next_cursor` on the previous page. Service list results are ordered by title ascending, then id ascending; the cursor encodes the last row's title and id for that ordering. schema: type: string - name: service_type in: query required: false schema: $ref: "#/components/schemas/ServiceType" - name: status in: query required: false schema: $ref: "#/components/schemas/ServiceStatus" - name: search in: query required: false schema: type: string responses: "200": description: > Service list response. Each `ServiceSummary` item includes `service_tier` (nullable) for admin list display and filtering context. content: application/json: schema: $ref: "#/components/schemas/ServiceListResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" post: operationId: postV1AdminServices summary: Create service security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CreateServiceRequest" responses: "201": description: Service created. content: application/json: schema: $ref: "#/components/schemas/ServiceResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" "409": description: > Service key and service tier conflict with another service (unique index on case-insensitive service_key and tier, NULL tiers treated as one bucket). Error body uses `field` value `service_key_tier` (see `ErrorResponse.field`). content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" /v1/admin/services/instances: get: operationId: getV1AdminServicesInstances summary: List service instances across services description: | Returns instances from all services, optionally filtered by `service_type` and/or `service_id`. Omit both filters to include every instance type. security: - AdminBearerAuth: [] parameters: - name: limit in: query required: false schema: type: integer minimum: 1 maximum: 100 default: 25 - name: cursor in: query required: false schema: type: string - name: status in: query required: false schema: $ref: "#/components/schemas/InstanceStatus" - name: service_id in: query required: false description: When set, only instances for this service UUID. schema: type: string format: uuid - name: service_type in: query required: false description: When set, only instances whose parent service has this type. schema: $ref: "#/components/schemas/ServiceType" - name: contact_id in: query required: false description: | When set, only instances with a non-cancelled enrollment attributed to this contact or to a family or organisation they belong to. Mutually exclusive with `family_id` and `organization_id`. schema: type: string format: uuid - name: family_id in: query required: false description: | When set, only instances with a non-cancelled enrollment attributed to this family or to one of its member contacts. Mutually exclusive with `contact_id` and `organization_id`. schema: type: string format: uuid - name: organization_id in: query required: false description: | When set, only instances with a non-cancelled enrollment attributed to this organisation or to one of its member contacts. Mutually exclusive with `contact_id` and `family_id`. schema: type: string format: uuid responses: "200": description: Service instance list response. content: application/json: schema: $ref: "#/components/schemas/InstanceListResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/services/{id}/discount-code-usage-summary: parameters: - $ref: "#/components/parameters/ServiceId" get: operationId: getV1AdminServicesByIdDiscountCodeUsageSummary summary: Discount code usage summary for a service description: > Returns aggregate `current_uses` across discount codes scoped to this service (`service_id` set) and how many such codes exist. Used by the admin UI before changing a service `service_key`. security: - AdminBearerAuth: [] responses: "200": description: Usage summary. content: application/json: schema: $ref: "#/components/schemas/DiscountCodeUsageSummaryResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/services/{id}: parameters: - $ref: "#/components/parameters/ServiceId" get: operationId: getV1AdminServicesById summary: Get service security: - AdminBearerAuth: [] responses: "200": description: Service response. content: application/json: schema: $ref: "#/components/schemas/ServiceResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" put: operationId: putV1AdminServicesById summary: Update service security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/UpdateServiceRequest" responses: "200": description: Service response. content: application/json: schema: $ref: "#/components/schemas/ServiceResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" "409": description: > Service key and service tier conflict with another service (unique index on case-insensitive service_key and tier, NULL tiers treated as one bucket). Error body uses `field` value `service_key_tier` (see `ErrorResponse.field`). content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" patch: operationId: patchV1AdminServicesById summary: Partially update service security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/PartialUpdateServiceRequest" responses: "200": description: Service response. content: application/json: schema: $ref: "#/components/schemas/ServiceResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" "409": description: > Service key and service tier conflict with another service (unique index on case-insensitive service_key and tier, NULL tiers treated as one bucket). Error body uses `field` value `service_key_tier` (see `ErrorResponse.field`). content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" delete: operationId: deleteV1AdminServicesById summary: Delete service security: - AdminBearerAuth: [] responses: "204": description: Service deleted. "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" "409": description: Service has instances and cannot be deleted. content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" /v1/admin/services/{id}/cover-image: parameters: - $ref: "#/components/parameters/ServiceId" post: operationId: postV1AdminServicesByIdCoverImage summary: Create service cover-image upload URL security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CreateServiceCoverImageUploadRequest" responses: "200": description: Cover image upload URL response. content: application/json: schema: $ref: "#/components/schemas/ServiceCoverImageUploadResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/services/{id}/instances: parameters: - $ref: "#/components/parameters/ServiceId" get: operationId: getV1AdminServicesByIdInstances summary: List service instances security: - AdminBearerAuth: [] responses: "200": description: Service instance list response. content: application/json: schema: $ref: "#/components/schemas/InstanceListResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" post: operationId: postV1AdminServicesByIdInstances summary: Create service instance security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CreateInstanceRequest" responses: "201": description: Service instance created. content: application/json: schema: $ref: "#/components/schemas/InstanceResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/services/{id}/instances/{instance_id}: parameters: - $ref: "#/components/parameters/ServiceId" - $ref: "#/components/parameters/InstanceId" get: operationId: getV1AdminServicesByIdInstancesByInstanceId summary: Get service instance security: - AdminBearerAuth: [] responses: "200": description: Service instance response. content: application/json: schema: $ref: "#/components/schemas/InstanceResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" put: operationId: putV1AdminServicesByIdInstancesByInstanceId summary: Update service instance description: > When `status` is set to `completed`, every enrollment on the instance that is still `registered` or `confirmed` is updated to `completed` in the same request (cancelled, waitlisted, and already-completed rows are left unchanged). security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/UpdateInstanceRequest" responses: "200": description: Service instance response. content: application/json: schema: $ref: "#/components/schemas/InstanceResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" delete: operationId: deleteV1AdminServicesByIdInstancesByInstanceId summary: Delete service instance security: - AdminBearerAuth: [] responses: "204": description: Service instance deleted. "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/services/{id}/instances/{instance_id}/enrollments: parameters: - $ref: "#/components/parameters/ServiceId" - $ref: "#/components/parameters/InstanceId" get: operationId: getV1AdminServicesByIdInstancesByInstanceIdEnrollments summary: List instance enrollments security: - AdminBearerAuth: [] responses: "200": description: Enrollment list response. content: application/json: schema: $ref: "#/components/schemas/EnrollmentListResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" post: operationId: postV1AdminServicesByIdInstancesByInstanceIdEnrollments summary: Create instance enrollment security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CreateEnrollmentRequest" responses: "201": description: Enrollment created. content: application/json: schema: $ref: "#/components/schemas/EnrollmentResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/services/{id}/instances/{instance_id}/enrollments/{enrollment_id}: parameters: - $ref: "#/components/parameters/ServiceId" - $ref: "#/components/parameters/InstanceId" - $ref: "#/components/parameters/EnrollmentId" patch: operationId: patchV1AdminServicesByIdInstancesByInstanceIdEnrollmentsByEnrollmentId summary: Update enrollment security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/UpdateEnrollmentRequest" responses: "200": description: Enrollment response. content: application/json: schema: $ref: "#/components/schemas/EnrollmentResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" delete: operationId: deleteV1AdminServicesByIdInstancesByInstanceIdEnrollmentsByEnrollmentId summary: Delete enrollment security: - AdminBearerAuth: [] responses: "204": description: Enrollment deleted. "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/discount-codes: get: operationId: getV1AdminDiscountCodes summary: List discount codes security: - AdminBearerAuth: [] parameters: - name: scope in: query required: false schema: type: string enum: - all - unscoped - service - instance description: > Optional scope facet: `unscoped` (no service/instance), `service` (service only), `instance` (instance-scoped). Omit or `all` for no scope facet filter. responses: "200": description: Discount code list response. content: application/json: schema: $ref: "#/components/schemas/DiscountCodeListResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" post: operationId: postV1AdminDiscountCodes summary: Create discount code security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CreateDiscountCodeRequest" responses: "201": description: Discount code created. content: application/json: schema: $ref: "#/components/schemas/DiscountCodeResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" "409": description: Discount code value conflict (duplicate code, case-insensitive). content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" /v1/admin/discount-codes/{id}: parameters: - $ref: "#/components/parameters/DiscountCodeId" put: operationId: putV1AdminDiscountCodesById summary: Update discount code security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/UpdateDiscountCodeRequest" responses: "200": description: Discount code response. content: application/json: schema: $ref: "#/components/schemas/DiscountCodeResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/completion-certificates: get: operationId: getV1AdminCompletionCertificates summary: List completion certificates security: - AdminBearerAuth: [] parameters: - name: contact_id in: query required: false schema: type: string format: uuid - name: service_id in: query required: false schema: type: string format: uuid - name: instance_id in: query required: false schema: type: string format: uuid - name: status in: query required: false schema: type: string enum: [issued, voided] - name: limit in: query required: false schema: type: integer minimum: 1 maximum: 200 - name: cursor in: query required: false schema: type: string description: Keyset cursor from a previous list response (`next_cursor`). responses: "200": description: Certificate list. content: application/json: schema: $ref: "#/components/schemas/CompletionCertificateListResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" post: operationId: postV1AdminCompletionCertificates summary: Issue completion certificate security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/IssueCompletionCertificateRequest" responses: "201": description: Certificate issued. content: application/json: schema: $ref: "#/components/schemas/CompletionCertificateResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/completion-certificates/preview: post: operationId: postV1AdminCompletionCertificatesPreview summary: Preview completion certificate PDF description: | Renders a certificate PDF from the request payload without persisting a row. Returns a short-lived CloudFront-signed download URL. security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/PreviewCompletionCertificateRequest" responses: "200": description: Signed preview URL. content: application/json: schema: $ref: "#/components/schemas/PdfDownloadResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" /v1/admin/completion-certificates/{id}: parameters: - $ref: "#/components/parameters/CompletionCertificateId" delete: operationId: deleteV1AdminCompletionCertificatesById summary: Delete completion certificate description: Permanently removes the certificate row and best-effort deletes the stored PDF. security: - AdminBearerAuth: [] responses: "200": description: Deleted. content: application/json: schema: type: object required: [deleted] properties: deleted: type: boolean "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/completion-certificates/{id}/pdf: parameters: - $ref: "#/components/parameters/CompletionCertificateId" get: operationId: getV1AdminCompletionCertificatesByIdPdf summary: Download issued completion certificate PDF security: - AdminBearerAuth: [] responses: "200": description: Signed download URL for an issued certificate. content: application/json: schema: $ref: "#/components/schemas/PdfDownloadResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/completion-certificates/{id}/void: parameters: - $ref: "#/components/parameters/CompletionCertificateId" post: operationId: postV1AdminCompletionCertificatesByIdVoid summary: Void completion certificate security: - AdminBearerAuth: [] responses: "200": description: Voided certificate. content: application/json: schema: $ref: "#/components/schemas/CompletionCertificateResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/calendar/manual-blocks: get: operationId: getV1AdminCalendarManualBlocks summary: List manual calendar blocks for a purpose description: | Returns **manual** rows from `calendar_manual_blocks` only (session-derived blockers are exposed on `GET /v1/calendar/blockers`). Current release supports `purpose=consultation_booking` only. security: - AdminBearerAuth: [] parameters: - name: purpose in: query required: true schema: type: string maxLength: 64 pattern: ^[a-z0-9]+(?:[-_][a-z0-9]+)*$ - name: from in: query required: true schema: type: string format: date - name: to in: query required: true schema: type: string format: date responses: "200": description: Manual block list. content: application/json: schema: $ref: "#/components/schemas/AdminCalendarManualBlockListResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" post: operationId: postV1AdminCalendarManualBlocks summary: Create manual calendar block security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CreateAdminCalendarManualBlockRequest" responses: "201": description: Block created. content: application/json: schema: $ref: "#/components/schemas/AdminCalendarManualBlockResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "409": description: Duplicate purpose/date/period. content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" /v1/admin/calendar/manual-blocks/{id}: parameters: - name: id in: path required: true schema: type: string format: uuid patch: operationId: patchV1AdminCalendarManualBlocksById summary: Update manual calendar block security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/UpdateAdminCalendarManualBlockRequest" responses: "200": description: Updated block. content: application/json: schema: $ref: "#/components/schemas/AdminCalendarManualBlockResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" "409": description: Duplicate purpose/date/period. content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" delete: operationId: deleteV1AdminCalendarManualBlocksById summary: Delete manual calendar block security: - AdminBearerAuth: [] responses: "200": description: Deleted. content: application/json: schema: $ref: "#/components/schemas/AdminCalendarManualBlockDeleteResponse" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/tags: get: operationId: getV1AdminTags summary: List CRM tags for administration description: | Returns tags sorted by name. Default: active tags only (`archived_at` is null). Use `include_archived=true` for active and archived together, or `archived_only=true` for archived rows only. Do not pass both `include_archived` and `archived_only`. security: - AdminBearerAuth: [] parameters: - name: include_archived in: query required: false schema: type: boolean default: false description: When true, include tags with a non-null `archived_at`. - name: archived_only in: query required: false schema: type: boolean default: false description: When true, return only archived tags (mutually exclusive with `include_archived`). responses: "200": description: Tag list with usage counts. content: application/json: schema: $ref: "#/components/schemas/AdminTagListResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" post: operationId: postV1AdminTags summary: Create CRM tag security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CreateAdminTagRequest" responses: "201": description: Tag created. content: application/json: schema: $ref: "#/components/schemas/AdminTagResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "409": description: Duplicate tag name (case-insensitive uniqueness). content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" /v1/admin/tags/{id}: parameters: - name: id in: path required: true schema: type: string format: uuid patch: operationId: patchV1AdminTagsById summary: Update CRM tag description: | Set `archived` to `false` to restore an archived tag (clear `archived_at`). System-managed tags (`expense_attachment`, `client_document`, `customer_invoice`) cannot be renamed or archived; they may be edited for color/description only. security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/UpdateAdminTagRequest" responses: "200": description: Updated tag. content: application/json: schema: $ref: "#/components/schemas/AdminTagResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" "409": description: Duplicate tag name (case-insensitive uniqueness). content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" delete: operationId: deleteV1AdminTagsById summary: Delete or archive CRM tag description: | Always returns **200** with `usage_count` and `deleted`. System-managed tags (`expense_attachment`, `client_document`, `customer_invoice`) return **400** and must not be removed. When `usage_count` is zero, the tag is **hard-deleted** (`deleted: true`), including an archived tag with no remaining links. When `usage_count` is greater than zero, the tag is **archived** (`deleted: false`, `tag` present); repeated calls are idempotent for in-use tags. If the client predicted delete vs archive from a stale list, compare `usage_count` to the prior value to detect a race. security: - AdminBearerAuth: [] responses: "200": description: Delete outcome (hard delete or archive). content: application/json: schema: $ref: "#/components/schemas/AdminTagDeleteResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/contacts/tags: get: operationId: getV1AdminContactsTags summary: List CRM tags for pickers description: Returns all tags sorted by name for contact/family/organization editors. security: - AdminBearerAuth: [] responses: "200": description: Tag list. content: application/json: schema: $ref: "#/components/schemas/EntityTagListResponse" "403": $ref: "#/components/responses/Forbidden" /v1/admin/contacts/search: get: operationId: getV1AdminContactsSearch summary: Search CRM contacts for pickers description: | Returns active contacts matching name, email, Instagram, and **phone** using server-side normalisation: ``+`` international forms, long digit strings, and substring matches against stored national significant numbers (with optional region match when the query resolves to a valid number). Requires at least two characters in `query`. Intended for referral and other admin pickers. security: - AdminBearerAuth: [] parameters: - name: query in: query required: true schema: type: string minLength: 2 maxLength: 255 - name: exclude_contact_id in: query required: false schema: type: string format: uuid description: Omit this contact from results (e.g. the subject contact when choosing a referrer). - name: limit in: query schema: type: integer minimum: 1 maximum: 100 responses: "200": description: Matching contacts as id/label rows. content: application/json: schema: $ref: "#/components/schemas/EntityPickerListResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" /v1/admin/contacts/merge: post: operationId: postV1AdminContactsMerge summary: Merge selected CRM contacts description: > Merges two or more contacts into the chosen keeper contact. Loser fields fill empty keeper identity fields. Related records (notes, enrollments, invoices, payments, conversations, certificates, tags, and sales leads) move onto the keeper. Sales leads stay as separate rows except uniqueness conflicts (same-guide dedupe and one open automated lead per contact). An incoming open automated lead is folded onto the keeper's open lead before the move is saved. The surviving lead keeps the higher lead-type rank and the further-along funnel stage. Orphaned loser contacts are deleted. At most 10 contacts per request. After the merge commits, emails that left the keeper are archived in Mailchimp. That call is best effort: a Mailchimp failure does not roll back the merge. Conflicting emails, Instagram handles, families, or organisations return 400. A remaining one-open-lead conflict returns 409. security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/MergeContactsRequest" responses: "200": description: Surviving contact after merge. content: application/json: schema: $ref: "#/components/schemas/AdminContactResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" "409": description: > Both contacts already have an open automated sales lead and the merge could not fold them. content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" /v1/admin/contacts/mailchimp-sync-run: post: operationId: postV1AdminContactsMailchimpSyncRun summary: Run one Mailchimp upsert batch (DB → audience) description: | Production-only. Paginated upsert for CRM contacts with the given ``only_statuses`` (default ``pending`` and ``failed``). Never include ``unsubscribed`` in ``only_statuses``: that would risk re-subscribing contacts who opted out in Mailchimp. Each row calls Mailchimp PUT + tag; unsubscribed or archived contacts are skipped without calling Mailchimp. Use ``next_cursor`` until null. ``dry_run`` counts rows without calling Mailchimp; when ``dry_run`` is true, ``would_process`` mirrors that count and ``processed``/``skipped`` remain populated for backward compatibility. security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/MailchimpSyncRunRequest" responses: "200": description: Batch outcome and optional next cursor. content: application/json: schema: $ref: "#/components/schemas/MailchimpSyncRunResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "409": description: Not production or Mailchimp list env not configured. content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" /v1/admin/contacts/mailchimp-sync-orphans: post: operationId: postV1AdminContactsMailchimpSyncOrphans summary: Reconcile Mailchimp audience orphans (one page) description: | Production-only. Scans one Mailchimp list page starting at ``mailchimp_offset``. Removes members whose email has no active CRM contact, or whose CRM row is archived or ``mailchimp_status`` is ``unsubscribed``. Default ``dry_run`` is ``true`` because this deletes or archives Mailchimp members; set ``dry_run`` to ``false`` to execute. ``mode=archive`` soft-archives (recoverable); ``mode=permanent`` is GDPR erase and must only be used when explicitly required. Mailchimp offset pagination is eventually consistent (webhooks or concurrent runs may shift rows between pages); archive mode remains idempotent on Mailchimp. With ``mode=permanent`` and ``dry_run=false``, when members are removed the response repeats ``next_offset`` equal to ``mailchimp_offset`` until a page removes zero rows, then advances by ``scanned`` when the page is full. security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/MailchimpOrphanCleanupRequest" responses: "200": description: Page scan outcome and optional next offset. content: application/json: schema: $ref: "#/components/schemas/MailchimpOrphanCleanupResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "409": description: Not production or Mailchimp list env not configured. content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" /v1/admin/contacts/mailchimp-sync-status: get: operationId: getV1AdminContactsMailchimpSyncStatus summary: Mailchimp sync counters for admin progress UI description: | Returns aggregate counts by ``mailchimp_status`` plus archived contacts that still carry a ``mailchimp_subscriber_id``. ``last_run_summary`` is reserved for a future release and is always null in v1. security: - AdminBearerAuth: [] responses: "200": description: Status snapshot. content: application/json: schema: $ref: "#/components/schemas/MailchimpSyncStatusResponse" "403": $ref: "#/components/responses/Forbidden" /v1/admin/contacts/map-pins: get: operationId: getV1AdminContactsMapPins summary: List confirmed CRM addresses for the Contacts Map tab description: | Returns one pin per active family, organisation, or contact that has a linked location with both coordinates and non-blank address text. Vendor and partner organisations are excluded (same default as `GET /v1/admin/organizations`). When a family is included, member contacts are omitted even if they have their own confirmed address. Family pins include `primary_contact_label` when a member is flagged as the main contact and has a first or last name. security: - AdminBearerAuth: [] responses: "200": description: Map pin list. content: application/json: schema: $ref: "#/components/schemas/AdminContactMapPinListResponse" "403": $ref: "#/components/responses/Forbidden" /v1/admin/contacts: get: operationId: getV1AdminContacts summary: List CRM contacts security: - AdminBearerAuth: [] parameters: - name: query in: query schema: type: string description: | Search first name, last name, email, Instagram, and phone (stored as ISO region + national digits; server normalises ``+`` / digit queries before matching). - name: active in: query schema: type: boolean - name: contact_type in: query schema: $ref: "#/components/schemas/EntityContactType" description: When set, only contacts with this contact type are returned. - name: cursor in: query schema: type: string - name: limit in: query schema: type: integer minimum: 1 maximum: 100 responses: "200": description: Contact list. content: application/json: schema: $ref: "#/components/schemas/AdminContactListResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" post: operationId: postV1AdminContacts summary: Create CRM contact security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CreateAdminContactRequest" responses: "201": description: Contact created. content: application/json: schema: $ref: "#/components/schemas/AdminContactResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" /v1/admin/contacts/{id}: parameters: - $ref: "#/components/parameters/AdminContactId" get: operationId: getV1AdminContactsById summary: Get CRM contact security: - AdminBearerAuth: [] responses: "200": description: Contact response. content: application/json: schema: $ref: "#/components/schemas/AdminContactResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" delete: operationId: deleteV1AdminContactsById summary: Delete CRM contact description: | Permanently removes the contact row. Dependent CRM notes on linked sales leads are removed first; enrollments and other references that use `ON DELETE SET NULL` clear their `contact_id`. Returns `400` if the database still blocks deletion. security: - AdminBearerAuth: [] responses: "204": description: Contact deleted. "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" patch: operationId: patchV1AdminContactsById summary: Update CRM contact security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/UpdateAdminContactRequest" responses: "200": description: Contact response. content: application/json: schema: $ref: "#/components/schemas/AdminContactResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/contacts/{id}/notes: parameters: - $ref: "#/components/parameters/AdminContactId" get: operationId: getV1AdminContactsByIdNotes summary: List standalone notes for a contact description: | Returns notes stored on the contact that are not tied to a sales lead (`lead_id` is null), newest first. Notes created on a lead remain on the lead detail only. security: - AdminBearerAuth: [] responses: "200": description: Note list. content: application/json: schema: $ref: "#/components/schemas/AdminNoteListResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" post: operationId: postV1AdminContactsByIdNotes summary: Add a standalone note to a contact security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CreateNoteRequest" responses: "201": description: Note created. content: application/json: schema: type: object required: [note] properties: note: $ref: "#/components/schemas/Note" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/contacts/{id}/services: parameters: - $ref: "#/components/parameters/AdminContactId" get: operationId: getV1AdminContactsByIdServices summary: List purchased services for a contact description: | Returns invoice-style labels for non-cancelled enrollments attributed to the contact or to any family or organisation the contact belongs to. Labels are deduplicated and sorted alphabetically. security: - AdminBearerAuth: [] responses: "200": description: Service label list. content: application/json: schema: $ref: "#/components/schemas/EntityServicesResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/contacts/{id}/notes/{note_id}: parameters: - $ref: "#/components/parameters/AdminContactId" - $ref: "#/components/parameters/NoteId" patch: operationId: patchV1AdminContactsByIdNotesByNoteId summary: Update a standalone note on a contact security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/UpdateNoteRequest" responses: "200": description: Note updated. content: application/json: schema: type: object required: [note] properties: note: $ref: "#/components/schemas/Note" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" delete: operationId: deleteV1AdminContactsByIdNotesByNoteId summary: Delete a standalone note on a contact security: - AdminBearerAuth: [] responses: "204": description: Note deleted. "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/families/picker: get: operationId: getV1AdminFamiliesPicker summary: List active CRM families for pickers description: | Returns active families ordered by name for admin UI dropdowns. At most 100 rows unless `limit` is set lower. security: - AdminBearerAuth: [] parameters: - name: limit in: query schema: type: integer minimum: 1 maximum: 100 responses: "200": description: Picker list. content: application/json: schema: $ref: "#/components/schemas/EntityPickerListResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" /v1/admin/families: get: operationId: getV1AdminFamilies summary: List CRM families security: - AdminBearerAuth: [] parameters: - name: query in: query description: > Case-insensitive substring match on family name or on any linked member contact's first name, last name, email, or trimmed "first last" display label. schema: type: string - name: active in: query schema: type: boolean - name: cursor in: query schema: type: string - name: limit in: query schema: type: integer minimum: 1 maximum: 100 responses: "200": description: Family list. content: application/json: schema: $ref: "#/components/schemas/AdminFamilyListResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" post: operationId: postV1AdminFamilies summary: Create CRM family security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CreateAdminFamilyRequest" responses: "201": description: Family created. content: application/json: schema: $ref: "#/components/schemas/AdminFamilyResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" /v1/admin/families/{id}: parameters: - $ref: "#/components/parameters/AdminFamilyId" patch: operationId: patchV1AdminFamiliesById summary: Update CRM family description: | When `relationship_type` is present, the server applies the same value to every linked member contact's CRM `relationship_type` (contacts belong to at most one family), so family and member records stay aligned. security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/UpdateAdminFamilyRequest" responses: "200": description: Family response. content: application/json: schema: $ref: "#/components/schemas/AdminFamilyResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" delete: operationId: deleteV1AdminFamiliesById summary: Delete CRM family description: | Permanently removes the family row. Sales leads linked to the family (and their lead notes) are deleted first; standalone notes and enrollments that reference the family are cleared. Returns `400` if the database still blocks deletion. security: - AdminBearerAuth: [] responses: "204": description: Family deleted. "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/families/{id}/services: parameters: - $ref: "#/components/parameters/AdminFamilyId" get: operationId: getV1AdminFamiliesByIdServices summary: List purchased services for a family description: | Returns invoice-style labels for non-cancelled enrollments attributed to the family or to any member contact. Labels are deduplicated and sorted alphabetically. security: - AdminBearerAuth: [] responses: "200": description: Service label list. content: application/json: schema: $ref: "#/components/schemas/EntityServicesResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/families/{id}/members: parameters: - $ref: "#/components/parameters/AdminFamilyId" post: operationId: postV1AdminFamiliesByIdMembers summary: Add family member security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/AddFamilyMemberRequest" responses: "201": description: Family with updated members. content: application/json: schema: $ref: "#/components/schemas/AdminFamilyResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/families/{id}/members/{member_id}: parameters: - $ref: "#/components/parameters/AdminFamilyId" - $ref: "#/components/parameters/AdminFamilyMemberId" patch: operationId: patchV1AdminFamiliesByIdMembersByMemberId summary: Update family member description: | Currently supports toggling the family's primary contact. At most one member may be primary; setting `is_primary_contact` to true clears the flag on other members in the same family. security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/UpdateFamilyMemberRequest" responses: "200": description: Family with updated members. content: application/json: schema: $ref: "#/components/schemas/AdminFamilyResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" delete: operationId: deleteV1AdminFamiliesByIdMembersByMemberId summary: Remove family member security: - AdminBearerAuth: [] responses: "200": description: Family with updated members. content: application/json: schema: $ref: "#/components/schemas/AdminFamilyResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/organizations/picker: get: operationId: getV1AdminOrganizationsPicker summary: List active CRM organisations for pickers description: | Returns active organisations ordered by name for admin UI dropdowns. When `relationship_type` is omitted, vendor and partner rows are both excluded (Contacts default). Pass `relationship_type=partner` for Services → Partners or `relationship_type=vendor` for Finance → Vendors. When `relationship_type` is set, only organisations with that relationship type are returned. At most 100 rows unless `limit` is set lower. security: - AdminBearerAuth: [] parameters: - name: relationship_type in: query description: > When set, only organizations with this CRM relationship type are returned. When omitted, vendor and partner rows are both excluded (Contacts default). schema: $ref: "#/components/schemas/EntityRelationshipType" - name: limit in: query schema: type: integer minimum: 1 maximum: 100 responses: "200": description: Picker list. content: application/json: schema: $ref: "#/components/schemas/EntityPickerListResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" /v1/admin/organizations: get: operationId: getV1AdminOrganizations summary: List CRM organizations description: | Lists organizations for CRM and Finance. When `relationship_type` is omitted, vendor and partner rows are both excluded (Contacts default). Pass `relationship_type=partner` for Services → Partners or `relationship_type=vendor` for Finance → Vendors. List responses may omit related loads for performance when listing vendors only (`include_relationships=false` server-side); partner lists still include tags, members, and location summary. Use `GET /v1/admin/organizations/{id}` for full detail when needed. security: - AdminBearerAuth: [] parameters: - name: query in: query schema: type: string - name: active in: query schema: type: boolean - name: relationship_type in: query description: > When set, only organizations with this CRM relationship type are returned (e.g. `vendor` for Finance). When omitted, vendor and partner rows are both excluded from the list (Contacts default). schema: $ref: "#/components/schemas/EntityRelationshipType" - name: sort in: query description: > Optional sort order. When `name`, results are ordered case-insensitively by trimmed `name` ascending, then by `id` ascending (stable pagination with the same `cursor` token as the default list). When omitted, rows are ordered by `created_at` descending (newest first), then `id` descending. schema: type: string enum: - name - name: cursor in: query schema: type: string - name: limit in: query schema: type: integer minimum: 1 maximum: 100 responses: "200": description: Organization list. content: application/json: schema: $ref: "#/components/schemas/AdminOrganizationListResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" post: operationId: postV1AdminOrganizations summary: Create CRM organization security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CreateAdminOrganizationRequest" responses: "201": description: Organization created. content: application/json: schema: $ref: "#/components/schemas/AdminOrganizationResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" /v1/admin/organizations/{id}: parameters: - $ref: "#/components/parameters/AdminOrganizationId" patch: operationId: patchV1AdminOrganizationsById summary: Update CRM organization security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/UpdateAdminOrganizationRequest" responses: "200": description: Organization response. content: application/json: schema: $ref: "#/components/schemas/AdminOrganizationResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" delete: operationId: deleteV1AdminOrganizationsById summary: Delete CRM organization description: | Permanently removes a non-vendor organisation row. Vendor organisations must be managed under Finance. Sales leads linked to the organisation (and their lead notes) are deleted first; standalone notes and enrollments that reference the organisation are cleared. Returns `400` if the database still blocks deletion. security: - AdminBearerAuth: [] responses: "204": description: Organization deleted. "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/organizations/{id}/services: parameters: - $ref: "#/components/parameters/AdminOrganizationId" get: operationId: getV1AdminOrganizationsByIdServices summary: List purchased services for an organization description: | Returns invoice-style labels for non-cancelled enrollments attributed to the organization or to any member contact. Labels are deduplicated and sorted alphabetically. security: - AdminBearerAuth: [] responses: "200": description: Service label list. content: application/json: schema: $ref: "#/components/schemas/EntityServicesResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/organizations/{id}/members: parameters: - $ref: "#/components/parameters/AdminOrganizationId" post: operationId: postV1AdminOrganizationsByIdMembers summary: Add organization member security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/AddOrganizationMemberRequest" responses: "201": description: Organization with updated members. content: application/json: schema: $ref: "#/components/schemas/AdminOrganizationResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/organizations/{id}/members/{member_id}: parameters: - $ref: "#/components/parameters/AdminOrganizationId" - $ref: "#/components/parameters/AdminOrganizationMemberId" patch: operationId: patchV1AdminOrganizationsByIdMembersByMemberId summary: Update organization member description: | Updates membership fields such as primary contact. Membership role is derived from the linked contact's `contact_type` (see `POST /v1/admin/organizations/{id}/members`). security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/UpdateOrganizationMemberRequest" responses: "200": description: Organization with updated members. content: application/json: schema: $ref: "#/components/schemas/AdminOrganizationResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" delete: operationId: deleteV1AdminOrganizationsByIdMembersByMemberId summary: Remove organization member security: - AdminBearerAuth: [] responses: "200": description: Organization with updated members. content: application/json: schema: $ref: "#/components/schemas/AdminOrganizationResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/billing/export: get: operationId: getV1AdminBillingExport summary: Export billing CSV (default export v2) description: > Default `export_version` is **2** (`?export_version=2` or omit). v2 rows include `document_type` in `payment`, `refund`, `invoice`, `invoice_line`, `receipt`, and `allocation` with columns for `payment_method`, `bank_reference` (payment `external_reference`), `counterparty_name_snapshot` (invoice line description or invoice snapshot display name), `tax_amount`, `created_by` (payment `confirmed_by`), bill-to fields on invoice rows, and Stripe / linkage ids. Pass `export_version=1` for the legacy payments+allocations-only shape. Payment rows are paginated via `limit` and `cursor`; allocations, invoices, invoice lines, and receipts are included only on the first page (`cursor` omitted) up to fixed per-entity caps (10,000 allocations; 5,000 invoices and receipts). security: - AdminBearerAuth: [] parameters: - name: export_version in: query required: false description: "`1` (legacy) or `2` (default)." schema: type: string enum: ["1", "2"] default: "2" - name: limit in: query required: false description: Maximum payment rows per page (default 1000, max 5000). schema: type: integer minimum: 1 maximum: 5000 default: 1000 - name: cursor in: query required: false description: Opaque pagination cursor from a prior export response `next_cursor`. schema: type: string responses: "200": description: Accounting-oriented CSV payload. content: application/json: schema: type: object required: - csv properties: csv: type: string next_cursor: type: string nullable: true description: Present when more payment rows are available. "403": $ref: "#/components/responses/Forbidden" /v1/admin/billing/payments: get: operationId: getV1AdminBillingPayments summary: List customer payments description: > Cursor-paginated list ordered by `created_at` descending, then `id` descending. Pass `next_cursor` from the previous response as `cursor` for the next page. security: - AdminBearerAuth: [] parameters: - name: invoice_id in: query required: false description: When set, return only payments that have at least one allocation to this invoice. schema: type: string format: uuid - name: cursor in: query required: false description: Opaque cursor from a prior `next_cursor` value. schema: type: string - name: limit in: query required: false schema: type: integer minimum: 1 maximum: 100 default: 25 responses: "200": description: Payment rows. content: application/json: schema: type: object required: - items properties: items: type: array items: $ref: "#/components/schemas/CustomerPaymentSummary" next_cursor: type: string nullable: true "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" post: operationId: postV1AdminBillingPayments summary: Create customer payment row description: > Creates either an outbound refund (`direction: refund` + `originalPaymentId`) or a manual inbound payment linked to an enrollment (`direction: inbound` + `enrollmentId`). Succeeded inbound payments follow the same receipt generation path as payment confirm. security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: oneOf: - $ref: "#/components/schemas/CreateCustomerRefundRequest" - $ref: "#/components/schemas/CreateManualInboundCustomerPaymentRequest" discriminator: propertyName: direction mapping: refund: "#/components/schemas/CreateCustomerRefundRequest" inbound: "#/components/schemas/CreateManualInboundCustomerPaymentRequest" responses: "201": description: Refund or inbound payment created. content: application/json: schema: type: object properties: payment: $ref: "#/components/schemas/CustomerPaymentSummary" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "409": description: > Duplicate manual inbound payment for the same enrollment and external reference (partial unique index on non-null `external_reference`). content: application/json: schema: type: object additionalProperties: true /v1/admin/billing/payments/{id}: get: operationId: getV1AdminBillingPaymentsById summary: Get customer payment with unapplied balance security: - AdminBearerAuth: [] parameters: - name: id in: path required: true schema: type: string format: uuid responses: "200": description: Payment detail. content: application/json: schema: allOf: - $ref: "#/components/schemas/CustomerPaymentSummary" - type: object properties: allocationInvoices: type: array description: Distinct invoices this payment is allocated to (newest invoice first). items: $ref: "#/components/schemas/CustomerPaymentAllocationInvoice" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" patch: operationId: patchV1AdminBillingPaymentsById summary: Update manual inbound customer payment description: > Updates a manual inbound payment (no Stripe PaymentIntent on the row). Enrollment cannot be changed. Pending rows may change amount, currency, method, status, and external reference (subject to allocation totals and enrollment billing currency). Succeeded rows allow `method` and `externalReference` only. Duplicate non-null `externalReference` per enrollment returns **409** (same partial unique index as create). security: - AdminBearerAuth: [] parameters: - name: id in: path required: true schema: type: string format: uuid requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/UpdateManualInboundCustomerPaymentRequest" responses: "200": description: Updated payment. content: application/json: schema: type: object properties: payment: $ref: "#/components/schemas/CustomerPaymentSummary" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" "409": description: Duplicate manual inbound payment for the same enrollment and external reference. content: application/json: schema: type: object additionalProperties: true delete: operationId: deleteV1AdminBillingPaymentsById summary: Delete orphan inbound customer payment description: > Removes an inbound payment row only when it is safe cleanup. Pending payments may be deleted even when linked to an enrollment that is not cancelled. Free ($0 method) or zero-amount payments may be deleted only when the enrollment id is null, the enrollment is cancelled, or the enrollment row is missing. The payment must have no invoice allocations, no customer receipt row, and no refund rows pointing at it. security: - AdminBearerAuth: [] parameters: - name: id in: path required: true schema: type: string format: uuid responses: "204": description: Payment deleted. "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/billing/payments/{id}/confirm: post: operationId: postV1AdminBillingPaymentsByIdConfirm summary: Confirm pending inbound payment (offline rails) security: - AdminBearerAuth: [] parameters: - name: id in: path required: true schema: type: string format: uuid requestBody: required: false content: application/json: schema: type: object properties: externalReference: type: string responses: "200": description: Payment confirmed and receipt generated when applicable. content: application/json: schema: type: object properties: payment: $ref: "#/components/schemas/CustomerPaymentSummary" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/billing/enrollments/recent-for-invoicing: get: operationId: getV1AdminBillingEnrollmentsRecentForInvoicing summary: List recent enrollments for draft invoice picker description: > Returns non-cancelled enrollments with `enrolled_at` within the last 730 days (two 365-day rolling windows by enrolled date), ordered by `enrolled_at` descending (cursor pagination). At most `limit` rows per response (default and maximum 500). Pass `next_cursor` from the prior response as `cursor`. Optional `q` filters server-side by enrollment UUID substring, instance title, cohort, contact email/name, bill-to contact, family name, organization name, or ticket tier name. Includes `invoiceLinked` when the enrollment already appears on a draft or issued customer invoice line (void invoices do not block). security: - AdminBearerAuth: [] parameters: - name: cursor in: query required: false description: Opaque cursor from a prior `next_cursor` value. schema: type: string - name: limit in: query required: false schema: type: integer minimum: 1 maximum: 500 default: 500 - name: q in: query required: false description: Case-insensitive partial match across enrollment id, instance title/cohort, contacts, family/org names, and tier name. schema: type: string responses: "200": description: Enrollment rows for invoicing UI. content: application/json: schema: type: object required: - items - truncated properties: items: type: array items: $ref: "#/components/schemas/BillingEnrollmentPickerRow" truncated: type: boolean description: True when another page may exist (results reached `limit`). next_cursor: type: string nullable: true description: Cursor for the next page when `truncated` is true. "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" /v1/admin/billing/invoices: get: operationId: getV1AdminBillingInvoices summary: List customer invoices description: > Cursor-paginated list ordered by `created_at` descending, then `id` descending. Pass `next_cursor` from the previous response as `cursor` for the next page. Returns all invoices for the tenant; **admin authorization is required** (API Gateway admin group). Filter by optional `currency` (three-letter ISO code), `status`, optional `settlement` (issued invoices only: `open`, `partially_paid`, `paid`, `no_charge` for zero-total issued invoices, or `not_completed` for draft invoices and issued positive-total rows that are neither paid nor no-charge; combined with `status` using AND), and free-text `q` (case-insensitive substring match on `invoice_number`, bill-to display name, email, location snapshot text, and ISO `invoice_date` formatted as `YYYY-MM-DD`). Optional `contact_id` restricts results to invoices billed to that contact or to a family or organisation they belong to. Optional `family_id` or `organization_id` restricts results to invoices billed to that party or to one of its member contacts. Only one of `contact_id`, `family_id`, or `organization_id` may be set. security: - AdminBearerAuth: [] parameters: - name: status in: query required: false schema: type: string enum: [draft, issued, void] - name: settlement in: query required: false description: > Issued-invoice settlement slice for admin filtering: `open` (issued with balance_due > 0), `partially_paid` (issued with amount_allocated > 0 and balance_due > 0), `paid` (issued, balance_due zero, amount_allocated > 0, total > 0), `no_charge` (issued with total = 0), or `not_completed` (draft invoices, or issued with total > 0 that are not in the `paid` or `no_charge` slices). Combined with `status` using AND. schema: type: string enum: [open, partially_paid, paid, no_charge, not_completed] - name: currency in: query required: false description: Three-letter ISO currency code (for example HKD). schema: type: string minLength: 3 maxLength: 3 - name: q in: query required: false description: > Case-insensitive substring filter on invoice number, bill-to name/email/location text, and invoice issue date (ISO `YYYY-MM-DD` only). schema: type: string maxLength: 200 - name: contact_id in: query required: false description: > Restrict to invoices billed to this contact or to a family or organisation they belong to. Mutually exclusive with `family_id` and `organization_id`. schema: type: string format: uuid - name: family_id in: query required: false description: > Restrict to invoices billed to this family or to one of its member contacts. Mutually exclusive with `contact_id` and `organization_id`. schema: type: string format: uuid - name: organization_id in: query required: false description: > Restrict to invoices billed to this organisation or to one of its member contacts. Mutually exclusive with `contact_id` and `family_id`. schema: type: string format: uuid - name: cursor in: query required: false description: Opaque cursor from a prior `next_cursor` value. schema: type: string - name: limit in: query required: false schema: type: integer minimum: 1 maximum: 100 default: 25 responses: "200": description: Invoice summaries. content: application/json: schema: type: object required: - items properties: items: type: array items: $ref: "#/components/schemas/CustomerInvoiceSummary" next_cursor: type: string nullable: true "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" post: operationId: postV1AdminBillingInvoices summary: Create draft customer invoice description: > Set `draftKind` to `enrollment_merge` with `enrollmentIds` to merge enrollments into one draft, or `customized_manual` with `billTo`, `currency`, and `lines` for manual line items without enrollment links. Do not send fields from the other mode (for example `billTo` with `enrollment_merge`). security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: oneOf: - $ref: "#/components/schemas/CreateDraftInvoiceRequest" - $ref: "#/components/schemas/CreateCustomizedDraftInvoiceRequest" discriminator: propertyName: draftKind mapping: enrollment_merge: "#/components/schemas/CreateDraftInvoiceRequest" customized_manual: "#/components/schemas/CreateCustomizedDraftInvoiceRequest" responses: "201": description: Draft invoice created. content: application/json: schema: type: object properties: invoiceId: type: string format: uuid status: type: string enum: [draft] "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" /v1/admin/billing/invoices/{id}: get: operationId: getV1AdminBillingInvoicesById summary: Get customer invoice with lines security: - AdminBearerAuth: [] parameters: - name: id in: path required: true schema: type: string format: uuid responses: "200": description: Invoice detail including line items. content: application/json: schema: type: object required: - invoice properties: invoice: $ref: "#/components/schemas/CustomerInvoiceDetail" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" delete: operationId: deleteV1AdminBillingInvoicesById summary: Delete draft customer invoice description: > Permanently deletes the invoice and its line rows. Allowed only when the invoice status is `draft`. Returns 400 if the invoice is issued or void, or when any `payment_allocations` row references the invoice. security: - AdminBearerAuth: [] parameters: - name: id in: path required: true schema: type: string format: uuid responses: "200": description: Invoice deleted. content: application/json: schema: type: object required: - invoiceId - deleted properties: invoiceId: type: string format: uuid deleted: type: boolean "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/billing/invoices/{id}/pdf: get: operationId: getV1AdminBillingInvoicesByIdPdf summary: Get time-limited URL to open invoice PDF description: > Returns a CloudFront-signed GET URL for the invoice PDF. Issued invoices use the canonical stored object; draft and void invoices render current lines to a preview key without mutating issued PDF metadata. security: - AdminBearerAuth: [] parameters: - name: id in: path required: true schema: type: string format: uuid responses: "200": description: Signed download URL and expiry. content: application/json: schema: type: object required: - downloadUrl - expiresAt properties: downloadUrl: type: string format: uri expiresAt: type: string format: date-time "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/billing/invoices/{id}/issue: post: operationId: postV1AdminBillingInvoicesByIdIssue summary: Issue invoice (assign number, PDF hash) description: > Issues a draft invoice (number, snapshot dates, PDF). For positive-total invoices, also creates one pending inbound `customer_payments` row with amount and currency copied from the invoice and method `fps`, unless a succeeded inbound Stripe payment already exists for an enrollment on the invoice (`method` `stripe_card` or a Stripe payment intent id). `enrollment_id` is set only when the invoice has exactly one enrollment line; customized and multi-enrollment invoices leave it unset. Zero-total invoices and invoices that already have that Stripe payment skip payment creation (`paymentId` is null). The payment is not allocated at issue time. security: - AdminBearerAuth: [] parameters: - name: id in: path required: true schema: type: string format: uuid responses: "200": description: Invoice issued. content: application/json: schema: type: object properties: invoiceId: type: string format: uuid invoiceNumber: type: string issuedPdfSha256: type: string nullable: true paymentId: type: string format: uuid nullable: true description: > Pending inbound customer payment created at issue. Null for zero-total invoices and when a succeeded Stripe payment already exists for an enrollment on the invoice. "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/billing/invoices/{id}/void: post: operationId: postV1AdminBillingInvoicesByIdVoid summary: Void invoice (issued) description: > Voids an issued invoice. Returns 400 if the invoice is draft or already void. Draft invoices must be deleted instead. Application audit rows use `VOID_FROM_ISSUED`. security: - AdminBearerAuth: [] parameters: - name: id in: path required: true schema: type: string format: uuid requestBody: required: true content: application/json: schema: type: object required: - reason properties: reason: type: string responses: "200": description: Invoice voided. content: application/json: schema: type: object properties: invoiceId: type: string format: uuid status: type: string enum: [void] "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/billing/invoices/{id}/email: post: operationId: postV1AdminBillingInvoicesByIdEmail summary: Email issued invoice PDF description: > Sends a branded transactional email (shared Evolve Sprouts HTML shell) with the issued invoice PDF attached. Recipients are operator-supplied. Draft invoices without an issued PDF are a no-op (response still reports `sent: true`). Locale for the current send path is `en`. security: - AdminBearerAuth: [] parameters: - name: id in: path required: true schema: type: string format: uuid requestBody: required: true content: application/json: schema: type: object required: - toEmail properties: toEmail: type: string description: > Recipient email address(es). Multiple addresses may be given as a comma-separated list (optional semicolons are treated like commas). example: "billing@example.com, accounts@example.com" responses: "200": description: Email sent (best-effort). content: application/json: schema: type: object properties: sent: type: boolean "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/billing/dashboard/resolve-bill-to-primary-contacts: post: operationId: postV1AdminBillingDashboardResolveBillToPrimaryContacts summary: Resolve primary CRM contacts for bill-to rollups description: > Returns a map from each requested family id and organisation id to the CRM contact id chosen as the billing primary (same ordering as invoice bill-to resolution: primary flag first, then earliest membership). Omitted keys mean the entity has no members. Used by the admin dashboard to attribute family- and organisation-billed issued invoice totals to a single main contact for spend rankings. security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/ResolveBillToPrimaryContactsRequest" responses: "200": description: Primary contact id maps keyed by family or organisation id. content: application/json: schema: $ref: "#/components/schemas/ResolveBillToPrimaryContactsResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" /v1/admin/billing/allocations: post: operationId: postV1AdminBillingAllocations summary: Allocate payment amount to invoice security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CreatePaymentAllocationRequest" responses: "201": description: Allocation created. content: application/json: schema: type: object properties: allocationId: type: string format: uuid "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/expenses: get: operationId: getV1AdminExpenses summary: List expenses description: >- Returns expenses ordered by invoice issue date (`invoice_date`) descending; rows without an invoice date appear after dated rows. Pagination uses stable key order (`invoice_date`, `id`). security: - AdminBearerAuth: [] parameters: - name: query in: query schema: type: string - name: status in: query schema: $ref: "#/components/schemas/ExpenseStatus" - name: parse_status in: query schema: $ref: "#/components/schemas/ExpenseParseStatus" - name: cursor in: query schema: type: string - name: limit in: query schema: type: integer minimum: 1 maximum: 100 responses: "200": description: Expense list response. content: application/json: schema: $ref: "#/components/schemas/ExpenseListResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" post: operationId: postV1AdminExpenses summary: Create expense security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CreateExpenseRequest" responses: "201": description: Expense created. content: application/json: schema: $ref: "#/components/schemas/ExpenseResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" /v1/admin/expenses/import-from-bulk-pdf: post: operationId: postV1AdminExpensesImportFromBulkPdf summary: Queue import of multiple expenses from one combined PDF description: > Upload a PDF as an admin asset, then call this endpoint with its asset id. The API enqueues an asynchronous OpenRouter bulk parse (SQS + dedicated Lambda) and returns **202** with a `bulk_import_job` id. Poll `GET /v1/admin/expenses/bulk-import-jobs/{job_id}` until `status` is `succeeded`, `succeeded_with_errors` (partial row failures; see `error_message`), or `failed` (`error_message` is set). You can also list recent jobs via `GET /v1/admin/expenses/bulk-import-jobs`. Parsed vendor names are matched to active vendors when possible; otherwise `default_vendor_id` is used. security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/BulkImportExpensesFromPdfRequest" responses: "202": description: Bulk import job accepted for asynchronous processing. content: application/json: schema: $ref: "#/components/schemas/BulkImportJobResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/expenses/bulk-import-jobs: get: operationId: getV1AdminExpensesBulkImportJobs summary: List bulk PDF import jobs for the signed-in admin description: > Returns jobs created by the authenticated admin, newest first. Use this to recover visibility after refresh or when polling times out. security: - AdminBearerAuth: [] parameters: - name: cursor in: query schema: type: string - name: limit in: query schema: type: integer minimum: 1 maximum: 100 responses: "200": description: Paginated bulk import jobs for the current admin. content: application/json: schema: $ref: "#/components/schemas/BulkImportJobListResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" /v1/admin/expenses/bulk-import-jobs/{job_id}: parameters: - name: job_id in: path required: true schema: type: string format: uuid description: Identifier returned from `POST /v1/admin/expenses/import-from-bulk-pdf`. get: operationId: getV1AdminExpensesBulkImportJobsByJobId summary: Get bulk PDF import job status description: > Poll this endpoint until `bulk_import_job.status` is `succeeded`, `succeeded_with_errors`, or `failed`. Only the admin user who created the job may read it. security: - AdminBearerAuth: [] responses: "200": description: Current job state (and expenses when the job finished with successes). content: application/json: schema: $ref: "#/components/schemas/BulkImportJobResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" delete: operationId: deleteV1AdminExpensesBulkImportJobsByJobId summary: Delete bulk PDF import job record description: > Permanently removes the `bulk_expense_import_jobs` row when it belongs to the authenticated admin. This does **not** delete expenses that were already created from the job. Pending SQS work for the removed id is acknowledged as a no-op when the worker runs. security: - AdminBearerAuth: [] responses: "204": description: Job record deleted. "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/expenses/{id}: parameters: - $ref: "#/components/parameters/ExpenseId" patch: operationId: patchV1AdminExpensesById summary: Update expense security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/UpdateExpenseRequest" responses: "200": description: Expense response. content: application/json: schema: $ref: "#/components/schemas/ExpenseResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" delete: operationId: deleteV1AdminExpensesById summary: Delete draft expense description: > Hard-deletes the expense row when its status is `draft`. Returns **400** when the expense is not a draft or when other expense rows reference this record as their amendment parent. security: - AdminBearerAuth: [] responses: "204": description: Expense deleted. "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" # `{id}` is a UUID. It does not overlap the static `bulk-import-jobs` segment at runtime. /v1/admin/expenses/{id}/cancel: parameters: - $ref: "#/components/parameters/ExpenseId" post: operationId: postV1AdminExpensesByIdCancel summary: Soft-void an expense security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CancelExpenseRequest" responses: "200": description: Expense response. content: application/json: schema: $ref: "#/components/schemas/ExpenseResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" # `{id}` is a UUID. It does not overlap the static `bulk-import-jobs` segment at runtime. /v1/admin/expenses/{id}/mark-paid: parameters: - $ref: "#/components/parameters/ExpenseId" post: operationId: postV1AdminExpensesByIdMarkPaid summary: Mark an expense as paid description: > Requires a linked vendor, invoice date, currency code, and total amount. Returns 400 if any of these are missing. security: - AdminBearerAuth: [] responses: "200": description: Expense response. content: application/json: schema: $ref: "#/components/schemas/ExpenseResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" # `{id}` is a UUID. It does not overlap the static `bulk-import-jobs` segment at runtime. /v1/admin/expenses/{id}/reparse: parameters: - $ref: "#/components/parameters/ExpenseId" post: operationId: postV1AdminExpensesByIdReparse summary: Queue expense parse request security: - AdminBearerAuth: [] responses: "202": description: Parse request queued. content: application/json: schema: $ref: "#/components/schemas/ActionMessageResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" # `{id}` is a UUID. It does not overlap the static `bulk-import-jobs` segment at runtime. /v1/admin/expenses/{id}/amend: parameters: - $ref: "#/components/parameters/ExpenseId" post: operationId: postV1AdminExpensesByIdAmend summary: Create amendment expense record security: - AdminBearerAuth: [] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/UpdateExpenseRequest" responses: "201": description: Amendment expense created. content: application/json: schema: $ref: "#/components/schemas/ExpenseResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/admin/forms: get: operationId: getV1AdminForms summary: List training form slugs with answer counts description: | Returns distinct form slugs discovered in the DynamoDB responses table, each with the number of stored answer rows. security: - AdminBearerAuth: [] responses: "200": description: Form summary list. content: application/json: schema: $ref: "#/components/schemas/AdminFormListResponse" "403": $ref: "#/components/responses/Forbidden" /v1/admin/forms/{form_slug}/answers: parameters: - $ref: "#/components/parameters/FormSlug" get: operationId: getV1AdminFormsByFormSlugAnswers summary: List stored answers for a form description: > Returns answer rows newest first. Pass `next_cursor` from the prior response as `cursor`. Default and maximum page size follow the standard admin list limit (25 / 100). Optional `contact_id` filters to rows stored for that CRM contact before pagination. `respondentContactIds` lists distinct contact ids from all stored rows for the form (not just the current page), independent of the `contact_id` filter. security: - AdminBearerAuth: [] parameters: - name: cursor in: query required: false description: Opaque continuation token from `next_cursor`. schema: type: string - name: limit in: query required: false schema: type: integer minimum: 1 maximum: 100 default: 25 - name: contact_id in: query required: false description: > When set, return only answer rows whose stored `contactId` matches this CRM contact UUID. schema: type: string format: uuid responses: "200": description: Form answer rows for the selected form. content: application/json: schema: $ref: "#/components/schemas/AdminFormAnswerListResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" delete: operationId: deleteV1AdminFormsByFormSlugAnswers summary: Clear all stored answers for a form description: Permanently deletes every answer row for the form slug in DynamoDB. security: - AdminBearerAuth: [] responses: "200": description: Form answers cleared. content: application/json: schema: $ref: "#/components/schemas/AdminFormClearAnswersResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" /v1/admin/forms/{form_slug}/answers/export: parameters: - $ref: "#/components/parameters/FormSlug" get: operationId: getV1AdminFormsByFormSlugAnswersExport summary: Export form answers as CSV security: - AdminBearerAuth: [] responses: "200": description: CSV export generated. content: text/csv: schema: type: string "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" /v1/admin/polls: get: operationId: getV1AdminPolls summary: List training poll slugs with answer counts description: | Returns distinct poll slugs discovered in the DynamoDB poll responses table, each with the number of stored answer rows. security: - AdminBearerAuth: [] responses: "200": description: Poll summary list. content: application/json: schema: $ref: "#/components/schemas/AdminPollListResponse" "403": $ref: "#/components/responses/Forbidden" /v1/admin/polls/{poll_slug}/answers: parameters: - $ref: "#/components/parameters/PollSlug" get: operationId: getV1AdminPollsByPollSlugAnswers summary: List stored answers for a poll description: > Returns answer rows newest first. Pass `next_cursor` from the prior response as `cursor`. Default and maximum page size follow the standard admin list limit (25 / 100). security: - AdminBearerAuth: [] parameters: - name: cursor in: query required: false description: Opaque continuation token from `next_cursor`. schema: type: string - name: limit in: query required: false schema: type: integer minimum: 1 maximum: 100 default: 25 responses: "200": description: Poll answer rows for the selected poll. content: application/json: schema: $ref: "#/components/schemas/AdminPollAnswerListResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" delete: operationId: deleteV1AdminPollsByPollSlugAnswers summary: Clear all stored answers for a poll description: Permanently deletes every answer row for the poll slug in DynamoDB. security: - AdminBearerAuth: [] responses: "200": description: Poll answers cleared. content: application/json: schema: $ref: "#/components/schemas/AdminPollClearAnswersResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" /v1/admin/polls/{poll_slug}/answers/export: parameters: - $ref: "#/components/parameters/PollSlug" get: operationId: getV1AdminPollsByPollSlugAnswersExport summary: Export poll answers as CSV security: - AdminBearerAuth: [] responses: "200": description: CSV export generated. content: text/csv: schema: type: string "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" /v1/user/assets: get: operationId: getV1UserAssets summary: List user assets description: Route for any authenticated Cognito user. security: - UserBearerAuth: [] responses: "200": description: User asset list response. content: application/json: schema: $ref: "#/components/schemas/AssetListResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" /v1/user/assets/{id}/download: parameters: - $ref: "#/components/parameters/AssetId" get: operationId: getV1UserAssetsByIdDownload summary: Generate user asset download security: - UserBearerAuth: [] responses: "200": description: Download response payload. content: application/json: schema: $ref: "#/components/schemas/AssetDownloadResponse" "400": $ref: "#/components/responses/BadRequest" "403": $ref: "#/components/responses/Forbidden" "404": $ref: "#/components/responses/NotFound" components: securitySchemes: SigV4Auth: type: apiKey in: header name: Authorization description: | AWS Signature Version 4 signed Authorization header (IAM auth). AdminBearerAuth: type: http scheme: bearer bearerFormat: JWT description: Cognito JWT validated by AdminGroupAuthorizerFunction. UserBearerAuth: type: http scheme: bearer bearerFormat: JWT description: Cognito JWT validated by UserAuthorizerFunction. parameters: AssetId: name: id in: path required: true schema: type: string description: Asset identifier. GrantId: name: grantId in: path required: true schema: type: string description: Asset grant identifier. LocationId: name: id in: path required: true schema: type: string format: uuid description: Location identifier. LeadId: name: id in: path required: true schema: type: string format: uuid description: Sales lead identifier. FormSlug: name: form_slug in: path required: true schema: type: string pattern: ^[a-z0-9]+(-[a-z0-9]+)*$ description: Training form slug (kebab-case). PollSlug: name: poll_slug in: path required: true schema: type: string pattern: ^[a-z0-9]+(-[a-z0-9]+)*$ description: Training poll slug (kebab-case). ServiceId: name: id in: path required: true schema: type: string format: uuid description: Service identifier. InstanceId: name: instance_id in: path required: true schema: type: string format: uuid description: Service instance identifier. EnrollmentId: name: enrollment_id in: path required: true schema: type: string format: uuid description: Enrollment identifier. DiscountCodeId: name: id in: path required: true schema: type: string format: uuid description: Discount code identifier. CompletionCertificateId: name: id in: path required: true schema: type: string format: uuid description: Completion certificate identifier. AdminContactId: name: id in: path required: true schema: type: string format: uuid description: CRM contact identifier. NoteId: name: note_id in: path required: true schema: type: string format: uuid description: CRM note identifier. AdminFamilyId: name: id in: path required: true schema: type: string format: uuid description: CRM family identifier. AdminFamilyMemberId: name: member_id in: path required: true schema: type: string format: uuid description: Family membership row identifier. AdminOrganizationId: name: id in: path required: true schema: type: string format: uuid description: CRM organization identifier. AdminOrganizationMemberId: name: member_id in: path required: true schema: type: string format: uuid description: Organization membership row identifier. ExpenseId: name: id in: path required: true schema: type: string format: uuid description: Expense identifier. responses: BadRequest: description: Validation or request format error. content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" Forbidden: description: Authorization failed. content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" NotFound: description: Resource not found. content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" schemas: AssetTagRef: type: object required: - id - name properties: id: type: string format: uuid name: type: string color: type: string nullable: true description: Optional CSS color (e.g. hex). Asset: type: object required: - id - title - asset_type - s3_key - file_name - visibility - tags properties: id: type: string format: uuid title: type: string description: type: string nullable: true asset_type: type: string enum: [guide, video, pdf, document] s3_key: type: string file_name: type: string content_type: type: string nullable: true content_language: type: string nullable: true description: > BCP 47-style tag for the language of the file content. Admin create/update accepts only en, zh-CN, or zh-HK (null clears). Public list filters accept any valid BCP 47-style tag. resource_key: type: string nullable: true description: Optional normalized key used to map public media submissions to this asset. visibility: type: string enum: [public, restricted] tags: type: array items: $ref: "#/components/schemas/AssetTagRef" description: Tags on this asset. Non-admin asset list responses use an empty array when tags are not loaded. created_by: type: string nullable: true created_at: type: string format: date-time nullable: true updated_at: type: string format: date-time nullable: true AssetGrant: type: object required: - id - asset_id - grant_type properties: id: type: string format: uuid asset_id: type: string format: uuid grant_type: type: string enum: [all_authenticated, organization, user] grantee_id: type: string nullable: true granted_by: type: string nullable: true created_at: type: string format: date-time nullable: true AssetListResponse: type: object required: - items properties: items: type: array items: $ref: "#/components/schemas/Asset" next_cursor: type: string nullable: true linked_tag_names: type: array items: type: string description: > Admin asset list only. Distinct tag names linked to at least one asset matching the request's asset_type filter (when provided). Omitted or empty when not applicable. AssetResponse: type: object required: - asset properties: asset: $ref: "#/components/schemas/Asset" AssetGrantListResponse: type: object required: - items properties: items: type: array items: $ref: "#/components/schemas/AssetGrant" AssetGrantResponse: type: object required: - grant properties: grant: $ref: "#/components/schemas/AssetGrant" AssetDownloadResponse: type: object required: - asset_id - download_url - expires_at properties: asset_id: type: string download_url: type: string format: uri description: CloudFront-signed URL generated for this request. expires_at: type: string format: date-time AssetShareLinkResponse: type: object required: - asset_id - share_url - allowed_domains properties: asset_id: type: string share_url: type: string format: uri description: Stable bearer link that resolves to a fresh signed download URL. allowed_domains: type: array minItems: 1 items: type: string description: Allowlisted source domains allowed to resolve this share link. AssetShareLinkPolicyRequest: type: object required: - allowed_domains properties: allowed_domains: type: array minItems: 1 items: type: string description: | Domain allowlist for share-link resolution, for example `www.example.com`. FunnelStage: type: string enum: [new, contacted, engaged, qualified, unqualified, converted, lost] LeadLostReason: type: string description: Controlled vocabulary for why a sales lead was marked lost. enum: - price_too_high - value_not_understood - ghosted - language_mismatch - other LeadType: type: string enum: [free_guide, event_inquiry, program_enrollment, consultation, partnership, other] LeadEventType: type: string enum: [ created, stage_changed, note_added, email_sent, email_opened, guide_downloaded, action_recorded, assigned, converted, lost, ] ContactSource: type: string enum: [ free_guide, newsletter, contact_form, reservation, referral, instagram, facebook, manual, whatsapp, linkedin, event, phone_call, public_website, ] LeadContact: type: object properties: id: type: string format: uuid nullable: true first_name: type: string nullable: true last_name: type: string nullable: true email: type: string nullable: true phone_region: type: string minLength: 2 maxLength: 2 pattern: "^[A-Z]{2}$" nullable: true phone_national_number: type: string pattern: "^[0-9]+$" maxLength: 20 nullable: true phone_e164: type: string pattern: "^\\+[1-9][0-9]{1,14}$" nullable: true readOnly: true instagram_handle: type: string nullable: true source: type: string enum: [ free_guide, newsletter, contact_form, reservation, referral, instagram, manual, whatsapp, linkedin, event, phone_call, public_website, ] nullable: true source_detail: type: string nullable: true contact_type: type: string nullable: true relationship_type: type: string nullable: true LeadEvent: type: object required: - id - event_type properties: id: type: string format: uuid event_type: $ref: "#/components/schemas/LeadEventType" from_stage: type: string enum: [new, contacted, engaged, qualified, unqualified, converted, lost] nullable: true to_stage: type: string enum: [new, contacted, engaged, qualified, unqualified, converted, lost] nullable: true metadata: type: object nullable: true additionalProperties: true created_by: type: string nullable: true created_at: type: string format: date-time nullable: true Note: type: object required: - id - content - created_by - created_at - updated_at properties: id: type: string format: uuid content: type: string created_by: type: string created_at: type: string format: date-time updated_at: type: string format: date-time AdminNoteListResponse: type: object required: - items properties: items: type: array items: $ref: "#/components/schemas/Note" EntityServiceItem: type: object required: - label properties: label: type: string EntityServicesResponse: type: object required: - items properties: items: type: array items: $ref: "#/components/schemas/EntityServiceItem" CreateNoteRequest: type: object required: - content properties: content: type: string UpdateNoteRequest: type: object required: - content properties: content: type: string LeadSummary: type: object required: - id - contact - lead_type - funnel_stage - note_count - tags properties: id: type: string format: uuid contact: $ref: "#/components/schemas/LeadContact" lead_type: $ref: "#/components/schemas/LeadType" funnel_stage: $ref: "#/components/schemas/FunnelStage" assigned_to: type: string nullable: true created_at: type: string format: date-time nullable: true updated_at: type: string format: date-time nullable: true converted_at: type: string format: date-time nullable: true lost_at: type: string format: date-time nullable: true lost_reason: allOf: - $ref: "#/components/schemas/LeadLostReason" nullable: true days_in_stage: type: integer last_activity_at: type: string format: date-time nullable: true note_count: type: integer description: Standalone contact notes for the lead's contact (same notes the pipeline Notes accordion shows). tags: type: array items: type: string LeadDetail: allOf: - $ref: "#/components/schemas/LeadSummary" - type: object properties: family: type: object nullable: true organization: type: object nullable: true events: type: array items: $ref: "#/components/schemas/LeadEvent" notes: type: array items: $ref: "#/components/schemas/Note" LeadAiFollowUp: type: object required: [channel, message_excerpt, draft_reply, rationale] properties: channel: type: string description: Conversation channel for the suggested reply. message_excerpt: type: string description: Short excerpt of the inbound message being addressed. draft_reply: type: string description: Suggested outbound reply text (not sent automatically). rationale: type: string description: Why this follow-up is recommended. LeadAiSuggestion: type: object required: - id - lead_id - summary - actions - follow_ups - risks - generated_at - is_stale - stale_reasons - stale_after properties: id: type: string format: uuid lead_id: type: string format: uuid summary: type: string actions: type: array items: type: string follow_ups: type: array items: $ref: "#/components/schemas/LeadAiFollowUp" risks: type: array items: type: string generated_at: type: string format: date-time generated_by: type: string nullable: true model: type: string nullable: true conversation_watermark_at: type: string format: date-time nullable: true is_stale: type: boolean stale_reasons: type: array items: type: string enum: [age, new_conversation] stale_after: type: string format: date-time description: Timestamp when the suggestion becomes age-stale (generated_at + 24h). latest_message_at: type: string format: date-time nullable: true description: Newest WhatsApp/Meta message time for the lead contact, if any. LeadAiSuggestionResponse: type: object required: [suggestion] properties: suggestion: allOf: - $ref: "#/components/schemas/LeadAiSuggestion" nullable: true LeadAiSuggestionJob: type: object required: [id, lead_id, status] properties: id: type: string format: uuid lead_id: type: string format: uuid status: type: string enum: [pending, processing, succeeded, failed] error_message: type: string nullable: true suggestion_id: type: string format: uuid nullable: true created_at: type: string format: date-time nullable: true started_at: type: string format: date-time nullable: true finished_at: type: string format: date-time nullable: true updated_at: type: string format: date-time nullable: true queue_wait_ms: type: integer nullable: true description: Milliseconds from created_at to started_at. duration_ms: type: integer nullable: true description: Milliseconds from started_at to finished_at (OpenRouter run). suggestion: allOf: - $ref: "#/components/schemas/LeadAiSuggestion" nullable: true LeadAiSuggestionJobResponse: type: object required: [job] properties: job: $ref: "#/components/schemas/LeadAiSuggestionJob" SalesDailyPlanPriority: type: object required: [title] properties: title: type: string why: type: string action: type: string kind: type: string nullable: true enum: [reply, close, chase_payment, book, offer] urgency: type: integer minimum: 1 maximum: 3 description: 1 is highest urgency. sources: type: array items: type: string lead_id: type: string format: uuid nullable: true invoice_id: type: string format: uuid nullable: true description: Unpaid issued invoice when the priority is a payment follow-up. conversation_id: type: string format: uuid nullable: true channel: type: string nullable: true assigned_to: type: string nullable: true item_key: type: string done: type: boolean description: True when an admin has ticked this priority on this plan. feedback: type: string nullable: true enum: [up, down, not_relevant] snoozed_until: type: string format: date-time nullable: true compare_status: type: string nullable: true enum: [new, carried] instruction_id: type: string format: uuid nullable: true description: Today-instruction this priority carries. from_instruction: type: boolean description: True when the server added this priority because the model omitted the instruction. resurfaced: type: boolean description: True when a done item returned because newer CRM activity arrived. SalesDailyPlanOutreach: type: object required: [channel] properties: channel: type: string lead_id: type: string format: uuid nullable: true conversation_id: type: string format: uuid nullable: true assigned_to: type: string nullable: true message_excerpt: type: string draft_reply: type: string rationale: type: string item_key: type: string feedback: type: string nullable: true enum: [up, down, not_relevant] snoozed_until: type: string format: date-time nullable: true saved_draft_reply: type: string nullable: true SalesDailyPlanDroppedPriority: type: object required: [title] properties: title: type: string lead_id: type: string format: uuid nullable: true invoice_id: type: string format: uuid nullable: true SalesDailyPlanQuestion: type: object required: [id, question, answer] properties: id: type: string format: uuid question: type: string answer: type: string asked_by: type: string asked_at: type: string format: date-time nullable: true model: type: string nullable: true SalesDailyPlan: type: object required: - id - focus - priorities - outreach - product_focus - offer_refinements - risks - generated_at - is_stale - stale_reasons - stale_after properties: id: type: string format: uuid focus: type: string priorities: type: array items: $ref: "#/components/schemas/SalesDailyPlanPriority" outreach: type: array items: $ref: "#/components/schemas/SalesDailyPlanOutreach" product_focus: type: string offer_refinements: type: array items: type: string risks: type: array items: type: string suppressed_items: type: array items: $ref: "#/components/schemas/SalesDailyPlanSuppressedItem" dropped_priorities: type: array items: $ref: "#/components/schemas/SalesDailyPlanDroppedPriority" questions: type: array items: $ref: "#/components/schemas/SalesDailyPlanQuestion" generated_at: type: string format: date-time generated_by: type: string nullable: true generated_by_name: type: string nullable: true description: Display name of the person this insight addresses (logged-in admin, or Sales default assignee for the 06:00 HKT run). model: type: string nullable: true operator_input: type: string nullable: true description: Refinement typed for this generation. Active instructions are returned separately and enforced on later runs. conversation_watermark_at: type: string format: date-time nullable: true pipeline_watermark_at: type: string format: date-time nullable: true is_stale: type: boolean stale_reasons: type: array items: type: string enum: [age, new_conversation, pipeline_changed, contacts_changed] stale_after: type: string format: date-time description: Timestamp when the plan becomes age-stale (generated_at + 24h). stale_counts: type: object description: Activity that landed after stored watermarks. properties: new_conversation: type: integer pipeline_changed: type: integer contacts_changed: type: integer latest_message_at: type: string format: date-time nullable: true latest_pipeline_at: type: string format: date-time nullable: true latest_contact_at: type: string format: date-time nullable: true SalesDailyPlanMemoryEntry: type: object required: [id, generated_at, focus, product_focus] properties: id: type: string format: uuid generated_at: type: string format: date-time focus: type: string product_focus: type: string operator_input: type: string nullable: true priorities: type: array items: $ref: "#/components/schemas/SalesDailyPlanDroppedPriority" SalesDailyPlanResponse: type: object required: [plan, memory, instructions] properties: plan: allOf: - $ref: "#/components/schemas/SalesDailyPlan" nullable: true memory: type: array description: Up to the five newest stored plans, newest first (including the latest). items: $ref: "#/components/schemas/SalesDailyPlanMemoryEntry" job: allOf: - $ref: "#/components/schemas/SalesDailyPlanJob" nullable: true description: Newest generation job, including a failed scheduled run. instructions: type: array description: Active today and standing instructions, oldest first. items: $ref: "#/components/schemas/SalesDailyPlanInstruction" SalesDailyPlanPriorityCompletionRequest: type: object required: [title, done] properties: plan_id: type: string format: uuid description: Plan currently shown. Must match the latest stored plan. title: type: string lead_id: type: string format: uuid nullable: true invoice_id: type: string format: uuid nullable: true done: type: boolean item_key: type: string description: Stable identity. When omitted, derived from title and ids. conversation_id: type: string format: uuid nullable: true kind: type: string nullable: true instruction_id: type: string format: uuid nullable: true SalesDailyPlanPriorityCompletionResponse: type: object required: [plan] properties: plan: $ref: "#/components/schemas/SalesDailyPlan" completion: type: object nullable: true properties: title: type: string lead_id: type: string format: uuid nullable: true invoice_id: type: string format: uuid nullable: true done_at: type: string format: date-time nullable: true done_by: type: string done_until: type: string format: date-time nullable: true item_key: type: string SalesDailyPlanSuppressedItem: type: object required: [title, item_key, item_kind, reason] properties: title: type: string item_key: type: string item_kind: type: string enum: [priority, outreach] reason: type: string enum: [done_today, dismissed, snoozed] lead_id: type: string format: uuid nullable: true invoice_id: type: string format: uuid nullable: true SalesDailyPlanInstruction: type: object required: [id, text, scope] properties: id: type: string format: uuid text: type: string scope: type: string enum: [today, standing] active_until: type: string format: date-time nullable: true created_by: type: string created_at: type: string format: date-time nullable: true SalesDailyPlanInstructionListResponse: type: object required: [instructions] properties: instructions: type: array items: $ref: "#/components/schemas/SalesDailyPlanInstruction" SalesDailyPlanInstructionRequest: type: object required: [text] properties: text: type: string maxLength: 4000 scope: type: string enum: [today, standing] SalesDailyPlanInstructionResponse: type: object required: [instruction] properties: instruction: $ref: "#/components/schemas/SalesDailyPlanInstruction" SalesDailyPlanInstructionArchiveResponse: type: object required: [instruction] properties: instruction: $ref: "#/components/schemas/SalesDailyPlanInstruction" plan: allOf: - $ref: "#/components/schemas/SalesDailyPlan" nullable: true SalesDailyPlanItemAnnotationRequest: type: object required: [item_kind] properties: plan_id: type: string format: uuid description: Plan currently shown. Must match the latest stored plan. item_kind: type: string enum: [priority, outreach] item_key: type: string maxLength: 1024 description: Stable row key. When omitted, derived from title/ids or channel fields. title: type: string lead_id: type: string format: uuid nullable: true invoice_id: type: string format: uuid nullable: true conversation_id: type: string format: uuid nullable: true channel: type: string message_excerpt: type: string feedback: type: string nullable: true enum: [up, down, not_relevant] snooze: type: string nullable: true enum: [tomorrow, next_week, clear] draft_reply: type: string nullable: true maxLength: 4000 SalesDailyPlanItemAnnotationResponse: type: object required: [plan] properties: plan: $ref: "#/components/schemas/SalesDailyPlan" annotation: type: object properties: item_kind: type: string item_key: type: string feedback: type: string nullable: true snoozed_until: type: string format: date-time nullable: true draft_reply: type: string nullable: true updated_by: type: string updated_at: type: string format: date-time nullable: true SalesDailyPlanQuestionRequest: type: object required: [question] properties: plan_id: type: string format: uuid description: Plan currently shown. Must match the latest stored plan. question: type: string maxLength: 2000 SalesDailyPlanQuestionResponse: type: object required: [plan, question] properties: plan: $ref: "#/components/schemas/SalesDailyPlan" question: $ref: "#/components/schemas/SalesDailyPlanQuestion" SalesDailyPlanGenerateRequest: type: object properties: operator_input: type: string nullable: true maxLength: 4000 description: Optional refinement saved as an instruction and stored on this plan. operator_input_scope: type: string enum: [today, standing] description: today lasts until the next 06:00 HKT. standing lasts until removed. Defaults to today. SalesDailyPlanJob: type: object required: [id, status] properties: id: type: string format: uuid status: type: string enum: [pending, processing, succeeded, failed] error_message: type: string nullable: true operator_input: type: string nullable: true plan_id: type: string format: uuid nullable: true created_at: type: string format: date-time nullable: true started_at: type: string format: date-time nullable: true finished_at: type: string format: date-time nullable: true updated_at: type: string format: date-time nullable: true queue_wait_ms: type: integer nullable: true duration_ms: type: integer nullable: true plan: allOf: - $ref: "#/components/schemas/SalesDailyPlan" nullable: true SalesDailyPlanJobResponse: type: object required: [job] properties: job: $ref: "#/components/schemas/SalesDailyPlanJob" WhatsAppConversationSummary: type: object required: - id - wa_id - inbound_count - outbound_count properties: id: type: string format: uuid wa_id: type: string profile_name: type: string nullable: true contact_id: type: string format: uuid nullable: true contact_name: type: string nullable: true lead_id: type: string format: uuid nullable: true first_inbound_at: type: string format: date-time nullable: true last_message_at: type: string format: date-time nullable: true inbound_count: type: integer outbound_count: type: integer created_at: type: string format: date-time nullable: true WhatsAppMessageSummary: type: object required: - id - wa_message_id - direction - message_type - sent_at properties: id: type: string format: uuid wa_message_id: type: string direction: type: string enum: [inbound, outbound] message_type: type: string body: type: string nullable: true sent_at: type: string format: date-time WhatsAppConversationListResponse: type: object required: - items - total_count properties: items: type: array items: $ref: "#/components/schemas/WhatsAppConversationSummary" next_cursor: type: string nullable: true total_count: type: integer WhatsAppMessageListResponse: type: object required: - conversation - items properties: conversation: $ref: "#/components/schemas/WhatsAppConversationSummary" items: type: array items: $ref: "#/components/schemas/WhatsAppMessageSummary" MetaChannel: type: string enum: [facebook, instagram] MetaConversationSummary: type: object required: - id - channel - platform_user_id - inbound_count - outbound_count properties: id: type: string format: uuid channel: $ref: "#/components/schemas/MetaChannel" platform_user_id: type: string page_id: type: string nullable: true profile_name: type: string nullable: true contact_id: type: string format: uuid nullable: true contact_name: type: string nullable: true lead_id: type: string format: uuid nullable: true first_inbound_at: type: string format: date-time nullable: true last_message_at: type: string format: date-time nullable: true inbound_count: type: integer outbound_count: type: integer created_at: type: string format: date-time nullable: true MetaMessageSummary: type: object required: - id - platform_message_id - direction - message_type - sent_at properties: id: type: string format: uuid platform_message_id: type: string direction: type: string enum: [inbound, outbound] message_type: type: string body: type: string nullable: true sent_at: type: string format: date-time MetaConversationListResponse: type: object required: - items - total_count properties: items: type: array items: $ref: "#/components/schemas/MetaConversationSummary" next_cursor: type: string nullable: true total_count: type: integer MetaMessageListResponse: type: object required: - conversation - items properties: conversation: $ref: "#/components/schemas/MetaConversationSummary" items: type: array items: $ref: "#/components/schemas/MetaMessageSummary" InboxImportKind: type: string enum: [meta_graph, whatsapp_export] InboxImportJobStatus: type: string enum: [pending, processing, succeeded, succeeded_with_errors, failed] InboxImportJobCounters: type: object additionalProperties: true properties: stored: type: integer duplicates: type: integer skipped: type: integer partial_threads: type: integer description: Conversations truncated after a conversation-scoped Graph error on a later message page contacts_created: type: integer leads_created: type: integer conversations: type: integer skipped_no_body: type: integer skipped_no_wa_id: type: integer InboxImportJobSummary: type: object required: - id - status properties: id: type: string format: uuid kind: $ref: "#/components/schemas/InboxImportKind" nullable: true channel: $ref: "#/components/schemas/MetaChannel" nullable: true attachment_asset_id: type: string format: uuid nullable: true created_by: type: string nullable: true description: Cognito sub or system actor (for example system:meta-graph-sync) status: $ref: "#/components/schemas/InboxImportJobStatus" error_message: type: string nullable: true counters: $ref: "#/components/schemas/InboxImportJobCounters" nullable: true created_at: type: string format: date-time nullable: true updated_at: type: string format: date-time nullable: true InboxImportJobListResponse: type: object required: - items - total_count properties: items: type: array items: $ref: "#/components/schemas/InboxImportJobSummary" next_cursor: type: string nullable: true total_count: type: integer InboxImportJobResponse: type: object required: - inbox_import_job properties: inbox_import_job: $ref: "#/components/schemas/InboxImportJobSummary" CreateMetaImportJobRequest: type: object required: - channel properties: channel: $ref: "#/components/schemas/MetaChannel" CreateWhatsAppExportImportJobRequest: type: object required: - attachment_asset_id properties: attachment_asset_id: type: string format: uuid counterparty_wa_id: type: string description: Optional E.164 digits for the chat partner when the export filename has no phone. business_display_names: type: array items: type: string description: Display names in the export that are the business (outbound). ApiKeyScope: type: string enum: [admin, user] description: > admin is full access on token-protected routes; user is GET only. ApiKeyStatus: type: string enum: [active, expired, revoked] ApiKeySummary: type: object required: - id - name - key_prefix - scope - status - created_at properties: id: type: string format: uuid name: type: string key_prefix: type: string scope: $ref: "#/components/schemas/ApiKeyScope" status: $ref: "#/components/schemas/ApiKeyStatus" created_by: type: string nullable: true created_at: type: string format: date-time expires_at: type: string format: date-time nullable: true revoked_at: type: string format: date-time nullable: true last_used_at: type: string format: date-time nullable: true ApiKeyListResponse: type: object required: - items properties: items: type: array items: $ref: "#/components/schemas/ApiKeySummary" next_cursor: type: string nullable: true CreateApiKeyRequest: type: object required: - name - scope properties: name: type: string maxLength: 200 scope: $ref: "#/components/schemas/ApiKeyScope" expires_at: type: string format: date-time nullable: true ApiKeyCreatedResponse: allOf: - $ref: "#/components/schemas/ApiKeySummary" - type: object required: - api_token properties: api_token: type: string description: Plaintext token, returned only on create. LeadListResponse: type: object required: - items - total_count properties: items: type: array items: $ref: "#/components/schemas/LeadSummary" next_cursor: type: string nullable: true total_count: type: integer LeadDetailResponse: type: object required: - lead properties: lead: $ref: "#/components/schemas/LeadDetail" MergeLeadsRequest: type: object required: - lead_ids - keeper_lead_id properties: lead_ids: type: array minItems: 2 items: type: string format: uuid keeper_lead_id: type: string format: uuid description: Lead that survives the merge; must be one of `lead_ids`. MergeContactsRequest: type: object required: - contact_ids - keeper_contact_id properties: contact_ids: type: array minItems: 2 maxItems: 10 items: type: string format: uuid keeper_contact_id: type: string format: uuid description: Contact that survives the merge; must be one of `contact_ids`. CreateLeadRequest: type: object required: - first_name - source - lead_type properties: first_name: type: string last_name: type: string nullable: true email: type: string nullable: true phone_region: type: string minLength: 2 maxLength: 2 pattern: "^[A-Z]{2}$" nullable: true description: | ISO 3166-1 alpha-2 region. Omit both `phone_region` and `phone_number` to leave phone unchanged on create; send both keys with JSON `null` to clear phone. phone_number: type: string pattern: "^[0-9]+$" maxLength: 20 nullable: true description: National significant digits only; must be provided with `phone_region` when setting phone. instagram_handle: type: string nullable: true source: $ref: "#/components/schemas/ContactSource" source_detail: type: string nullable: true lead_type: $ref: "#/components/schemas/LeadType" contact_type: type: string nullable: true assigned_to: type: string nullable: true note: type: string nullable: true UpdateLeadRequest: type: object minProperties: 1 properties: funnel_stage: $ref: "#/components/schemas/FunnelStage" assigned_to: type: string nullable: true lost_reason: allOf: - $ref: "#/components/schemas/LeadLostReason" nullable: true SalesSettings: type: object required: - default_assigned_to - notify_assignee_on_assignment - helper_detector_enabled - openrouter_model properties: default_assigned_to: type: string nullable: true description: > Cognito `sub` applied to new leads when create omits `assigned_to`. The scheduled 06:00 HKT insight is addressed to this person's Cognito name. maxLength: 128 notify_assignee_on_assignment: type: boolean description: > When true, email the new assignee on first assignment and reassignment. Unassign does not send mail. helper_detector_enabled: type: boolean description: > When true, new automated leads are classified with OpenRouter; Filipino or Bahasa (Indonesian/Malay) name/username signals set funnel stage to `unqualified` and contact type to `helper` when the contact type is `other`. openrouter_model: type: string nullable: true description: > OpenRouter model id for lead closing suggestions and the dashboard insight. Null means Auto (`openrouter/auto`). Helper Detector, invoice parsing, and JSON repair keep using the deployed `OPENROUTER_MODEL`. Operators type a model code such as `openai/gpt-4.1-mini`. maxLength: 128 updated_at: type: string format: date-time nullable: true updated_by: type: string nullable: true SalesSettingsResponse: type: object required: - settings properties: settings: $ref: "#/components/schemas/SalesSettings" UpdateSalesSettingsRequest: type: object minProperties: 1 properties: default_assigned_to: type: string nullable: true maxLength: 128 notify_assignee_on_assignment: type: boolean helper_detector_enabled: type: boolean openrouter_model: type: string nullable: true maxLength: 128 LeadAnalyticsResponse: type: object required: - funnel properties: funnel: type: object additionalProperties: type: integer conversion_rate: type: number avg_days_to_convert: type: number nullable: true leads_this_week: type: integer leads_this_month: type: integer source_breakdown: type: object additionalProperties: type: integer stage_conversion_rates: type: object additionalProperties: type: number avg_days_in_stage: type: object additionalProperties: type: number leads_over_time: type: array items: type: object required: [period, count] properties: period: type: string count: type: integer assignee_stats: type: array items: type: object required: [assigned_to, total, converted, conversion_rate] properties: assigned_to: type: string nullable: true total: type: integer converted: type: integer conversion_rate: type: number ServiceType: type: string enum: [training_course, event, consultation, intro_call] description: | Product category for a service template. `intro_call` is the free public intro-call flow (`service_key` / instance slug pair used by public reservations); it stores consultation-style pricing defaults like `consultation`. ServiceStatus: type: string enum: [draft, published, archived] ServiceDeliveryMode: type: string enum: [online, in_person, hybrid] TrainingFormat: type: string enum: [group, private] TrainingPricingUnit: type: string enum: [per_person, per_family] EventCategory: type: string enum: [workshop, webinar, open_house, community_meetup, other] ConsultationFormat: type: string enum: [one_on_one, group] ConsultationPricingModel: type: string enum: [free, hourly, package] InstanceStatus: type: string enum: [scheduled, open, full, in_progress, completed, cancelled] EventbriteSyncStatus: type: string enum: [pending, syncing, synced, failed, skipped] description: > Eventbrite async publish pipeline state on `service_instances`. `skipped` is used for rows that intentionally do not sync (for example consultation booking children). DiscountType: type: string enum: [percentage, absolute, referral] description: | Discount type. `referral` codes are tracking-only: the server always coerces `discount_value` to "0" and `currency` to "HKD", and the public discount-validate endpoint rejects referral codes. EnrollmentStatus: type: string enum: [registered, waitlisted, confirmed, cancelled, completed] ServiceTrainingDetails: type: object properties: pricing_unit: $ref: "#/components/schemas/TrainingPricingUnit" default_price: type: string nullable: true default_currency: type: string nullable: true ServiceEventDetails: type: object properties: event_category: $ref: "#/components/schemas/EventCategory" default_price: type: string nullable: true pattern: ^-?\d+(\.\d{1,2})?$ description: Optional default ticket price for new event instances. default_currency: type: string minLength: 3 maxLength: 3 pattern: ^[A-Z]{3}$ description: ISO 4217 currency code for default_price (defaults to HKD). ServiceConsultationDetails: type: object properties: consultation_format: $ref: "#/components/schemas/ConsultationFormat" max_group_size: type: integer nullable: true duration_minutes: type: integer nullable: true pricing_model: $ref: "#/components/schemas/ConsultationPricingModel" default_hourly_rate: type: string nullable: true default_package_price: type: string nullable: true default_package_sessions: type: integer nullable: true default_currency: type: string nullable: true DiscountCodeUsageSummaryResponse: type: object required: - total_current_uses - referencing_code_count properties: total_current_uses: type: integer minimum: 0 referencing_code_count: type: integer minimum: 0 ServiceSummary: type: object required: - id - service_type - title - delivery_mode - status - instances_count properties: id: type: string format: uuid service_type: $ref: "#/components/schemas/ServiceType" title: type: string service_key: type: string nullable: true maxLength: 80 pattern: ^[a-z0-9]+(-[a-z0-9]+)*$ description: > Optional lowercase public service key for URLs and booking identity (e.g. `my-best-auntie-training-course`). Uniqueness is enforced case-insensitively in Aurora (with `service_tier`). booking_system: type: string nullable: true maxLength: 80 description: > Optional label for which booking system or flow applies to this service (free-form text, same max length as service key). description: type: string nullable: true cover_image_s3_key: type: string nullable: true delivery_mode: $ref: "#/components/schemas/ServiceDeliveryMode" status: $ref: "#/components/schemas/ServiceStatus" service_tier: type: string nullable: true maxLength: 128 pattern: ^[a-z0-9]+(-[a-z0-9]+)*$ description: > Optional slug-like tier identifier for the service template, shared across all instances. location_id: type: string format: uuid nullable: true description: > Optional default venue UUID (FK to locations.id, ON DELETE SET NULL). Instances may override via service_instances.location_id. created_by: type: string created_at: type: string format: date-time nullable: true updated_at: type: string format: date-time nullable: true training_details: allOf: - $ref: "#/components/schemas/ServiceTrainingDetails" nullable: true description: Present for training_course rows when details exist. event_details: allOf: - $ref: "#/components/schemas/ServiceEventDetails" nullable: true description: Present for event rows when details exist. consultation_details: allOf: - $ref: "#/components/schemas/ServiceConsultationDetails" nullable: true description: Present for consultation rows when details exist. instances_count: type: integer minimum: 0 description: Number of service instances for this template (list and detail payloads). Service: allOf: - $ref: "#/components/schemas/ServiceSummary" - type: object properties: tag_ids: type: array items: type: string format: uuid asset_ids: type: array items: type: string format: uuid training_details: $ref: "#/components/schemas/ServiceTrainingDetails" event_details: $ref: "#/components/schemas/ServiceEventDetails" consultation_details: $ref: "#/components/schemas/ServiceConsultationDetails" ServiceListResponse: type: object required: [items, total_count] properties: items: type: array items: $ref: "#/components/schemas/ServiceSummary" next_cursor: type: string nullable: true total_count: type: integer ServiceResponse: type: object required: [service] properties: service: $ref: "#/components/schemas/Service" CreateServiceRequest: type: object required: [service_type, title, delivery_mode] properties: service_type: $ref: "#/components/schemas/ServiceType" title: type: string service_key: type: string nullable: true maxLength: 80 pattern: ^[a-z0-9]+(-[a-z0-9]+)*$ description: Optional service key (lowercase letters, numbers, hyphens). booking_system: type: string nullable: true maxLength: 80 description: Optional booking system label (free-form text). description: type: string nullable: true cover_image_s3_key: type: string nullable: true delivery_mode: $ref: "#/components/schemas/ServiceDeliveryMode" status: $ref: "#/components/schemas/ServiceStatus" service_tier: type: string nullable: true maxLength: 128 pattern: ^[a-z0-9]+(-[a-z0-9]+)*$ description: > Optional slug-like tier identifier for the service template, shared across all instances. location_id: type: string format: uuid nullable: true description: > Optional default venue UUID (FK to locations.id, ON DELETE SET NULL). Instances may override via service_instances.location_id. tag_ids: type: array items: type: string format: uuid asset_ids: type: array items: type: string format: uuid training_details: $ref: "#/components/schemas/ServiceTrainingDetails" event_details: $ref: "#/components/schemas/ServiceEventDetails" consultation_details: $ref: "#/components/schemas/ServiceConsultationDetails" UpdateServiceRequest: allOf: - $ref: "#/components/schemas/CreateServiceRequest" PartialUpdateServiceRequest: type: object minProperties: 1 properties: title: type: string service_key: type: string nullable: true maxLength: 80 pattern: ^[a-z0-9]+(-[a-z0-9]+)*$ booking_system: type: string nullable: true maxLength: 80 description: type: string nullable: true cover_image_s3_key: type: string nullable: true delivery_mode: $ref: "#/components/schemas/ServiceDeliveryMode" status: $ref: "#/components/schemas/ServiceStatus" service_tier: type: string nullable: true maxLength: 128 pattern: ^[a-z0-9]+(-[a-z0-9]+)*$ description: > Optional slug-like tier identifier for the service template, shared across all instances. location_id: type: string format: uuid nullable: true description: > Optional default venue UUID (FK to locations.id, ON DELETE SET NULL). Instances may override via service_instances.location_id. tag_ids: type: array items: type: string format: uuid asset_ids: type: array items: type: string format: uuid training_details: $ref: "#/components/schemas/ServiceTrainingDetails" event_details: $ref: "#/components/schemas/ServiceEventDetails" consultation_details: $ref: "#/components/schemas/ServiceConsultationDetails" CreateServiceCoverImageUploadRequest: type: object required: [file_name] properties: file_name: type: string content_type: type: string nullable: true ServiceCoverImageUploadResponse: type: object required: [upload_url, upload_method, s3_key, expires_at] properties: upload_url: type: string format: uri upload_method: type: string upload_headers: type: object additionalProperties: type: string s3_key: type: string expires_at: type: string format: date-time service: type: object properties: id: type: string format: uuid cover_image_s3_key: type: string SessionSlot: type: object properties: id: type: string format: uuid nullable: true instance_id: type: string format: uuid nullable: true purpose_service_id: type: string format: uuid nullable: true description: > When set, identifies the catalog `services.id` used for cross-booking slot uniqueness (consultation tiers and intro-call). Null for event/training slots. location_id: type: string format: uuid nullable: true starts_at: type: string format: date-time nullable: true description: > Instant in UTC or with a numeric timezone offset (RFC 3339). On create/update requests, each value must be timezone-aware (Z suffix or ±HH:MM offset); naive date-time strings are rejected. ends_at: type: string format: date-time nullable: true description: > Same rules as starts_at. On create/update requests, must be timezone-aware and strictly after starts_at. sort_order: type: integer nullable: true EventTicketTier: type: object properties: id: type: string format: uuid nullable: true instance_id: type: string format: uuid nullable: true name: type: string nullable: true description: type: string nullable: true price: type: string nullable: true pattern: ^-?\d+(\.\d{1,2})?$ currency: type: string nullable: true minLength: 3 maxLength: 3 pattern: ^[A-Z]{3}$ max_quantity: type: integer nullable: true sort_order: type: integer nullable: true InstancePartnerOrganization: type: object required: [id, name, archived] properties: id: type: string format: uuid name: type: string archived: type: boolean description: True when the organization is archived (omitted from active pickers). location_id: type: string format: uuid nullable: true description: Partner organization venue id when set (FK locations). ServiceInstance: type: object required: [id, service_id, status, slug, resolved_slug, eventbrite_sync_status] properties: id: type: string format: uuid service_id: type: string format: uuid title: type: string nullable: true slug: type: string description: > Public instance slug (required for all service types). URL-safe: lowercase letters, digits, and single hyphens between segments (e.g. spring-workshop). Stored normalized to lowercase. Globally unique across `service_instances`. description: type: string nullable: true cover_image_s3_key: type: string nullable: true status: $ref: "#/components/schemas/InstanceStatus" delivery_mode: $ref: "#/components/schemas/ServiceDeliveryMode" location_id: type: string format: uuid nullable: true max_capacity: type: integer nullable: true capacity_enrolled_count: type: integer description: > Count of enrollments that consume instance capacity (registered, confirmed, completed). Included on admin instance payloads for display and capacity logic. capacity_left_override: type: integer nullable: true minimum: 0 description: > Optional display-only soft cap for spots remaining. When set with a non-null `max_capacity`, admin and public consumers use the minimum of this value and the computed remaining seats. Does not change booking eligibility (capacity guards still use `max_capacity` vs enrollment counts). Ignored when `max_capacity` is null. When `max_capacity` is null, a stored value may still be returned for editing; clearing `max_capacity` in an update should send `capacity_left_override: null` to drop it. capacity_left_effective: type: integer nullable: true readOnly: true description: > Read-only effective spots remaining for display: `max(0, max_capacity - capacity_enrolled_count)` capped by `capacity_left_override` when both `max_capacity` and `capacity_left_override` are set; null when `max_capacity` is null (even if `capacity_left_override` is stored on the row). waitlist_enabled: type: boolean eventbrite_sync_status: $ref: "#/components/schemas/EventbriteSyncStatus" description: Eventbrite publish pipeline state for this instance row. eventbrite_event_url: type: string format: uri pattern: ^https?:// nullable: true maxLength: 500 readOnly: true description: > Public Eventbrite event URL written by the sync processor. Null until a create or update stores a URL. Distinct from `external_url`. eventbrite_last_error: type: string nullable: true readOnly: true description: > Last Eventbrite sync failure, or a notice when the row is synced but Eventbrite would not publish or unpublish. Null when the last sync had nothing to report. Blank stored text is returned as null. external_url: type: string format: uri pattern: ^https?:// nullable: true maxLength: 500 description: > Optional external registration or info URL (http/https only). Distinct from Eventbrite sync URLs on the instance. partner_organizations: type: array items: $ref: "#/components/schemas/InstancePartnerOrganization" instructor_id: type: string nullable: true cohort: type: string nullable: true maxLength: 128 pattern: ^[a-z0-9]+(-[a-z0-9]+)*$ description: > Optional label using the same normalization rules as instance referral slugs (lowercase letters, digits, single hyphens between segments). notes: type: string nullable: true tags: type: array items: $ref: "#/components/schemas/EntityTagRef" tag_ids: type: array items: type: string format: uuid created_by: type: string created_at: type: string format: date-time nullable: true updated_at: type: string format: date-time nullable: true resolved_title: type: string nullable: true resolved_description: type: string nullable: true resolved_cover_image_s3_key: type: string nullable: true resolved_delivery_mode: type: string nullable: true resolved_slug: type: string description: > Public instance slug; same as `slug`. Kept for backwards compatibility. resolved_location_id: type: string format: uuid nullable: true description: > Instance location_id when set, otherwise the parent service default location_id. This is admin-only catalog inheritance. The public calendar does not use this value; physical offerings with no instance or slot venue emit `location_tbc: true` instead. resolved_training_details: type: object nullable: true description: > Effective training pricing: instance row when present, otherwise the parent service training_course_details defaults. properties: training_format: $ref: "#/components/schemas/TrainingFormat" price: type: string currency: type: string pricing_unit: $ref: "#/components/schemas/TrainingPricingUnit" resolved_event_ticket_tiers: type: array description: > Effective event tiers for display: instance tiers when present, otherwise a synthetic tier from the parent service event defaults. items: $ref: "#/components/schemas/EventTicketTier" resolved_consultation_details: type: object nullable: true description: > Effective consultation pricing from the parent service `consultation_details` row (tier-per-service catalog). properties: pricing_model: $ref: "#/components/schemas/ConsultationPricingModel" price: type: string nullable: true currency: type: string package_sessions: type: integer nullable: true session_slots: type: array items: $ref: "#/components/schemas/SessionSlot" training_details: type: object nullable: true properties: training_format: $ref: "#/components/schemas/TrainingFormat" price: type: string currency: type: string pricing_unit: $ref: "#/components/schemas/TrainingPricingUnit" event_ticket_tiers: type: array items: $ref: "#/components/schemas/EventTicketTier" consultation_details: type: object nullable: true properties: pricing_model: $ref: "#/components/schemas/ConsultationPricingModel" price: type: string nullable: true currency: type: string package_sessions: type: integer nullable: true parent_service_title: type: string nullable: true description: Parent service title (present on cross-service list responses). parent_service_tier: type: string nullable: true description: > Parent service tier slug (present on cross-service list responses; same column as services.service_tier). parent_service_type: nullable: true description: Parent service type (present on cross-service list responses). allOf: - $ref: "#/components/schemas/ServiceType" parent_service_key: type: string nullable: true description: > Parent service public key (`services.service_key`) when set; mirrors the parent service row for cross-service instance list responses. InstanceListResponse: type: object required: [items, total_count] properties: items: type: array items: $ref: "#/components/schemas/ServiceInstance" next_cursor: type: string nullable: true total_count: type: integer InstanceResponse: type: object required: [instance] properties: instance: $ref: "#/components/schemas/ServiceInstance" CreateInstanceRequest: type: object required: [slug] description: > Instance create body for `POST /v1/admin/services/{id}/instances`. `slug` is required for all service types (400 with `field: slug` when missing or invalid). Duplicate instance slugs return 409 with `field: slug`. properties: title: type: string nullable: true slug: type: string description: > Public instance slug (required). URL-safe: lowercase letters, digits, and single hyphens between segments (e.g. spring-workshop). Stored normalized to lowercase. Must be unique among instances. description: type: string nullable: true cover_image_s3_key: type: string nullable: true status: $ref: "#/components/schemas/InstanceStatus" delivery_mode: $ref: "#/components/schemas/ServiceDeliveryMode" location_id: type: string format: uuid nullable: true max_capacity: type: integer nullable: true capacity_left_override: type: integer nullable: true minimum: 0 description: > Optional display-only soft cap for spots remaining. Omit to leave unset on create. Send JSON null to clear on update when `max_capacity` is set. When `max_capacity` is null, the server stores the value but public display ignores the override until `max_capacity` is set. waitlist_enabled: type: boolean external_url: type: string format: uri pattern: ^https?:// nullable: true maxLength: 500 partner_organization_ids: type: array items: type: string format: uuid description: > Ordered partner organization ids for event instances. Unknown ids return 400. instructor_id: type: string nullable: true cohort: type: string nullable: true maxLength: 128 pattern: ^[a-z0-9]+(-[a-z0-9]+)*$ notes: type: string nullable: true tag_ids: type: array items: type: string format: uuid description: > Replaces all instance tag associations when present (including on PUT). The admin web UI sends this on every instance save; omit the field only if a non-UI client must patch other fields without changing tags. session_slots: type: array items: $ref: "#/components/schemas/SessionSlot" training_details: type: object nullable: true properties: training_format: $ref: "#/components/schemas/TrainingFormat" price: type: string description: > Required for training_course instances. Decimal amount as a string; zero is allowed (free offerings). currency: type: string pricing_unit: $ref: "#/components/schemas/TrainingPricingUnit" event_ticket_tiers: type: array items: $ref: "#/components/schemas/EventTicketTier" consultation_details: type: object nullable: true properties: pricing_model: $ref: "#/components/schemas/ConsultationPricingModel" price: type: string nullable: true currency: type: string package_sessions: type: integer nullable: true UpdateInstanceRequest: allOf: - $ref: "#/components/schemas/CreateInstanceRequest" required: - status description: > Clearing `slug` to null returns 400 with `field: slug`. Enrollment: type: object required: [id, instance_id, status] properties: id: type: string format: uuid instance_id: type: string format: uuid contact_id: type: string format: uuid nullable: true family_id: type: string format: uuid nullable: true organization_id: type: string format: uuid nullable: true ticket_tier_id: type: string format: uuid nullable: true discount_code_id: type: string format: uuid nullable: true status: $ref: "#/components/schemas/EnrollmentStatus" amount_paid: type: string nullable: true currency: type: string nullable: true enrolled_at: type: string format: date-time nullable: true cancelled_at: type: string format: date-time nullable: true notes: type: string nullable: true invoice_number: type: string nullable: true description: Non-void invoice number for this enrollment, when one exists. invoice_status: type: string nullable: true description: draft or issued. Void invoices are omitted. payment_status: type: string nullable: true description: Latest non-failed inbound payment status for this enrollment. billing_warning: type: string nullable: true description: > Set when the invoice was left as a draft, was not created, or needs a refund after cancellation. party_display_name: type: string description: > Display label for the enrollment party. For contact enrollment this is `contact name · email` (middle dot) when both name and email are known; otherwise the best available single label. For family or organization enrollment this is `entity name · primary contact name` (middle dot) when both the entity and primary contact names are known; otherwise the best available single label. Matches the billing enrollment picker `partyDisplayName` convention. created_by: type: string created_at: type: string format: date-time nullable: true updated_at: type: string format: date-time nullable: true EnrollmentListResponse: type: object required: [items, total_count] properties: items: type: array items: $ref: "#/components/schemas/Enrollment" next_cursor: type: string nullable: true total_count: type: integer EnrollmentResponse: type: object required: [enrollment] properties: enrollment: $ref: "#/components/schemas/Enrollment" CreateEnrollmentRequest: type: object properties: contact_id: type: string format: uuid nullable: true family_id: type: string format: uuid nullable: true organization_id: type: string format: uuid nullable: true ticket_tier_id: type: string format: uuid nullable: true discount_code_id: type: string format: uuid nullable: true description: > Must be globally scoped, scoped to this instance's service, or scoped to this instance; otherwise the API returns 400. status: $ref: "#/components/schemas/EnrollmentStatus" amount_paid: type: string nullable: true currency: type: string nullable: true notes: type: string nullable: true bill_later: type: boolean description: > When true, the enrollment is saved with no payment and no invoice so Finance can merge it onto a later invoice. Omit every billing field to keep the previous client, which records the payment in a second request. payment_method: type: string description: > fps (default), bank_transfer, cash, cheque, or free. Free is only valid when the amount is zero. payment_received: type: boolean description: > When true, the payment is recorded as succeeded. Otherwise it stays pending until staff confirm it. send_invoice_email: type: boolean description: > When true and auto-invoicing is enabled, email the issued invoice. Default false. An invoice with no bill-to email is still issued. UpdateEnrollmentRequest: type: object minProperties: 1 properties: promote_to_family_id: type: string format: uuid description: > One-time conversion from a contact-only enrollment (contact_id set, family and organization null) to a family enrollment. Mutually exclusive with promote_to_organization_id. Clears contact_id, sets family_id, and aligns bill-to fields to the family. promote_to_organization_id: type: string format: uuid description: > One-time conversion from a contact-only enrollment to an organization enrollment. Mutually exclusive with promote_to_family_id. Clears contact_id, sets organization_id, and aligns bill-to fields to the organization. status: $ref: "#/components/schemas/EnrollmentStatus" enrolled_at: type: string format: date-time description: > ISO 8601 instant for when the enrollment was recorded. Omit to leave unchanged. Null or empty strings are rejected (the enrollment row requires a timestamp). amount_paid: type: string nullable: true currency: type: string nullable: true discount_code_id: type: string format: uuid nullable: true description: > Set to null to clear the enrollment discount; changing the id adjusts discount code usage counts accordingly. The new id must be globally scoped, scoped to this instance's service, or scoped to this instance; otherwise the API returns 400. notes: type: string nullable: true DiscountCode: type: object required: [id, code, discount_type, discount_value, active] properties: id: type: string format: uuid code: type: string description: type: string nullable: true discount_type: $ref: "#/components/schemas/DiscountType" discount_value: type: string currency: type: string nullable: true valid_from: type: string format: date-time nullable: true valid_until: type: string format: date-time nullable: true service_id: type: string format: uuid nullable: true instance_id: type: string format: uuid nullable: true max_uses: type: integer nullable: true current_uses: type: integer active: type: boolean created_by: type: string created_at: type: string format: date-time nullable: true updated_at: type: string format: date-time nullable: true DiscountCodeListResponse: type: object required: [items, total_count] properties: items: type: array items: $ref: "#/components/schemas/DiscountCode" next_cursor: type: string nullable: true total_count: type: integer DiscountCodeResponse: type: object required: [discount_code] properties: discount_code: $ref: "#/components/schemas/DiscountCode" CreateDiscountCodeRequest: type: object required: [code, discount_type, discount_value] properties: code: type: string description: type: string nullable: true discount_type: $ref: "#/components/schemas/DiscountType" discount_value: type: string description: > For `referral` type the server coerces this to "0"; client-supplied values are ignored (including malformed strings). currency: type: string nullable: true description: > For `referral` type the server coerces this to "HKD"; client-supplied values are ignored. valid_from: type: string format: date-time nullable: true valid_until: type: string format: date-time nullable: true service_id: type: string format: uuid nullable: true instance_id: type: string format: uuid nullable: true max_uses: type: integer nullable: true active: type: boolean nullable: true UpdateDiscountCodeRequest: type: object minProperties: 1 properties: description: type: string nullable: true discount_type: $ref: "#/components/schemas/DiscountType" discount_value: type: string description: > Must be greater than 0 unless the effective discount type after this update is `referral` (tracking-only), in which case `0` is accepted and the server coerces the stored value to "0"; other client-supplied values are ignored for referral. currency: type: string nullable: true description: > When the resulting type is `referral`, the server coerces this to "HKD"; client-supplied values are ignored. valid_from: type: string format: date-time nullable: true valid_until: type: string format: date-time nullable: true service_id: type: string format: uuid nullable: true instance_id: type: string format: uuid nullable: true max_uses: type: integer nullable: true active: type: boolean AuditLog: type: object required: - id - table_name - record_id - action - source - timestamp properties: id: type: string format: uuid table_name: type: string record_id: type: string action: type: string enum: [INSERT, UPDATE, DELETE] user_id: type: string nullable: true description: > Cognito subject, `api-key:` for token writes, or a system actor (`system`, `webhook:whatsapp`, `webhook:meta`, `alembic`, `system:sales-daily-plan`). user_email: type: string nullable: true description: > Display label for the actor: Cognito email, API key `name` when `user_id` is `api-key:`, or a system-actor label such as `WhatsApp webhook` (optional). request_id: type: string nullable: true old_values: type: object additionalProperties: true nullable: true new_values: type: object additionalProperties: true nullable: true changed_fields: type: array items: type: string nullable: true timestamp: type: string format: date-time source: type: string description: Source of the row (`trigger` or `application`). ip_address: type: string nullable: true user_agent: type: string nullable: true AuditLogListResponse: type: object required: - items properties: items: type: array items: $ref: "#/components/schemas/AuditLog" next_cursor: type: string nullable: true AdminUser: type: object required: - sub properties: sub: type: string email: type: string nullable: true name: type: string nullable: true AdminUserListResponse: type: object required: - items properties: items: type: array items: $ref: "#/components/schemas/AdminUser" CognitoStaffGroup: type: string enum: - admin - manager - instructor CognitoUser: type: object required: - username - sub - email_verified - enabled - status - groups properties: username: type: string sub: type: string email: type: string nullable: true name: type: string nullable: true email_verified: type: boolean enabled: type: boolean status: type: string groups: type: array items: type: string created_at: type: string nullable: true updated_at: type: string nullable: true last_auth_time: type: string nullable: true CognitoUserListResponse: type: object required: - items properties: items: type: array items: $ref: "#/components/schemas/CognitoUser" next_cursor: type: string nullable: true CreateCognitoUserRequest: type: object required: - email properties: email: type: string name: type: string group: $ref: "#/components/schemas/CognitoStaffGroup" UpdateCognitoUserRequest: type: object properties: email: type: string name: type: string group: allOf: - $ref: "#/components/schemas/CognitoStaffGroup" nullable: true enabled: type: boolean DeleteCognitoUserResponse: type: object required: - deleted - username properties: deleted: type: boolean username: type: string GeographicArea: type: object required: - id - name - name_translations - level - active - display_order properties: id: type: string format: uuid parent_id: type: string format: uuid nullable: true name: type: string name_translations: type: object additionalProperties: type: string level: type: string enum: [country, region, city, district] code: type: string nullable: true sovereign_country_id: type: string format: uuid nullable: true description: > FK to the sovereign country row (e.g. HK → China) for geocoding ``countrycodes`` composition. active: type: boolean display_order: type: integer GeographicAreaListResponse: type: object required: - items properties: items: type: array items: $ref: "#/components/schemas/GeographicArea" Location: type: object required: - id - area_id - locked_from_partner_org - partner_organization_labels - partner_organization_ids properties: id: type: string format: uuid name: type: string maxLength: 200 nullable: true area_id: type: string format: uuid address: type: string nullable: true lat: type: number format: double nullable: true lng: type: number format: double nullable: true created_at: type: string format: date-time nullable: true updated_at: type: string format: date-time nullable: true locked_from_partner_org: type: boolean description: > True when at least one active CRM organisation with relationship type partner references this location. The venue name is managed from the organisation record; delete is blocked server-side. partner_organization_labels: type: array description: > Names of active partner organisations linked to this venue (for display). items: type: string partner_organization_ids: type: array description: > UUIDs of active partner organisations linked to this venue, in the same order as ``partner_organization_labels`` (sorted by partner name). items: type: string format: uuid LocationResponse: type: object required: - location properties: location: $ref: "#/components/schemas/Location" LocationListResponse: type: object required: - items - total_count properties: items: type: array items: $ref: "#/components/schemas/Location" next_cursor: type: string nullable: true total_count: type: integer minimum: 0 description: Total number of locations matching the current filters (not page size). GeocodeLocationRequest: type: object required: - area_id - address properties: area_id: type: string format: uuid address: type: string maxLength: 500 GeocodeLocationResponse: type: object required: - lat - lng properties: lat: type: number format: double lng: type: number format: double display_name: type: string description: Provider-resolved label for the top match. nullable: true CreateLocationRequest: type: object required: - area_id properties: area_id: type: string format: uuid name: type: string maxLength: 200 nullable: true address: type: string maxLength: 500 nullable: true lat: type: number format: double minimum: -90 maximum: 90 nullable: true lng: type: number format: double minimum: -180 maximum: 180 nullable: true UpdateLocationRequest: allOf: - $ref: "#/components/schemas/CreateLocationRequest" PartialUpdateLocationRequest: type: object minProperties: 1 properties: area_id: type: string format: uuid name: type: string maxLength: 200 nullable: true address: type: string maxLength: 500 nullable: true lat: type: number format: double minimum: -90 maximum: 90 nullable: true lng: type: number format: double minimum: -180 maximum: 180 nullable: true CreateAssetRequest: type: object required: - title - file_name - asset_type - visibility properties: title: type: string maxLength: 255 description: type: string nullable: true asset_type: type: string enum: [guide, video, pdf, document] file_name: type: string maxLength: 255 resource_key: type: string maxLength: 200 nullable: true content_type: type: string maxLength: 127 nullable: true content_language: type: string maxLength: 35 nullable: true enum: [en, zh-CN, zh-HK] description: > BCP 47-style tag for the language of the file content. Admin writes allow only en, zh-CN, or zh-HK. Used by `GET /v1/assets/free` when filtering by `language`. visibility: type: string enum: [public, restricted] description: > `public` also seeds a share-link domain allowlist from `ASSET_SHARE_LINK_DEFAULT_ALLOWED_DOMAINS`. Restricted assets do not receive a share link on create. client_tag: type: string nullable: true enum: [client_document] description: > Optional. When set to client_document, links the asset to the client_document tag after create. When omitted or null, no client tag is linked. UpdateAssetRequest: allOf: - $ref: "#/components/schemas/CreateAssetRequest" PartialUpdateAssetRequest: type: object minProperties: 1 properties: title: type: string maxLength: 255 description: type: string nullable: true asset_type: type: string enum: [guide, video, pdf, document] file_name: type: string maxLength: 255 resource_key: type: string maxLength: 200 nullable: true content_type: type: string maxLength: 127 nullable: true content_language: type: string maxLength: 35 nullable: true enum: [en, zh-CN, zh-HK] description: > BCP 47-style tag for the language of the file content. Admin writes allow only en, zh-CN, or zh-HK. Send null to clear. visibility: type: string enum: [public, restricted] description: > Must remain `restricted` for assets tagged `expense_attachment` or `customer_invoice` (400 if set to `public`). Changing a non-system asset to `public` seeds a share-link allowlist from `ASSET_SHARE_LINK_DEFAULT_ALLOWED_DOMAINS` when the asset does not already have a share link. client_tag: type: string nullable: true enum: [client_document] description: > When present, sets or clears the client_document tag on the asset. Omit this property to leave the client tag unchanged. Must not be sent for assets that have the `expense_attachment` or `customer_invoice` tag (400). CreateAssetResponse: type: object required: - asset - upload_url - upload_method - upload_headers - expires_at properties: asset: $ref: "#/components/schemas/Asset" upload_url: type: string format: uri upload_method: type: string upload_headers: type: object additionalProperties: type: string expires_at: type: string format: date-time InitAssetContentReplaceRequest: type: object required: - file_name properties: file_name: type: string maxLength: 255 content_type: type: string maxLength: 127 nullable: true InitAssetContentReplaceResponse: type: object required: - pending_s3_key - upload_method - upload_headers - expires_at properties: pending_s3_key: type: string maxLength: 1024 upload_url: type: string format: uri upload_method: type: string upload_headers: type: object additionalProperties: type: string expires_at: type: string format: date-time CompleteAssetContentReplaceRequest: type: object required: - pending_s3_key - file_name properties: pending_s3_key: type: string maxLength: 1024 file_name: type: string maxLength: 255 description: > Must match the sanitized filename segment in `pending_s3_key` (same value as sent to init). content_type: type: string maxLength: 127 nullable: true description: Optional; when null the server may use the object's S3 Content-Type after upload. CreateAssetGrantRequest: type: object required: - grant_type properties: grant_type: type: string enum: [all_authenticated, organization, user] grantee_id: type: string nullable: true ExpenseStatus: type: string enum: [draft, submitted, paid, voided, amended] ExpenseParseStatus: type: string enum: [not_requested, queued, processing, succeeded, failed] ExpenseLineItem: type: object properties: description: type: string nullable: true quantity: type: string nullable: true unit_price: type: string nullable: true amount: type: string nullable: true ExpenseAttachment: type: object required: - id - asset_id - sort_order properties: id: type: string format: uuid asset_id: type: string format: uuid sort_order: type: integer file_name: type: string nullable: true content_type: type: string nullable: true asset_title: type: string nullable: true Expense: type: object required: - id - status - parse_status - attachments properties: id: type: string format: uuid amends_expense_id: type: string format: uuid nullable: true status: $ref: "#/components/schemas/ExpenseStatus" parse_status: $ref: "#/components/schemas/ExpenseParseStatus" vendor_id: type: string format: uuid nullable: true vendor_name: type: string nullable: true description: > Name of the linked vendor organization when vendor_id resolves to a vendor; derived for display, not stored on the expense row. invoice_number: type: string nullable: true invoice_date: type: string format: date nullable: true due_date: type: string format: date nullable: true currency: type: string nullable: true subtotal: type: string nullable: true tax: type: string nullable: true total: type: string nullable: true line_items: type: array items: $ref: "#/components/schemas/ExpenseLineItem" parse_confidence: type: string nullable: true parser_raw: type: object nullable: true additionalProperties: true notes: type: string nullable: true void_reason: type: string nullable: true submitted_at: type: string format: date-time nullable: true paid_at: type: string format: date-time nullable: true voided_at: type: string format: date-time nullable: true created_by: type: string updated_by: type: string nullable: true created_at: type: string format: date-time updated_at: type: string format: date-time attachments: type: array items: $ref: "#/components/schemas/ExpenseAttachment" ExpenseResponse: type: object required: - expense properties: expense: $ref: "#/components/schemas/Expense" CustomerPaymentAllocationInvoice: type: object properties: invoiceId: type: string format: uuid invoiceNumber: type: string nullable: true CustomerPaymentSummary: type: object required: - orphanPaymentDeletable - party - unappliedAmount properties: id: type: string format: uuid direction: type: string enum: [inbound, refund] status: type: string enum: [pending, succeeded, failed] method: type: string amount: type: string currency: type: string minLength: 3 maxLength: 3 originalPaymentId: type: string format: uuid nullable: true stripePaymentIntentId: type: string nullable: true stripeRefundId: type: string nullable: true enrollmentId: type: string format: uuid nullable: true contactId: type: string format: uuid nullable: true externalReference: type: string nullable: true description: Bank reference or external id when set on the payment row. party: type: string description: > Bill-to party display label from the linked enrollment when present; otherwise the linked contact display name, or an em dash when unknown. unappliedAmount: type: string description: > Remaining payment amount not allocated to invoices (payment currency). Included on all CustomerPaymentSummary responses (list, detail, create, confirm, patch). orphanPaymentDeletable: type: boolean description: > True when DELETE /v1/admin/billing/payments/{id} is allowed for this row. Pending inbound payments qualify even when linked to an active enrollment. Free or zero-amount payments qualify only when the enrollment is unlinked or cancelled. Allocations, a receipt, or refund children always block delete. succeededAt: type: string format: date-time nullable: true createdAt: type: string format: date-time CustomerInvoiceLine: type: object properties: id: type: string format: uuid invoiceId: type: string format: uuid enrollmentId: oneOf: - type: string format: uuid - type: "null" description: Present when the line is tied to an enrollment; null for customized invoice lines. lineOrder: type: integer description: type: string quantity: type: string unitAmount: type: string lineTotal: type: string discountAmount: type: string nullable: true taxRate: type: string nullable: true taxAmount: type: string nullable: true currency: type: string minLength: 3 maxLength: 3 createdAt: type: string format: date-time updatedAt: type: string format: date-time CustomerInvoiceSummary: type: object properties: id: type: string format: uuid status: type: string enum: [draft, issued, void] invoiceNumber: type: string nullable: true invoiceSequence: type: integer nullable: true currency: type: string minLength: 3 maxLength: 3 subtotal: type: string taxTotal: type: string total: type: string amountAllocated: type: string description: Sum of payment_allocations for this invoice in the invoice currency (cached). balanceDue: type: string description: max(total - amount_allocated, 0) in invoice currency (cached). paidAt: type: string format: date-time nullable: true description: Time the issued invoice became fully settled (best-effort on historical backfill). isPaid: type: boolean description: True when status is issued, total > 0, and balance_due is zero. billToKind: type: string enum: [contact, family, organization] billToContactId: type: string format: uuid nullable: true billToFamilyId: type: string format: uuid nullable: true billToOrganizationId: type: string format: uuid nullable: true billToDisplayName: type: string nullable: true billToEmail: type: string nullable: true billToLocationText: type: string nullable: true issuedAt: type: string format: date-time nullable: true invoiceDate: type: string format: date nullable: true dueDate: type: string format: date nullable: true voidedAt: type: string format: date-time nullable: true issuedPdfSha256: type: string nullable: true lineCount: type: integer createdAt: type: string format: date-time updatedAt: type: string format: date-time CustomerInvoiceDetail: allOf: - $ref: "#/components/schemas/CustomerInvoiceSummary" - type: object properties: voidReason: type: string nullable: true billToSnapshot: type: object nullable: true additionalProperties: true emailSentAt: type: string format: date-time nullable: true lines: type: array items: $ref: "#/components/schemas/CustomerInvoiceLine" CreateCustomerRefundRequest: type: object required: - direction - originalPaymentId - amount - currency properties: direction: type: string enum: [refund] originalPaymentId: type: string format: uuid amount: type: string currency: type: string minLength: 3 maxLength: 3 method: type: string stripeRefundId: type: string nullable: true CreateManualInboundCustomerPaymentRequest: type: object required: - direction - amount - currency - method properties: direction: type: string enum: [inbound] enrollmentId: type: string format: uuid nullable: true description: > Optional. Omit (or send `null`) to record a payment with no enrollment link (for example to settle a customized invoice that is not linked to any enrollment). When provided, currency must match the enrollment billing currency. contactId: type: string format: uuid nullable: true description: > Optional CRM contact for attribution. When `enrollmentId` is provided, `contactId` is derived from the enrollment unless explicitly overridden here. amount: type: string description: Decimal amount as string; must be non-negative. currency: type: string minLength: 3 maxLength: 3 method: type: string description: > Must normalize to one of: `free`, `stripe_card`, `fps`, `bank_transfer`, `adjustment`, `cash`, `cheque` (aliases such as card, wire, transfer, check are accepted). Stored values follow the same canonical set (for example `bank_transfer`, `fps`, `stripe_card`, `cash`, `free`). Zero amounts are coerced to `free` and `succeeded`. minLength: 1 maxLength: 64 status: type: string enum: [pending, succeeded] default: pending description: > `pending` for funds not yet cleared; `succeeded` when funds are received (receipt generation follows server rules). Zero amounts are always stored as succeeded `free`. externalReference: type: string nullable: true description: Optional bank reference or external id stored on the payment row. UpdateManualInboundCustomerPaymentRequest: type: object required: - amount - currency - method - status properties: amount: type: string description: Decimal amount as string; must be non-negative. currency: type: string minLength: 3 maxLength: 3 method: type: string description: > Same normalization rules as manual inbound create (for example `fps`, `bank_transfer`). minLength: 1 maxLength: 64 status: type: string enum: [pending, succeeded] description: > Pending rows may move to succeeded (receipt generation follows server rules). Succeeded rows must submit the same `status` value when updating method or reference. externalReference: type: string nullable: true description: Optional bank reference or external id stored on the payment row. BillingEnrollmentPickerRow: type: object additionalProperties: false required: - enrollmentId - partyDisplayName - invoiceLinked - currency - billToMergeKey properties: enrollmentId: type: string format: uuid partyDisplayName: type: string description: > Display label for the bill-to / enrollment party. For `contact` the admin UI combines this with `partyEmail` as `name · email` when both are known. For `family` or `organization` this is `entity name · primary contact name` (middle dot) when both the entity and primary contact names are known; otherwise the best available single label. partyEmail: type: string format: email nullable: true billToKind: type: string enum: - contact - family - organization description: Bill-to kind for this enrollment (matches `billing_bill_to_kind`). instanceTitle: type: string nullable: true description: Trimmed instance-specific title when set. parentServiceTitle: type: string nullable: true description: Parent service template title from the instance's service (for display when `instanceTitle` is empty). serviceTierName: type: string nullable: true description: > Display tier label: event ticket tier name when the enrollment has a ticket tier; otherwise the parent service's `service_tier` when present. instanceCohort: type: string nullable: true amountPaid: type: string description: Decimal amount as string; mirrors enrollment `amount_paid`. nullable: true currency: type: string minLength: 3 maxLength: 3 enrolledAt: type: string format: date-time nullable: true invoiceLinked: type: boolean description: True when linked to a draft or issued invoice line. billToMergeKey: type: string description: Stable client-side key for matching bill-to identity across enrollments. CreateDraftInvoiceRequest: type: object required: - draftKind - enrollmentIds description: > `draftKind` must be `enrollment_merge`. Invoice currency defaults to the shared enrollment currency (all enrollments must match). Optional `currency` must equal that currency when provided. Line totals default to each enrollment's `amount_paid` at draft time. Optional `lineTotalsByEnrollmentId` maps enrollment UUID strings to decimal amounts to override mispriced or stale `amount_paid` before issue. Do not send `billTo` or `lines` with this request. properties: draftKind: type: string enum: [enrollment_merge] enrollmentIds: type: array items: type: string format: uuid minItems: 1 currency: type: string nullable: true description: Optional ISO currency code; when set must match every enrollment. Omit to derive. pattern: "^[A-Z]{3}$" lineTotalsByEnrollmentId: type: object additionalProperties: type: string description: Decimal amount as string invoiceDate: type: string format: date nullable: true description: Optional ISO date (YYYY-MM-DD). When omitted, defaults to today in INVOICE_DISPLAY_TIMEZONE (or UTC if unset). InvoiceBillToInput: type: object required: - kind description: > Bill-to party for a customized draft. Supply exactly one of contactId, familyId, or organizationId matching `kind`. properties: kind: type: string enum: [contact, family, organization] contactId: type: string format: uuid description: Required when kind is contact. familyId: type: string format: uuid description: Required when kind is family. organizationId: type: string format: uuid description: Required when kind is organization. CustomizedInvoiceLineInput: type: object required: - description - quantity - unitAmount description: > Line total is computed as quantity × unitAmount − discountAmount + tax. Omit discount and tax fields for a simple quantity × unitAmount line. Tax may be given as `taxAmount` or derived from `taxRate` × (quantity × unitAmount − discountAmount). properties: description: type: string maxLength: 500 quantity: type: string description: Decimal quantity; must be positive. unitAmount: type: string description: Decimal unit price in invoice currency. discountAmount: type: string nullable: true description: Optional decimal discount; defaults to 0. Must not exceed quantity × unitAmount. taxRate: type: string nullable: true description: Optional decimal tax rate applied to taxable amount (quantity × unitAmount − discountAmount). Mutually exclusive with `taxAmount`. taxAmount: type: string nullable: true description: Optional explicit decimal tax amount. Mutually exclusive with `taxRate`. CreateCustomizedDraftInvoiceRequest: type: object required: - draftKind - billTo - currency - lines description: > `draftKind` must be `customized_manual`. Creates a draft invoice with manually specified lines. Lines are not linked to enrollments (`enrollmentId` is null on each line). At most 50 lines per request. Do not send `enrollmentIds` with this request. properties: draftKind: type: string enum: [customized_manual] billTo: $ref: "#/components/schemas/InvoiceBillToInput" currency: type: string minLength: 3 maxLength: 3 pattern: "^[A-Z]{3}$" lines: type: array items: $ref: "#/components/schemas/CustomizedInvoiceLineInput" minItems: 1 maxItems: 50 invoiceDate: type: string format: date nullable: true description: Optional ISO date (YYYY-MM-DD). When omitted, defaults to today in INVOICE_DISPLAY_TIMEZONE (or UTC if unset). ResolveBillToPrimaryContactsRequest: type: object additionalProperties: false properties: familyIds: type: array items: type: string format: uuid description: CRM family ids to resolve (deduplicated; max 400). organizationIds: type: array items: type: string format: uuid description: CRM organisation ids to resolve (deduplicated; max 400). ResolveBillToPrimaryContactsResponse: type: object required: - familyPrimaryContactById - organizationPrimaryContactById additionalProperties: false properties: familyPrimaryContactById: type: object description: Map from family id (UUID string) to primary contact id (UUID string). additionalProperties: type: string format: uuid organizationPrimaryContactById: type: object description: Map from organisation id (UUID string) to primary contact id (UUID string). additionalProperties: type: string format: uuid CreatePaymentAllocationRequest: type: object required: - paymentId - invoiceId - allocatedAmount - currency properties: paymentId: type: string format: uuid invoiceId: type: string format: uuid invoiceLineId: type: string format: uuid nullable: true allocatedAmount: type: string description: >- Must be strictly positive. Zero is rejected (matches the database constraint on `payment_allocations.allocated_amount`); use other billing flows for complimentary or fully discounted invoices rather than a zero payment allocation row. currency: type: string minLength: 3 maxLength: 3 ExpenseListResponse: type: object required: - items - total_count properties: items: type: array items: $ref: "#/components/schemas/Expense" next_cursor: type: string nullable: true total_count: type: integer CreateExpenseRequest: type: object required: - vendor_id - attachment_asset_ids properties: status: $ref: "#/components/schemas/ExpenseStatus" vendor_id: type: string format: uuid nullable: true invoice_number: type: string nullable: true invoice_date: type: string format: date nullable: true due_date: type: string format: date nullable: true currency: type: string nullable: true subtotal: type: string nullable: true tax: type: string nullable: true total: type: string nullable: true line_items: type: array items: $ref: "#/components/schemas/ExpenseLineItem" notes: type: string nullable: true attachment_asset_ids: type: array minItems: 1 items: type: string format: uuid parse_requested: type: boolean BulkImportJobStatus: type: string enum: - pending - processing - succeeded - succeeded_with_errors - failed description: Asynchronous bulk PDF import lifecycle. BulkImportJob: type: object required: - id - status properties: id: type: string format: uuid status: $ref: "#/components/schemas/BulkImportJobStatus" error_message: type: string nullable: true description: > Populated when `status` is `failed`, or carries a short operator-facing summary when `status` is `succeeded_with_errors`. created_count: type: integer nullable: true minimum: 0 description: Number of expenses created when the job finished with successes. expenses: type: array nullable: true items: $ref: "#/components/schemas/Expense" description: > Full expense payloads when `status` is `succeeded` or `succeeded_with_errors` (order matches `created_expense_ids` insertion order); otherwise null. BulkImportJobListResponse: type: object required: - items - next_cursor - total_count properties: items: type: array items: $ref: "#/components/schemas/BulkImportJobSummary" next_cursor: type: string nullable: true total_count: type: integer minimum: 0 BulkImportJobSummary: type: object required: - id - status - created_at - updated_at - attachment_asset_id - default_vendor_id - expense_status properties: id: type: string format: uuid status: $ref: "#/components/schemas/BulkImportJobStatus" error_message: type: string nullable: true created_count: type: integer nullable: true minimum: 0 created_at: type: string format: date-time updated_at: type: string format: date-time attachment_asset_id: type: string format: uuid default_vendor_id: type: string format: uuid expense_status: $ref: "#/components/schemas/ExpenseStatus" BulkImportJobResponse: type: object required: - bulk_import_job properties: bulk_import_job: $ref: "#/components/schemas/BulkImportJob" BulkImportExpensesFromPdfRequest: type: object required: - attachment_asset_id - default_vendor_id properties: attachment_asset_id: type: string format: uuid description: Uploaded PDF asset id (same presign flow as single expense attachments). default_vendor_id: type: string format: uuid description: > Vendor applied when a parsed row has no resolvable vendor_name match. status: $ref: "#/components/schemas/ExpenseStatus" description: > Optional. Expense status applied to every row created from the PDF; defaults to `submitted` when omitted. UpdateExpenseRequest: type: object properties: status: $ref: "#/components/schemas/ExpenseStatus" vendor_id: type: string format: uuid nullable: true invoice_number: type: string nullable: true invoice_date: type: string format: date nullable: true due_date: type: string format: date nullable: true currency: type: string nullable: true subtotal: type: string nullable: true tax: type: string nullable: true total: type: string nullable: true line_items: type: array items: $ref: "#/components/schemas/ExpenseLineItem" notes: type: string nullable: true attachment_asset_ids: type: array items: type: string format: uuid parse_requested: type: boolean CancelExpenseRequest: type: object required: - reason properties: reason: type: string EntityContactType: type: string enum: [parent, child, helper, professional, other] EntityRelationshipType: type: string description: > Stored relationship for contacts and read responses. Family and organization create/update requests use narrower enums (`EntityFamilyRelationshipType`, `EntityOrganizationRelationshipType`). Historical rows may still return values outside those narrower sets; PATCH bodies must send an allowed value (for example map unknown values to `other` before submit, matching the admin UI). enum: [prospect, client, past_client, partner, vendor, other] EntityFamilyRelationshipType: type: string enum: [prospect, client, other] description: Allowed values when setting a family's CRM relationship. EntityOrganizationRelationshipType: type: string enum: [prospect, client, partner, vendor, other] description: > Allowed values when setting an organization's CRM relationship. `past_client` is not permitted for organizations (use contacts for that lifecycle). EntityContactSource: type: string enum: - free_guide - newsletter - contact_form - reservation - referral - instagram - facebook - whatsapp - linkedin - event - phone_call - public_website - manual EntityMailchimpSyncStatus: type: string enum: [pending, synced, failed, unsubscribed] EntityFamilyRole: type: string enum: [parent, child, helper, guardian, other] EntityOrganizationType: type: string enum: [school, company, community_group, ngo, other] EntityOrganizationRole: type: string enum: [admin, staff, teacher, member, client, partner, other] EntityTagRef: type: object required: - id - name properties: id: type: string format: uuid name: type: string color: type: string nullable: true AdminTagRef: allOf: - $ref: "#/components/schemas/EntityTagRef" - type: object required: - description - archived_at - usage_count - is_system properties: description: type: string nullable: true maxLength: 255 archived_at: type: string format: date-time nullable: true description: When set, the tag is archived and hidden from assignment pickers. usage_count: type: integer minimum: 0 description: > Count of junction rows across contacts, families, organisations, assets, services, and service instances referencing this tag. is_system: type: boolean description: > True for reserved asset-pipeline tags (`expense_attachment`, `client_document`, `customer_invoice`). These cannot be renamed, archived, or deleted via the admin API. AdminCalendarManualBlockRef: type: object required: - id - purpose - block_date - period properties: id: type: string format: uuid purpose: type: string maxLength: 64 block_date: type: string format: date period: type: string enum: [am, pm, both] note: type: string nullable: true maxLength: 500 created_at: type: string format: date-time nullable: true updated_at: type: string format: date-time nullable: true created_by: type: string nullable: true maxLength: 128 description: Cognito subject of the admin who created the row (when known). updated_by: type: string nullable: true maxLength: 128 description: Cognito subject of the admin who last updated the row (when known). AdminCalendarManualBlockListResponse: type: object required: - items properties: items: type: array items: $ref: "#/components/schemas/AdminCalendarManualBlockRef" AdminCalendarManualBlockResponse: type: object required: - block properties: block: $ref: "#/components/schemas/AdminCalendarManualBlockRef" AdminCalendarManualBlockDeleteResponse: type: object required: - deleted properties: deleted: type: boolean CreateAdminCalendarManualBlockRequest: type: object required: - purpose - blockDate - period properties: purpose: type: string maxLength: 64 pattern: ^[a-z0-9]+(?:[-_][a-z0-9]+)*$ blockDate: type: string format: date period: type: string enum: [am, pm, both] note: type: string nullable: true maxLength: 500 UpdateAdminCalendarManualBlockRequest: type: object description: > Partial update: include only fields to change. Omitted fields are left unchanged. At least one of `blockDate`, `period`, or `note` must be present. properties: blockDate: type: string format: date period: type: string enum: [am, pm, both] note: type: string nullable: true maxLength: 500 AdminTagDeleteResponse: type: object required: - deleted - usage_count properties: deleted: type: boolean description: True when the tag row was removed from the database. usage_count: type: integer minimum: 0 description: Junction usage count evaluated at delete time. tag: $ref: "#/components/schemas/AdminTagRef" nullable: true description: Present when `deleted` is false (archived in-use tag). AdminTagListResponse: type: object required: - items properties: items: type: array items: $ref: "#/components/schemas/AdminTagRef" AdminFormSummary: type: object required: - formSlug - answerCount properties: formSlug: type: string pattern: ^[a-z0-9]+(-[a-z0-9]+)*$ answerCount: type: integer minimum: 0 AdminFormListResponse: type: object required: - items properties: items: type: array items: $ref: "#/components/schemas/AdminFormSummary" AdminFormAnswerRow: type: object required: - formSlug - sessionId - questionId - questionType - createdAt - updatedAt properties: formSlug: type: string pattern: ^[a-z0-9]+(-[a-z0-9]+)*$ sessionId: type: string format: uuid questionId: type: string pattern: ^[a-z0-9]+(-[a-z0-9]+)*$ questionType: type: string enum: - select - multiselect - rating - segmented - consent - text - email selectedOption: type: string maxLength: 500 selectedOptions: type: array maxItems: 20 items: type: string maxLength: 500 ratingValue: type: integer minimum: 1 maximum: 10 booleanAnswer: type: boolean freeText: type: string maxLength: 4000 contactId: type: string format: uuid description: > CRM contact this answer was personalised for, when the training-site link included `contact`. Omitted on answers collected without a contact. createdAt: type: string format: date-time updatedAt: type: string format: date-time AdminFormAnswerListResponse: type: object required: - items - respondentContactIds properties: items: type: array items: $ref: "#/components/schemas/AdminFormAnswerRow" next_cursor: type: string nullable: true description: Opaque cursor for the next page, or null when no further rows remain. respondentContactIds: type: array items: type: string format: uuid description: > Distinct CRM contact ids that have stored answers for this form, in first-seen order from the newest-first full set. Independent of pagination and of the `contact_id` filter. AdminFormClearAnswersResponse: type: object required: - formSlug - deletedCount properties: formSlug: type: string pattern: ^[a-z0-9]+(-[a-z0-9]+)*$ deletedCount: type: integer minimum: 0 AdminPollSummary: type: object required: - pollSlug - answerCount properties: pollSlug: type: string pattern: ^[a-z0-9]+(-[a-z0-9]+)*$ answerCount: type: integer minimum: 0 AdminPollListResponse: type: object required: - items properties: items: type: array items: $ref: "#/components/schemas/AdminPollSummary" AdminPollAnswerRow: type: object required: - pollSlug - sessionId - questionId - questionType - createdAt - updatedAt properties: pollSlug: type: string pattern: ^[a-z0-9]+(-[a-z0-9]+)*$ sessionId: type: string format: uuid questionId: type: string pattern: ^[a-z0-9]+(-[a-z0-9]+)*$ questionType: type: string enum: [select, multiselect, truefalse, text, email] selectedOption: type: string maxLength: 500 selectedOptions: type: array items: type: string maxLength: 500 maxItems: 20 booleanAnswer: type: boolean freeText: type: string maxLength: 4000 createdAt: type: string format: date-time updatedAt: type: string format: date-time AdminPollAnswerListResponse: type: object required: - items properties: items: type: array items: $ref: "#/components/schemas/AdminPollAnswerRow" next_cursor: type: string nullable: true description: Opaque cursor for the next page, or null when no further rows remain. AdminPollClearAnswersResponse: type: object required: - pollSlug - deletedCount properties: pollSlug: type: string pattern: ^[a-z0-9]+(-[a-z0-9]+)*$ deletedCount: type: integer minimum: 0 AdminTagResponse: type: object required: - tag properties: tag: $ref: "#/components/schemas/AdminTagRef" CreateAdminTagRequest: type: object required: - name properties: name: type: string minLength: 1 maxLength: 100 color: type: string nullable: true pattern: "^#[0-9A-Fa-f]{6}$" description: Optional UI color as `#RRGGBB`. description: type: string nullable: true maxLength: 255 UpdateAdminTagRequest: type: object properties: name: type: string minLength: 1 maxLength: 100 color: type: string nullable: true pattern: "^#[0-9A-Fa-f]{6}$" description: type: string nullable: true maxLength: 255 archived: type: boolean description: > When `false`, clears `archived_at` (restore). When `true`, sets `archived_at` unless the tag is system-managed (those reject archive). Omit when not changing archive state. EntityTagListResponse: type: object required: - items properties: items: type: array items: $ref: "#/components/schemas/EntityTagRef" EntityPickerListItem: type: object required: - id - label properties: id: type: string format: uuid label: type: string description: > Single-line display label. For CRM contact picker items this matches admin contact pickers (`name · email` when both known). For family and organisation picker items this is `entity name · primary contact name` when both are known; otherwise the best available label. EntityPickerListResponse: type: object required: - items properties: items: type: array items: $ref: "#/components/schemas/EntityPickerListItem" AdminContactMapPinEntityType: type: string enum: [contact, family, organization] AdminContactMapPin: type: object required: - entity_type - id - label - area_name - lat - lng properties: entity_type: $ref: "#/components/schemas/AdminContactMapPinEntityType" id: type: string format: uuid label: type: string description: Family name, organisation name, or contact display name. address: type: string nullable: true area_name: type: string lat: type: number format: double lng: type: number format: double contact_type: allOf: - $ref: "#/components/schemas/EntityContactType" description: Present when `entity_type` is `contact`. organization_type: allOf: - $ref: "#/components/schemas/EntityOrganizationType" description: Present when `entity_type` is `organization`. member_labels: type: array items: type: string description: Display names of family or organisation members. primary_contact_label: type: string description: > First and last name of the family's main contact. Present when `entity_type` is `family` and a primary member has a non-blank name. AdminContactMapPinListResponse: type: object required: - items properties: items: type: array items: $ref: "#/components/schemas/AdminContactMapPin" EntityLocationVenueSummary: type: object required: - id - area_id - area_name properties: id: type: string format: uuid name: type: string maxLength: 200 nullable: true area_id: type: string format: uuid area_name: type: string address: type: string nullable: true lat: type: number format: double nullable: true lng: type: number format: double nullable: true AdminContact: type: object required: - id - first_name - contact_type - relationship_type - source - mailchimp_status - active - tag_ids - tags - family_ids - organization_ids - standalone_note_count - has_completion_certificate - has_sales_conversation - has_service_instance - has_invoice properties: id: type: string format: uuid email: type: string nullable: true instagram_handle: type: string nullable: true first_name: type: string last_name: type: string nullable: true phone_region: type: string minLength: 2 maxLength: 2 pattern: "^[A-Z]{2}$" nullable: true phone_national_number: type: string pattern: "^[0-9]+$" maxLength: 20 nullable: true phone_e164: type: string pattern: "^\\+[1-9][0-9]{1,14}$" nullable: true readOnly: true contact_type: $ref: "#/components/schemas/EntityContactType" relationship_type: $ref: "#/components/schemas/EntityRelationshipType" date_of_birth: type: string format: date nullable: true location_id: type: string format: uuid nullable: true location_summary: allOf: - $ref: "#/components/schemas/EntityLocationVenueSummary" nullable: true family_location_summary: allOf: - $ref: "#/components/schemas/EntityLocationVenueSummary" nullable: true description: | When the contact belongs to at least one family with a saved location, the venue summary for the lexicographically first such family (by family id). Read-only in the admin UI; edit location on the family record. organization_location_summary: allOf: - $ref: "#/components/schemas/EntityLocationVenueSummary" nullable: true description: | When the contact belongs to at least one organisation with a saved location, the venue summary for the lexicographically first such organisation (by organisation id). Read-only in the admin UI; edit location on the organisation record. source: $ref: "#/components/schemas/EntityContactSource" source_detail: type: string nullable: true job_title: type: string nullable: true maxLength: 200 description: Optional job title (persons only; shown next to source detail in the admin editor). referral_contact_id: type: string format: uuid nullable: true description: | When `source` is `referral`, the contact UUID of the referring contact (stored in `source_metadata`). mailchimp_status: $ref: "#/components/schemas/EntityMailchimpSyncStatus" active: type: boolean archived_at: type: string format: date-time nullable: true created_at: type: string format: date-time updated_at: type: string format: date-time tag_ids: type: array items: type: string format: uuid tags: type: array items: $ref: "#/components/schemas/EntityTagRef" family_ids: type: array items: type: string format: uuid organization_ids: type: array items: type: string format: uuid standalone_note_count: type: integer minimum: 0 description: | Count of CRM notes on this contact that are not tied to a sales lead (`lead_id` is null). Lead-attached notes are excluded. has_completion_certificate: type: boolean description: | True when the contact has at least one issued (non-voided) completion certificate. has_sales_conversation: type: boolean description: | True when the contact is linked to at least one WhatsApp, Instagram, or Messenger conversation. sales_conversation_channel: type: string nullable: true enum: [whatsapp, instagram, messenger] description: | Preferred Sales inbox tab for this contact: the channel of the most recently active linked conversation. Null when `has_sales_conversation` is false. has_service_instance: type: boolean description: | True when the contact has at least one non-cancelled enrollment attributed to the contact or to a family or organisation they belong to. has_invoice: type: boolean description: | True when at least one customer invoice is billed to the contact or to a family or organisation they belong to. PdfDownloadResponse: type: object required: [downloadUrl, expiresAt] properties: downloadUrl: type: string format: uri expiresAt: type: string format: date-time CompletionCertificateStatus: type: string enum: [issued, voided] CompletionCertificate: type: object required: - id - contact_id - contact_label - instance_id - instance_label - service_id - service_label - enrollment_id - participation_date - recipient_display_name - program_title - body_text - status - issued_at - issued_by properties: id: type: string format: uuid contact_id: type: string format: uuid contact_label: type: string instance_id: type: string format: uuid instance_label: type: string service_id: type: string format: uuid service_label: type: string enrollment_id: type: string format: uuid partner_organization_id: type: string format: uuid nullable: true participation_date: type: string format: date recipient_display_name: type: string program_title: type: string partner_display_name: type: string nullable: true partner_signer_name: type: string nullable: true body_text: type: string status: $ref: "#/components/schemas/CompletionCertificateStatus" issued_at: type: string format: date-time issued_by: type: string voided_at: type: string format: date-time nullable: true voided_by: type: string nullable: true issued_pdf_sha256: type: string nullable: true pdf_template_version: type: string nullable: true created_at: type: string format: date-time nullable: true updated_at: type: string format: date-time nullable: true CompletionCertificateListResponse: type: object required: [items] properties: items: type: array items: $ref: "#/components/schemas/CompletionCertificate" next_cursor: type: string nullable: true CompletionCertificateResponse: type: object required: [certificate] properties: certificate: $ref: "#/components/schemas/CompletionCertificate" PreviewCompletionCertificateRequest: type: object required: - contact_id - service_id - instance_id - participation_date properties: contact_id: type: string format: uuid service_id: type: string format: uuid instance_id: type: string format: uuid participation_date: type: string format: date program_title: type: string nullable: true description: Optional override; defaults to instance or service title. partner_organization_id: type: string format: uuid nullable: true description: Required when the instance has linked partner organisations. IssueCompletionCertificateRequest: allOf: - $ref: "#/components/schemas/PreviewCompletionCertificateRequest" AdminContactListResponse: type: object required: - items - total_count properties: items: type: array items: $ref: "#/components/schemas/AdminContact" next_cursor: type: string nullable: true total_count: type: integer minimum: 0 AdminContactResponse: type: object required: - contact properties: contact: $ref: "#/components/schemas/AdminContact" CreateAdminContactRequest: type: object required: - first_name - contact_type properties: first_name: type: string maxLength: 100 last_name: type: string maxLength: 100 nullable: true email: type: string nullable: true instagram_handle: type: string maxLength: 30 nullable: true phone_region: type: string minLength: 2 maxLength: 2 pattern: "^[A-Z]{2}$" nullable: true phone_number: type: string pattern: "^[0-9]+$" maxLength: 20 nullable: true description: | National significant digits. Omit both `phone_region` and `phone_number` to leave phone unset; send both keys with JSON `null` to clear phone on create. contact_type: $ref: "#/components/schemas/EntityContactType" relationship_type: $ref: "#/components/schemas/EntityRelationshipType" source: $ref: "#/components/schemas/EntityContactSource" source_detail: type: string nullable: true job_title: type: string nullable: true maxLength: 200 date_of_birth: type: string format: date nullable: true location_id: type: string format: uuid nullable: true tag_ids: type: array items: type: string format: uuid family_ids: type: array maxItems: 1 items: type: string format: uuid description: | Optional. At most one family. Omit or send an empty array to unlink. organization_ids: type: array maxItems: 1 items: type: string format: uuid description: | Optional. At most one organisation (non-vendor). Omit or send an empty array to unlink. referral_contact_id: type: string format: uuid nullable: true description: Required when `source` is `referral` on create. UpdateAdminContactRequest: type: object properties: first_name: type: string maxLength: 100 last_name: type: string maxLength: 100 nullable: true email: type: string nullable: true instagram_handle: type: string maxLength: 30 nullable: true phone_region: type: string minLength: 2 maxLength: 2 pattern: "^[A-Z]{2}$" nullable: true phone_number: type: string pattern: "^[0-9]+$" maxLength: 20 nullable: true contact_type: $ref: "#/components/schemas/EntityContactType" relationship_type: $ref: "#/components/schemas/EntityRelationshipType" source: $ref: "#/components/schemas/EntityContactSource" source_detail: type: string nullable: true job_title: type: string nullable: true maxLength: 200 date_of_birth: type: string format: date nullable: true location_id: type: string format: uuid nullable: true active: type: boolean tag_ids: type: array items: type: string format: uuid family_ids: type: array maxItems: 1 items: type: string format: uuid organization_ids: type: array maxItems: 1 items: type: string format: uuid referral_contact_id: type: string format: uuid nullable: true description: | When `source` is `referral`, must be set to a valid active contact UUID (omit or null to clear only when source is not referral). MailchimpSyncRunRequest: type: object required: - tag_name properties: max_contacts: type: integer minimum: 1 maximum: 200 default: 50 cursor: type: string nullable: true description: Opaque cursor from the prior response's `next_cursor`. only_statuses: type: array items: type: string enum: - pending - failed description: | Defaults to `pending` and `failed`. Must not include `unsubscribed` (non-compliant re-subscribe risk). tag_name: type: string minLength: 1 maxLength: 100 pattern: "^[a-zA-Z0-9 ._\\-]+$" dry_run: type: boolean default: false MailchimpSyncRunErrorSampleItem: type: object required: - contact_id - reason - lead_email_masked properties: contact_id: type: string format: uuid reason: type: string status: type: integer nullable: true description: HTTP status from Mailchimp when `reason` is `mailchimp_api_error`. lead_email_masked: type: string description: Masked email for operator triage. MailchimpSyncRunResponse: type: object required: - processed - succeeded - failed - skipped - next_cursor - errors_sample - dry_run - would_process properties: processed: type: integer succeeded: type: integer failed: type: integer skipped: type: integer next_cursor: type: string nullable: true errors_sample: type: array items: $ref: "#/components/schemas/MailchimpSyncRunErrorSampleItem" dry_run: type: boolean would_process: type: integer description: | When `dry_run` is true, equals the number of rows that would have been sent to Mailchimp. Zero when `dry_run` is false. MailchimpOrphanCleanupRequest: type: object properties: max_members: type: integer minimum: 1 maximum: 1000 default: 200 mailchimp_offset: type: integer minimum: 0 maximum: 10000000 default: 0 mode: type: string enum: - archive - permanent default: archive dry_run: type: boolean default: true MailchimpOrphanRemovedSampleItem: type: object required: - email - status properties: email: type: string description: Masked email for logs/UI samples. status: type: string description: Mailchimp member status when scanned. MailchimpOrphanCleanupResponse: type: object description: | Mailchimp offset pagination is not transactionally consistent: concurrent audience changes (for example webhook-driven unsubscribes) can shift which members appear between batches. Archive mode remains idempotent on Mailchimp; permanent mode keeps the same offset while removals occur (see `next_offset`). required: - scanned - kept - removed - failed - next_offset - removed_sample - dry_run - already_archived - would_remove properties: scanned: type: integer kept: type: integer removed: type: integer failed: type: integer next_offset: type: integer nullable: true description: | For `mode=archive` or any `dry_run` request, the next offset is `mailchimp_offset + scanned` when the page is full (same length as `max_members`), otherwise null. For `mode=permanent` with `dry_run=false`, when at least one member was removed this page, repeats `mailchimp_offset` so the caller re-reads the same offset (permanent deletes shift indices). When zero members were removed and the page is full, advances by `scanned`; otherwise null. removed_sample: type: array items: $ref: "#/components/schemas/MailchimpOrphanRemovedSampleItem" dry_run: type: boolean already_archived: type: integer description: | Archive mode only: members already in Mailchimp `archived` state skipped without API calls. Zero in permanent mode (archived members are still eligible for permanent erase). would_remove: type: integer description: | When `dry_run` is true, counts members that would be removed or archived. Zero when `dry_run` is false; use `removed` for executed runs. MailchimpSyncStatusResponse: type: object required: - counts_by_status - archived_with_mailchimp_record - last_run_summary properties: counts_by_status: type: object additionalProperties: type: integer description: Keys are `pending`, `synced`, `failed`, `unsubscribed`. archived_with_mailchimp_record: type: integer last_run_summary: nullable: true description: Reserved; always null in v1. AdminFamilyMember: type: object description: | Persisted membership fields. `role` matches the contact's `contact_type` when the membership is created and is refreshed when `contact_type` is updated on the contact. required: - id - contact_id - contact_label - role - is_primary_contact properties: id: type: string format: uuid contact_id: type: string format: uuid contact_label: type: string role: $ref: "#/components/schemas/EntityFamilyRole" is_primary_contact: type: boolean AdminFamily: type: object required: - id - family_name - relationship_type - active - tag_ids - tags - members - has_sales_conversation - has_service_instance - has_invoice properties: id: type: string format: uuid family_name: type: string relationship_type: $ref: "#/components/schemas/EntityRelationshipType" location_id: type: string format: uuid nullable: true location_summary: allOf: - $ref: "#/components/schemas/EntityLocationVenueSummary" nullable: true active: type: boolean archived_at: type: string format: date-time nullable: true created_at: type: string format: date-time updated_at: type: string format: date-time tag_ids: type: array items: type: string format: uuid tags: type: array items: $ref: "#/components/schemas/EntityTagRef" members: type: array items: $ref: "#/components/schemas/AdminFamilyMember" has_sales_conversation: type: boolean description: | True when any family member is linked to at least one WhatsApp, Instagram, or Messenger conversation. sales_conversation_channel: type: string nullable: true enum: [whatsapp, instagram, messenger] description: | Preferred Sales inbox tab for this family: the channel of the most recently active conversation among members. Null when `has_sales_conversation` is false. has_service_instance: type: boolean description: | True when the family has at least one non-cancelled enrollment attributed to the family or to one of its member contacts. has_invoice: type: boolean description: | True when at least one customer invoice is billed to the family or to one of its member contacts. AdminFamilyListResponse: type: object required: - items - total_count properties: items: type: array items: $ref: "#/components/schemas/AdminFamily" next_cursor: type: string nullable: true total_count: type: integer minimum: 0 AdminFamilyResponse: type: object required: - family properties: family: $ref: "#/components/schemas/AdminFamily" CreateAdminFamilyRequest: type: object required: - family_name properties: family_name: type: string maxLength: 150 relationship_type: $ref: "#/components/schemas/EntityFamilyRelationshipType" location_id: type: string format: uuid nullable: true tag_ids: type: array items: type: string format: uuid UpdateAdminFamilyRequest: type: object properties: family_name: type: string maxLength: 150 relationship_type: $ref: "#/components/schemas/EntityFamilyRelationshipType" location_id: type: string format: uuid nullable: true active: type: boolean tag_ids: type: array items: type: string format: uuid AddFamilyMemberRequest: type: object required: - contact_id properties: contact_id: type: string format: uuid role: type: string deprecated: true description: | Ignored. Membership role is derived from the contact's `contact_type` (parent, child, helper map to the same family roles; professional and other map to `other`). is_primary_contact: type: boolean UpdateFamilyMemberRequest: type: object required: - is_primary_contact properties: is_primary_contact: type: boolean description: | When true, this member becomes the family's sole primary contact. When false, this member is cleared as primary (other members are unchanged). UpdateOrganizationMemberRequest: type: object required: - is_primary_contact properties: is_primary_contact: type: boolean description: | When true, this member becomes the organisation's sole primary contact. When false, this member is cleared as primary (other members are unchanged). AdminOrganizationMember: type: object required: - id - contact_id - contact_label - role - is_primary_contact properties: id: type: string format: uuid contact_id: type: string format: uuid contact_label: type: string role: $ref: "#/components/schemas/EntityOrganizationRole" description: | Stored organisation membership role derived from the contact's `contact_type` (parent, helper, and professional map to `staff`; child maps to `member`; other maps to `other`). is_primary_contact: type: boolean AdminOrganization: type: object required: - id - name - organization_type - relationship_type - active - tag_ids - tags - members - has_sales_conversation - has_service_instance - has_invoice properties: id: type: string format: uuid name: type: string organization_type: $ref: "#/components/schemas/EntityOrganizationType" relationship_type: $ref: "#/components/schemas/EntityRelationshipType" partner_key: type: string nullable: true description: > Optional URL-safe partner key for partner organisations only (lowercase letters, digits, single hyphens between segments). Null when not a partner or unset. Uniqueness is enforced case-insensitively among partner rows. legal_name: type: string nullable: true maxLength: 255 description: > Optional legal entity name for partner organisations only. Used on AR invoice Bill To lines (with fallback to ``name``). Null when not a partner or unset. website: type: string nullable: true location_id: type: string format: uuid nullable: true location_summary: allOf: - $ref: "#/components/schemas/EntityLocationVenueSummary" nullable: true active: type: boolean archived_at: type: string format: date-time nullable: true created_at: type: string format: date-time updated_at: type: string format: date-time tag_ids: type: array items: type: string format: uuid tags: type: array items: $ref: "#/components/schemas/EntityTagRef" members: type: array items: $ref: "#/components/schemas/AdminOrganizationMember" has_sales_conversation: type: boolean description: | True when any organisation member is linked to at least one WhatsApp, Instagram, or Messenger conversation. sales_conversation_channel: type: string nullable: true enum: [whatsapp, instagram, messenger] description: | Preferred Sales inbox tab for this organisation: the channel of the most recently active conversation among members. Null when `has_sales_conversation` is false. has_service_instance: type: boolean description: | True when the organisation has at least one non-cancelled enrollment attributed to the organisation or to one of its member contacts. has_invoice: type: boolean description: | True when at least one customer invoice is billed to the organisation or to one of its member contacts. AdminOrganizationListResponse: type: object required: - items - total_count properties: items: type: array items: $ref: "#/components/schemas/AdminOrganization" next_cursor: type: string nullable: true total_count: type: integer minimum: 0 AdminOrganizationResponse: type: object required: - organization properties: organization: $ref: "#/components/schemas/AdminOrganization" CreateAdminOrganizationRequest: type: object required: - name - organization_type properties: name: type: string maxLength: 255 organization_type: $ref: "#/components/schemas/EntityOrganizationType" relationship_type: $ref: "#/components/schemas/EntityOrganizationRelationshipType" partner_key: type: string maxLength: 128 nullable: true description: > Optional partner-only key. Omit or null to clear. Must be null when relationship_type is not partner. legal_name: type: string maxLength: 255 nullable: true description: > Optional partner-only legal entity name for invoice Bill To display. Omit or null to clear. Must be null when relationship_type is not partner. website: type: string maxLength: 500 nullable: true location_id: type: string format: uuid nullable: true tag_ids: type: array items: type: string format: uuid active: type: boolean description: > When false, the organization is created archived (`archived_at` set). Omit for default active (not archived). UpdateAdminOrganizationRequest: type: object properties: name: type: string maxLength: 255 organization_type: $ref: "#/components/schemas/EntityOrganizationType" relationship_type: $ref: "#/components/schemas/EntityOrganizationRelationshipType" partner_key: type: string maxLength: 128 nullable: true description: > Optional partner-only key. Omit or null to clear. Must be null when relationship_type is not partner. legal_name: type: string maxLength: 255 nullable: true description: > Optional partner-only legal entity name for invoice Bill To display. Omit or null to clear. Must be null when relationship_type is not partner. website: type: string maxLength: 500 nullable: true location_id: type: string format: uuid nullable: true active: type: boolean tag_ids: type: array items: type: string format: uuid AddOrganizationMemberRequest: type: object required: - contact_id properties: contact_id: type: string format: uuid role: type: string deprecated: true description: | Ignored. Membership role is derived from the contact's `contact_type` (parent, helper, and professional map to `staff`; child maps to `member`; other maps to `other`). is_primary_contact: type: boolean ActionMessageResponse: type: object required: - message properties: message: type: string ErrorResponse: type: object required: - error properties: error: type: string detail: type: string nullable: true field: type: string nullable: true description: > Optional input field key for validation-style errors. Duplicate service service_key+tier conflicts use the literal `service_key_tier` (not `service_key` or `service_tier`). HealthResponse: type: object required: - healthy - version - environment properties: healthy: type: boolean version: type: string environment: type: string checks: type: array items: type: object additionalProperties: true